agentix-cli 0.154.0 → 0.154.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/dist/{App-OL5GYZBS.js → App-6T6NVB7O.js} +2 -2
- package/dist/{ChatApp-EEHKOZQX.js → ChatApp-QZBJ4NHC.js} +2 -2
- package/dist/{absorb-eval-PVCA7UE6.js → absorb-eval-EVX7LDXR.js} +2 -2
- package/dist/{agent-3ETFZSEZ.js → agent-F2NT6B25.js} +2 -2
- package/dist/{board-dashboard-RUO6R5NI.js → board-dashboard-642BO7GV.js} +4 -4
- package/dist/{chunk-GDNKUNT7.js → chunk-37I654UJ.js} +2 -2
- package/dist/{chunk-BMZK232D.js → chunk-4CWACHEH.js} +2 -2
- package/dist/{chunk-FFPQS2C4.js → chunk-743RAKLP.js} +2 -2
- package/dist/{chunk-M5TMFCPA.js → chunk-ABCQ6QMJ.js} +2 -2
- package/dist/{chunk-HOLJZIVJ.js → chunk-AKCEMKQM.js} +2 -2
- package/dist/{chunk-HF55LKFC.js → chunk-B75BLZ2M.js} +2 -2
- package/dist/{chunk-TDMX6HTT.js → chunk-CUAS4ITR.js} +2 -2
- package/dist/{chunk-U3PHNPIJ.js → chunk-E76HREC7.js} +3 -3
- package/dist/{chunk-ABKEGNY4.js → chunk-EGTANAFI.js} +2 -2
- package/dist/{chunk-2FH4TULF.js → chunk-GFRAHUAQ.js} +2 -2
- package/dist/{chunk-NUMWHIFL.js → chunk-GRVTLUQ6.js} +2 -2
- package/dist/{chunk-4FKFEWCE.js → chunk-HSCZSNOX.js} +2 -2
- package/dist/{chunk-5NTEGDXT.js → chunk-HUN6COOF.js} +2 -2
- package/dist/{chunk-VCAVVCXT.js → chunk-IA4J3YLB.js} +2 -2
- package/dist/{chunk-RTXFDYFR.js → chunk-IWWEUXZQ.js} +2 -2
- package/dist/{chunk-RARXW4KB.js → chunk-KA2NV7H4.js} +2 -2
- package/dist/{chunk-NKTBJHIF.js → chunk-MLC5INGD.js} +5 -5
- package/dist/{chunk-CJKN4APJ.js → chunk-OKVQYPPF.js} +5 -5
- package/dist/{chunk-F5KWRBTF.js → chunk-S3EX64LR.js} +2 -2
- package/dist/{chunk-IYL4YUXQ.js → chunk-SD3CC4EX.js} +2 -2
- package/dist/{chunk-IRDPIQRR.js → chunk-U4YTTWR6.js} +2 -2
- package/dist/{chunk-GVJMPSE2.js → chunk-VKEH4IBA.js} +16 -16
- package/dist/chunk-VKEH4IBA.js.map +1 -0
- package/dist/{chunk-JXY7EEAR.js → chunk-VRF4YW46.js} +2 -2
- package/dist/{chunk-USCFJVVI.js → chunk-W2RB5XG7.js} +2 -2
- package/dist/{chunk-2K2QDTGP.js → chunk-XOUK5ZIQ.js} +2 -2
- package/dist/{chunk-MKIJAGES.js → chunk-YJNUVAM4.js} +2 -2
- package/dist/{chunk-UWUJVING.js → chunk-YL26FRKJ.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-WBAWHYAY.js → client-OCLSGJYQ.js} +2 -2
- package/dist/{config-VXXKMXHH.js → config-FZTWI3VG.js} +2 -2
- package/dist/{config-mutate-MMTHEXWM.js → config-mutate-X5IKMROK.js} +2 -2
- package/dist/config-mutator-C5BMIBZO.js +2 -0
- package/dist/{contributions-3ZE2TK24.js → contributions-KHGGVSR6.js} +2 -2
- package/dist/{doctor-TP4GSLZV.js → doctor-KNCRQ3YO.js} +2 -2
- package/dist/{follow-up-tool-L3QXZIU2.js → follow-up-tool-TGKEPA5C.js} +2 -2
- package/dist/{hub-U65U7SE6.js → hub-HQUAH5H6.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-7WISM624.js → program-HFN24YLA.js} +23 -23
- package/dist/{promote-GP2MZX7S.js → promote-VD4OVQGL.js} +2 -2
- package/dist/{query-WHNB46XD.js → query-5CPK6G2H.js} +2 -2
- package/dist/{query-settings-U5ZMQREP.js → query-settings-35GDM3HU.js} +2 -2
- package/dist/{registry-GXGHPROE.js → registry-JCHKHCRE.js} +2 -2
- package/dist/{request-planner-HALSGCA5.js → request-planner-ZIG4YVXC.js} +2 -2
- package/dist/{review-candidates-WIXZZCF7.js → review-candidates-LPZWOR2K.js} +2 -2
- package/dist/{routing-U543HNNU.js → routing-BLOYDLU4.js} +2 -2
- package/dist/schedule-tool-7KFO3NPD.js +2 -0
- package/dist/{scheduler-OEKYXZPJ.js → scheduler-BEJRDQR3.js} +2 -2
- package/dist/{seat-FWF2HKWS.js → seat-NU3UJC6C.js} +2 -2
- package/dist/{select-QDSG7NQX.js → select-IWAFX4XJ.js} +2 -2
- package/dist/{set-enabled-W7U5SXYX.js → set-enabled-JF75TSFU.js} +2 -2
- package/dist/{tool-VN7W6QGC.js → tool-PQBQJWM5.js} +2 -2
- package/dist/{tool-QIFV7Q4M.js → tool-WTOOPTGC.js} +2 -2
- package/dist/{wiki-TN5WFJ5P.js → wiki-DXG655NP.js} +2 -2
- package/dist/wiki-enrich-5VQCT6BT.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-GVJMPSE2.js.map +0 -1
- package/dist/config-mutator-R75BQXMB.js +0 -2
- package/dist/schedule-tool-FIKDTGXF.js +0 -2
- package/dist/wiki-enrich-GEHA6NJQ.js +0 -2
- /package/dist/{App-OL5GYZBS.js.map → App-6T6NVB7O.js.map} +0 -0
- /package/dist/{ChatApp-EEHKOZQX.js.map → ChatApp-QZBJ4NHC.js.map} +0 -0
- /package/dist/{absorb-eval-PVCA7UE6.js.map → absorb-eval-EVX7LDXR.js.map} +0 -0
- /package/dist/{agent-3ETFZSEZ.js.map → agent-F2NT6B25.js.map} +0 -0
- /package/dist/{board-dashboard-RUO6R5NI.js.map → board-dashboard-642BO7GV.js.map} +0 -0
- /package/dist/{chunk-GDNKUNT7.js.map → chunk-37I654UJ.js.map} +0 -0
- /package/dist/{chunk-BMZK232D.js.map → chunk-4CWACHEH.js.map} +0 -0
- /package/dist/{chunk-FFPQS2C4.js.map → chunk-743RAKLP.js.map} +0 -0
- /package/dist/{chunk-M5TMFCPA.js.map → chunk-ABCQ6QMJ.js.map} +0 -0
- /package/dist/{chunk-HOLJZIVJ.js.map → chunk-AKCEMKQM.js.map} +0 -0
- /package/dist/{chunk-HF55LKFC.js.map → chunk-B75BLZ2M.js.map} +0 -0
- /package/dist/{chunk-TDMX6HTT.js.map → chunk-CUAS4ITR.js.map} +0 -0
- /package/dist/{chunk-U3PHNPIJ.js.map → chunk-E76HREC7.js.map} +0 -0
- /package/dist/{chunk-ABKEGNY4.js.map → chunk-EGTANAFI.js.map} +0 -0
- /package/dist/{chunk-2FH4TULF.js.map → chunk-GFRAHUAQ.js.map} +0 -0
- /package/dist/{chunk-NUMWHIFL.js.map → chunk-GRVTLUQ6.js.map} +0 -0
- /package/dist/{chunk-4FKFEWCE.js.map → chunk-HSCZSNOX.js.map} +0 -0
- /package/dist/{chunk-5NTEGDXT.js.map → chunk-HUN6COOF.js.map} +0 -0
- /package/dist/{chunk-VCAVVCXT.js.map → chunk-IA4J3YLB.js.map} +0 -0
- /package/dist/{chunk-RTXFDYFR.js.map → chunk-IWWEUXZQ.js.map} +0 -0
- /package/dist/{chunk-RARXW4KB.js.map → chunk-KA2NV7H4.js.map} +0 -0
- /package/dist/{chunk-NKTBJHIF.js.map → chunk-MLC5INGD.js.map} +0 -0
- /package/dist/{chunk-CJKN4APJ.js.map → chunk-OKVQYPPF.js.map} +0 -0
- /package/dist/{chunk-F5KWRBTF.js.map → chunk-S3EX64LR.js.map} +0 -0
- /package/dist/{chunk-IYL4YUXQ.js.map → chunk-SD3CC4EX.js.map} +0 -0
- /package/dist/{chunk-IRDPIQRR.js.map → chunk-U4YTTWR6.js.map} +0 -0
- /package/dist/{chunk-JXY7EEAR.js.map → chunk-VRF4YW46.js.map} +0 -0
- /package/dist/{chunk-USCFJVVI.js.map → chunk-W2RB5XG7.js.map} +0 -0
- /package/dist/{chunk-2K2QDTGP.js.map → chunk-XOUK5ZIQ.js.map} +0 -0
- /package/dist/{chunk-MKIJAGES.js.map → chunk-YJNUVAM4.js.map} +0 -0
- /package/dist/{chunk-UWUJVING.js.map → chunk-YL26FRKJ.js.map} +0 -0
- /package/dist/{client-WBAWHYAY.js.map → client-OCLSGJYQ.js.map} +0 -0
- /package/dist/{config-VXXKMXHH.js.map → config-FZTWI3VG.js.map} +0 -0
- /package/dist/{config-mutate-MMTHEXWM.js.map → config-mutate-X5IKMROK.js.map} +0 -0
- /package/dist/{config-mutator-R75BQXMB.js.map → config-mutator-C5BMIBZO.js.map} +0 -0
- /package/dist/{contributions-3ZE2TK24.js.map → contributions-KHGGVSR6.js.map} +0 -0
- /package/dist/{doctor-TP4GSLZV.js.map → doctor-KNCRQ3YO.js.map} +0 -0
- /package/dist/{follow-up-tool-L3QXZIU2.js.map → follow-up-tool-TGKEPA5C.js.map} +0 -0
- /package/dist/{hub-U65U7SE6.js.map → hub-HQUAH5H6.js.map} +0 -0
- /package/dist/{program-7WISM624.js.map → program-HFN24YLA.js.map} +0 -0
- /package/dist/{promote-GP2MZX7S.js.map → promote-VD4OVQGL.js.map} +0 -0
- /package/dist/{query-WHNB46XD.js.map → query-5CPK6G2H.js.map} +0 -0
- /package/dist/{query-settings-U5ZMQREP.js.map → query-settings-35GDM3HU.js.map} +0 -0
- /package/dist/{registry-GXGHPROE.js.map → registry-JCHKHCRE.js.map} +0 -0
- /package/dist/{request-planner-HALSGCA5.js.map → request-planner-ZIG4YVXC.js.map} +0 -0
- /package/dist/{review-candidates-WIXZZCF7.js.map → review-candidates-LPZWOR2K.js.map} +0 -0
- /package/dist/{routing-U543HNNU.js.map → routing-BLOYDLU4.js.map} +0 -0
- /package/dist/{schedule-tool-FIKDTGXF.js.map → schedule-tool-7KFO3NPD.js.map} +0 -0
- /package/dist/{scheduler-OEKYXZPJ.js.map → scheduler-BEJRDQR3.js.map} +0 -0
- /package/dist/{seat-FWF2HKWS.js.map → seat-NU3UJC6C.js.map} +0 -0
- /package/dist/{select-QDSG7NQX.js.map → select-IWAFX4XJ.js.map} +0 -0
- /package/dist/{set-enabled-W7U5SXYX.js.map → set-enabled-JF75TSFU.js.map} +0 -0
- /package/dist/{tool-VN7W6QGC.js.map → tool-PQBQJWM5.js.map} +0 -0
- /package/dist/{tool-QIFV7Q4M.js.map → tool-WTOOPTGC.js.map} +0 -0
- /package/dist/{wiki-TN5WFJ5P.js.map → wiki-DXG655NP.js.map} +0 -0
- /package/dist/{wiki-enrich-GEHA6NJQ.js.map → wiki-enrich-5VQCT6BT.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Jm,b as ni,g as Gm}from"./chunk-
|
|
1
|
+
import{a as Jm,b as ni,g as Gm}from"./chunk-IWWEUXZQ.js";import{a as Wm,b as Bm}from"./chunk-4CWACHEH.js";import{b as Um}from"./chunk-SD3CC4EX.js";import{D as Am,E as Em,F as sc,G as Rm,J as Nm,K as Im,L as jm,N as rc,O as _m,Q as Dm,R as Pm,S as Mm,a as rm,e as im,f as am,g as cm,h as lm,i as dm,j as gm,m as ti,n as oi,o as Qt,p as pm,q as fm,r as $m,s as bm,u as km,v as vm,w as xm,x as nc,y as Sm}from"./chunk-HUN6COOF.js";import{a as Cm,c as Tm,d as Om}from"./chunk-5NTWGUSJ.js";import{n as ic}from"./chunk-ABCQ6QMJ.js";import{a as Lm,b as Fm,d as Ds,e as qm}from"./chunk-B75BLZ2M.js";import"./chunk-XVTD6I34.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as St}from"./chunk-CUAS4ITR.js";import{a as um,c as mm}from"./chunk-EGTANAFI.js";import{d as hm,e as oc,h as ym,i as wm}from"./chunk-LLJZMS23.js";import{a as ec}from"./chunk-LNY6N73E.js";import"./chunk-B2QYMUTD.js";import{a as _a,b as fg}from"./chunk-RKPAVWXF.js";import{$ as lo,A as Ba,Aa as ei,B as mu,Ba as tc,C as pu,Ca as sm,D as fu,E as hu,F as yu,G as Gr,H as wu,I as $u,J as Hr,K as ku,L as Su,M as Au,N as Eu,O as Ru,P as Cu,Q as Ja,R as Tu,S as Ou,T as Nu,U as Iu,V as ju,W as _u,X as Du,Y as Pu,Z as Bu,_ as Vr,a as xg,aa as Ao,b as Sg,ba as qn,ca as Xr,da as Kr,ea as Va,fa as Ju,ga as Gu,h as Ir,ha as Hu,i as Cg,ia as zu,j as Os,ja as Yu,k as jr,ka as Vu,l as Og,la as Un,m as Ig,ma as Wn,n as Jg,na as Xu,o as Gg,oa as js,p as Fr,pa as Ku,q as Fa,qa as st,r as Qg,ra as Qr,s as au,sa as _s,t as cu,ta as Xa,u as lu,ua as Qu,v as Ua,va as tm,w as du,wa as Za,x as gu,xa as nm,y as Wa,ya as Zr,z as uu,za as Bn}from"./chunk-OKVQYPPF.js";import{$ as Ga,B as Br,C as ru,F as iu,G as Jr,J as bu,Pa as Zu,Qa as Ka,Ra as em,Sa as Qa,Y as Ns,aa as zr,ba as Mu,eb as Kt,gb as om,ia as So,ja as Lu,ka as Ha,ma as za,oa as Fu,p as Ng,pa as qu,qa as Is,ua as Yr,xa as Uu,ya as Wu,z as su,za as Ya}from"./chunk-HSCZSNOX.js";import"./chunk-GTJIKXDB.js";import{a as Ag,c as Pa,e as Eg,f as Rg}from"./chunk-GFRAHUAQ.js";import{D as Pr,E as Wg,F as Bg,a as ja,b as dg,d as gg,e as ug,l as _r,m as Dr,n as jg,o as _g,p as Dg,r as Pg,s as Mg,u as Lg,v as Fg,w as qg,x as Ug}from"./chunk-XOUK5ZIQ.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import{c as zg,e as Mr,g as Lr}from"./chunk-LQE73AZR.js";import{a as Yg,b as Vg,c as Xg,d as Kg}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BNOGNRAM.js";import{a as Zg,b as Vo,c as eu,d as qr,g as tu,h as ou,j as nu,k as qa,n as Ur,o as Xo,p as Wr}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as vu,b as xu}from"./chunk-EKJG63EJ.js";import{a as Ma,p as Tg}from"./chunk-S3EX64LR.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as xt}from"./chunk-EMGB23H5.js";import{c as Hg}from"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import{b as La}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{a as Xt}from"./chunk-MNG2AMKZ.js";import"./chunk-X7UQY7CH.js";import{a as Da,e as hg,f as yg,h as wg,i as $g,k as bg,l as kg,m as vg}from"./chunk-AKCEMKQM.js";import{b as Fn,e as pg}from"./chunk-PYHR4HXO.js";import{c as mg}from"./chunk-KP7KDLZ2.js";import"./chunk-A5GYG56I.js";import{A as Oa,B as Yd,N as xo,T as ag,g as qd,r as Ud,ra as lg}from"./chunk-MLC5INGD.js";import{F as rg,U as ig,W as cg,b as In,g as jn,h as Or,i as Nr,j as _n,k as Vd,l as ko,n as vo}from"./chunk-YL26FRKJ.js";import{b as zo}from"./chunk-MEFPXHQJ.js";import"./chunk-YJNUVAM4.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as Kd}from"./chunk-SZDACK6O.js";import{f as Qd,g as Zd,h as Na}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as tg,f as Yo,k as Pn}from"./chunk-5TTHN7DP.js";import{a as Hd,k as eg}from"./chunk-W2RB5XG7.js";import{a as Mn,b as ge,c as Je,d as Ln,e as og}from"./chunk-GRVTLUQ6.js";import{a as ng,b as Ia,h as sg}from"./chunk-3UOTLMXD.js";import{f as Bd,g as Jd}from"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import{a as Ta,b as Gd}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as zd}from"./chunk-X5C5W3E4.js";import{a as Dn}from"./chunk-GV7S5BAX.js";import{e as Xd}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Ca}from"./chunk-U4YTTWR6.js";import"./chunk-IA4J3YLB.js";import{c as Wd}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-E76HREC7.js";import"./chunk-SKSYII3K.js";import{g as bo,i as Tr}from"./chunk-KA2NV7H4.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-37I654UJ.js";import{a as va,b as hd,c as D$,d as Sr,e as yd,f as Id,g as B$,h as jd,i as J$,m as Nn,n as Dd,q as Pd,u as Md,y as Vt,z as Ts}from"./chunk-743RAKLP.js";import{a as co,b as On,e as Td,f as Cs}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Cr,b as _d}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{g as $o,i as Ld}from"./chunk-6TURWSMN.js";import{n as Fd}from"./chunk-AV7T3SYT.js";import"./chunk-U23LVMMZ.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-JNG3P5V2.js";import{a as Yt,b as _$}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{F as Ar,G as xd,J as Sd,Ja as Er,K as L$,Ka as Rs,L as Sa,La as C,M as Ad,Na as Rr,S as Ed,T as F$,Ua as ae,fa as Rd,ga as Aa,h as wd,i as $d,ia as Ea,j as bd,k as kd,l as vd,m as P$,pa as q$,qa as Ra,sa as Cd,ta as U$,v as xa,w as M$}from"./chunk-VKEH4IBA.js";import"./chunk-BRK6M6LA.js";import{f as vt,n as Es}from"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import{g as Od,k as Nd,l as W$}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as G$}from"commander";var Hm=new G$().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 Sg({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()});ae();import{Command as H$}from"commander";import{execFileSync as It}from"node:child_process";import{cpSync as zm,existsSync as lc,mkdirSync as ac,mkdtempSync as z$,readdirSync as Y$,rmSync as Ym,writeFileSync as Vm}from"node:fs";import{dirname as Xm,join as rt}from"node:path";import{homedir as si,release as V$,tmpdir as X$}from"node:os";import{setTimeout as K$}from"node:timers/promises";function ri(){let e=jg(process.platform,process.arch,V$());if(e)throw new Error(e)}function ii(){let e=rt(si(),"Library/LaunchAgents"),t=[];try{t=Y$(e).filter(Pg)}catch{}let o=t.flatMap(n=>{let s=rt(e,n);try{return[{file:s,plist:It("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Mg(e,o)}function Ps(e){return`gui/${process.getuid()}/${e.label}`}async function cc(e){try{It("launchctl",["bootout",Ps(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{It("launchctl",["print",Ps(e)],{stdio:"pipe"})}catch{return}await K$(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Km(e){if(!lc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{It("launchctl",["print",Ps(e)],{stdio:"pipe"})}catch{t=!1}t||It("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),It("launchctl",["kickstart",Ps(e)],{stdio:"pipe"})}function Q$(){let e=Ug();if(e&&lc(rt(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 Jn=new H$("desktop").description("install and control the macOS desktop assistant");Jn.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=>{ri();let t=C(),o=_g(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=Q$(),i=rt(si(),"Applications"),{keep:a,remove:c}=ii();if(console.log(`Desktop assistant \u2192 ${rt(i,_r)}
|
|
2
2
|
Computer-use helper \u2192 ${rt(i,Dr)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -41,7 +41,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
41
41
|
`))});function Up(e){let t=vt();return t||(console.log(Q.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new ec(t))}function Zb(){let e=vt({quiet:!0});if(!e)return[];let t=new Map;for(let o of new ec(e).list()){if(!La(o.deviceId))continue;let n=t.get(o.deviceId)??{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,subscriptions:0};n.subscriptions++,n.createdAt=Math.max(n.createdAt,o.createdAt),t.set(o.deviceId,n)}return[...t.values()]}function ek(e){let t=Math.round(zg/6e4),o=[` Pairing code: ${Q.bold.cyan(Mr(e.code))}`,Q.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Q.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Q.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://")||o.push(Q.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function Sc(){let e;try{e=JSON.parse(qp("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 t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var tk=new Set(["/app","/api/app","/member","/api/member"]),Fp="/.well-known/assetlinks.json";function ok(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=Kb().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(Qb()))for(let o of t??[])e.add(Wp(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var nk={http:80,https:443,"https+insecure":443};function sk(e){let t=e.match(/^(\d+)(\/[^?#]*)?$/);if(t)return{host:"localhost",port:Number(t[1]),path:t[2]??""};let o=e.match(/^(?:([a-z][a-z0-9+.-]*):\/\/)?(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)(?::(\d+))?([^?#]*)/i);if(!o)return null;let n=o[3]?Number(o[3]):nk[(o[1]??"http").toLowerCase()];return n?{host:Wp(o[2].replace(/^\[|\]$/g,"").replace(/%.*$/,"").replace(/\.$/,"").toLowerCase()),port:n,path:o[4]}:null}function Wp(e){let t=e.includes(":");if(!t&&!/^[0-9a-fx.]+$/.test(e))return e;let o;try{o=new URL(`http://${t?`[${e}]`:e}/`).hostname.replace(/^\[|\]$/g,"")}catch{return e}let n=o.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!n)return o;let[s,r]=[parseInt(n[1],16),parseInt(n[2],16)];return`::ffff:${s>>8}.${s&255}.${r>>8}.${r&255}`}function rk(e,t){let o=e.replace(/^::ffff:/,"");return t.has(e)||t.has(o)||e===""||e.endsWith(".localhost")||/^127\.\d+\.\d+\.\d+$/.test(o)||o==="0.0.0.0"}function Ac(e,t,o=ok()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let c of n){s.push({label:"",cfg:c});for(let[l,g]of Object.entries(c?.Services??{}))s.push({label:`${l} `,cfg:g})}let r=new Set(o);for(let{cfg:c}of s){for(let l of Object.keys(c?.Web??{}))r.add(l.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let l of Object.values(c?.TCP??{}))l?.TerminateTLS&&r.add(String(l.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=c=>{let l=sk(c.trim());return l&&l.port===t&&rk(l.host,r)?l:null},a=[];for(let{label:c,cfg:l}of s){for(let[g,d]of Object.entries(l?.Web??{}))for(let[f,p]of Object.entries(d?.Handlers??{})){if(p?.Proxy==null)continue;let u=i(String(p.Proxy));if(!u)continue;let h=f.replace(/\/+$/,"")||"/",y=h===Fp&&u.path===Fp;!tk.has(h)&&!y&&a.push(`${c}${g}${f}`)}for(let[g,d]of Object.entries(l?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${c}TCP port ${g}`)}return a}function Ec(){try{return JSON.parse(qp("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Bs(){try{return C().dashboard.port||4202}catch{return 4202}}ae();import{Command as to}from"commander";import w from"chalk";import ot from"prompts";import{readFileSync as Ro,writeFileSync as Vn,existsSync as Fe,mkdirSync as eo,cpSync as Rc,readdirSync as ik}from"fs";import{resolve as ne,join as Eo,dirname as ak}from"path";import{fileURLToPath as ck}from"url";function xe(){let e=ne(process.cwd(),"agentx.json");if(!Fe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ro(e,"utf-8"))}function dt(e){return ge(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(w.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(w.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(w.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var en=new to().name("agent").description("manage agents \u2014 add, list, remove");en.command("list").alias("ls").description("list configured agents").action(()=>{let e=xe();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${w.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(w.dim(` workspace: ${o.workspace}`)),n&&console.log(w.dim(` mentions: ${n}`))}console.log()});en.command("add").description("add a new agent interactively").action(async()=>{let e=xe(),t=await ot([{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:ne(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(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Eo(t.workspace,t.id);eo(ne(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-HAV4CQV7.js"),r=s(t.id,n,"19900",(...l)=>{console.log(w.dim(` ${l.join(" ")}`))}),i=ne(process.cwd(),"src/wiki/SKILL.md"),a=ne(ak(ck(import.meta.url)),"../wiki/SKILL.md"),c=Fe(i)?i:a;Fe(c)&&(eo(ne(o,".claude/skills/wiki"),{recursive:!0}),Rc(c,ne(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await dt(e),console.log(w.green(`
|
|
42
42
|
Agent "${t.id}" added`)),console.log(w.dim(` Workspace: ${o}`)),console.log(w.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});en.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=xe();if(!t.agents?.[e]){console.log(w.red(` Agent "${e}" not found`));return}delete t.agents[e],await dt(t),console.log(w.green(` Agent "${e}" removed from config (workspace preserved)`))});en.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,t)=>{let o=xe(),n=o.agents?.[e];if(n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(w.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):w.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":w.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||w.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(r=>r.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let r=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(r)||r<0||r>50)&&(console.log(w.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=r,s.push(`maxDelegationDepth=${r}`)}if(t.contextReferences!==void 0){let r=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(r)||(console.log(w.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=r==="true"||r==="on"||r==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(w.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let r=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(r)||r<1||r>240)&&(console.log(w.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(w.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await dt(o),console.log(w.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(w.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Js=new to().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Js.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=xe().agents?.[e];n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(w.dim(`
|
|
43
43
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
44
|
-
`));return}console.log(),console.log(w.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?w.green(`${g}:${d}=set`):w.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(w.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(w.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?w.cyan(r.kind.padEnd(14)):w.dim(r.kind.padEnd(14))} ${w.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${w.dim(l)}`),i||console.log(` ${w.dim("(disabled)")}`)}console.log()});Js.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,t)=>{let o=xe();o.agents?.[e]||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-VXXKMXHH.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await ot({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(w.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await ot({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(w.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let f=await ot({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"}]});f.scheme==="tokenEnv"?a=((await ot({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await ot({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await ot({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(w.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(w.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(f=>f.kind===r&&f.label===i)&&(console.log(w.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await dt(o),console.log(w.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(w.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Js.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=xe(),n=o.agents?.[e];n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log(w.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await dt(o),console.log(w.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Js.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=xe().agents?.[e];n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(w.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){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){i+=1,console.log(` ${w.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${w.dim(g)}`)}else console.log(` ${w.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});en.addCommand(Js);var mi=new to().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");mi.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=xe();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(w.bold(" Telegram:"));for(let[s,r]of Object.entries(t.accounts||{}))console.log(` ${w.cyan(s)} -> agent: ${r.agentBinding}`)}else console.log(w.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(w.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let r=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${r} -> agent: ${s.agent}`)}}else console.log(w.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(w.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(w.dim(" GitLab: disabled"));console.log()});mi.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=xe(),t=Object.keys(e.agents||{});if(!t.length){console.log(w.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ot({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 ot([{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:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(w.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(w.red(` Invalid token: ${r.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 dt(e),console.log(w.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ot([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 r=[],i=s.addRoute;for(;i;){let a=await ot([{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:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await dt(e),eo(ne(process.cwd(),s.sessionDir),{recursive:!0}),console.log(w.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(w.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ot([{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 r=[],i=s.addRoute;for(;i;){let a=await ot([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await dt(e),console.log(w.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(w.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(w.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(w.dim(` Secret token: ${s.webhookSecret}`)),console.log(w.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(w.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Xn=new to().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Xn.command("list").alias("ls").description("list cron jobs").action(()=>{let e=xe();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?w.green("\u25CF"):w.dim("\u25CB");console.log(` ${n} ${w.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(w.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(w.dim(" No cron jobs configured")),console.log()});Xn.command("add").description("add a cron job").action(async()=>{let e=xe(),t=Object.keys(e.agents||{}),o=await ot([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await dt(e),console.log(w.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Xn.command("enable <id>").description("enable a cron job").action(async e=>{let t=xe();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(w.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await dt(t),console.log(w.green(` Cron "${e}" enabled`))});Xn.command("disable <id>").description("disable a cron job").action(async e=>{let t=xe();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await dt(t),console.log(w.green(` Cron "${e}" disabled`))});var Et=new to().name("mesh").description("manage mesh peers \u2014 add, list, remove");Et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=xe();if(console.log(),!e.mesh?.enabled)console.log(w.dim(" Mesh: disabled"));else{console.log(w.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=w.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=w.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${w.cyan(t.name)} ${w.dim(t.url)} ${o}`)}}console.log()});Et.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=xe(),t=await ot([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(w.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(w.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:t.url,name:t.name,...t.token?{token:t.token}:{}}),await dt(e),console.log(w.green(` Peer "${t.name}" added`)),console.log()}});Et.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=xe();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await dt(t),console.log(w.green(` Peer "${e}" removed`)))});Et.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 t=xe();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(w.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(w.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(w.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await dt(t),console.log(w.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(w.dim(" Restart the daemon for the new cadence to take effect."))});Et.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,t)=>{let o=t.node||"";if(!o)try{o=C().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(w.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(w.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+w.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(w.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var Bp=e=>{let t=e||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function pi(e,t,o={}){let n=Bp(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(w.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(w.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(w.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var tn=Et.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");tn.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:t}=await import("./token-store-AY6OBDVI.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-YGA654NI.js"),i=C(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.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(w.red(` ${a.error}`)),process.exit(1));let c=(e.url||Bp()).replace(/\/+$/,"");console.log(),console.log(` Grant ${w.bold(a.grant.name)} for ${w.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(w.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(` ${w.cyan(c)}`),console.log(` ${w.bold(n(a.code))}`),console.log(),console.log(` They run: ${w.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()});tn.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:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(w.dim(`
|
|
44
|
+
`));return}console.log(),console.log(w.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?w.green(`${g}:${d}=set`):w.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(w.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(w.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?w.cyan(r.kind.padEnd(14)):w.dim(r.kind.padEnd(14))} ${w.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${w.dim(l)}`),i||console.log(` ${w.dim("(disabled)")}`)}console.log()});Js.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,t)=>{let o=xe();o.agents?.[e]||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-FZTWI3VG.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await ot({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(w.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await ot({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(w.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let f=await ot({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"}]});f.scheme==="tokenEnv"?a=((await ot({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await ot({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await ot({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(w.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(w.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(f=>f.kind===r&&f.label===i)&&(console.log(w.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await dt(o),console.log(w.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(w.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Js.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=xe(),n=o.agents?.[e];n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log(w.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await dt(o),console.log(w.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Js.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=xe().agents?.[e];n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(w.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){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){i+=1,console.log(` ${w.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${w.dim(g)}`)}else console.log(` ${w.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});en.addCommand(Js);var mi=new to().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");mi.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=xe();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(w.bold(" Telegram:"));for(let[s,r]of Object.entries(t.accounts||{}))console.log(` ${w.cyan(s)} -> agent: ${r.agentBinding}`)}else console.log(w.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(w.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let r=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${r} -> agent: ${s.agent}`)}}else console.log(w.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(w.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(w.dim(" GitLab: disabled"));console.log()});mi.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=xe(),t=Object.keys(e.agents||{});if(!t.length){console.log(w.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ot({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 ot([{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:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(w.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(w.red(` Invalid token: ${r.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 dt(e),console.log(w.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ot([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 r=[],i=s.addRoute;for(;i;){let a=await ot([{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:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await dt(e),eo(ne(process.cwd(),s.sessionDir),{recursive:!0}),console.log(w.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(w.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ot([{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 r=[],i=s.addRoute;for(;i;){let a=await ot([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await dt(e),console.log(w.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(w.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(w.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(w.dim(` Secret token: ${s.webhookSecret}`)),console.log(w.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(w.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Xn=new to().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Xn.command("list").alias("ls").description("list cron jobs").action(()=>{let e=xe();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?w.green("\u25CF"):w.dim("\u25CB");console.log(` ${n} ${w.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(w.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(w.dim(" No cron jobs configured")),console.log()});Xn.command("add").description("add a cron job").action(async()=>{let e=xe(),t=Object.keys(e.agents||{}),o=await ot([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await dt(e),console.log(w.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Xn.command("enable <id>").description("enable a cron job").action(async e=>{let t=xe();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(w.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await dt(t),console.log(w.green(` Cron "${e}" enabled`))});Xn.command("disable <id>").description("disable a cron job").action(async e=>{let t=xe();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await dt(t),console.log(w.green(` Cron "${e}" disabled`))});var Et=new to().name("mesh").description("manage mesh peers \u2014 add, list, remove");Et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=xe();if(console.log(),!e.mesh?.enabled)console.log(w.dim(" Mesh: disabled"));else{console.log(w.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=w.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=w.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${w.cyan(t.name)} ${w.dim(t.url)} ${o}`)}}console.log()});Et.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=xe(),t=await ot([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(w.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(w.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:t.url,name:t.name,...t.token?{token:t.token}:{}}),await dt(e),console.log(w.green(` Peer "${t.name}" added`)),console.log()}});Et.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=xe();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await dt(t),console.log(w.green(` Peer "${e}" removed`)))});Et.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 t=xe();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(w.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(w.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(w.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await dt(t),console.log(w.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(w.dim(" Restart the daemon for the new cadence to take effect."))});Et.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,t)=>{let o=t.node||"";if(!o)try{o=C().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(w.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(w.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+w.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(w.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var Bp=e=>{let t=e||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function pi(e,t,o={}){let n=Bp(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(w.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(w.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(w.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var tn=Et.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");tn.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:t}=await import("./token-store-AY6OBDVI.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-YGA654NI.js"),i=C(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.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(w.red(` ${a.error}`)),process.exit(1));let c=(e.url||Bp()).replace(/\/+$/,"");console.log(),console.log(` Grant ${w.bold(a.grant.name)} for ${w.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(w.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(` ${w.cyan(c)}`),console.log(` ${w.bold(n(a.code))}`),console.log(),console.log(` They run: ${w.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()});tn.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:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(w.dim(`
|
|
45
45
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
46
46
|
`));return}console.log();for(let n of o){let s=n.state==="active"?w.green("active"):n.state==="pending"?w.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?w.yellow("paused"):w.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${w.cyan(n.id)} ${w.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(w.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()});tn.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t,n=o.get(e);n||(console.log(w.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${w.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"}
|
|
47
47
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -52,7 +52,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
52
52
|
Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
|
|
53
53
|
`));return}console.log();for(let n of o){let s=await t(n),r=s.ok?s.grant.state==="active"?w.green("active"):w.yellow(String(s.grant.state)):s.status===403?w.yellow(s.error):w.red(s.error);console.log(` ${w.cyan(n.name)} ${w.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${r}`)}console.log()});Et.command("ask <host> <message...>").description("ask the host's agent something, inside the grant").action(async(e,t)=>{let{GuestHostStore:o,askHost:n}=await import("./hosts-NFNCYKGY.js"),s=new o().get(e);s||(console.log(w.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let r=await n(s,t.join(" "));r.error&&(console.log(w.red(` ${r.error}`)),process.exit(1)),console.log(`
|
|
54
54
|
${r.content}
|
|
55
|
-
`)});Et.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:t}=await import("./hosts-NFNCYKGY.js");new t().remove(e)||(console.log(w.red(` No host "${e}".`)),process.exit(1)),console.log(w.green(` \u2713 Left ${e}`))});var on=new to().name("skill").description("manage skills \u2014 add to agent(s), list");on.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,t)=>{let o=xe(),n=ne(e);if(!Fe(n)){console.log(w.red(` Skill not found: ${n}`));return}let s=Fe(Eo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await ot({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(w.yellow(` Agent "${i}" not found, skipping`));continue}let c=ti(a.tier,a.workspace);if(!c){console.log(w.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=ne(c,s);eo(l,{recursive:!0}),Fe(Eo(n,"SKILL.md"))?Rc(n,l,{recursive:!0}):n.endsWith(".md")&&Rc(n,Eo(l,"SKILL.md")),console.log(w.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});on.command("list").alias("ls").description("list skills per agent").action(()=>{let e=xe();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!ti(o.tier,o.workspace)){console.log(` ${w.cyan(t)}: ${w.dim(`(${o.tier} does not use skills)`)}`);continue}let n=oi(o.tier,o.workspace).map(s=>s.name);console.log(` ${w.cyan(t)}: ${n.length?n.join(", "):w.dim("(none)")}`)}console.log()});on.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[ne(n,"src",e,"SKILL.md"),ne(n,"skills",e,"SKILL.md")],r=s.find($=>Fe($));if(!r){console.log(w.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(w.dim(` ${$}`));return}let i=Ro(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch($){console.log(w.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([$])=>$===t.agent):g;if(d.length===0){console.log(w.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(w.bold(` Skill sync \u2014 ${e}`)),console.log(w.dim(` Source: ${r}`)),console.log(w.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(w.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let f=0,p=0,u=0,h=0;for(let[$,b]of d){let v=b.workspace;if(!v||!Fe(v)){console.log(` ${w.yellow("\u2717")} ${$.padEnd(22)} ${w.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let x=ti(b.tier,v);if(!x){console.log(` ${w.dim("\xB7")} ${$.padEnd(22)} ${w.dim(`(skipped \u2014 ${b.tier} does not use skills)`)}`),h++;continue}let A=oi(b.tier,v).find(N=>N.name===e)?.dir??ne(x,e),k=ne(A,"SKILL.md");if(!Fe(k)){if(!t.allWorkspaces){console.log(` ${w.dim("\xB7")} ${$.padEnd(22)} ${w.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(eo(A,{recursive:!0}),Vn(k,i)),console.log(` ${w.green("+")} ${$.padEnd(22)} ${w.dim("\u2192 seeded v"+c)}`),f++;continue}let S=Ro(k,"utf-8");if(o("sha256").update(S).digest("hex").slice(0,12)===a){console.log(` ${w.dim("=")} ${$.padEnd(22)} ${w.dim("up to date (v"+c+")")}`),u++;continue}let O=(S.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Vn(k,i),console.log(` ${w.yellow("\u21BB")} ${$.padEnd(22)} ${w.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let y=t.dryRun?"would":"did";console.log(w.dim(` Summary: ${y} seed ${f}, ${y} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(w.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});on.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:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),r=[];if(e.workspace){let p=xe().agents?.[e.workspace];p||(console.log(w.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(ne(p.workspace))}else if(e.allWorkspaces){let f=xe();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(ne(p.workspace))}else r.push(ne(e.cwd));let i=ne(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(f=>t(f)))).flat(),[l,g]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(f=>({name:f.name,verdict:f.verdict,reasons:f.reasons,path:f.skill?.path})),null,2));else{let f={PASS:0,REVIEW:0,FAILING:0};for(let p of d)f[p.verdict]++;console.log();for(let p of d){let u=p.verdict==="PASS"?w.green("PASS "):p.verdict==="REVIEW"?w.yellow("REVIEW "):w.red("FAILING");console.log(` ${u} ${w.bold(p.name)}${p.skill?.path?w.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${w.dim("\xB7")} ${h}`)}console.log(),console.log(` ${w.green(`${f.PASS} PASS`)} ${w.yellow(`${f.REVIEW} REVIEW`)} ${w.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});on.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,t)=>{let o=xe(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(w.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-
|
|
55
|
+
`)});Et.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:t}=await import("./hosts-NFNCYKGY.js");new t().remove(e)||(console.log(w.red(` No host "${e}".`)),process.exit(1)),console.log(w.green(` \u2713 Left ${e}`))});var on=new to().name("skill").description("manage skills \u2014 add to agent(s), list");on.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,t)=>{let o=xe(),n=ne(e);if(!Fe(n)){console.log(w.red(` Skill not found: ${n}`));return}let s=Fe(Eo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await ot({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(w.yellow(` Agent "${i}" not found, skipping`));continue}let c=ti(a.tier,a.workspace);if(!c){console.log(w.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=ne(c,s);eo(l,{recursive:!0}),Fe(Eo(n,"SKILL.md"))?Rc(n,l,{recursive:!0}):n.endsWith(".md")&&Rc(n,Eo(l,"SKILL.md")),console.log(w.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});on.command("list").alias("ls").description("list skills per agent").action(()=>{let e=xe();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!ti(o.tier,o.workspace)){console.log(` ${w.cyan(t)}: ${w.dim(`(${o.tier} does not use skills)`)}`);continue}let n=oi(o.tier,o.workspace).map(s=>s.name);console.log(` ${w.cyan(t)}: ${n.length?n.join(", "):w.dim("(none)")}`)}console.log()});on.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[ne(n,"src",e,"SKILL.md"),ne(n,"skills",e,"SKILL.md")],r=s.find($=>Fe($));if(!r){console.log(w.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(w.dim(` ${$}`));return}let i=Ro(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch($){console.log(w.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([$])=>$===t.agent):g;if(d.length===0){console.log(w.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(w.bold(` Skill sync \u2014 ${e}`)),console.log(w.dim(` Source: ${r}`)),console.log(w.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(w.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let f=0,p=0,u=0,h=0;for(let[$,b]of d){let v=b.workspace;if(!v||!Fe(v)){console.log(` ${w.yellow("\u2717")} ${$.padEnd(22)} ${w.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let x=ti(b.tier,v);if(!x){console.log(` ${w.dim("\xB7")} ${$.padEnd(22)} ${w.dim(`(skipped \u2014 ${b.tier} does not use skills)`)}`),h++;continue}let A=oi(b.tier,v).find(N=>N.name===e)?.dir??ne(x,e),k=ne(A,"SKILL.md");if(!Fe(k)){if(!t.allWorkspaces){console.log(` ${w.dim("\xB7")} ${$.padEnd(22)} ${w.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(eo(A,{recursive:!0}),Vn(k,i)),console.log(` ${w.green("+")} ${$.padEnd(22)} ${w.dim("\u2192 seeded v"+c)}`),f++;continue}let S=Ro(k,"utf-8");if(o("sha256").update(S).digest("hex").slice(0,12)===a){console.log(` ${w.dim("=")} ${$.padEnd(22)} ${w.dim("up to date (v"+c+")")}`),u++;continue}let O=(S.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Vn(k,i),console.log(` ${w.yellow("\u21BB")} ${$.padEnd(22)} ${w.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let y=t.dryRun?"would":"did";console.log(w.dim(` Summary: ${y} seed ${f}, ${y} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(w.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});on.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:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),r=[];if(e.workspace){let p=xe().agents?.[e.workspace];p||(console.log(w.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(ne(p.workspace))}else if(e.allWorkspaces){let f=xe();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(ne(p.workspace))}else r.push(ne(e.cwd));let i=ne(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(f=>t(f)))).flat(),[l,g]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(f=>({name:f.name,verdict:f.verdict,reasons:f.reasons,path:f.skill?.path})),null,2));else{let f={PASS:0,REVIEW:0,FAILING:0};for(let p of d)f[p.verdict]++;console.log();for(let p of d){let u=p.verdict==="PASS"?w.green("PASS "):p.verdict==="REVIEW"?w.yellow("REVIEW "):w.red("FAILING");console.log(` ${u} ${w.bold(p.name)}${p.skill?.path?w.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${w.dim("\xB7")} ${h}`)}console.log(),console.log(` ${w.green(`${f.PASS} PASS`)} ${w.yellow(`${f.REVIEW} REVIEW`)} ${w.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});on.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,t)=>{let o=xe(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(w.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-IWAFX4XJ.js"),c=await i(r.workspace);if(c.length===0){console.log(w.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.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(` ${w.green("\u2192")} ${w.bold(l.skill.frontmatter.name)} ${w.dim(`\xB7 ${l.reason}`)}`),console.log(` ${w.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${w.yellow("\xB7")} no skill for this ${w.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(w.dim(`
|
|
56
56
|
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(w.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(w.dim(`
|
|
57
57
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Gs=new to().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Gs.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(w.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=ne(t.cwd),n=ne(o,"references/example"),s=ne(o,"references/recipes/example.yaml");Fe(n)||(console.log(w.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let r=ne(o,".agentx/references",e),i=ne(o,".agentx/references/recipes");eo(r,{recursive:!0}),eo(i,{recursive:!0});let a=ik(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let f=Eo(r,d);if(Fe(f)&&!t.force){console.log(w.dim(` skip ${f} (exists; --force to overwrite)`)),l++;continue}let u=Ro(Eo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Vn(f,u),console.log(w.green(` + ${f}`)),c++}let g=Eo(i,`${e}.yaml`);if(Fe(g)&&!t.force)console.log(w.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(Fe(s)){let d=Ro(s,"utf-8").replaceAll("example.",`${e}.`);Vn(g,d),console.log(w.green(` + ${g}`)),c++}console.log(),console.log(w.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(w.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(w.dim(" 2. agentx skill audit # verify references resolve")),console.log(w.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Gs.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(w.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),r=ne(t.cwd),i=t.from?String(t.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await o(r),c=n(a,{namespace:e,filter:i,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(w.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log(w.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(w.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,y])=>[h,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=ne(t.referencesCwd||t.cwd),f=ne(d,".agentx/references",e);if(!t.write){console.log(),console.log(w.dim(` Dry-run \u2014 would write to ${f}/`));for(let[h,y]of Object.entries(g))console.log(w.cyan(`
|
|
58
58
|
--- ${h} ---`)),console.log(y.split(`
|
|
@@ -61,7 +61,7 @@ ${r.content}
|
|
|
61
61
|
`).length>30&&console.log(w.dim(` \u2026 (${y.split(`
|
|
62
62
|
`).length-30} more lines truncated in preview)`));console.log(),console.log(w.dim(` Re-run with --write to commit these to ${f}/`)),console.log();return}eo(f,{recursive:!0});let p=0,u=0;for(let[h,y]of Object.entries(g)){let $=Eo(f,h);if(Fe($)&&!t.force){console.log(w.dim(` skip ${$} (exists; --force to overwrite)`)),u++;continue}Vn($,y),console.log(w.green(` + ${$}`)),p++}console.log(),console.log(w.dim(` ${p} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(w.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Gs.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:t}=await import("./loader-KKMG24O5.js"),o=await t(ne(e.cwd)),n=[...o.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(w.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let r=o.sourceById.get(s.id);console.log(` ${w.cyan(s.id)} ${w.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(w.dim(` ${r}`))}console.log(),console.log(w.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Tc=new to().name("hook").description("manage hooks \u2014 add to agent workspace");Tc.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=xe().agents?.[e];if(!o){console.log(w.red(` Agent "${e}" not found`));return}let n=ne(o.workspace,".claude/settings.json"),s=Fe(n)?JSON.parse(Ro(n,"utf-8")):{},r=await ot([{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(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),eo(ne(o.workspace,".claude"),{recursive:!0}),Vn(n,JSON.stringify(s,null,2)),console.log(w.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Oc=new to().name("migrate").description("import configuration from OpenClaw or other tools");Oc.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,t)=>{let o=[e,ne(process.env.HOME||"",".openclaw/openclaw.json"),ne(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let p of o)if(p&&Fe(p)){n=p;break}if(!n){console.log(w.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(w.dim(` Reading: ${n}`));let s=JSON.parse(Ro(n,"utf-8")),r=Fe(ne(process.cwd(),"agentx.json"))?xe():{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:[]}},i=s.agents?.list||[],a=s.bindings||[],c={};for(let p of a)p.match?.channel==="telegram"&&(c[p.match.accountId]=p.agentId);i.find(p=>p.id==="main"||p.default)&&(c.default="main");let l=0;for(let p of i){if(p.workspace?.startsWith("/data"))continue;let u=p.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=p.groupChat?.mentionPatterns||[];if(h.some(y=>y===u)||h.push(u),r.agents[u]={name:p.name,workspace:p.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:p.id==="main"?2:1,systemPrompt:`You are ${p.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){eo(ne(p.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-HAV4CQV7.js");y(u,r.agents[u])}}console.log(` ${w.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[p,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[p]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[p]={token:u.botToken,agentBinding:y},r.channels.telegram.enabled=!0,d++}console.log(` ${w.green(d)} Telegram accounts imported`);let f=ne(n,"../cron/jobs.json");if(Fe(f)){let p=JSON.parse(Ro(f,"utf-8")),u=0;for(let h of p.jobs||[]){let y=h.name||h.id,$=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[y]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:$,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${w.green(u)} cron jobs imported`)}t.dryRun?(console.log(w.yellow(`
|
|
63
63
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await dt(r),console.log(w.green(`
|
|
64
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Co=new to().name("config").description("validate and inspect configuration");Co.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 t=C(e.config);console.log(w.green(" \u2713 Config valid")),console.log(w.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(w.dim(` Bind: ${t.node.bind}`)),console.log(w.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(w.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(w.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(w.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(w.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Rr(t);if(n.length){console.log(),console.log(w.yellow(" Warnings:"));for(let s of n)console.log(w.yellow(` \u26A0 ${s}`))}else console.log(w.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Fe(ne(i,".claude")),c=Fe(ne(i,"CLAUDE.md")),l=Fe(ne(i,".claude/settings.json")),g=oi(r.tier,i).length,d=[a?w.green("\u2713"):w.red("\u2717"),".claude",c?w.green("\u2713"):w.yellow("\u25CB"),"CLAUDE.md",l?w.green("\u2713"):w.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${w.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(w.red(` \u2717 ${t.message}`))}console.log()});Co.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=C(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(w.red(t.message))}});function lk(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Cc(e){return e===void 0?w.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Co.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-
|
|
64
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Co=new to().name("config").description("validate and inspect configuration");Co.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 t=C(e.config);console.log(w.green(" \u2713 Config valid")),console.log(w.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(w.dim(` Bind: ${t.node.bind}`)),console.log(w.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(w.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(w.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(w.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(w.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Rr(t);if(n.length){console.log(),console.log(w.yellow(" Warnings:"));for(let s of n)console.log(w.yellow(` \u26A0 ${s}`))}else console.log(w.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Fe(ne(i,".claude")),c=Fe(ne(i,"CLAUDE.md")),l=Fe(ne(i,".claude/settings.json")),g=oi(r.tier,i).length,d=[a?w.green("\u2713"):w.red("\u2717"),".claude",c?w.green("\u2713"):w.yellow("\u25CB"),"CLAUDE.md",l?w.green("\u2713"):w.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${w.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(w.red(` \u2717 ${t.message}`))}console.log()});Co.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=C(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(w.red(t.message))}});function lk(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Cc(e){return e===void 0?w.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Co.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-C5BMIBZO.js"),{expandEnvVars:i}=await import("./config-FZTWI3VG.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(w.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:i(c),g=r(l,e);t.json?console.log(JSON.stringify(g)):console.log(Cc(g))});Co.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,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:r}=await import("./config-mutator-C5BMIBZO.js"),i=lk(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(w.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log(w.yellow(` (dry-run) ${w.cyan(e)} would become: ${Cc(c)}`)):(console.log(w.green(` \u2713 ${w.cyan(e)} = ${Cc(c)}`)),a.reloaded?console.log(w.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(w.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Co.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,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-C5BMIBZO.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(w.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(w.dim(` (no-op) ${w.cyan(e)} was not set`));return}t.dryRun?console.log(w.yellow(` (dry-run) ${w.cyan(e)} would be removed`)):(console.log(w.green(` \u2713 ${w.cyan(e)} removed`)),r.reloaded&&console.log(w.dim(" Daemon hot-reloaded.")))});Co.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 t=!1,o=0,n;try{let d=C(e.config);t=!!d.business?.enabled,o=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),r=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),i=r==="true"||r==="1"||r==="yes",a=i&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:i,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(w.bold(" Governance flags")),console.log(),n&&(console.log(w.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?w.green:s==="shadow"?w.cyan:s==="off"?w.dim:w.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":w.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?w.green("active"):i?w.yellow("env=true but business.enabled=false \u2192 inactive"):w.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(w.dim(` business.enabled ${t?w.green("true"):w.dim("false")}`)),console.log(w.dim(` business.projects[] ${o}`)),console.log(),console.log(w.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(w.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});Es();import{Command as dk}from"commander";import To from"chalk";import{resolve as Oo}from"path";import{existsSync as gk}from"fs";var go=new dk().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function nn(e){let t=Oo(e,".agentx/db.sqlite");gk(t)||(console.log(To.red(` No SQLite at ${t}`)),console.log(To.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=vt({path:t});return o||(console.log(To.red(` Could not open ${t}`)),console.log(To.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function sn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(To.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.map(r=>Math.max(r.length,...e.map(i=>String(i[r]??"").length))),s=r=>r.map((i,a)=>String(i??"").padEnd(n[a])).join(" ");console.log(s(o)),console.log(o.map((r,i)=>"-".repeat(n[i])).join(" "));for(let r of e)console.log(s(o.map(i=>r[i])))}go.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 t=nn(Oo(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
|
|
65
65
|
SELECT agent_id, channel, status, duration_ms,
|
|
66
66
|
input_tokens, output_tokens,
|
|
67
67
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -489,7 +489,7 @@ return aid ?? null`}function Yx(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
489
489
|
Resume plan${n.plan?` (${n.plan.author==="agent"?"written by the agent":`written by AgentX: ${n.plan.note}`})`:""}:`)),console.log(n.plan?n.plan.text.split(`
|
|
490
490
|
`).map(s=>` ${s}`).join(`
|
|
491
491
|
`):" not written yet")});or(fn.command("resume <id>").description("resume a stopped task from its plan, in the same chat").option("-r, --reason <reason>","why: recorded on the resume event")).action(async(e,t)=>{let o=await tr(t,"POST","/api/signals/resume",{id:e,reason:t.reason,node:t.peer});console.log(Oe.green(` resumed ${o.agentId} task ${o.id}`)),o.delivery&&console.log(Oe.dim(` its answer goes to ${o.delivery}`))});or(fn.command("drop <id>").description("forget a stopped task and its resume plan, when it won't be resumed")).action(async(e,t)=>{let o=await tr(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(Oe.green(` dropped ${o.agentId} task ${o.id}`))});ae();import{Command as z0}from"commander";import gt from"chalk";var Bi=new z0().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function Y0(e){let t=e.node||"",o=e.token||"";if(!t||!o)try{let s=C(e.config);t||(t=s.dashboard?.daemonUrl||""),o||(o=s.dashboard?.token||"")}catch{}let n={"Content-Type":"application/json"};return o&&(n.Authorization=`Bearer ${o}`),{baseUrl:(t||"http://localhost:18800").replace(/\/+$/,""),headers:n}}async function Mh(e,t,o,n){let{baseUrl:s,headers:r}=Y0(e),i;try{i=await fetch(`${s}${o}`,{method:t,headers:r,...n?{body:JSON.stringify(n)}:{}})}catch(a){console.log(gt.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(!i.ok){let a=await i.json().catch(()=>({}));console.log(gt.red(` HTTP ${i.status}${a.error?` \u2014 ${a.error}`:""}`)),process.exit(1)}return i}var Lh=e=>e.option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)"),Fh=e=>e==="success"?gt.green(e):e==="failure"?gt.red(e):gt.yellow(e);Lh(Bi.command("list").description("recent reviews, with what they cost and how long they took").option("--days <n>","how many days back","7").option("--replays","include replayed reviews")).action(async e=>{let t=new URLSearchParams({days:String(e.days)});e.replays&&t.set("replays","1");let o=await(await Mh(e,"GET",`/api/review-gate/reviews?${t}`)).json(),n=o.summary;console.log(gt.bold(` Last ${o.days} days: ${n.reviews} reviews on ${n.prs} PRs`)+gt.dim(` \u2014 ${n.byState.success} passed, ${n.byState.failure} failed, ${n.byState.error} errors`)),console.log(gt.dim(` cost $${n.costUsd}${n.unpriced?` (+${n.unpriced} unpriced)`:""}, ${n.minutes} min, ${n.tokens} tokens`+(n.p90SincePushMinutes!==void 0?`, push \u2192 status p90 ${n.p90SincePushMinutes} min`:"")));for(let s of o.reviews)console.log(` ${s.at.slice(0,16).replace("T"," ")} ${s.repo}#${s.pr} ${s.sha.slice(0,7)} ${Fh(s.state)} ${gt.dim(s.reason)}${s.replay?gt.dim(" (replay)"):""}`)});Lh(Bi.command("replay <repo> <prs...>").description("review past PRs at their head commit without posting anything; counts how many get flagged")).action(async(e,t,o)=>{let s=(await Mh(o,"POST","/api/review-gate/replay",{repo:e,prs:t.map(Number)})).body.getReader(),r=new TextDecoder,i="";for(;;){let{done:a,value:c}=await s.read();c&&(i+=r.decode(c,{stream:!0}));let l;for(;(l=i.indexOf(`
|
|
492
|
-
`))>=0;){let g=i.slice(0,l).trim();if(i=i.slice(l+1),!g)continue;let d=JSON.parse(g);d.done?console.log(gt.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${gt.yellow("error")} ${gt.dim(d.error)}`):console.log(` #${d.pr} ${Fh(d.state)}${d.flagged?gt.red(" flagged"):""} ${gt.dim(d.reason)}`)}if(a)break}});import{Command as V0}from"commander";import at from"chalk";import{existsSync as ul,rmSync as X0}from"fs";import{resolve as ml}from"path";var is=new V0().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");is.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(at.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Qd(e,t,{verbose:n}),i=Date.now()-s;console.log(at.green(` \u2713 indexed ${r.docs} doc(s) for ${at.bold(e)} in ${i}ms`)),console.log(at.dim(` \u2192 ${r.path}`))});is.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=ml(e.cwd,".agentx","rag");if(!ul(t)){console.log(at.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>ul(ml(t,s,"index.json")));if(n.length===0){console.log(at.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Na(s);console.log(` ${at.bold(s)} ${r.docs} doc(s) ${at.dim(r.path)}`)}});is.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=Zd(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Na(e);r.exists?console.log(at.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(at.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${at.bold(r.title)} ${at.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${at.dim(r.path)}`),console.log(` ${at.dim(r.snippet.slice(0,200))}`)});is.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=ml(process.cwd(),".agentx","rag",e);if(!ul(t)){console.log(at.dim(` no index for ${e} \u2014 nothing to clear`));return}X0(t,{recursive:!0,force:!0}),console.log(at.green(` \u2713 cleared index for ${e}`))});ae();import{Command as K0}from"commander";import de from"chalk";import as from"prompts";var hn=new K0().name("backlog").description("manage the local backlog used by business workSource=backlog");function nr(e){let t=C(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Zu(n)}}function Q0(e){return e?de.cyan(`${e.type}:${e.project}#${e.iid}`):de.dim("manual")}function Z0(e){return{todo:de.gray("todo"),doing:de.yellow("doing"),blocked:de.red("blocked"),done:de.green("done")}[e]}hn.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=nr(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(de.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?de.magenta(`@${n.assignee}`):de.dim("unassigned");console.log(` ${Z0(n.status).padEnd(7)} ${Q0(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(de.dim(` ${n.source.url}`))}console.log(),console.log(de.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});hn.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=nr(o.config);n.store.findById(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(de.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=em([t],r.source,n.config),a=await Qa(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(de.dim(" sync:"),...c));console.log(a.ok?de.dim(` synced -> ${a.url??r.source.type}`):de.yellow(` sync failed: ${a.error}`))}});hn.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=nr(t.config);o.store.findById(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(de.green(` done: ${s.title}`)),s.source){let r=await Qa(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(de.dim(" sync:"),...i));console.log(r.ok?de.dim(` synced -> ${r.url??s.source.type}`):de.yellow(` sync failed: ${r.error}`))}});hn.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=nr(t.config);o.remove(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1)),console.log(de.green(` removed ${e}`))});hn.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=nr(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(de.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await as({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(de.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(de.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?tS(t.config):oS(t.config);y.length?(r=(await as({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await as({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await as({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await as({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(de.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await nS(t.config,r,a):await sS(t.config,r,a);if(!c.length){console.log(de.yellow(" no open issues matched"));return}console.log(de.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let $=Ka({type:s,project:l,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?de.dim(" (already imported)"):""}`,value:y,disabled:b}}),p=(await as({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!p.length){console.log(de.dim(" nothing selected"));return}let u=p.map(y=>{let $={type:s,host:s==="gitlab"?eS(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ka($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(de.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(de.dim(` ${y.id} \u2014 ${y.title}`))});function eS(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function tS(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function oS(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function nS(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let r=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);let i=await r.json();return Array.isArray(i)?i.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function sS(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},r;if(o){let c=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(r,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(qh)}r=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let i=await fetch(r,{headers:s});if(!i.ok)throw new Error(`GitHub ${i.status}: ${await i.text().catch(()=>"")}`);let a=await i.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(qh):[]}function qh(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as rS}from"commander";import V from"chalk";import{existsSync as iS,readFileSync as aS}from"fs";import{resolve as cS}from"path";import lS from"prompts";ae();function Uh(e){let t=e||cS(process.cwd(),"agentx.json");return iS(t)||(console.log(V.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(aS(t,"utf-8"))}async function dS(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(V.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await lS([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!r?void 0:{channel:s,chatId:r,accountId:i||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(V.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var uo=new rS().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');uo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Da})`,Da).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){uo.help();return}t.agent||(console.log(V.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(V.red(' --do "<prompt>" is required')),process.exit(1));let o=_a(e);o||(console.log(V.red(` Couldn't parse: "${e}"`)),console.log(V.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(V.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(V.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Uh(t.config),s=Rs(n);n.agents?.[t.agent]||(console.log(V.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(V.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await dS(t.notify,s),i=t.id||fg(o.matched,t.agent),a=yg({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,onError:hg(t.onError),enabled:!t.disabled}),c=a.onError,l=await ge(d=>Je(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(V.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(V.green(` \u2713 ${g} cron ${V.cyan(i)}`)),console.log(V.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(V.dim(` Agent: ${t.agent}`)),r&&console.log(V.dim(` Notify: ${r.channel} ${r.chatId}${a.deliverResult===!1?" (failures only)":" (results and failures)"}`)),c.length&&console.log(V.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=Uh(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-VXXKMXHH.js");for(let[i,a]of Object.entries(r(e.config).crons))o[i]||(s.add(i),n.push([i,a]))}catch{}if(!n.length){console.log(V.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?V.yellow("\u25D0"):i.enabled?V.green("\u25CF"):V.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${V.cyan(r.padEnd(32))} ${V.dim(i.schedule.padEnd(14))} ${V.dim("\u2192")} ${i.agent}`),console.log(V.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(V.dim(` notify: ${i.notify.channel} ${i.notify.chatId}${i.deliverResult===!1?" (failures only)":" (results and failures)"}`)),i.createdBy&&console.log(V.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(V.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let l=i.timezone||"UTC",g=$g(wg(i.schedule,l),l);console.log(V.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(V.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])uo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await vg(o,t);n.success||(console.log(V.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(V.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ge(o=>{if(!Ln(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);og(o,`crons.${e}`)});t.success||(console.log(V.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(V.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",bg,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",kg,"reject an agent's pending create/delete request (drops the request)"]])uo.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let r=await t(n,{configPath:s.config});r.success||(console.log(V.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(V.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=_a(t);o||(console.log(V.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(V.green(` "${t}"`)),console.log(V.dim(` \u2192 ${o.cron}`)),console.log(V.dim(` \u2192 ${o.human}`))});import{Command as gS}from"commander";import Pe from"chalk";import mo from"chalk";function Wh(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var Bh=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Jh(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(t,o)=>{if(process.platform!=="darwin"){console.error(mo.red(" the popup needs macOS")),process.exitCode=1;return}let n=t?.startsWith("card:")?t.slice(5):t,s=o.sample?Wh():n?Ur(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(mo.red(t?` no card waiting for "${t}"`:" give a card key, or --sample")),process.exitCode=1;return}let r={...Qt().popup};(o.theme==="system"||o.theme==="light"||o.theme==="dark")&&(r.theme=o.theme),o.timeout&&(r.timeoutSeconds=Number(o.timeout));let i=await bu(s,r,{from:o.sample?"Assistant":void 0,capture:o.capture,pick:Number(o.pick)||void 0});if(o.capture&&console.log(mo.dim(` picture saved to ${o.capture}`)),o.sample){console.log(` answer (not recorded): ${JSON.stringify(i)}`);return}if(i.action==="dismiss"){console.log(mo.dim(` not answered${i.why?` (${i.why})`:""}; the card is still waiting`));return}let a=await Jr({root:process.cwd()},`card:${s.id}`,i.action,{by:"operator (popup)",...i.action==="yes"?{choice:i.choice,text:i.text}:{}});if(!a.ok){console.error(mo.red(` ${a.error}`)),process.exitCode=1;return}console.log(mo.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async t=>{let o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${Bh()}/approvals/checkin`,{method:"POST",headers:o,body:JSON.stringify({daily:!!t.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(mo.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(mo.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(mo.red(` couldn't reach the daemon at ${Bh()}: ${n?.message??n}`)),process.exitCode=1}})}var po=new gS("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),uS={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Gh(){return{root:process.cwd()}}function pl(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function mS(e){console.log(` ${Pe.cyan(e.key)} ${Pe.dim(`[${uS[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?Pe.dim(` (later: until ${pl(e.snoozed_until)})`):""}`),console.log(` ${Pe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${Pe.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((t,o)=>console.log(` ${Pe.magenta(`${o+1}.`)} ${t}`)),e.expires&&console.log(Pe.yellow(` Expires ${pl(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(Pe.dim(` ${e.detail}`)),e.source&&console.log(Pe.dim(` ${e.source}`)),console.log(Pe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}po.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=iu(Gh(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(Pe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(Pe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)mS(o),console.log();console.log(Pe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function fl(e,t,o){let n=Qt(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(Pe.red(" --hours must be a positive number")),process.exitCode=1;return}let r=await Jr(Gh(),e,t,{force:o.force,note:o.note,laterHours:s,choice:o.choice,text:o.text});if(!r.ok){console.error(Pe.red(` ${r.error}`)),process.exitCode=1;return}console.log(Pe.green(` \u2713 ${r.message}`))}po.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,t)=>fl(e,"yes",t));po.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>fl(e,"no",t));po.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>fl(e,"later",t));po.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${nu.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,t=[])=>[...t,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(async e=>{let t=Qt(),o={raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},n=t.forwardTo?await pS(o):Wr(process.cwd(),o,{settings:t});if(!n.ok){console.error(Pe.red(` ${n.error}`)),process.exitCode=1;return}let s=t.forwardTo?` on ${t.forwardTo}`:"";console.log(Pe.green(` \u2713 card:${n.card.id} raised${s}; expires ${pl(n.card.expires)}, then: ${n.card.if_silent}`))});async function pS(e){let t=(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,""),o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${t}/approvals`,{method:"POST",headers:o,body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));return n.ok?{ok:!0,card:s.card}:{ok:!1,error:s.error??`HTTP ${n.status}`}}catch(n){return{ok:!1,error:`couldn't reach the daemon at ${t} (it forwards cards when approvals.forwardTo is set): ${n?.message??n}`}}}Jh(po);po.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--forward-to <peer>",`send this machine's cards to that mesh peer's inbox and popup; "none" to keep them here`).option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let t={},o=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo==="none"?null:e.forwardTo),t.digestEnabled=n("--digest",e.digest),t.popupEnabled=n("--popup",e.popup),t.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(t.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(t.popupSound=e.popupSound==="none"?"":e.popupSound),t.popupTimeoutSeconds=o("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(t.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(t.popupTheme=e.popupTheme),t.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(t.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(t.checkinDailyAt=e.checkinDaily),t.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(t.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let g=pm(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=g}}catch(l){console.error(Pe.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await fm(t);if(!l.success){console.error(Pe.red(` ${l.error}`)),process.exitCode=1;return}console.log(Pe.green(" \u2713 saved")+(l.reloaded?Pe.dim(" (daemon reloaded)"):""))}let r=Qt(),i=r.digest.destination;console.log(` Cards expire after ${r.defaultExpiryDays} day(s) unless they say (at most ${r.maxExpiryDays})`),console.log(` "Later" hides an item ${r.laterHours} hour(s)`),console.log(` Tell the agent ${r.notifyAgent?"on":"off"}`),console.log(` Cards go to ${r.forwardTo?`${r.forwardTo} (mesh peer)`:"this machine"}`),console.log(` Daily digest ${r.digest.enabled?`on, at ${r.digest.time}${r.digest.timezone?` (${r.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${i?`${i.channel} ${i.chatId}`:"notifications.destination"}`);let a=r.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=r.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as fS}from"commander";import G from"chalk";ae();Es();q$();var wt=new fS("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),hl=Rd,Hh="-".repeat(64);function Ji(){let e=90;try{e=C().members.logRetentionDays}catch{}return new cg(process.cwd(),Date.now,e)}var zh=(e,t=[])=>[...t,e];function Xh(e){let t=[];try{t=Object.keys(C().agents)}catch{return}let o=e.filter(n=>!t.includes(n));o.length&&(console.log(G.yellow(` ! not an agent on this machine: ${o.join(", ")}. Agents here: ${t.join(", ")||"none"}.`)),console.log(G.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var Kh="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",hS="An owner is never limited. Change the role first if that is what you want.",yl=["tools","skills"];function yS(e){let t=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return yl.includes(t)?t:null}async function yn(e){let t="",o=await ge(n=>{n.people=Array.isArray(n.people)?n.people:[],t=e(n.people)});o.success||(console.error(G.red(`\u2717 ${(o.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(G.green(`\u2713 ${t}`)),o.reloaded&&console.log(G.dim(" daemon hot-reloaded"))}function cs(e,t){let o=e.find(n=>n?.id===t);if(!o)throw new Error(`No person "${t}". See \`agentx people list\`.`);return o.identities=Array.isArray(o.identities)?o.identities:[],o}function Qh(e,t){let o=Ea(e),n=Ea(t);return!!o&&!!n&&o.channel===n.channel&&o.value===n.value}function Zh(e){let t=yl.filter(o=>e.deny?.[o]?.length).map(o=>` \xB7 no ${o}: ${e.deny[o].join(", ")}`).join("");console.log(` ${G.bold(e.id)} ${e.name}${e.say?G.dim(` (said "${e.say}")`):""} ${G.dim(`\xB7 ${e.role}`)}${e.agents?.length?G.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${G.dim(t)}`),console.log(G.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}wt.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let t=C().people;if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(),t.length===0&&(console.log(G.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${Aa}"; senders on other channels are unknown.`)),console.log(G.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let o of t)Zh(o);console.log()});wt.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${hl.join(" | ")}. A client is someone you do work for; their page is "Your project"`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",zh,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",zh,[]).action(async(e,t)=>{await yn(o=>{if(o.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(!hl.includes(t.role))throw new Error(`--role must be one of: ${hl.join(", ")}`);if(t.role==="owner"&&t.agent.length)throw new Error(Kh);return o.push({id:e,name:t.name,role:t.role,identities:t.identity,agents:t.agent}),`added ${e} (${t.role})${t.agent.length?`, may reach ${t.agent.join(", ")}`:""}`}),Xh(t.agent)});wt.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,t)=>{let o=t.length===1&&t[0].toLowerCase()==="all";await yn(n=>{let s=cs(n,e);if(!o&&s.role==="owner")throw new Error(Kh);return s.agents=o?[]:[...new Set(t)],o?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),o||Xh(t)});wt.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,t,o)=>{let n=yS(t);n||(console.error(G.red(`\u2717 level must be one of: ${yl.join(", ")}`)),process.exit(1));let s=o.length===1&&o[0].toLowerCase()==="none";await yn(r=>{let i=cs(r,e);if(!s&&i.role==="owner")throw new Error(hS);return i.deny={...i.deny??{},[n]:s?[]:[...new Set(o)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${i.deny[n].join(", ")}`})});wt.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,t)=>{await yn(o=>{let n=cs(o,e);return n.identities.some(s=>Qh(s,t))?`${e} already has ${t}`:(n.identities.push(t),`${t} is now ${e}`)})});wt.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,t)=>{await yn(o=>{let n=cs(o,e),s=n.identities.length;if(n.identities=n.identities.filter(r=>!Qh(r,t)),n.identities.length===s)throw new Error(`"${e}" has no identity ${t}.`);return`${t} is no longer ${e}`})});wt.command("say <id> [spoken...]").description(`how the person's name is said aloud, e.g. "A-neess Ma-roo-shee"; the written name stays. "none" clears it`).action(async(e,t=[])=>{let o=t.join(" ").trim();if(!o){let n=C().people.find(s=>s.id===e);n||(console.error(G.red(`\u2717 No person "${e}". See \`agentx people list\`.`)),process.exit(1)),console.log(n.say?` ${n.name} is said "${n.say}"`:` ${n.name} is said as written`);return}await yn(n=>{let s=cs(n,e);if(o.toLowerCase()==="none")return delete s.say,`${s.name} is said as written`;if(o.length>120)throw new Error("The spoken form is at most 120 characters");return s.say=o,`${s.name} is now said "${o}"; written, it stays ${s.name}`})});wt.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await yn(o=>(cs(o,e),o.splice(o.findIndex(n=>n?.id===e),1),`removed ${e}`));let t=Em({tokens:new xt,members:Ji()},e);t.length&&console.log(G.green(`\u2713 ended ${t.length} machine(s) of ${e}: ${t.map(o=>o.name).join(", ")}`)),console.log(G.dim(" If you shared this computer with them on the private network, remove that share too."))});wt.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own page (/member): My work for a teammate, Your project for a client. Ends with a message to forward to them as it is").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,t)=>{try{let o=Bs(),n=Ac(Ec(),o);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${o}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${o}/api/member`].join(`
|
|
492
|
+
`))>=0;){let g=i.slice(0,l).trim();if(i=i.slice(l+1),!g)continue;let d=JSON.parse(g);d.done?console.log(gt.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${gt.yellow("error")} ${gt.dim(d.error)}`):console.log(` #${d.pr} ${Fh(d.state)}${d.flagged?gt.red(" flagged"):""} ${gt.dim(d.reason)}`)}if(a)break}});import{Command as V0}from"commander";import at from"chalk";import{existsSync as ul,rmSync as X0}from"fs";import{resolve as ml}from"path";var is=new V0().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");is.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(at.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Qd(e,t,{verbose:n}),i=Date.now()-s;console.log(at.green(` \u2713 indexed ${r.docs} doc(s) for ${at.bold(e)} in ${i}ms`)),console.log(at.dim(` \u2192 ${r.path}`))});is.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=ml(e.cwd,".agentx","rag");if(!ul(t)){console.log(at.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>ul(ml(t,s,"index.json")));if(n.length===0){console.log(at.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Na(s);console.log(` ${at.bold(s)} ${r.docs} doc(s) ${at.dim(r.path)}`)}});is.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=Zd(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Na(e);r.exists?console.log(at.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(at.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${at.bold(r.title)} ${at.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${at.dim(r.path)}`),console.log(` ${at.dim(r.snippet.slice(0,200))}`)});is.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=ml(process.cwd(),".agentx","rag",e);if(!ul(t)){console.log(at.dim(` no index for ${e} \u2014 nothing to clear`));return}X0(t,{recursive:!0,force:!0}),console.log(at.green(` \u2713 cleared index for ${e}`))});ae();import{Command as K0}from"commander";import de from"chalk";import as from"prompts";var hn=new K0().name("backlog").description("manage the local backlog used by business workSource=backlog");function nr(e){let t=C(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Zu(n)}}function Q0(e){return e?de.cyan(`${e.type}:${e.project}#${e.iid}`):de.dim("manual")}function Z0(e){return{todo:de.gray("todo"),doing:de.yellow("doing"),blocked:de.red("blocked"),done:de.green("done")}[e]}hn.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=nr(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(de.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?de.magenta(`@${n.assignee}`):de.dim("unassigned");console.log(` ${Z0(n.status).padEnd(7)} ${Q0(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(de.dim(` ${n.source.url}`))}console.log(),console.log(de.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});hn.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=nr(o.config);n.store.findById(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(de.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=em([t],r.source,n.config),a=await Qa(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(de.dim(" sync:"),...c));console.log(a.ok?de.dim(` synced -> ${a.url??r.source.type}`):de.yellow(` sync failed: ${a.error}`))}});hn.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=nr(t.config);o.store.findById(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(de.green(` done: ${s.title}`)),s.source){let r=await Qa(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(de.dim(" sync:"),...i));console.log(r.ok?de.dim(` synced -> ${r.url??s.source.type}`):de.yellow(` sync failed: ${r.error}`))}});hn.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=nr(t.config);o.remove(e)||(console.error(de.red(` item ${e} not found`)),process.exit(1)),console.log(de.green(` removed ${e}`))});hn.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=nr(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(de.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await as({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(de.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(de.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?tS(t.config):oS(t.config);y.length?(r=(await as({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await as({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await as({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await as({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(de.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await nS(t.config,r,a):await sS(t.config,r,a);if(!c.length){console.log(de.yellow(" no open issues matched"));return}console.log(de.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let $=Ka({type:s,project:l,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?de.dim(" (already imported)"):""}`,value:y,disabled:b}}),p=(await as({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!p.length){console.log(de.dim(" nothing selected"));return}let u=p.map(y=>{let $={type:s,host:s==="gitlab"?eS(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ka($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(de.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(de.dim(` ${y.id} \u2014 ${y.title}`))});function eS(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function tS(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function oS(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function nS(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let r=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);let i=await r.json();return Array.isArray(i)?i.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function sS(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},r;if(o){let c=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(r,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(qh)}r=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let i=await fetch(r,{headers:s});if(!i.ok)throw new Error(`GitHub ${i.status}: ${await i.text().catch(()=>"")}`);let a=await i.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(qh):[]}function qh(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as rS}from"commander";import V from"chalk";import{existsSync as iS,readFileSync as aS}from"fs";import{resolve as cS}from"path";import lS from"prompts";ae();function Uh(e){let t=e||cS(process.cwd(),"agentx.json");return iS(t)||(console.log(V.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(aS(t,"utf-8"))}async function dS(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(V.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await lS([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!r?void 0:{channel:s,chatId:r,accountId:i||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(V.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var uo=new rS().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');uo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Da})`,Da).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){uo.help();return}t.agent||(console.log(V.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(V.red(' --do "<prompt>" is required')),process.exit(1));let o=_a(e);o||(console.log(V.red(` Couldn't parse: "${e}"`)),console.log(V.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(V.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(V.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Uh(t.config),s=Rs(n);n.agents?.[t.agent]||(console.log(V.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(V.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await dS(t.notify,s),i=t.id||fg(o.matched,t.agent),a=yg({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,onError:hg(t.onError),enabled:!t.disabled}),c=a.onError,l=await ge(d=>Je(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(V.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(V.green(` \u2713 ${g} cron ${V.cyan(i)}`)),console.log(V.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(V.dim(` Agent: ${t.agent}`)),r&&console.log(V.dim(` Notify: ${r.channel} ${r.chatId}${a.deliverResult===!1?" (failures only)":" (results and failures)"}`)),c.length&&console.log(V.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=Uh(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-FZTWI3VG.js");for(let[i,a]of Object.entries(r(e.config).crons))o[i]||(s.add(i),n.push([i,a]))}catch{}if(!n.length){console.log(V.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?V.yellow("\u25D0"):i.enabled?V.green("\u25CF"):V.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${V.cyan(r.padEnd(32))} ${V.dim(i.schedule.padEnd(14))} ${V.dim("\u2192")} ${i.agent}`),console.log(V.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(V.dim(` notify: ${i.notify.channel} ${i.notify.chatId}${i.deliverResult===!1?" (failures only)":" (results and failures)"}`)),i.createdBy&&console.log(V.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(V.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let l=i.timezone||"UTC",g=$g(wg(i.schedule,l),l);console.log(V.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(V.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])uo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await vg(o,t);n.success||(console.log(V.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(V.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ge(o=>{if(!Ln(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);og(o,`crons.${e}`)});t.success||(console.log(V.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(V.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",bg,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",kg,"reject an agent's pending create/delete request (drops the request)"]])uo.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let r=await t(n,{configPath:s.config});r.success||(console.log(V.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(V.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(V.dim(" Daemon hot-reloaded."))});uo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=_a(t);o||(console.log(V.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(V.green(` "${t}"`)),console.log(V.dim(` \u2192 ${o.cron}`)),console.log(V.dim(` \u2192 ${o.human}`))});import{Command as gS}from"commander";import Pe from"chalk";import mo from"chalk";function Wh(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var Bh=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Jh(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(t,o)=>{if(process.platform!=="darwin"){console.error(mo.red(" the popup needs macOS")),process.exitCode=1;return}let n=t?.startsWith("card:")?t.slice(5):t,s=o.sample?Wh():n?Ur(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(mo.red(t?` no card waiting for "${t}"`:" give a card key, or --sample")),process.exitCode=1;return}let r={...Qt().popup};(o.theme==="system"||o.theme==="light"||o.theme==="dark")&&(r.theme=o.theme),o.timeout&&(r.timeoutSeconds=Number(o.timeout));let i=await bu(s,r,{from:o.sample?"Assistant":void 0,capture:o.capture,pick:Number(o.pick)||void 0});if(o.capture&&console.log(mo.dim(` picture saved to ${o.capture}`)),o.sample){console.log(` answer (not recorded): ${JSON.stringify(i)}`);return}if(i.action==="dismiss"){console.log(mo.dim(` not answered${i.why?` (${i.why})`:""}; the card is still waiting`));return}let a=await Jr({root:process.cwd()},`card:${s.id}`,i.action,{by:"operator (popup)",...i.action==="yes"?{choice:i.choice,text:i.text}:{}});if(!a.ok){console.error(mo.red(` ${a.error}`)),process.exitCode=1;return}console.log(mo.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async t=>{let o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${Bh()}/approvals/checkin`,{method:"POST",headers:o,body:JSON.stringify({daily:!!t.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(mo.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(mo.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(mo.red(` couldn't reach the daemon at ${Bh()}: ${n?.message??n}`)),process.exitCode=1}})}var po=new gS("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),uS={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Gh(){return{root:process.cwd()}}function pl(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function mS(e){console.log(` ${Pe.cyan(e.key)} ${Pe.dim(`[${uS[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?Pe.dim(` (later: until ${pl(e.snoozed_until)})`):""}`),console.log(` ${Pe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${Pe.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((t,o)=>console.log(` ${Pe.magenta(`${o+1}.`)} ${t}`)),e.expires&&console.log(Pe.yellow(` Expires ${pl(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(Pe.dim(` ${e.detail}`)),e.source&&console.log(Pe.dim(` ${e.source}`)),console.log(Pe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}po.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=iu(Gh(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(Pe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(Pe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)mS(o),console.log();console.log(Pe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function fl(e,t,o){let n=Qt(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(Pe.red(" --hours must be a positive number")),process.exitCode=1;return}let r=await Jr(Gh(),e,t,{force:o.force,note:o.note,laterHours:s,choice:o.choice,text:o.text});if(!r.ok){console.error(Pe.red(` ${r.error}`)),process.exitCode=1;return}console.log(Pe.green(` \u2713 ${r.message}`))}po.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,t)=>fl(e,"yes",t));po.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>fl(e,"no",t));po.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>fl(e,"later",t));po.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${nu.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,t=[])=>[...t,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(async e=>{let t=Qt(),o={raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},n=t.forwardTo?await pS(o):Wr(process.cwd(),o,{settings:t});if(!n.ok){console.error(Pe.red(` ${n.error}`)),process.exitCode=1;return}let s=t.forwardTo?` on ${t.forwardTo}`:"";console.log(Pe.green(` \u2713 card:${n.card.id} raised${s}; expires ${pl(n.card.expires)}, then: ${n.card.if_silent}`))});async function pS(e){let t=(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,""),o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${t}/approvals`,{method:"POST",headers:o,body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));return n.ok?{ok:!0,card:s.card}:{ok:!1,error:s.error??`HTTP ${n.status}`}}catch(n){return{ok:!1,error:`couldn't reach the daemon at ${t} (it forwards cards when approvals.forwardTo is set): ${n?.message??n}`}}}Jh(po);po.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--forward-to <peer>",`send this machine's cards to that mesh peer's inbox and popup; "none" to keep them here`).option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let t={},o=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo==="none"?null:e.forwardTo),t.digestEnabled=n("--digest",e.digest),t.popupEnabled=n("--popup",e.popup),t.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(t.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(t.popupSound=e.popupSound==="none"?"":e.popupSound),t.popupTimeoutSeconds=o("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(t.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(t.popupTheme=e.popupTheme),t.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(t.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(t.checkinDailyAt=e.checkinDaily),t.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(t.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let g=pm(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=g}}catch(l){console.error(Pe.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await fm(t);if(!l.success){console.error(Pe.red(` ${l.error}`)),process.exitCode=1;return}console.log(Pe.green(" \u2713 saved")+(l.reloaded?Pe.dim(" (daemon reloaded)"):""))}let r=Qt(),i=r.digest.destination;console.log(` Cards expire after ${r.defaultExpiryDays} day(s) unless they say (at most ${r.maxExpiryDays})`),console.log(` "Later" hides an item ${r.laterHours} hour(s)`),console.log(` Tell the agent ${r.notifyAgent?"on":"off"}`),console.log(` Cards go to ${r.forwardTo?`${r.forwardTo} (mesh peer)`:"this machine"}`),console.log(` Daily digest ${r.digest.enabled?`on, at ${r.digest.time}${r.digest.timezone?` (${r.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${i?`${i.channel} ${i.chatId}`:"notifications.destination"}`);let a=r.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=r.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as fS}from"commander";import G from"chalk";ae();Es();q$();var wt=new fS("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),hl=Rd,Hh="-".repeat(64);function Ji(){let e=90;try{e=C().members.logRetentionDays}catch{}return new cg(process.cwd(),Date.now,e)}var zh=(e,t=[])=>[...t,e];function Xh(e){let t=[];try{t=Object.keys(C().agents)}catch{return}let o=e.filter(n=>!t.includes(n));o.length&&(console.log(G.yellow(` ! not an agent on this machine: ${o.join(", ")}. Agents here: ${t.join(", ")||"none"}.`)),console.log(G.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var Kh="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",hS="An owner is never limited. Change the role first if that is what you want.",yl=["tools","skills"];function yS(e){let t=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return yl.includes(t)?t:null}async function yn(e){let t="",o=await ge(n=>{n.people=Array.isArray(n.people)?n.people:[],t=e(n.people)});o.success||(console.error(G.red(`\u2717 ${(o.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(G.green(`\u2713 ${t}`)),o.reloaded&&console.log(G.dim(" daemon hot-reloaded"))}function cs(e,t){let o=e.find(n=>n?.id===t);if(!o)throw new Error(`No person "${t}". See \`agentx people list\`.`);return o.identities=Array.isArray(o.identities)?o.identities:[],o}function Qh(e,t){let o=Ea(e),n=Ea(t);return!!o&&!!n&&o.channel===n.channel&&o.value===n.value}function Zh(e){let t=yl.filter(o=>e.deny?.[o]?.length).map(o=>` \xB7 no ${o}: ${e.deny[o].join(", ")}`).join("");console.log(` ${G.bold(e.id)} ${e.name}${e.say?G.dim(` (said "${e.say}")`):""} ${G.dim(`\xB7 ${e.role}`)}${e.agents?.length?G.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${G.dim(t)}`),console.log(G.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}wt.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let t=C().people;if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(),t.length===0&&(console.log(G.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${Aa}"; senders on other channels are unknown.`)),console.log(G.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let o of t)Zh(o);console.log()});wt.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${hl.join(" | ")}. A client is someone you do work for; their page is "Your project"`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",zh,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",zh,[]).action(async(e,t)=>{await yn(o=>{if(o.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(!hl.includes(t.role))throw new Error(`--role must be one of: ${hl.join(", ")}`);if(t.role==="owner"&&t.agent.length)throw new Error(Kh);return o.push({id:e,name:t.name,role:t.role,identities:t.identity,agents:t.agent}),`added ${e} (${t.role})${t.agent.length?`, may reach ${t.agent.join(", ")}`:""}`}),Xh(t.agent)});wt.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,t)=>{let o=t.length===1&&t[0].toLowerCase()==="all";await yn(n=>{let s=cs(n,e);if(!o&&s.role==="owner")throw new Error(Kh);return s.agents=o?[]:[...new Set(t)],o?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),o||Xh(t)});wt.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,t,o)=>{let n=yS(t);n||(console.error(G.red(`\u2717 level must be one of: ${yl.join(", ")}`)),process.exit(1));let s=o.length===1&&o[0].toLowerCase()==="none";await yn(r=>{let i=cs(r,e);if(!s&&i.role==="owner")throw new Error(hS);return i.deny={...i.deny??{},[n]:s?[]:[...new Set(o)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${i.deny[n].join(", ")}`})});wt.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,t)=>{await yn(o=>{let n=cs(o,e);return n.identities.some(s=>Qh(s,t))?`${e} already has ${t}`:(n.identities.push(t),`${t} is now ${e}`)})});wt.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,t)=>{await yn(o=>{let n=cs(o,e),s=n.identities.length;if(n.identities=n.identities.filter(r=>!Qh(r,t)),n.identities.length===s)throw new Error(`"${e}" has no identity ${t}.`);return`${t} is no longer ${e}`})});wt.command("say <id> [spoken...]").description(`how the person's name is said aloud, e.g. "A-neess Ma-roo-shee"; the written name stays. "none" clears it`).action(async(e,t=[])=>{let o=t.join(" ").trim();if(!o){let n=C().people.find(s=>s.id===e);n||(console.error(G.red(`\u2717 No person "${e}". See \`agentx people list\`.`)),process.exit(1)),console.log(n.say?` ${n.name} is said "${n.say}"`:` ${n.name} is said as written`);return}await yn(n=>{let s=cs(n,e);if(o.toLowerCase()==="none")return delete s.say,`${s.name} is said as written`;if(o.length>120)throw new Error("The spoken form is at most 120 characters");return s.say=o,`${s.name} is now said "${o}"; written, it stays ${s.name}`})});wt.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await yn(o=>(cs(o,e),o.splice(o.findIndex(n=>n?.id===e),1),`removed ${e}`));let t=Em({tokens:new xt,members:Ji()},e);t.length&&console.log(G.green(`\u2713 ended ${t.length} machine(s) of ${e}: ${t.map(o=>o.name).join(", ")}`)),console.log(G.dim(" If you shared this computer with them on the private network, remove that share too."))});wt.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own page (/member): My work for a teammate, Your project for a client. Ends with a message to forward to them as it is").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,t)=>{try{let o=Bs(),n=Ac(Ec(),o);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${o}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${o}/api/member`].join(`
|
|
493
493
|
`));let s=(t.url?String(t.url):Sc()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(s))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${s}`);let r=C().people,i=vm({tokens:new xt,codes:new Lr,members:Ji(),people:()=>r},e);if(!i.ok)throw new Error(i.error);console.log(),console.log(` Invite for ${G.bold(i.person.name)} (${i.person.id}, ${i.person.role}). Their page is ${G.bold(nc(i.person.role))}.`),console.log(),console.log(" 1. Share this computer with them on your private network, if you have not yet:"),console.log(G.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(G.dim(' Limit what shared users can reach to port 443 in your access rules (see the docs page "Invite a teammate").')),console.log(` 2. Send them the message below, or this address and code. The code works once, for ${xm} minutes:`),console.log(),console.log(` ${G.cyan(`${s}/member`)}`),console.log(` ${G.bold(Mr(i.code))}`),console.log(),console.log(` 3. When they pair, a card "New machine for ${i.person.name}" asks you to approve that machine. Then ${nc(i.person.role)} opens for them.`),console.log(G.dim(` Their key stops after ${km} days; invite again then. Machine id: ${i.tokenId}`)),console.log(),console.log(` ${G.bold("Message to forward")} ${G.dim("(copy everything between the two lines; the rest of this output is for you)")}`),console.log(G.dim(Hh)),console.log(Sm({person:i.person,origin:s,code:i.code})),console.log(G.dim(Hh)),console.log()}catch(o){console.log(G.red(` ${o.message}`)),process.exit(1)}});wt.command("devices [id]").description("the machines paired to people's own pages (My work, Your project): state, where from, first and last use").option("--json","machine-readable output").action((e,t)=>{let o=Ji().devices(e);if(t.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(G.dim(`
|
|
494
494
|
No machines${e?` for ${e}`:""}. Run \`agentx people invite <id>\`.
|
|
495
495
|
`));return}console.log();for(let n of o){let s=n.state==="active"?G.green("active"):n.state==="pending"?G.yellow("waiting for your approval"):G.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${G.cyan(n.tokenId)} ${G.bold(n.personId)} ${n.name} ${s}`),console.log(G.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});wt.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let t=Am({tokens:new xt,members:Ji()},e);t||(console.log(G.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(G.green(`
|
|
@@ -506,7 +506,7 @@ return aid ?? null`}function Yx(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
506
506
|
Plan ${L.dim(`[${s.state}] by ${s.createdBy}, ${wn(s.createdAt)}`)}`),sy(n.steps(e)),console.log(`
|
|
507
507
|
Log`);for(let r of n.events(e))console.log(L.dim(` ${wn(r.at)} ${r.step?`step ${r.step} `:""}${r.kind}: ${r.detail}`))}});Lo.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(L.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=sr();if(!s)return;let r=Gi();if(!r){process.exitCode=1;return}let i=Number(t),a=wu(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(L.red(` ${a}`)),process.exitCode=1;return}console.log(L.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+L.dim(" (the daemon goes on within a minute)")),sy(r.steps(e))});function ry(e,t,o,n){let s=Lo.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=sr();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(L.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(L.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(L.red(` ${r} is already closed (${wl[l.state]??l.state})`)),process.exitCode=1;return}console.log(L.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}ry("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");ry("drop","drop a request you no longer want","--reason <text>","");Lo.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${Ar.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let c=(p,u)=>{if(u===void 0)return;let h=Number(u);if(!(h>0))throw new Error(`${p} must be a positive number`);return h},l=(p,u)=>p===void 0?void 0:p===u?[]:p.split(",").map(h=>h.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=l(e.from,"none"),t.channels=l(e.channels,"all"),t.staleAfterHours=c("--stale-hours",e.staleHours),t.retentionDays=c("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}let g={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");g.enabled=e.plans==="on"}if(g.stallMinutes=c("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let p=Number(e.maxNudges);if(!Number.isInteger(p)||p<0)throw new Error("--max-nudges must be a whole number, 0 or more");g.maxNudges=p}if(g.approveKinds=l(e.approveKinds,"none"),g.disabledAgents=l(e.plansOffFor,"none"),g.requireForWork=l(e.planFor,"none"),e.planOver!==void 0){let p=Number(e.planOver);if(!(p>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");g.requireOverMinutes=p}Object.values(g).some(p=>p!==void 0)&&(t.plans=g);let d={},f=l(e.checks,"none");if(f){let p=f.filter(u=>!Ar.includes(u));if(p.length)throw new Error(`unknown check ${p.join(", ")}: use ${Ar.join(", ")}`);d.enabled=f}d.checkEveryMinutes=c("--check-every",e.checkEvery),Object.values(d).some(p=>p!==void 0)&&(t.checkers=d)}catch(c){console.error(L.red(` ${c.message}`)),process.exitCode=1;return}if(Object.values(t).some(c=>c!==void 0)){let c=await ru(t);if(!c.success){console.error(L.red(` ${c.error}`)),process.exitCode=1;return}console.log(L.green(" \u2713 saved")+(c.reloaded?L.dim(" (daemon reloaded)"):""))}let o=Br();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`);let n=o.plans??Gr;console.log(` Plans ${n.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${n.stallMinutes} minute(s), up to ${n.maxNudges} time(s)`),console.log(` You approve up front ${n.approveKinds.length?n.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${n.disabledAgents.length?n.disabledAgents.join(", "):"no agent"}`);let s=n.requireOverMinutes??Gr.requireOverMinutes,r=n.requireForWork??Gr.requireForWork;console.log(` Plan before starting ${[r.length?`${r.join(", ")} work`:"",s>0?`work over ${s} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let i=o.checkers??xd;console.log(` Loop checks ${i.enabled.length?i.enabled.join(", "):"off"}, every ${i.checkEveryMinutes} minute(s)`);let a=Object.keys(i.repos);console.log(` Repos for git-ancestor ${a.length?a.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as RS}from"commander";import ls from"chalk";ae();var iy=new RS("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",sc.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(ls.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ge(r=>{n=Rm(r,e,t==="on")});s.success||(console.error(ls.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(ls.green(`\u2713 ${n}`)),s.reloaded&&console.log(ls.dim(" daemon hot-reloaded"))}let o=C().requestStatus.channels.map(n=>n.toLowerCase());for(let n of sc)console.log(` ${n.padEnd(8)} ${o.includes(n)?ls.green("on"):ls.dim("off")}`)});import{Command as XS}from"commander";import ds from"chalk";import ye from"chalk";import ir from"prompts";import{readFileSync as CS,writeFileSync as TS,existsSync as OS}from"fs";import{resolve as ay}from"path";var NS=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function IS(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function bl(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function cy(e=".env"){let t=ay(e);if(!OS(t))return[];let o=CS(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(NS);r?n.push({kind:"kv",key:r[1],value:IS(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function jS(e){return e.map(t=>t.kind==="kv"?`${t.key}=${bl(t.value)}`:t.raw).join(`
|
|
508
508
|
`)+`
|
|
509
|
-
`}function rr(e,t,o=".env"){let n=ay(o),s=cy(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${bl(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${bl(t)}`})),TS(n,jS(s))}function kl(e,t=".env"){return cy(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var ly="https://t.me/BotFather";async function _S(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function DS(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function dy(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${ly}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await ir({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Zo(ly);let{token:o}=await ir({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await _S(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await ir({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await ir({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;rr(p,o.trim()),process.env[p]=o.trim();let u=await ge(b=>{Je(b,"channels.telegram.enabled",!0),Je(b,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let v=Ln(b,`agents.${g}.mentions`)||[],x=`@${n.username}`;v.includes(x)||(v.push(x),Je(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await ir({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await DS(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await ge(b=>{Je(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ye.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Ce from"chalk";import vl from"prompts";import{existsSync as Sl,mkdirSync as PS,readdirSync as MS,readFileSync as gy}from"fs";import{resolve as xl}from"path";var LS=".agentx/whatsapp-sessions";function FS(){let e=xl(process.cwd(),".agentx/daemon.pid");if(!Sl(e))return!1;try{let t=parseInt(gy(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function qS(e){if(!Sl(e))return!1;try{return MS(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function US(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Ce.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Ce.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;PS(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Ce.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Ce.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Ce.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Ce.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function uy(e={}){if(console.log(),console.log(Ce.bold(" Connect WhatsApp")),console.log(),FS()){console.log(Ce.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Ce.dim(" agentx daemon stop")),console.log();let{cont:l}=await vl({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Ce.red(" Aborted")),process.exit(1))}let t=e.configPath||xl(process.cwd(),"agentx.json");Sl(t)||(console.log(Ce.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(gy(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||LS,s=xl(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await vl({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Ce.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(qS(s)&&a){let{keep:l}=await vl({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(Ce.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await US(s,g=>console.log(g))||(console.log(Ce.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{Je(l,"channels.whatsapp.enabled",!0),Je(l,"channels.whatsapp.sessionDir",n),Je(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Ce.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Ce.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Ce.dim(` Session: ${n}`)),console.log(Ce.dim(" Start the daemon to begin receiving:")),console.log(Ce.dim(" agentx daemon start")),console.log(Ce.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Ce.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Ce.dim(" Add routes later with:")),console.log(Ce.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as WS}from"crypto";import We from"chalk";import my from"prompts";var Hi="agentx-mesh:",zi="//join/";function BS(e){return Buffer.from(e,"utf-8").toString("base64url")}function JS(e){return Buffer.from(e,"base64url").toString("utf-8")}function GS(e){return`${Hi}${zi}${BS(JSON.stringify(e))}`}function HS(e){if(!e.startsWith(`${Hi}${zi}`))throw new Error(`Not a mesh invite link \u2014 expected ${Hi}${zi}\u2026`);let t=e.slice(Hi.length+zi.length),o=JSON.parse(JS(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function zS(){return WS(32).toString("hex")}function YS(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function VS(e){return e?.node?.name||e?.node?.id||"node"}async function py(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(We.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=kl("MESH_TOKEN");i||(i=zS(),rr("MESH_TOKEN",i),console.log(We.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||YS(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await my({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(We.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{Je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(We.red(` \u2717 ${l.error}`)),process.exit(1));let g=GS({url:a,token:i,name:VS(r),version:1});console.log(),console.log(We.bold(" Mesh invite")),console.log(),console.log(` ${We.cyan(g)}`),console.log(),console.log(We.dim(" Run on the other node:")),console.log(We.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(We.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function fy(e,t={}){let o;try{o=HS(e)}catch(r){console.log(We.red(` \u2717 ${r.message}`)),process.exit(1)}let n=kl("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await my({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(We.red(" Aborted (keeping existing .env)")),process.exit(1))}rr("MESH_TOKEN",o.token);let s=await ge(r=>{Je(r,"mesh.enabled",!0);let i=Ln(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),Je(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(We.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(We.green(" \u2713 Joined mesh")),console.log(We.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(We.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(We.dim(" Daemon hot-reloaded.")):console.log(We.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(We.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(We.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(We.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var gs=new XS().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");gs.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 dy({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});gs.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 uy({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var hy=gs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");hy.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 py({url:e.url,configPath:e.config})});hy.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await fy(e,{configPath:t.config})});gs.action(()=>{console.log(),console.log(ds.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ds.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ds.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ds.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ds.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ds.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as KS}from"commander";import te from"chalk";var $n=new KS().name("usage").description("token usage analysis and reporting");$n.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(te.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(te.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${te.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${te.red(String(s.totalErrors))}`),console.log(),console.log(te.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${te.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${te.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${e.message}`))}});$n.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=C(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:te.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(te.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(te.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?te.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(te.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${t.message}`))}});$n.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(te.red(` Script not found: ${s}`)),console.log(te.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(te.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(te.red(" Analysis failed. Is Python 3 installed?"))}});$n.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(te.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(te.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(te.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(te.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(te.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let $=r(h),b=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(y),x=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log(b)}console.log(),c&&console.log(te.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(te.dim(` Saved ${e.save}`)),console.log()});$n.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-7WISM624.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(te.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${te.dim("\xB7")} ${d}`);console.log(),console.log(te.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(te.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(te.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(te.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(te.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(te.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=te.dim(`${r.days}d`);console.log(` ${te.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(te.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as QS}from"commander";import Me from"chalk";import{readFileSync as ZS}from"fs";import{resolve as eA}from"path";ae();var Fo=new QS().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Fo.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{Ld(eA(process.cwd(),".env"))}catch{}let t=tA(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-RUO6R5NI.js");o(t)}catch(t){console.log(Me.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Me.dim(t.stack)),process.exit(1)}});function tA(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Me.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Me.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
509
|
+
`}function rr(e,t,o=".env"){let n=ay(o),s=cy(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${bl(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${bl(t)}`})),TS(n,jS(s))}function kl(e,t=".env"){return cy(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var ly="https://t.me/BotFather";async function _S(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function DS(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function dy(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${ly}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await ir({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Zo(ly);let{token:o}=await ir({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await _S(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await ir({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await ir({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;rr(p,o.trim()),process.env[p]=o.trim();let u=await ge(b=>{Je(b,"channels.telegram.enabled",!0),Je(b,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let v=Ln(b,`agents.${g}.mentions`)||[],x=`@${n.username}`;v.includes(x)||(v.push(x),Je(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await ir({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await DS(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await ge(b=>{Je(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ye.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Ce from"chalk";import vl from"prompts";import{existsSync as Sl,mkdirSync as PS,readdirSync as MS,readFileSync as gy}from"fs";import{resolve as xl}from"path";var LS=".agentx/whatsapp-sessions";function FS(){let e=xl(process.cwd(),".agentx/daemon.pid");if(!Sl(e))return!1;try{let t=parseInt(gy(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function qS(e){if(!Sl(e))return!1;try{return MS(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function US(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Ce.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Ce.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;PS(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Ce.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Ce.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Ce.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Ce.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function uy(e={}){if(console.log(),console.log(Ce.bold(" Connect WhatsApp")),console.log(),FS()){console.log(Ce.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Ce.dim(" agentx daemon stop")),console.log();let{cont:l}=await vl({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Ce.red(" Aborted")),process.exit(1))}let t=e.configPath||xl(process.cwd(),"agentx.json");Sl(t)||(console.log(Ce.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(gy(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||LS,s=xl(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await vl({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Ce.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(qS(s)&&a){let{keep:l}=await vl({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(Ce.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await US(s,g=>console.log(g))||(console.log(Ce.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{Je(l,"channels.whatsapp.enabled",!0),Je(l,"channels.whatsapp.sessionDir",n),Je(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Ce.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Ce.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Ce.dim(` Session: ${n}`)),console.log(Ce.dim(" Start the daemon to begin receiving:")),console.log(Ce.dim(" agentx daemon start")),console.log(Ce.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Ce.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Ce.dim(" Add routes later with:")),console.log(Ce.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as WS}from"crypto";import We from"chalk";import my from"prompts";var Hi="agentx-mesh:",zi="//join/";function BS(e){return Buffer.from(e,"utf-8").toString("base64url")}function JS(e){return Buffer.from(e,"base64url").toString("utf-8")}function GS(e){return`${Hi}${zi}${BS(JSON.stringify(e))}`}function HS(e){if(!e.startsWith(`${Hi}${zi}`))throw new Error(`Not a mesh invite link \u2014 expected ${Hi}${zi}\u2026`);let t=e.slice(Hi.length+zi.length),o=JSON.parse(JS(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function zS(){return WS(32).toString("hex")}function YS(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function VS(e){return e?.node?.name||e?.node?.id||"node"}async function py(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(We.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=kl("MESH_TOKEN");i||(i=zS(),rr("MESH_TOKEN",i),console.log(We.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||YS(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await my({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(We.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{Je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(We.red(` \u2717 ${l.error}`)),process.exit(1));let g=GS({url:a,token:i,name:VS(r),version:1});console.log(),console.log(We.bold(" Mesh invite")),console.log(),console.log(` ${We.cyan(g)}`),console.log(),console.log(We.dim(" Run on the other node:")),console.log(We.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(We.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function fy(e,t={}){let o;try{o=HS(e)}catch(r){console.log(We.red(` \u2717 ${r.message}`)),process.exit(1)}let n=kl("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await my({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(We.red(" Aborted (keeping existing .env)")),process.exit(1))}rr("MESH_TOKEN",o.token);let s=await ge(r=>{Je(r,"mesh.enabled",!0);let i=Ln(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),Je(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(We.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(We.green(" \u2713 Joined mesh")),console.log(We.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(We.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(We.dim(" Daemon hot-reloaded.")):console.log(We.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(We.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(We.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(We.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var gs=new XS().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");gs.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 dy({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});gs.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 uy({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var hy=gs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");hy.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 py({url:e.url,configPath:e.config})});hy.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await fy(e,{configPath:t.config})});gs.action(()=>{console.log(),console.log(ds.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ds.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ds.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ds.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ds.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ds.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as KS}from"commander";import te from"chalk";var $n=new KS().name("usage").description("token usage analysis and reporting");$n.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(te.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(te.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${te.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${te.red(String(s.totalErrors))}`),console.log(),console.log(te.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${te.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${te.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${e.message}`))}});$n.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=C(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:te.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(te.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(te.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?te.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(te.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${t.message}`))}});$n.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(te.red(` Script not found: ${s}`)),console.log(te.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(te.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(te.red(" Analysis failed. Is Python 3 installed?"))}});$n.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(te.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(te.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(te.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(te.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(te.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let $=r(h),b=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(y),x=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log(b)}console.log(),c&&console.log(te.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(te.dim(` Saved ${e.save}`)),console.log()});$n.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-HFN24YLA.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(te.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${te.dim("\xB7")} ${d}`);console.log(),console.log(te.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(te.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(te.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(te.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(te.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(te.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=te.dim(`${r.days}d`);console.log(` ${te.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(te.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as QS}from"commander";import Me from"chalk";import{readFileSync as ZS}from"fs";import{resolve as eA}from"path";ae();var Fo=new QS().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Fo.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{Ld(eA(process.cwd(),".env"))}catch{}let t=tA(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-642BO7GV.js");o(t)}catch(t){console.log(Me.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Me.dim(t.stack)),process.exit(1)}});function tA(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Me.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Me.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
510
510
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Fo.command("list").description("list configured boards").action(()=>{try{let e=C();if(!e.boards?.length){console.log(Me.dim(`
|
|
511
511
|
No boards configured.
|
|
512
512
|
`));return}console.log();for(let t of e.boards){console.log(` ${Me.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Me.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Me.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Me.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Me.red(` ${e.message}`)),process.exit(1)}});Fo.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{ar(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Me.red(` ${o.message}`)),process.exit(1)}});Fo.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{ar(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Me.red(` ${o.message}`)),process.exit(1)}});var Al=Fo.command("column").description("manage a board's columns (add / remove / edit / list)");Al.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(ZS("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Me.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Me.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Me.dim(r)}`)}}catch(t){console.log(Me.red(` ${t.message}`)),process.exit(1)}});Al.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{ar(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Me.red(` ${n.message}`)),process.exit(1)}});Al.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{ar(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Me.red(` ${o.message}`)),process.exit(1)}});Fo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{ar(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Me.red(` ${t.message}`)),process.exit(1)}});function ar(e){let{summary:t,backupPath:o}=St(n=>e(n));console.log(Me.green(`
|
|
@@ -536,19 +536,19 @@ An edit that breaks these rules is refused and the note is deferred.
|
|
|
536
536
|
|
|
537
537
|
${t}
|
|
538
538
|
`}function by(e,t,o,n){let s=n.today??new Date().toISOString().slice(0,10),r=new Map;for(let i of t){let a=e.find(c=>c.id===i.id||i.id.length>=4&&c.id.startsWith(i.id));a&&!r.has(a.id)&&r.set(a.id,i)}return e.map(i=>{let a=r.get(i.id);if(!a)return{id:i.id,outcome:"deferred",reason:"absorb did not answer this note",patched:[]};let c=Yi(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:c,patched:[]};let l=oA(a.edits,o,n.paths,n.agentId);if("refused"in l)return{id:i.id,outcome:"deferred",reason:Yi(`patch refused: ${l.refused}. Absorb said: ${c}`),patched:[]};let g=[],d="";for(let[p,{article:u,content:h}]of l.articles){let y=!1;try{y=o.writeArticle(p,{...u.meta,lastUpdated:s,sources:[...new Set([...u.meta.sources??[],Rl(i.id)])]},h,n.agentId)}catch($){d=`${p}: ${$?.message??$}`}if(!y){d||=p;break}g.push({path:p,article:u})}if(d){for(let p of g)try{o.writeArticle(p.path,p.article.meta,p.article.content,n.agentId)}catch{}return{id:i.id,outcome:"deferred",reason:Yi(`patch not saved: could not write ${d}. Absorb said: ${c}`),patched:[]}}let f=g.map(p=>p.path);return{id:i.id,outcome:"patched",reason:Yi(`${c} (edited ${f.join(", ")})`),patched:f}})}function oA(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>cr.edits)return{refused:`more than ${cr.edits} edits`};let s=new Map;for(let r of e){if(!o.has(r.path))return{refused:`${r.path} is not an article shown in full`};let i=s.get(r.path);if(!i){let c=t.readArticle(r.path);if(!c)return{refused:`${r.path} is not an existing article`};if(t.canWrite&&!t.canWrite(c.meta,n))return{refused:`no permission to write ${r.path}`};i={article:c,content:c.content,replaced:0},s.set(r.path,i)}if(!r.find.trim())return{refused:`an edit to ${r.path} quotes nothing`};if(r.find.length>cr.find||r.replace.length>cr.replace)return{refused:`an edit to ${r.path} is too long for a patch`};if(i.replaced+=r.find.length,i.replaced>i.article.content.length*cr.share)return{refused:`the edits replace most of ${r.path}; a note only patches`};let a=i.content.indexOf(r.find);if(a<0)return{refused:`the quoted passage is not in ${r.path}`};if(i.content.indexOf(r.find,a+1)>=0)return{refused:`the quoted passage appears more than once in ${r.path}`};i.content=i.content.slice(0,a)+r.replace+i.content.slice(a+r.find.length)}for(let[r,{article:i,content:a}]of s){let c=[...nA(i.content,a),...aA(i.content,a)];if(c.length>0)return{refused:`the edit to ${r} drops ${c.slice(0,4).join("; ")}${c.length>4?"; \u2026":""}`}}return{articles:s}}function nA(e,t){let o=Ds(e,t),n=Ds(t,e),s=i=>i.startsWith("link [[")?"wikilink":i.split(" ")[0],r=new Map;for(let i of n)r.set(s(i),(r.get(s(i))??0)+1);return o.filter(i=>{let a=r.get(s(i))??0;return a===0?!0:(r.set(s(i),a-1),!1)})}var sA=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,rA=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,iA=/^\s*(?:[-*]\s*)?(?:\|\s*)?\**\s*(role|job title|position|organi[sz]ation|company|team|employer|e-?mail|phone|mobile|tel|whatsapp|telegram|signal|slack|handle|contact|address)\s*\**\s*(?::|\|)\s*\**\s*(.+?)\s*\|?\s*$/gim;function aA(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(sA))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(rA))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(iA)){let r=s[2].replace(/\*+/g,"").trim();!r||/^(unknown|n\/a|none|-+|tbd)$/i.test(r)||o.includes(r.toLowerCase())||n.push(`${s[1].toLowerCase()} "${r}"`)}return[...new Set(n)]}function Yi(e){return e.length>Ia.reason?`${e.slice(0,Ia.reason-1)}\u2026`:e}import qe from"chalk";import{resolve as cA}from"path";var lA=e=>e||cA(process.cwd(),".agentx/wiki");async function us(e){let{FactLedger:t}=await import("./ledger-P62U3FHT.js");return new t(lA(e))}function ms(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(qe.red(` ${o?.message??o}`)),process.exitCode=1}}}function ky(e){let t=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");t.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(ms(async n=>{let{isStaleFact:s}=await import("./ledger-P62U3FHT.js"),r=(await us(n.dir)).list().filter(i=>!n.stale||s(i));if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(qe.dim(" no facts recorded"));return}for(let i of r){let a=i.undated?qe.yellow(" UNCHECKED"):s(i)?qe.yellow(" STALE"):"";console.log(` ${qe.cyan(i.id)} ${qe.bold(i.subject)} \xB7 ${i.attribute}: ${i.value}${a}`),console.log(qe.dim(` ${i.volatility} \xB7 ${i.source} \xB7 checked ${i.verifiedAt.slice(0,10)} by ${i.verifiedBy}`))}})),t.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(ms(async(n,s)=>{let r=(await us(s.dir)).get(n);if(!r){console.error(qe.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(r,null,2))})),t.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${Ta.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(ms(async n=>{if(n.class&&!Gd(n.class)){console.error(qe.red(` --class must be one of ${Ta.join(", ")}`)),process.exitCode=1;return}let r=(await us(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(r.status==="contradiction"){let i=r.fact.confirmedBy?`${r.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(qe.yellow(` not replaced: the wiki says "${r.fact.value}" (checked ${r.fact.verifiedAt.slice(0,10)}), ${i}.`)),console.log(r.questionId?qe.dim(` Queued question ${r.questionId}: agentx wiki questions \xB7 agentx wiki answer ${r.questionId} "<true value>"`):r.questionClosed?qe.dim(` A person already ${r.questionClosed} this same claim, so it is not asked again.`):qe.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(qe.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))}));let o=t.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");o.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(ms(async n=>{let{listFactProposals:s}=await import("./fact-proposals-X2O4W7VN.js"),r=s(await us(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(qe.dim(" no fact proposals waiting"));return}for(let i of r)console.log(` ${qe.cyan(i.id)} ${i.status==="pending"?"":qe.dim(`[${i.status}] `)}${i.claim}`),console.log(qe.dim(` ${i.agentId} \xB7 ${i.origin} \xB7 ${i.source} \xB7 ${i.verifiedAt.slice(0,10)}`));console.log(qe.dim(`
|
|
539
|
-
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(ms(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await us(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(qe.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(ms(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await us(s.dir),n,s.by,s.reason);console.log(qe.dim(` rejected: ${i.claim}`))}))}import ze from"chalk";import{existsSync as vy,readFileSync as xy}from"fs";import{resolve as Tl}from"path";var Cl=e=>e||Tl(process.cwd(),".agentx/wiki");function dA(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=Tl(process.cwd(),"agentx.json");if(vy(t)){let o=JSON.parse(xy(t,"utf-8"))?.node?.bind;if(typeof o=="string"&&o.includes(":")){let[n,s]=o.split(":");return`http://${n==="0.0.0.0"?"127.0.0.1":n}:${s}`}}}catch{}return"http://127.0.0.1:18800"}function ro(e){console.error(ze.red(` ${e}`)),process.exitCode=1}function Vi(e){return async(...t)=>{try{await e(...t)}catch(o){ro(o?.message??String(o))}}}function Sy(e){let t=e.command("notes").description("notes agents leave for the wiki observe/sweep run: add, list, handle, config");t.command("add").description("leave a note for the wiki observe/sweep run: what changed, the source, the date").requiredOption("--change <text>","what changed, in a sentence or two").requiredOption("--source <text>",'where you saw it: a system, URL, command, or "owner said"').option("--date <YYYY-MM-DD>","when it changed or when you saw it (default: today)").option("--from <agent>","your agent id",process.env.AGENTX_AGENT_ID).option("--daemon <url>","this node's daemon (default: AGENTX_DAEMON_URL, else node.bind in agentx.json)").option("--dir <path>","write straight into this wiki directory instead of going through the daemon (needs --to)").option("--to <agent>","inbox agent, with --dir").option("--json").action(Vi(async o=>{if(!o.from){ro("say who you are with --from <agent id>");return}let n={from:o.from,change:o.change,source:o.source,date:o.date},s;if(o.dir){if(!o.to){ro("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:c}=await import("./notes-WJJEJ4CJ.js"),l=c({...n,to:o.to});if("error"in l){ro(l.error);return}s={ok:!0,...new a(Cl(o.dir)).add(l.note)}}else{let a=dA(o.daemon),c;try{c=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(l){ro(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){ro(s?.error||`daemon answered ${c.status}`);return}}if(o.json){console.log(JSON.stringify(s,null,2));return}let r=s.note,i=s.peer?` on ${s.peer}`:"";console.log(s.added===!1?ze.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):ze.green(` note ${r?.id} left for ${r?.to}${i}; the next observe/sweep run reads it`))})),t.command("list").description("notes in this node's inbox (waiting ones by default)").option("--status <status>","waiting | open | patched | rejected | deferred | expired | all","waiting").option("--dir <path>","wiki directory").option("--json").action(Vi(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){ro(`--status must be one of ${s.join(", ")}`);return}let r=new n(Cl(o.dir)),i=r.load();if(i.unreadable){ro(`${r.path} is unreadable (${i.unreadable}); repair or move it aside`);return}let a=r.list(o.status==="all"?void 0:o.status);if(o.json){console.log(JSON.stringify(a,null,2));return}if(a.length===0){console.log(ze.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?ze.yellow("open"):c.status==="deferred"?ze.yellow("deferred"):ze.dim(c.status);console.log(` ${ze.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(ze.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(ze.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(ze.dim(` ${c.handled.outcome}${c.deferrals?` (deferred ${c.deferrals}x)`:""} by ${c.handled.by} ${c.handled.at.slice(0,10)}: ${c.handled.reason}`)),c.expired&&console.log(ze.dim(` expired ${c.expired.at.slice(0,10)} after ${c.expired.after} deferrals; no longer offered to the run`))}})),t.command("handle <id>").description("record what the run did with a note: patched, rejected or deferred, with a reason").requiredOption("--outcome <outcome>","patched | rejected | deferred").requiredOption("--reason <text>","what you patched, why you rejected it, or why it waits").option("--run <id>","the run that used it").option("--by <agent>","who handled it",process.env.AGENTX_AGENT_ID||"operator").option("--dir <path>","wiki directory").action(Vi(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Cl(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(ze.green(` note ${r.id}: ${r.status}`))})),t.command("config").description("show or set the inbox agent, and the schedules and absorb pass that read it").option("--inbox <agent>",'agent that runs the wiki observe/sweep schedule ("" clears it)').option("--cron <ids>",'comma-separated schedule ids that read the inbox ("" for none)').option("--absorb <agent>",'agent whose `wiki absorb` pass reads and answers the notes ("" clears it)').option("--max <n>","most notes one run is given (1-100)").option("--max-deferrals <n>","times a note may be deferred before it expires (1-20)").option("--enable","turn wiki notes on").option("--disable","turn wiki notes off").option("--json").action(Vi(async o=>{let{patchWikiNotes:n,wikiNotesSettings:s}=await import("./notes-settings-VPXI5IIS.js"),r={};if(o.inbox!==void 0&&(r.inbox=o.inbox),o.cron!==void 0&&(r.crons=String(o.cron).split(",")),o.absorb!==void 0&&(r.absorbAgent=o.absorb),o.max!==void 0&&(r.maxNotesPerRun=Number(o.max)),o.maxDeferrals!==void 0&&(r.maxDeferrals=Number(o.maxDeferrals)),o.enable&&o.disable){ro("pick one of --enable and --disable");return}if(o.enable&&(r.enabled=!0),o.disable&&(r.enabled=!1),Object.keys(r).length>0){let{mutateAgentxConfig:c}=await import("./config-mutate-MMTHEXWM.js"),{summary:l}=c(g=>n(g,r));console.log(ze.green(` ${l}`))}let i=Tl(process.cwd(),"agentx.json");if(!vy(i)){ro(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(xy(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?ze.green("on"):ze.dim("off")}`),console.log(` inbox agent: ${a.inbox||ze.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):ze.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:ze.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import qo from"chalk";import{resolve as gA}from"path";var Ol=e=>e||gA(process.cwd(),".agentx/wiki");function Ay(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-LQ2I2PQI.js");try{let s=n(Ol(o.dir));console.log(qo.green(` wrote ${s}`))}catch(s){console.error(qo.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{file:s,errors:r}=n(Ol(o.dir));if(!s){console.log(qo.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(qo.green(` ${s}: no problems`));return}console.log(qo.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-U65U7SE6.js"),i=Ol(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),g=new r(i,()=>{}),d=new s().get(g,c,a(i,g.listAgents([]),c.agent_names)),f=new Map;for(let p of d.entities.values())f.set(p.type,(f.get(p.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(f),errors:l},null,2));return}console.log(qo.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(y=>y.pillar===p.id),h=u.reduce((y,$)=>y+(f.get($.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${qo.dim(u.map(y=>`${y.id} ${f.get(y.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(qo.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import Xe from"chalk";import{resolve as uA}from"path";var Nl=e=>e||uA(process.cwd(),".agentx/wiki"),mA=()=>new Date().toISOString().slice(0,10);async function Il(e){let{WikiHub:t}=await import("./hub-U65U7SE6.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function Ey(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(Xe.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Ry(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-GEHA6NJQ.js"),i=Ey(o.max,"--max"),a=Ey(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(Xe.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await Il(Nl(o.dir)),d=o.about??[],{normName:f}=await import("./graph-ZVKV3JBD.js"),p=d.filter($=>!g.names.has(f($))&&!g.entities.has($));if(p.length){console.error(Xe.red(` no page is titled: ${p.join(", ")}`)),process.exitCode=1;return}let u=await n(l,g,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:mA()}),h=s(g,u,d);if(o.json){console.log(JSON.stringify({...u,about:h},null,2));return}for(let $ of u.outcomes){let b=$.status==="written"?Xe.green("\u2713"):$.status==="dry-run"?Xe.cyan("~"):Xe.yellow("\xB7"),v=$.importance?`${$.importance}${$.proposed?` (proposed ${$.proposed})`:""}`:$.status;console.log(` ${b} ${$.date||"no date "} ${v.padEnd(8)} ${$.title} ${Xe.dim(`${$.by??$.status}${$.about.length?` \xB7 about ${$.about.join(", ")}`:""}${$.why?` \xB7 ${$.why}`:""}`)}`);for(let x of $.dropped.slice(0,4))console.log(Xe.dim(` dropped: ${x}`))}for(let $ of h)console.log(Xe.bold(` ${$.title}`)+Xe.dim(` (${$.type}): ${$.before} events in its History before \xB7 after: ${$.after.major} major, ${$.after.normal} normal, ${$.after.minor} minor (folded)`));let y=u.outcomes.filter($=>$.importance).length;u.outcomes.length===0&&console.log(Xe.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(Xe.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${u.left} left \xB7 ${u.calls} model call${u.calls===1?"":"s"} \xB7 spent $${u.costUsd.toFixed(3)} of $${c}${u.capped?" \xB7 stopped at the cap":""}`)),u.outcomes.some($=>$.status==="failed")&&(process.exitCode=1)});t.command("set <title> <level>").description("set an event's importance yourself (minor, normal or major); no later run changes it").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(o,n,s,r)=>{let{setEventLevel:i}=await import("./event-levels-NBOMTB23.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(Xe.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await Il(Nl(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(Xe.green(` ${d.title} is now ${c}`)+Xe.dim(` (${d.page})`)):(console.error(Xe.red(` not set: ${d.reason}`)),process.exitCode=1)}),t.command("proposed").description("list events a run suggests as major, waiting for you to decide").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print as JSON").action(async(o,n)=>{let s=n.optsWithGlobals(),{g:r}=await Il(Nl(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,c)=>(c.date||"").localeCompare(a.date||""));if(s.json){console.log(JSON.stringify(i.map(a=>({id:a.id,title:a.title,date:a.date,importance:a.importance,proposed:a.importanceProposed})),null,2));return}for(let a of i)console.log(` ${a.date||"no date "} ${a.title} ${Xe.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(Xe.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import kt from"chalk";import{resolve as pA}from"path";var fA=e=>e||pA(process.cwd(),".agentx/wiki");function Cy(e){e.command("rules [pages...]").description("write one obligation page per rule the wiki states, with deadline, penalty, source and check date").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--words <list>","comma-separated words that mark a page as stating rules (default: deadline, penalty, filing\u2026 in English, French and Arabic)").option("--max <n>","most source pages per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","read again pages that did not change").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async(t,o)=>{let{WikiHub:n}=await import("./hub-U65U7SE6.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=fA(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(kt.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let p=Number(o.maxCost);if(!Number.isFinite(p)||p<=0){console.error(kt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(kt.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(x=>x.id==="obligation")){console.error(kt.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let $=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),b=a(d),v=await l(h,$,Wm(o.model),{only:t,words:c(u),max:f,maxCostUsd:p,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>g(d,x)},b);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let A=x.status==="written"?kt.green("\u2713"):x.status==="dry-run"?kt.cyan("~"):kt.yellow("\xB7");console.log(` ${A} ${x.title} ${kt.dim(`${x.status} \xB7 ${x.page??"no page"} \xB7 ${x.rules.length} rules \xB7 $${x.costUsd.toFixed(3)}`)}`);for(let k of x.rules){let S=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${kt.dim(`\xB7 ${k.page}${S.length?` \xB7 ${S.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(kt.dim(k.preview.split(`
|
|
539
|
+
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(ms(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await us(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(qe.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(ms(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await us(s.dir),n,s.by,s.reason);console.log(qe.dim(` rejected: ${i.claim}`))}))}import ze from"chalk";import{existsSync as vy,readFileSync as xy}from"fs";import{resolve as Tl}from"path";var Cl=e=>e||Tl(process.cwd(),".agentx/wiki");function dA(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=Tl(process.cwd(),"agentx.json");if(vy(t)){let o=JSON.parse(xy(t,"utf-8"))?.node?.bind;if(typeof o=="string"&&o.includes(":")){let[n,s]=o.split(":");return`http://${n==="0.0.0.0"?"127.0.0.1":n}:${s}`}}}catch{}return"http://127.0.0.1:18800"}function ro(e){console.error(ze.red(` ${e}`)),process.exitCode=1}function Vi(e){return async(...t)=>{try{await e(...t)}catch(o){ro(o?.message??String(o))}}}function Sy(e){let t=e.command("notes").description("notes agents leave for the wiki observe/sweep run: add, list, handle, config");t.command("add").description("leave a note for the wiki observe/sweep run: what changed, the source, the date").requiredOption("--change <text>","what changed, in a sentence or two").requiredOption("--source <text>",'where you saw it: a system, URL, command, or "owner said"').option("--date <YYYY-MM-DD>","when it changed or when you saw it (default: today)").option("--from <agent>","your agent id",process.env.AGENTX_AGENT_ID).option("--daemon <url>","this node's daemon (default: AGENTX_DAEMON_URL, else node.bind in agentx.json)").option("--dir <path>","write straight into this wiki directory instead of going through the daemon (needs --to)").option("--to <agent>","inbox agent, with --dir").option("--json").action(Vi(async o=>{if(!o.from){ro("say who you are with --from <agent id>");return}let n={from:o.from,change:o.change,source:o.source,date:o.date},s;if(o.dir){if(!o.to){ro("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:c}=await import("./notes-WJJEJ4CJ.js"),l=c({...n,to:o.to});if("error"in l){ro(l.error);return}s={ok:!0,...new a(Cl(o.dir)).add(l.note)}}else{let a=dA(o.daemon),c;try{c=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(l){ro(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){ro(s?.error||`daemon answered ${c.status}`);return}}if(o.json){console.log(JSON.stringify(s,null,2));return}let r=s.note,i=s.peer?` on ${s.peer}`:"";console.log(s.added===!1?ze.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):ze.green(` note ${r?.id} left for ${r?.to}${i}; the next observe/sweep run reads it`))})),t.command("list").description("notes in this node's inbox (waiting ones by default)").option("--status <status>","waiting | open | patched | rejected | deferred | expired | all","waiting").option("--dir <path>","wiki directory").option("--json").action(Vi(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){ro(`--status must be one of ${s.join(", ")}`);return}let r=new n(Cl(o.dir)),i=r.load();if(i.unreadable){ro(`${r.path} is unreadable (${i.unreadable}); repair or move it aside`);return}let a=r.list(o.status==="all"?void 0:o.status);if(o.json){console.log(JSON.stringify(a,null,2));return}if(a.length===0){console.log(ze.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?ze.yellow("open"):c.status==="deferred"?ze.yellow("deferred"):ze.dim(c.status);console.log(` ${ze.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(ze.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(ze.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(ze.dim(` ${c.handled.outcome}${c.deferrals?` (deferred ${c.deferrals}x)`:""} by ${c.handled.by} ${c.handled.at.slice(0,10)}: ${c.handled.reason}`)),c.expired&&console.log(ze.dim(` expired ${c.expired.at.slice(0,10)} after ${c.expired.after} deferrals; no longer offered to the run`))}})),t.command("handle <id>").description("record what the run did with a note: patched, rejected or deferred, with a reason").requiredOption("--outcome <outcome>","patched | rejected | deferred").requiredOption("--reason <text>","what you patched, why you rejected it, or why it waits").option("--run <id>","the run that used it").option("--by <agent>","who handled it",process.env.AGENTX_AGENT_ID||"operator").option("--dir <path>","wiki directory").action(Vi(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Cl(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(ze.green(` note ${r.id}: ${r.status}`))})),t.command("config").description("show or set the inbox agent, and the schedules and absorb pass that read it").option("--inbox <agent>",'agent that runs the wiki observe/sweep schedule ("" clears it)').option("--cron <ids>",'comma-separated schedule ids that read the inbox ("" for none)').option("--absorb <agent>",'agent whose `wiki absorb` pass reads and answers the notes ("" clears it)').option("--max <n>","most notes one run is given (1-100)").option("--max-deferrals <n>","times a note may be deferred before it expires (1-20)").option("--enable","turn wiki notes on").option("--disable","turn wiki notes off").option("--json").action(Vi(async o=>{let{patchWikiNotes:n,wikiNotesSettings:s}=await import("./notes-settings-VPXI5IIS.js"),r={};if(o.inbox!==void 0&&(r.inbox=o.inbox),o.cron!==void 0&&(r.crons=String(o.cron).split(",")),o.absorb!==void 0&&(r.absorbAgent=o.absorb),o.max!==void 0&&(r.maxNotesPerRun=Number(o.max)),o.maxDeferrals!==void 0&&(r.maxDeferrals=Number(o.maxDeferrals)),o.enable&&o.disable){ro("pick one of --enable and --disable");return}if(o.enable&&(r.enabled=!0),o.disable&&(r.enabled=!1),Object.keys(r).length>0){let{mutateAgentxConfig:c}=await import("./config-mutate-X5IKMROK.js"),{summary:l}=c(g=>n(g,r));console.log(ze.green(` ${l}`))}let i=Tl(process.cwd(),"agentx.json");if(!vy(i)){ro(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(xy(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?ze.green("on"):ze.dim("off")}`),console.log(` inbox agent: ${a.inbox||ze.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):ze.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:ze.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import qo from"chalk";import{resolve as gA}from"path";var Ol=e=>e||gA(process.cwd(),".agentx/wiki");function Ay(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-LQ2I2PQI.js");try{let s=n(Ol(o.dir));console.log(qo.green(` wrote ${s}`))}catch(s){console.error(qo.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{file:s,errors:r}=n(Ol(o.dir));if(!s){console.log(qo.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(qo.green(` ${s}: no problems`));return}console.log(qo.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-HQUAH5H6.js"),i=Ol(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),g=new r(i,()=>{}),d=new s().get(g,c,a(i,g.listAgents([]),c.agent_names)),f=new Map;for(let p of d.entities.values())f.set(p.type,(f.get(p.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(f),errors:l},null,2));return}console.log(qo.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(y=>y.pillar===p.id),h=u.reduce((y,$)=>y+(f.get($.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${qo.dim(u.map(y=>`${y.id} ${f.get(y.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(qo.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import Xe from"chalk";import{resolve as uA}from"path";var Nl=e=>e||uA(process.cwd(),".agentx/wiki"),mA=()=>new Date().toISOString().slice(0,10);async function Il(e){let{WikiHub:t}=await import("./hub-HQUAH5H6.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function Ey(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(Xe.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Ry(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-5VQCT6BT.js"),i=Ey(o.max,"--max"),a=Ey(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(Xe.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await Il(Nl(o.dir)),d=o.about??[],{normName:f}=await import("./graph-ZVKV3JBD.js"),p=d.filter($=>!g.names.has(f($))&&!g.entities.has($));if(p.length){console.error(Xe.red(` no page is titled: ${p.join(", ")}`)),process.exitCode=1;return}let u=await n(l,g,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:mA()}),h=s(g,u,d);if(o.json){console.log(JSON.stringify({...u,about:h},null,2));return}for(let $ of u.outcomes){let b=$.status==="written"?Xe.green("\u2713"):$.status==="dry-run"?Xe.cyan("~"):Xe.yellow("\xB7"),v=$.importance?`${$.importance}${$.proposed?` (proposed ${$.proposed})`:""}`:$.status;console.log(` ${b} ${$.date||"no date "} ${v.padEnd(8)} ${$.title} ${Xe.dim(`${$.by??$.status}${$.about.length?` \xB7 about ${$.about.join(", ")}`:""}${$.why?` \xB7 ${$.why}`:""}`)}`);for(let x of $.dropped.slice(0,4))console.log(Xe.dim(` dropped: ${x}`))}for(let $ of h)console.log(Xe.bold(` ${$.title}`)+Xe.dim(` (${$.type}): ${$.before} events in its History before \xB7 after: ${$.after.major} major, ${$.after.normal} normal, ${$.after.minor} minor (folded)`));let y=u.outcomes.filter($=>$.importance).length;u.outcomes.length===0&&console.log(Xe.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(Xe.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${u.left} left \xB7 ${u.calls} model call${u.calls===1?"":"s"} \xB7 spent $${u.costUsd.toFixed(3)} of $${c}${u.capped?" \xB7 stopped at the cap":""}`)),u.outcomes.some($=>$.status==="failed")&&(process.exitCode=1)});t.command("set <title> <level>").description("set an event's importance yourself (minor, normal or major); no later run changes it").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(o,n,s,r)=>{let{setEventLevel:i}=await import("./event-levels-NBOMTB23.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(Xe.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await Il(Nl(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(Xe.green(` ${d.title} is now ${c}`)+Xe.dim(` (${d.page})`)):(console.error(Xe.red(` not set: ${d.reason}`)),process.exitCode=1)}),t.command("proposed").description("list events a run suggests as major, waiting for you to decide").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print as JSON").action(async(o,n)=>{let s=n.optsWithGlobals(),{g:r}=await Il(Nl(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,c)=>(c.date||"").localeCompare(a.date||""));if(s.json){console.log(JSON.stringify(i.map(a=>({id:a.id,title:a.title,date:a.date,importance:a.importance,proposed:a.importanceProposed})),null,2));return}for(let a of i)console.log(` ${a.date||"no date "} ${a.title} ${Xe.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(Xe.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import kt from"chalk";import{resolve as pA}from"path";var fA=e=>e||pA(process.cwd(),".agentx/wiki");function Cy(e){e.command("rules [pages...]").description("write one obligation page per rule the wiki states, with deadline, penalty, source and check date").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--words <list>","comma-separated words that mark a page as stating rules (default: deadline, penalty, filing\u2026 in English, French and Arabic)").option("--max <n>","most source pages per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","read again pages that did not change").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async(t,o)=>{let{WikiHub:n}=await import("./hub-HQUAH5H6.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=fA(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(kt.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let p=Number(o.maxCost);if(!Number.isFinite(p)||p<=0){console.error(kt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(kt.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(x=>x.id==="obligation")){console.error(kt.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let $=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),b=a(d),v=await l(h,$,Wm(o.model),{only:t,words:c(u),max:f,maxCostUsd:p,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>g(d,x)},b);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let A=x.status==="written"?kt.green("\u2713"):x.status==="dry-run"?kt.cyan("~"):kt.yellow("\xB7");console.log(` ${A} ${x.title} ${kt.dim(`${x.status} \xB7 ${x.page??"no page"} \xB7 ${x.rules.length} rules \xB7 $${x.costUsd.toFixed(3)}`)}`);for(let k of x.rules){let S=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${kt.dim(`\xB7 ${k.page}${S.length?` \xB7 ${S.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(kt.dim(k.preview.split(`
|
|
540
540
|
`).map(R=>` | ${R}`).join(`
|
|
541
|
-
`)))}for(let k of x.dropped.slice(0,6))console.log(kt.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(kt.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(kt.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import Xi from"chalk";import{resolve as hA}from"path";var yA=e=>e||hA(process.cwd(),".agentx/wiki");function Ty(e){e.command("summarize").description("write the one-line page summaries `wiki query` picks pages from; only new or changed pages are summarised").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--agent <id>","summarise this agent's pages (default: the calling agent)").option("--all","summarise every agent's pages and the shared pages").option("--model <m>","model (default: wiki.summaries.model, haiku)").option("--batch <n>","pages per model call (default: wiki.summaries.batchSize, 20)").option("--workers <n>","model calls running at once","4").option("--limit <n>","most pages to summarise per agent in this run (0 = all)","0").option("--dry-run","show how many pages are due, call no model, write nothing").option("--json","print the run as JSON").action(async t=>{let{WikiHub:o}=await import("./wiki-
|
|
541
|
+
`)))}for(let k of x.dropped.slice(0,6))console.log(kt.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(kt.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(kt.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import Xi from"chalk";import{resolve as hA}from"path";var yA=e=>e||hA(process.cwd(),".agentx/wiki");function Ty(e){e.command("summarize").description("write the one-line page summaries `wiki query` picks pages from; only new or changed pages are summarised").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--agent <id>","summarise this agent's pages (default: the calling agent)").option("--all","summarise every agent's pages and the shared pages").option("--model <m>","model (default: wiki.summaries.model, haiku)").option("--batch <n>","pages per model call (default: wiki.summaries.batchSize, 20)").option("--workers <n>","model calls running at once","4").option("--limit <n>","most pages to summarise per agent in this run (0 = all)","0").option("--dry-run","show how many pages are due, call no model, write nothing").option("--json","print the run as JSON").action(async t=>{let{WikiHub:o}=await import("./wiki-DXG655NP.js"),{summarizeStore:n}=await import("./summaries-BIRSNWGH.js"),{claudeModelCall:s}=await import("./model-call-J7JATTMW.js"),r={model:"haiku",batchSize:20,maxWords:35};try{let{loadDaemonConfig:g}=await import("./config-FZTWI3VG.js");r=g().wiki.summaries}catch{}let i=new o(yA(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log(Xi.red(" Name an agent with --agent <id>, or pass --all.")),process.exitCode=1;return}let c=t.all?[...i.sharedScope("").map(g=>({id:g.id,store:g.store,skip:g.skip}))]:[{id:a,store:i.getAgentWiki(a),skip:void 0}],l=[];for(let g of c){let d=await n(g.store,{call:s,model:t.model??r.model,batchSize:t.batch?parseInt(t.batch):r.batchSize,maxWords:r.maxWords,workers:parseInt(t.workers),limit:parseInt(t.limit),dryRun:t.dryRun,skip:g.skip,log:t.json?void 0:f=>console.log(Xi.dim(` ${g.id}: ${f}`))});if(l.push({agent:g.id,...d}),!t.json&&(d.pages>0||d.removed>0)){let f=t.dryRun?`${d.due} due`:`${d.written} written${d.failed?Xi.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${Xi.bold(g.id)}: ${d.pages} pages, ${f}`)}}t.json&&console.log(JSON.stringify(l,null,2)),l.some(g=>g.failed>0)&&(process.exitCode=1)})}import{resolve as q,relative as Oy,dirname as Ny}from"path";import{exec as $A,execSync as bn}from"child_process";import{promisify as bA}from"util";import{appendFileSync as kA,statSync as vA,writeFileSync as Ot,mkdirSync as Bt,readFileSync as Nt,readdirSync as xA,renameSync as Ki,rmSync as _l,existsSync as Ke}from"fs";var My=bA($A);function we(e,t){return new Ca(ut(e),void 0,t||"graph")}async function Ly(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-FZTWI3VG.js");t=(n().mesh?.peers||[]).map(s=>({url:s.url,token:s.token}))}catch{}if(!e?.length)return t;let o=n=>n.replace(/\/$/,"");return e.map(n=>({url:n,token:t.find(s=>o(s.url)===o(n))?.token}))}async function Fy(){try{let{loadDaemonConfig:e}=await import("./config-FZTWI3VG.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function Iy(){try{let{loadDaemonConfig:e}=await import("./config-FZTWI3VG.js"),t=e().wikiNotes;return!t?.enabled||!t.inbox||!t.absorbAgent?null:{inbox:t.inbox,absorbAgent:t.absorbAgent,max:t.maxNotesPerRun,maxDeferrals:t.maxDeferrals}}catch{return null}}async function SA(){try{let{loadDaemonConfig:e}=await import("./config-FZTWI3VG.js");return Nm(e().agents||{})}catch{return new Set}}function kn(e,t){let o=e.syncedFrom(t);return o?(console.log(m.yellow(` ${t}'s articles are copied from ${o.node} and read-only here; change them on ${o.node}.`)),process.exitCode=1,!0):!1}async function jy(){let{sharedQueryEnabled:e}=await import("./query-5CPK6G2H.js");return e()}async function qy(e){let{loadQuerySettings:t}=await import("./query-settings-35GDM3HU.js"),o=await t();if(e.method&&!["auto","summaries","catalog"].includes(e.method))return console.log(m.red(` --method takes auto, summaries or catalog, not "${e.method}".`)),process.exitCode=1,null;let n=e.linked===void 0?o.summaries.linkedPages:Number(e.linked);if(!Number.isInteger(n)||n<0||n>10)return console.log(m.red(` --linked takes a whole number from 0 to 10, not "${e.linked}".`)),process.exitCode=1,null;let s={...o.summaries.live,enabled:o.summaries.live.enabled&&e.live!==!1},r={...o.notes,enabled:o.notes.enabled&&e.notes!==!1};return{...o,method:e.method??o.method,summaries:{...o.summaries,linkedPages:n,live:s},notes:r}}function ut(e){return e||q(process.cwd(),".agentx/wiki")}function Dl(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var H=new wA().name("wiki").description("wiki knowledge base management");ky(H);Sy(H);Ay(H);Bm(H);Ry(H);Cy(H);Ty(H);H.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,o=we(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Dl(t)}]`)),console.log(),console.log(` Total raw entries: ${r}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),console.log(m.dim(` Cited by an article: ${a.cited} Read, not cited: ${a.readNotCited}`)),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let i=n.reduce((a,c)=>a+c.unabsorbed,0);i>0&&(console.log(m.dim(` ${i} raw entries wait for absorb \u2014 run 'agentx wiki absorb'.`)),console.log())});H.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let t=we(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let i of o){let c=t.getAgentWiki(i).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(i)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(i)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-P62U3FHT.js"),r=s(ut(e.dir));if(n+=r.length,r.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${r.length} contradiction(s)`)}`);for(let i of r)console.log(` [!] ${m.dim(i.type)} ${i.articles[0]}: ${i.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});H.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").option("--until <date>","only entries dated on or before YYYY-MM-DD").option("--model <model>","compile model (default: AGENTX_WIKI_ABSORB_MODEL, else sonnet)").option("--run-label <label>","tag this run's lines in _absorb-runs.jsonl, for `wiki absorb-runs`").option("--no-notes","do not read the wiki notes inbox, even for wikiNotes.absorbAgent").action(async e=>{let t=e.mode,o;try{o=El(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=we(e.dir,t),s=await Fy(),{agents:r,skipped:i}=Im(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await SA()}),a=i.length&&e.notes!==!1?(await Iy())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(jm(R,a))}`);let c=r.filter(R=>{let O=n.syncedFrom(R);return O&&console.log(` ${m.cyan(R)}: ${m.dim(`copied from ${O.node}, read-only here; absorb it there`)}`),!O}),l=parseInt(e.max),g=(()=>{try{let R=q(process.cwd(),".agentx/graph");return Ke(R)?new bo({baseDir:R}):null}catch{return null}})(),d=new Map;if(g)try{let R=g.loadIndex();for(let[O,N]of Object.entries(R.entries))d.set(O,N.path)}catch{}let f,p=R=>{let O=R.meta?.intentPath;if(Array.isArray(O)&&O.every(_=>typeof _=="string")&&O.length>0)return O;if(!g||d.size===0)return;let N=String(R.meta?.sender??""),D=g.fingerprint({text:R.content,channel:R.source,sender:N});return d.get(D)},u=(R,O)=>{let N=new Map;for(let _ of R){let J=O.find(Ee=>Ee.id===_);if(!J)continue;let W=p(J);if(!W?.length)continue;let X=W.join("/"),K=N.get(X);K?K.n++:N.set(X,{path:W,n:1})}if(N.size===0)return;let D;for(let _ of N.values())(!D||_.n>D.n)&&(D=_);return D?.path},h=0,y=0,$=0,b=q(n.getBaseDir(),"_absorb-runs.jsonl"),v=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,x=R=>{if(!e.dryRun)try{kA(b,`${JSON.stringify(R)}
|
|
542
542
|
`)}catch{}},A=new Date().toISOString(),k=e.notes===!1?null:await Iy(),S=k?new sg(n.getBaseDir()):null;for(let R of c){let O=Date.now(),N=typeof e.since=="string"?e.since.trim():"",D=typeof e.until=="string"?e.until.trim():"",_=n.getUnabsorbedEntries(R).filter(ie=>!N||(ie.date??"")>=N).filter(ie=>!D||(ie.date??"").slice(0,10)<=D).slice(0,l),J=!!(k&&S&&k.absorbAgent===R),W=`absorb/${R}/${A.replace(/[:.]/g,"-")}`,X=[];if(J&&e.dryRun?X=S.peekForRun(k.inbox,k.max,k.maxDeferrals):J&&(X=S.takeForRun(k.inbox,W,k.max,k.maxDeferrals)),_.length===0&&X.length===0){console.log(` ${m.cyan(R)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(R)}: ${_.length} entries to absorb`));for(let ie of _.slice(0,3))console.log(m.dim(` [${ie.date} via ${ie.source}] ${ie.content.slice(0,80)}...`));if(_.length>3&&console.log(m.dim(` ... and ${_.length-3} more`)),X.length>0&&console.log(m.dim(` Wiki notes: ${X.length} from the ${k.inbox} inbox${e.dryRun?"":` (run ${W})`}`)),e.dryRun)continue;let K=n.getAgentWiki(R),Ee=K.rebuildIndex(),Be=K.getWorldview()||n.getSharedStore().getWorldview()||"",P=_.map(ie=>`--- ENTRY ${ie.id} [${ie.date} ${ie.agentId} via ${ie.source}] ---
|
|
543
543
|
${ie.content}
|
|
544
544
|
--- END ENTRY ---`).join(`
|
|
545
545
|
|
|
546
|
-
`),re="";if(e.facts!==!1){let{extractHints:ie,resolveFacts:Jo,mergeRecords:En,renderFactsBlock:Rn,installPrompts:xr,defaultSources:Cn,recordsFromEntries:Go}=await import("./facts-ROUMKS7I.js");if(!f){let F=new Set;for(let Le of n.listAgents())for(let mt of n.getAgentWiki(Le).listArticles(Le))mt.meta.type==="person"&&F.add(mt.meta.title);f=[...F]}let Ho=ie(_.map(F=>({context:F.sourceContext,content:F.content,sender:typeof F.meta?.sender=="string"?F.meta.sender:void 0})),{known:f}),Tn=Go(_);if(Ho.length>0||Tn.length>0){let F=Cn(),{records:Le,results:mt}=Ho.length>0?await Jo(Ho,{sources:F}):{records:[],results:[]},be=En([...Tn,...Le]);re=Rn(be);let tt=[...Tn.length>0?[`entries:${Tn.length}`]:[],...mt.filter(je=>je.records.length>0).map(je=>`${je.source}:${je.records.length}`)];console.log(m.dim(` Facts: ${Ho.length} entities \u2192 ${be.length} resolved${tt.length?` (${tt.join(" ")})`:""}`));for(let je of xr(mt,F))console.log(m.yellow(` ! ${je.source} ${je.kind} \u2014 would supply ${je.provides.join(", ")}`)),console.log(m.dim(` ${je.hint}`))}}let Te=Ee.articles.filter(ie=>ie.path&&!ie.path.includes("/_versions/")),le=await Lm([..._,...X.map(ie=>({id:Rl(ie.id),content:ie.change}))],K,R,Te);le.length>0&&console.log(m.dim(` Existing: ${le.map(ie=>ie.path).join(", ")}`));let I=Fm(le),fe=$y(X),et=Ma(t,R,Be,Ee.articles,P,_.length,re,I,fe);console.log(m.dim(` Mode: ${Dl(t)}`));let zt=q(K.baseDir,"_tmp");Bt(zt,{recursive:!0});let Ne=q(zt,"absorb-prompt.txt");Ot(Ne,et),console.log(m.dim(` Compiling with Claude (${o})...`));let Ie={kind:"call",at:"",label:v,agent:R,model:o,entries:_.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:et.length,promptParts:{entries:P.length,catalog:et.length-Ma(t,R,Be,[],P,_.length,re,I,fe).length,catalogArticles:Ee.articles.length,covering:I.length,facts:re.length,worldview:Be.length,notes:fe.length},...X.length?{notes:X.length}:{}},ao=Date.now();Ie.prepMs=ao-O;try{let ie,Jo=!1;try{ie=bn(`cat '${Ne}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:$o(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(F){if(ie=F.stdout||"",!ie)throw F;Jo=!0}let En=ie;try{let F=JSON.parse(ie);Object.assign(Ie,ic(F)),F.is_error===!0&&(Jo=!0),En=F.result||F.content||"",En||(console.log(m.dim(` Claude envelope keys: ${Object.keys(F).join(", ")}`)),console.log(m.dim(` is_error: ${F.is_error}, stop_reason: ${F.stop_reason}`)))}catch{}let Rn=yy(En);if("error"in Rn){X.length>0&&console.log(m.yellow(` ${X.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Rn.error}`)),console.log(m.dim(` First 500 chars: ${En.slice(0,500)}`));continue}let{articles:xr,gaps:Cn}=Rn,Go=new Set,Ho=new Set,Tn=new Set(_.map(F=>F.id));for(let F of xr){let Le=new Date().toISOString().slice(0,10),mt=Array.isArray(F.sources)?F.sources:[],be=X.length>0?mt.filter(wo=>Tn.has(wo)):mt;if(X.length>0&&be.length===0){console.log(m.yellow(` ! refused ${F.path}: cites no entry from this batch; a wiki note only patches`)),Ie.refused++;continue}let tt=qm(F,Te);tt!==F.path&&(console.log(m.dim(` ~ ${F.path} \u2192 ${tt} (an article with this title exists)`)),F.path=tt);let je=K.readArticle(F.path);if(je){let wo=Ds(je.content,String(F.content??""));if(wo.length>0){console.log(m.yellow(` ! refused ${F.path}: the rewrite drops ${wo.length} fact(s) the article has`)),console.log(m.dim(` ${wo.slice(0,8).join("; ")}${wo.length>8?"; \u2026":""}`));for(let j$ of be)Go.add(j$);Ie.refused++;continue}}let ka=u(be,_)??je?.meta.graphPath;K.writeArticle(F.path,{title:F.title,type:F.type,related:Array.isArray(F.related)?F.related:void 0,tags:F.tags||[],owner:R,access:je?.meta.access??"public",sharedWith:je?.meta.sharedWith?.length?je.meta.sharedWith:void 0,created:je?.meta.created||Le,lastUpdated:Le,sources:[...new Set([...je?.meta.sources??[],...be])],graphPath:ka},F.content,R);let N$=F.type?m.magenta(`[${F.type}]`)+" ":"",I$=Array.isArray(F.related)&&F.related.length?` \u2192 ${F.related.slice(0,3).join(", ")}${F.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(je?"~":"+")} ${N$}${F.path}: ${F.title}${m.dim(I$)}`);let fd=(F.tags||[]).slice(0,4).join(", ");fd&&console.log(m.dim(` tags: ${fd}`)),ka?.length&&(console.log(m.dim(` graphPath: ${ka.join(" \u203A ")}`)),y++),h++,Ie.articles++;for(let wo of be)Ho.add(wo)}if(X.length>0&&!Jo){let F=X.filter(be=>{let tt=S.get(be.id);return tt&&tt.status!=="open"&&tt.status!=="deferred"?(console.log(m.dim(` note ${be.id} already ${tt.status} by ${tt.handled?.by??"another run"}; left as it is`)),!1):tt?.handled&&tt.handled.at>A?(console.log(m.dim(` note ${be.id} already deferred by ${tt.handled.by} during this run; left as it is`)),!1):!0}),Le=by(F,wy(Rn.notes),K,{agentId:R,paths:new Set(le.map(be=>be.path))}),mt=0;for(let be of Le){try{S.handle(be.id,be.outcome,be.reason,R,W),mt++}catch(je){console.log(m.yellow(` ! note ${be.id}: could not record ${be.outcome}: ${je?.message??je}`))}let tt=be.outcome==="patched"?m.green("~"):be.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${tt} note ${be.id} ${be.outcome}: ${m.dim(be.reason.slice(0,160))}`)}Ie.notesPatched=Le.filter(be=>be.outcome==="patched").length,Ie.notesRecorded=mt}else X.length>0&&console.log(m.yellow(` ${X.length} wiki note(s) stay waiting`));if(Ie.failed=Jo,Ie.heldCited=[...Go].filter(F=>Ho.has(F)).length,Jo)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let F=_.map(Le=>Le.id).filter(Le=>!Go.has(Le));Go.size>0&&console.log(m.yellow(` ${_.length-F.length} entries stay queued behind refused saves`)),n.markProcessed(R,F,xr.flatMap(Le=>Le.sources||[]).filter(Le=>!Go.has(Le)))}if(Cn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Cn.length} missing pieces):`));for(let F of Cn)console.log(m.yellow(` ? ${F}`));try{let{QuestionStore:F}=await import("./questions-ZATLU5AW.js"),Le=new F(ut(e.dir)).add(Cn.map(mt=>({kind:"article",agentId:R,path:"",subject:String(mt).slice(0,120),question:`No article yet for: ${String(mt).slice(0,160)}`})));Le.added>0&&console.log(m.dim(` queued ${Le.added} for follow-up (agentx wiki questions)`))}catch{}}K.rebuildIndex()}catch(ie){console.log(m.red(` Absorb failed: ${ie.message?.slice(0,200)}`)),ie.stderr&&console.log(m.dim(String(ie.stderr).slice(0,300))),ie.stdout&&console.log(m.dim("stdout: "+String(ie.stdout).slice(0,300)))}finally{Ie.at=new Date().toISOString(),Ie.wallMs=Date.now()-ao,Ie.failed&&$++,x(Ie)}}if(x({kind:"run",label:v,startedAt:A,endedAt:new Date().toISOString(),max:l,model:o,failed:$}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${c.length} agent(s)`)),g)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}$>0&&(console.log(m.red(` ${$} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});H.command("absorb-eval").description("score absorbed articles against the entries they cite").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's articles").option("--since <date>","only articles last updated on or after YYYY-MM-DD").option("--changed-after <time>","only articles whose file changed after this time (ISO, e.g. 2026-10-07T20:05:00Z)").option("--n <n>","articles in the sample","40").option("--seed <seed>","sample seed; the same seed picks the same articles","absorb-eval").option("--sample <file>","reuse the sample saved in this file, or save it there on first use").option("--judge","also ask a model to check each article's claims (one call per article)").option("--judge-model <model>","model for --judge","sonnet").option("--out <file>","write the scorecard as Markdown to this file").option("--json","print the scorecard and every article's checks as JSON").action(async e=>{let{pickSample:t,checkArticle:o,findDuplicates:n,buildJudgePrompt:s,parseJudgeReply:r,buildScorecard:i,renderScorecard:a,uncitedWithFacts:c}=await import("./absorb-eval-
|
|
546
|
+
`),re="";if(e.facts!==!1){let{extractHints:ie,resolveFacts:Jo,mergeRecords:En,renderFactsBlock:Rn,installPrompts:xr,defaultSources:Cn,recordsFromEntries:Go}=await import("./facts-ROUMKS7I.js");if(!f){let F=new Set;for(let Le of n.listAgents())for(let mt of n.getAgentWiki(Le).listArticles(Le))mt.meta.type==="person"&&F.add(mt.meta.title);f=[...F]}let Ho=ie(_.map(F=>({context:F.sourceContext,content:F.content,sender:typeof F.meta?.sender=="string"?F.meta.sender:void 0})),{known:f}),Tn=Go(_);if(Ho.length>0||Tn.length>0){let F=Cn(),{records:Le,results:mt}=Ho.length>0?await Jo(Ho,{sources:F}):{records:[],results:[]},be=En([...Tn,...Le]);re=Rn(be);let tt=[...Tn.length>0?[`entries:${Tn.length}`]:[],...mt.filter(je=>je.records.length>0).map(je=>`${je.source}:${je.records.length}`)];console.log(m.dim(` Facts: ${Ho.length} entities \u2192 ${be.length} resolved${tt.length?` (${tt.join(" ")})`:""}`));for(let je of xr(mt,F))console.log(m.yellow(` ! ${je.source} ${je.kind} \u2014 would supply ${je.provides.join(", ")}`)),console.log(m.dim(` ${je.hint}`))}}let Te=Ee.articles.filter(ie=>ie.path&&!ie.path.includes("/_versions/")),le=await Lm([..._,...X.map(ie=>({id:Rl(ie.id),content:ie.change}))],K,R,Te);le.length>0&&console.log(m.dim(` Existing: ${le.map(ie=>ie.path).join(", ")}`));let I=Fm(le),fe=$y(X),et=Ma(t,R,Be,Ee.articles,P,_.length,re,I,fe);console.log(m.dim(` Mode: ${Dl(t)}`));let zt=q(K.baseDir,"_tmp");Bt(zt,{recursive:!0});let Ne=q(zt,"absorb-prompt.txt");Ot(Ne,et),console.log(m.dim(` Compiling with Claude (${o})...`));let Ie={kind:"call",at:"",label:v,agent:R,model:o,entries:_.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:et.length,promptParts:{entries:P.length,catalog:et.length-Ma(t,R,Be,[],P,_.length,re,I,fe).length,catalogArticles:Ee.articles.length,covering:I.length,facts:re.length,worldview:Be.length,notes:fe.length},...X.length?{notes:X.length}:{}},ao=Date.now();Ie.prepMs=ao-O;try{let ie,Jo=!1;try{ie=bn(`cat '${Ne}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:$o(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(F){if(ie=F.stdout||"",!ie)throw F;Jo=!0}let En=ie;try{let F=JSON.parse(ie);Object.assign(Ie,ic(F)),F.is_error===!0&&(Jo=!0),En=F.result||F.content||"",En||(console.log(m.dim(` Claude envelope keys: ${Object.keys(F).join(", ")}`)),console.log(m.dim(` is_error: ${F.is_error}, stop_reason: ${F.stop_reason}`)))}catch{}let Rn=yy(En);if("error"in Rn){X.length>0&&console.log(m.yellow(` ${X.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Rn.error}`)),console.log(m.dim(` First 500 chars: ${En.slice(0,500)}`));continue}let{articles:xr,gaps:Cn}=Rn,Go=new Set,Ho=new Set,Tn=new Set(_.map(F=>F.id));for(let F of xr){let Le=new Date().toISOString().slice(0,10),mt=Array.isArray(F.sources)?F.sources:[],be=X.length>0?mt.filter(wo=>Tn.has(wo)):mt;if(X.length>0&&be.length===0){console.log(m.yellow(` ! refused ${F.path}: cites no entry from this batch; a wiki note only patches`)),Ie.refused++;continue}let tt=qm(F,Te);tt!==F.path&&(console.log(m.dim(` ~ ${F.path} \u2192 ${tt} (an article with this title exists)`)),F.path=tt);let je=K.readArticle(F.path);if(je){let wo=Ds(je.content,String(F.content??""));if(wo.length>0){console.log(m.yellow(` ! refused ${F.path}: the rewrite drops ${wo.length} fact(s) the article has`)),console.log(m.dim(` ${wo.slice(0,8).join("; ")}${wo.length>8?"; \u2026":""}`));for(let j$ of be)Go.add(j$);Ie.refused++;continue}}let ka=u(be,_)??je?.meta.graphPath;K.writeArticle(F.path,{title:F.title,type:F.type,related:Array.isArray(F.related)?F.related:void 0,tags:F.tags||[],owner:R,access:je?.meta.access??"public",sharedWith:je?.meta.sharedWith?.length?je.meta.sharedWith:void 0,created:je?.meta.created||Le,lastUpdated:Le,sources:[...new Set([...je?.meta.sources??[],...be])],graphPath:ka},F.content,R);let N$=F.type?m.magenta(`[${F.type}]`)+" ":"",I$=Array.isArray(F.related)&&F.related.length?` \u2192 ${F.related.slice(0,3).join(", ")}${F.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(je?"~":"+")} ${N$}${F.path}: ${F.title}${m.dim(I$)}`);let fd=(F.tags||[]).slice(0,4).join(", ");fd&&console.log(m.dim(` tags: ${fd}`)),ka?.length&&(console.log(m.dim(` graphPath: ${ka.join(" \u203A ")}`)),y++),h++,Ie.articles++;for(let wo of be)Ho.add(wo)}if(X.length>0&&!Jo){let F=X.filter(be=>{let tt=S.get(be.id);return tt&&tt.status!=="open"&&tt.status!=="deferred"?(console.log(m.dim(` note ${be.id} already ${tt.status} by ${tt.handled?.by??"another run"}; left as it is`)),!1):tt?.handled&&tt.handled.at>A?(console.log(m.dim(` note ${be.id} already deferred by ${tt.handled.by} during this run; left as it is`)),!1):!0}),Le=by(F,wy(Rn.notes),K,{agentId:R,paths:new Set(le.map(be=>be.path))}),mt=0;for(let be of Le){try{S.handle(be.id,be.outcome,be.reason,R,W),mt++}catch(je){console.log(m.yellow(` ! note ${be.id}: could not record ${be.outcome}: ${je?.message??je}`))}let tt=be.outcome==="patched"?m.green("~"):be.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${tt} note ${be.id} ${be.outcome}: ${m.dim(be.reason.slice(0,160))}`)}Ie.notesPatched=Le.filter(be=>be.outcome==="patched").length,Ie.notesRecorded=mt}else X.length>0&&console.log(m.yellow(` ${X.length} wiki note(s) stay waiting`));if(Ie.failed=Jo,Ie.heldCited=[...Go].filter(F=>Ho.has(F)).length,Jo)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let F=_.map(Le=>Le.id).filter(Le=>!Go.has(Le));Go.size>0&&console.log(m.yellow(` ${_.length-F.length} entries stay queued behind refused saves`)),n.markProcessed(R,F,xr.flatMap(Le=>Le.sources||[]).filter(Le=>!Go.has(Le)))}if(Cn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Cn.length} missing pieces):`));for(let F of Cn)console.log(m.yellow(` ? ${F}`));try{let{QuestionStore:F}=await import("./questions-ZATLU5AW.js"),Le=new F(ut(e.dir)).add(Cn.map(mt=>({kind:"article",agentId:R,path:"",subject:String(mt).slice(0,120),question:`No article yet for: ${String(mt).slice(0,160)}`})));Le.added>0&&console.log(m.dim(` queued ${Le.added} for follow-up (agentx wiki questions)`))}catch{}}K.rebuildIndex()}catch(ie){console.log(m.red(` Absorb failed: ${ie.message?.slice(0,200)}`)),ie.stderr&&console.log(m.dim(String(ie.stderr).slice(0,300))),ie.stdout&&console.log(m.dim("stdout: "+String(ie.stdout).slice(0,300)))}finally{Ie.at=new Date().toISOString(),Ie.wallMs=Date.now()-ao,Ie.failed&&$++,x(Ie)}}if(x({kind:"run",label:v,startedAt:A,endedAt:new Date().toISOString(),max:l,model:o,failed:$}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${c.length} agent(s)`)),g)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}$>0&&(console.log(m.red(` ${$} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});H.command("absorb-eval").description("score absorbed articles against the entries they cite").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's articles").option("--since <date>","only articles last updated on or after YYYY-MM-DD").option("--changed-after <time>","only articles whose file changed after this time (ISO, e.g. 2026-10-07T20:05:00Z)").option("--n <n>","articles in the sample","40").option("--seed <seed>","sample seed; the same seed picks the same articles","absorb-eval").option("--sample <file>","reuse the sample saved in this file, or save it there on first use").option("--judge","also ask a model to check each article's claims (one call per article)").option("--judge-model <model>","model for --judge","sonnet").option("--out <file>","write the scorecard as Markdown to this file").option("--json","print the scorecard and every article's checks as JSON").action(async e=>{let{pickSample:t,checkArticle:o,findDuplicates:n,buildJudgePrompt:s,parseJudgeReply:r,buildScorecard:i,renderScorecard:a,uncitedWithFacts:c}=await import("./absorb-eval-EVX7LDXR.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=we(e.dir,e.mode),d=e.agent?[e.agent]:g.listAgents(),f=typeof e.since=="string"?e.since.trim():"",p=typeof e.changedAfter=="string"&&e.changedAfter.trim()?new Date(e.changedAfter.trim()):null;if(p&&Number.isNaN(p.getTime())){console.log(m.red(` not a time: ${e.changedAfter}`)),process.exitCode=1;return}let u=p?p.toISOString().slice(0,19):f,h=new Map;for(let P of g.getSharedStore().listEntries())h.set(P.id,{id:P.id,date:P.date,content:P.content});let y=[];for(let P of d)for(let re of g.getAgentWiki(P).listArticles(P))y.push({key:`${P}/${re.path}`,agent:P,article:re});let $=new Map;for(let P of y)for(let re of P.article.meta.sources??[]){let Te=$.get(re);Te?Te.push(P.article.content):$.set(re,[P.article.content])}let b=P=>{if(!p)return!0;try{return vA(q(g.getAgentWiki(P.agent).baseDir,P.article.path)).mtimeMs>p.getTime()}catch{return!1}},v=y.filter(P=>!f||(P.article.meta.lastUpdated??"")>=f.slice(0,10)).filter(b),x=String(e.seed),A;if(e.sample&&Ke(e.sample)){let P=JSON.parse(Nt(e.sample,"utf-8"));x=P.seed??x;let re=new Map(y.map(le=>[le.key,le]));A=P.keys.map(le=>re.get(le)).filter(le=>!!le);let Te=P.keys.length-A.length;Te>0&&console.error(m.yellow(` ${Te} sampled article(s) no longer exist`))}else A=t(v.map(P=>({...P,path:P.key})),parseInt(e.n),x),e.sample&&(Ot(e.sample,`${JSON.stringify({seed:x,since:u||void 0,keys:A.map(P=>P.key)},null,2)}
|
|
547
547
|
`),console.error(m.dim(` sample saved to ${e.sample}`)));if(A.length===0){console.log(m.yellow(` no articles${u?` changed since ${u}`:""} to score`));return}let k=P=>P.replace(/^---\n[\s\S]*?\n---\n?/,""),S=P=>{let re=g.getAgentWiki(P.agent).getVersions(P.article.path),Te=u?re.filter(I=>I.timestamp>=u):re.slice(0,1),le=Te[Te.length-1];if(le)try{return k(Nt(le.path,"utf-8"))}catch{return}},R=A.map(P=>({path:P.key,title:P.article.meta.title,type:P.article.meta.type,content:P.article.content,sources:P.article.meta.sources??[],lastUpdated:P.article.meta.lastUpdated,previous:S(P)})),O=R.map(P=>o(P,h,re=>$.get(re)??[])),N=new Set(A.map(P=>P.key)),D=d.flatMap(P=>n(y.filter(re=>re.agent===P).map(re=>({path:re.key,title:re.article.meta.title,type:re.article.meta.type,sources:re.article.meta.sources})),N)),_=[];if(e.judge){let P;try{P=El(e.judgeModel)}catch(le){console.log(m.red(` ${le.message}`)),process.exitCode=1;return}let re=q(g.getBaseDir(),"_tmp");Bt(re,{recursive:!0});let Te=R.map((le,I)=>({a:le,i:I}));await Promise.all(Array.from({length:Math.min(3,Te.length)},async()=>{for(let le=Te.shift();le;le=Te.shift()){let{a:I,i:fe}=le,et=I.sources.map(Ne=>h.get(Ne)).filter(Ne=>!!Ne),zt=q(re,`absorb-eval-${process.pid}-${fe}.txt`);Ot(zt,s(I,et));try{let{stdout:Ne}=await My(`cat '${zt}' | claude -p - --output-format json --max-turns 1 --model '${P}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:$o(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),Ie=Ne;try{Ie=JSON.parse(Ne).result??Ne}catch{}let ao=r(l(Ie));ao?_.push({path:I.path,verdict:ao}):console.error(m.yellow(` judge reply for ${I.path} was not usable`))}catch(Ne){console.error(m.yellow(` judge failed for ${I.path}: ${String(Ne?.message??Ne).slice(0,160)}`))}finally{_l(zt,{force:!0})}}})),_.sort((le,I)=>le.path.localeCompare(I.path))}let J=new Set(y.flatMap(P=>P.article.meta.sources??[])),W=[];for(let P of d){let re=q(g.getBaseDir(),"agents",P,"_absorbed.json");if(!Ke(re))continue;let Te={};try{Te=JSON.parse(Nt(re,"utf-8")).entries??{}}catch{continue}for(let[le,I]of Object.entries(Te)){if(J.has(le)||u&&String(I.at??"")<u)continue;let fe=h.get(le);fe&&W.push(fe)}}let X=y.map(P=>P.article.content).join(`
|
|
548
|
-
`),K=c(W,X),Ee=i(O,D,{seed:x,since:u||void 0},_,5,{entries:W.length,lost:K}),Be=a(Ee);e.out&&Ot(e.out,Be),e.json?console.log(JSON.stringify({card:Ee,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Be)});H.command("query-runs").description("count wiki queries by outcome, with timing").option("--dir <path>","wiki directory").option("--since <date>","only queries on or after this date or time (ISO)").option("--json","print the summary as JSON").action(async e=>{let{QUERY_RUNS_FILE:t,summariseQueryRuns:o}=await import("./query-runs-VXS572PQ.js"),n=q(ut(e.dir),t);if(!Ke(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Nt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,c)=>c[1]-a[1]))console.log(` ${r.padEnd(14)} ${i}`);console.log(m.dim(` from: ${Object.entries(s.bySource).map(([r,i])=>`${r} ${i}`).join(" \xB7 ")}`)),console.log()});H.command("absorb-runs").description("time, cost and throughput of absorb runs, grouped by --run-label").option("--dir <path>","wiki directory").option("--label <label>","only this run label").option("--json","print the summary as JSON").action(async e=>{let{summariseRuns:t}=await import("./absorb-eval-
|
|
549
|
-
`).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}).filter(c=>!e.label||(c.label||"(none)")===e.label),s=t(n);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(m.yellow(" no matching runs"));return}let r=[["label",c=>c.label],["calls",c=>`${c.calls}${c.failed?` (${c.failed} failed)`:""}`],["entries",c=>String(c.entries)],["articles",c=>`${c.articles}${c.refused?` (${c.refused} refused${c.heldCited?`, ${c.heldCited} held entries lost`:""})`:""}`],["wall",c=>`${(c.wallMs/6e4).toFixed(1)} min`],["call p50/p95",c=>`${Math.round(c.callMsP50/1e3)}/${Math.round(c.callMsP95/1e3)} s`],["entries/min",c=>c.entriesPerMinute.toFixed(1)],["prep",c=>`${(c.prepMs/6e4).toFixed(1)} min`],["cost",c=>`$${c.costUsd.toFixed(2)}`],["$/entry",c=>`$${c.costPerEntry.toFixed(3)}`]],i=s.map(c=>r.map(([,l])=>l(c))),a=r.map(([c],l)=>Math.max(c.length,...i.map(g=>g[l].length)));console.log(),console.log(m.bold(r.map(([c],l)=>c.padEnd(a[l])).join(" ")));for(let c of i)console.log(c.map((l,g)=>l.padEnd(a[g])).join(" "));console.log()});H.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=AA(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-
|
|
548
|
+
`),K=c(W,X),Ee=i(O,D,{seed:x,since:u||void 0},_,5,{entries:W.length,lost:K}),Be=a(Ee);e.out&&Ot(e.out,Be),e.json?console.log(JSON.stringify({card:Ee,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Be)});H.command("query-runs").description("count wiki queries by outcome, with timing").option("--dir <path>","wiki directory").option("--since <date>","only queries on or after this date or time (ISO)").option("--json","print the summary as JSON").action(async e=>{let{QUERY_RUNS_FILE:t,summariseQueryRuns:o}=await import("./query-runs-VXS572PQ.js"),n=q(ut(e.dir),t);if(!Ke(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Nt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,c)=>c[1]-a[1]))console.log(` ${r.padEnd(14)} ${i}`);console.log(m.dim(` from: ${Object.entries(s.bySource).map(([r,i])=>`${r} ${i}`).join(" \xB7 ")}`)),console.log()});H.command("absorb-runs").description("time, cost and throughput of absorb runs, grouped by --run-label").option("--dir <path>","wiki directory").option("--label <label>","only this run label").option("--json","print the summary as JSON").action(async e=>{let{summariseRuns:t}=await import("./absorb-eval-EVX7LDXR.js"),o=q(ut(e.dir),"_absorb-runs.jsonl");if(!Ke(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Nt(o,"utf-8").split(`
|
|
549
|
+
`).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}).filter(c=>!e.label||(c.label||"(none)")===e.label),s=t(n);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(m.yellow(" no matching runs"));return}let r=[["label",c=>c.label],["calls",c=>`${c.calls}${c.failed?` (${c.failed} failed)`:""}`],["entries",c=>String(c.entries)],["articles",c=>`${c.articles}${c.refused?` (${c.refused} refused${c.heldCited?`, ${c.heldCited} held entries lost`:""})`:""}`],["wall",c=>`${(c.wallMs/6e4).toFixed(1)} min`],["call p50/p95",c=>`${Math.round(c.callMsP50/1e3)}/${Math.round(c.callMsP95/1e3)} s`],["entries/min",c=>c.entriesPerMinute.toFixed(1)],["prep",c=>`${(c.prepMs/6e4).toFixed(1)} min`],["cost",c=>`$${c.costUsd.toFixed(2)}`],["$/entry",c=>`$${c.costPerEntry.toFixed(3)}`]],i=s.map(c=>r.map(([,l])=>l(c))),a=r.map(([c],l)=>Math.max(c.length,...i.map(g=>g[l].length)));console.log(),console.log(m.bold(r.map(([c],l)=>c.padEnd(a[l])).join(" ")));for(let c of i)console.log(c.map((l,g)=>l.padEnd(a[g])).join(" "));console.log()});H.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=AA(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-LPZWOR2K.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Ke(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));r=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let f=r.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${r.length} candidate finding(s), ${f} seen in more than one session`));let p=r[0];p&&(p.occurrences??1)>1&&console.log(m.dim(` most recurrent (${p.occurrences} sessions): ${p.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-NQX2JMMS.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Ke(d))console.log(m.yellow(` --failures: no ${d}`));else{let f=new g(d,{readonly:!0});try{let p=c(f,{since:Date.now()-(t??6048e5)}),u=l(p,{minSessions:a});console.log(m.dim(` ${p.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let h=u[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),r=[...r,...u]}finally{f.close()}}}let i=await Tg({extraCandidates:r,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(i.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${i.candidates.length} candidate(s) in ${i.clusters.length} cluster(s):`);for(let a of i.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),i.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of i.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of i.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(i.gaps.length){console.log(),console.log(m.yellow(` Gaps (${i.gaps.length}):`));for(let a of i.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of i.warnings)console.log(m.dim(` ! ${a}`));for(let a of i.errors)console.log(m.red(` x ${a}`));console.log(),console.log(i.errors.length?m.red(` ${i.proposed.length} proposed, ${i.errors.length} error(s)`):m.green(` ${i.proposed.length} proposed, ${i.skipped.length} skipped`)),i.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),i.errors.length&&process.exit(1)});var Qi=H.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Zi(e){return e?q(e):q(process.cwd(),".agentx","wiki")}Qi.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Zi(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,r=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",i=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${r}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${i}`))}});Qi.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Zi(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
550
550
|
`).map(s=>` ${s}`).join(`
|
|
551
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Qi.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-
|
|
551
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Qi.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-VD4OVQGL.js"),n=o(Zi(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Qi.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-VD4OVQGL.js"),n=o(Zi(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function AA(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}H.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",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-5CPK6G2H.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=we(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=r(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let f=[],p=o(d).sort().reverse();for(let y of p){let $=i(d,y),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(f.length>=g)break;try{let x=JSON.parse(n(i($,v),"utf-8")),A=x.message||x.task?.message;typeof A=="string"&&A.trim().length>10&&f.push({id:x.id||v.replace(".json",""),message:A.trim(),ts:x.at||x.timestamp||y})}catch{}}if(f.length>=g)break}if(f.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${f.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${f.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<f.length;y++){let $=f[y];process.stdout.write(m.dim(` [${y+1}/${f.length}] querying... `));let v=l.findRelevant($.message,c,3).map(A=>`- **${A.meta.title}** [${A.meta.type||"?"}] (${A.path})`).join(`
|
|
552
552
|
`)||"_(none returned)_",x;try{let A=await t($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(A.status!=="ok")x=`_(status: ${A.status}${A.error?" \u2014 "+A.error:""})_`;else{let k=A.citations.map(S=>`\`${S.title}\` [${S.type||"?"}]`).join(", ");x=`**Answer:**
|
|
553
553
|
|
|
554
554
|
${A.answer}
|
|
@@ -565,14 +565,14 @@ Q: ${I.q}
|
|
|
565
565
|
A: ${I.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(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(`
|
|
566
566
|
`),x=q(a.baseDir,"_tmp");Bt(x,{recursive:!0});let A=q(x,`interview-${o().slice(0,8)}.txt`);Ot(A,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let k="";try{let I=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=bn(I,{env:$o(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let et=JSON.parse(fe);k=String(et.result||et.content||"")}catch{k=fe}}catch(I){console.log(m.red(` synthesis failed: ${I.message?.slice(0,200)}`)),c?.close();return}k=k.trim();let S=k.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);S&&(k=S[1].trim());let R=k.indexOf("---");R>0&&(k=k.slice(R));let O=k.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!O){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(k.slice(0,600)),c?.close();return}let N={};for(let I of O[1].split(`
|
|
567
567
|
`)){let fe=I.match(/^(\w+):\s*(.+)$/);fe&&(N[fe[1]]=fe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=O[2],_=N.title||g,J=_.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),X=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${J}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${X}`)),console.log(),console.log(k),console.log();let K=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),K==="scrap"||K==="/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 ${A} (prompt only; no article file)`));return}let Ee=D,Be={title:_,type:N.type||d,related:N.related?N.related.replace(/^\[|\]$/g,"").split(",").map(I=>I.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:N.tags?N.tags.replace(/^\[|\]$/g,"").split(",").map(I=>I.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:N.access||"public",created:N.created||new Date().toISOString().slice(0,10),lastUpdated:N.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(K==="edit"){let I=process.env.EDITOR||"vi",fe=q(x,`draft-${o().slice(0,8)}.md`);Ot(fe,k);try{bn(`${I} '${fe}'`,{stdio:"inherit"});let zt=Nt(fe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(zt){let Ne={};for(let Ie of zt[1].split(`
|
|
568
|
-
`)){let ao=Ie.match(/^(\w+):\s*(.+)$/);ao&&(Ne[ao[1]]=ao[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=zt[2],Be={...Be,title:Ne.title||Be.title,type:Ne.type||Be.type,access:Ne.access||Be.access,related:Ne.related?Ne.related.replace(/^\[|\]$/g,"").split(",").map(Ie=>Ie.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Be.related,tags:Ne.tags?Ne.tags.replace(/^\[|\]$/g,"").split(",").map(Ie=>Ie.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Be.tags}}}catch(et){console.log(m.red(` editor failed: ${et.message}`));return}}if(!a.writeArticle(X,Be,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${X} saved.`));let re=a.extractWikilinks(Ee),Te=new Map;for(let I of a.listArticles(e.agent))Te.set(I.meta.title.toLowerCase(),!0);let le=re.filter(I=>!Te.has(I.toLowerCase()));if(le.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let I of le.slice(0,8))console.log(m.dim(` - ${I}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});H.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-
|
|
568
|
+
`)){let ao=Ie.match(/^(\w+):\s*(.+)$/);ao&&(Ne[ao[1]]=ao[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=zt[2],Be={...Be,title:Ne.title||Be.title,type:Ne.type||Be.type,access:Ne.access||Be.access,related:Ne.related?Ne.related.replace(/^\[|\]$/g,"").split(",").map(Ie=>Ie.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Be.related,tags:Ne.tags?Ne.tags.replace(/^\[|\]$/g,"").split(",").map(Ie=>Ie.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Be.tags}}}catch(et){console.log(m.red(` editor failed: ${et.message}`));return}}if(!a.writeArticle(X,Be,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${X} saved.`));let re=a.extractWikilinks(Ee),Te=new Map;for(let I of a.listArticles(e.agent))Te.set(I.meta.title.toLowerCase(),!0);let le=re.filter(I=>!Te.has(I.toLowerCase()));if(le.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let I of le.slice(0,8))console.log(m.dim(` - ${I}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});H.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-5CPK6G2H.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=we(e.dir);if(e.commit!==!1&&kn(s,e.agent))return;let r;try{r=s.getAgentWiki(e.agent)}catch(p){console.log(m.red(` can't open wiki for agent "${e.agent}": ${p.message}`));return}let i=null;if(e.script){let u=Nt(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);i=[];for(let h of u){let y=h.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&i.push({q:$,verdict:b})}}let a=i?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async p=>a?(await a.question(p)).trim():"",l=Math.min(parseInt(e.rounds)||20,i?.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 ${i?`scripted (${i.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],f=0;for(let p=0;p<l;p++){let u,h;if(i){let W=i[p];if(!W)break;u=W.q,h=W.verdict,console.log(m.cyan(` [${p+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${p+1}] Q: `)),!u||u==="/done"||u==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,r,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(W){console.log(m.red(`failed: ${W.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let W=y.citations.map(X=>`${X.title} [${X.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
569
569
|
`)),console.log(m.dim(" citations: "+W))}i||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let $={q:u,answer:y.answer,citations:y.citations,verdict:h},b=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push($);continue}let v=b[1].toLowerCase(),x=(b[2]||"").trim();if(d.push($),v==="/ok"||v==="/skip")continue;if(!x){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let A=y.citations[0];if(!A){console.log(m.yellow(" no cited article to patch."));continue}let k=r.readArticle(A.path);if(!k){console.log(m.red(` can't read ${A.path} to patch.`));continue}console.log(m.dim(` patching ${A.title} (${A.path})...`));let S=TA(k.content,v,x,k.meta.title,k.meta.type),R=q(r.baseDir,"_tmp");Bt(R,{recursive:!0});let O=q(R,`quiz-patch-${o().slice(0,8)}.txt`);Ot(O,S);let N="";try{let W=`cat '${O}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,X=bn(W,{env:$o(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ee=JSON.parse(X);N=String(Ee.result||Ee.content||"")}catch{N=X}let K=N.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);K&&(N=K[1].trim()),N=N.trim()}catch(W){console.log(m.red(` patch failed: ${W.message?.slice(0,120)}`));continue}if(!N||N.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=k.content.split(`
|
|
570
570
|
`).length,_=N.split(`
|
|
571
571
|
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${_} lines (${_-D>=0?"+":""}${_-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=A.path+" (dry)";continue}if(!r.writeArticle(A.path,{...k.meta,lastUpdated:new Date().toISOString().slice(0,10)},N,e.agent)){console.log(m.red(" write failed (permission?)"));continue}f++,$.patched=A.path,console.log(m.green(` \u2713 patched ${A.path}`))}if(a&&a.close(),f>0&&g&&r.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${f} patches applied.`)),e.out){let p=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${f} patches_`,""];for(let u=0;u<d.length;u++){let h=d[u];p.push(`## ${u+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}Ot(e.out,p.join(`
|
|
572
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});H.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=we(o.dir);if(kn(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let r=dr(s,t,e);if(!r){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let i=q(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{bn(`${a} '${i}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(r);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),d=c.meta.related||[];(g.some(p=>!d.includes(p))||d.some(p=>!g.includes(p)))&&(s.writeArticle(r,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${r} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});async function EA(){let{loadDaemonConfig:e}=await import("./config-
|
|
572
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});H.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=we(o.dir);if(kn(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let r=dr(s,t,e);if(!r){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let i=q(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{bn(`${a} '${i}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(r);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),d=c.meta.related||[];(g.some(p=>!d.includes(p))||d.some(p=>!g.includes(p)))&&(s.writeArticle(r,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${r} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});async function EA(){let{loadDaemonConfig:e}=await import("./config-FZTWI3VG.js"),t=e(),o=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",n={"Content-Type":"application/json"};return t.dashboard?.token&&(n.Authorization=`Bearer ${t.dashboard.token}`),{url:o,headers:n}}function RA(e){console.log(m.bold(` Page changed: +${e.added} / \u2212${e.removed} lines`));for(let t of e.diff||[]){let o=` ${t.op===" "?" ":t.op} ${t.text}`;console.log(t.op==="+"?m.green(o):t.op==="-"?m.red(o):m.dim(o))}if(e.sources?.length){console.log(m.bold(" Sources"));for(let t of e.sources)console.log(` - ${t}`)}else console.log(m.yellow(" No sources were cited for this change."));e.version&&console.log(m.dim(` Undo: agentx wiki restore <agent> <page> ${e.version}`))}H.command("curate <agent> <titleOrPath> <instruction>").description("ask the page curator agent to research and edit one page (needs the daemon)").option("--dir <path>","wiki directory").option("--timeout <minutes>","stop waiting after this long","30").action(async(e,t,o,n)=>{let s=we(n.dir);if(kn(s,e))return;let r=dr(s.getAgentWiki(e),t,e);if(!r){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let{url:i,headers:a}=await EA(),c=async(f,p,u)=>{let h=await fetch(i+p,{method:f,headers:a,...u?{body:JSON.stringify(u)}:{}}),y=await h.json().catch(()=>({}));if(!h.ok)throw new Error(y.error||`HTTP ${h.status}`);return y},l;try{l=await c("POST","/api/wiki/curate",{agent:e,path:r,message:o})}catch(f){console.log(m.red(` ${f.message?.includes("fetch failed")?`the daemon at ${i} is not running`:f.message}`)),process.exitCode=1;return}console.log(m.dim(` ${l.curator} is working on ${r}\u2026`));let g=`?agent=${encodeURIComponent(e)}&path=${encodeURIComponent(r)}`,d=Date.now()+Number(n.timeout||30)*6e4;for(;Date.now()<d;){await new Promise(u=>setTimeout(u,2e3));let p=(await c("GET",`/api/wiki/curate${g}`).catch(()=>null))?.messages?.find(u=>u.id===l.id);if(!(!p||p.status==="pending")){console.log(p.status==="error"?m.red(` ${p.text}`):` ${p.text}`),p.edit&&(p.edit.added||p.edit.removed)&&RA(p.edit),p.status==="error"&&(process.exitCode=1);return}}console.log(m.yellow(" still working; the result will show in the chat on the page."))});H.command("versions <agent> <titleOrPath>").description("list the saved earlier versions of one page, newest first").option("--dir <path>","wiki directory").action((e,t,o)=>{let n=we(o.dir).getAgentWiki(e),s=dr(n,t,e);if(!s){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let r=n.getVersions(s);if(!r.length){console.log(m.dim(` ${s} has no earlier versions.`));return}console.log(m.bold(` ${s}`));for(let i of r)console.log(` ${i.timestamp}`)});H.command("restore <agent> <titleOrPath> [version]").description("put a page back to an earlier version (default: the newest); the current text is kept as a version").option("--dir <path>","wiki directory").action((e,t,o,n)=>{let s=we(n.dir);if(kn(s,e))return;let r=s.getAgentWiki(e),i=dr(r,t,e);if(!i){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let a=o||r.getVersions(i)[0]?.timestamp,c=!1;try{c=!!a&&r.restoreVersion(i,a)}catch(l){if(!(l instanceof Wd))throw l;console.log(m.red(` ${i} was not restored: the page was busy; run again.`)),process.exitCode=1;return}if(!c){console.log(m.red(` no version ${a?`"${a}" `:""}of ${i}; see agentx wiki versions ${e} "${t}"`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${i} restored to ${a}.`))});H.command("curator").description("show or change the page curator: the chat bubble on wiki pages").option("--on","show the bubble on wiki pages").option("--off","hide the bubble and refuse curator requests").option("--agent <id>","agent that answers on every page").option("--owner","let each page's owner agent answer (the default)").action(async e=>{if(e.on&&e.off){console.log(m.red(" pick --on or --off, not both")),process.exitCode=1;return}if(e.agent&&e.owner){console.log(m.red(" pick --agent or --owner, not both")),process.exitCode=1;return}let{loadDaemonConfig:t}=await import("./config-FZTWI3VG.js");if(e.on||e.off||e.agent||e.owner){if(e.agent&&!Object.keys(t().agents||{}).includes(e.agent)){console.log(m.red(` no agent "${e.agent}" in agentx.json`)),process.exitCode=1;return}let{mutateAgentxConfig:n}=await import("./config-mutate-X5IKMROK.js");n(s=>(s.wiki=s.wiki||{},s.wiki.curator=s.wiki.curator||{},e.on&&(s.wiki.curator.enabled=!0),e.off&&(s.wiki.curator.enabled=!1),e.agent&&(s.wiki.curator.agent=e.agent),e.owner&&delete s.wiki.curator.agent,"wiki.curator updated"))}let o=t().wiki?.curator??{enabled:!0};console.log(` Page curator: ${o.enabled?m.green("on"):m.yellow("off")}`),console.log(` Answers: ${o.agent?o.agent:"each page's owner agent"}`)});H.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").option("--allow-fact-loss","save even when the patch shrinks the article or drops a phone number, email, role, link or number it had").action(async(e,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:r}=await import("node:crypto"),i=we(n.dir);if(kn(i,e))return;let a;try{a=i.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=dr(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=CA(l.content,l.meta.title,l.meta.type,o),d=q(a.baseDir,"_tmp");Bt(d,{recursive:!0});let f=q(d,`patch-${r().slice(0,8)}.txt`);Ot(f,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let p="";try{let x=`cat '${f}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,A=bn(x,{env:$o(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let S=JSON.parse(A);p=String(S.result||S.content||"")}catch{p=A}let k=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(p=k[1].trim()),p=p.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=l.content.split(`
|
|
573
573
|
`).length,h=p.split(`
|
|
574
|
-
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${h} lines (${h-u>=0?"+":""}${h-u})`)),console.log(),console.log(p),console.log();let y=Um(l.content,p);if(y.length){for(let x of y)console.log(m.yellow(` ! ${x}`));if(n.commit&&!n.allowFactLoss){console.log(m.yellow(" not saved. If this change is intended, run again with --allow-fact-loss.")),process.exitCode=1;return}}if(!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let $=!!n.yes;if(!$){let x=s.createInterface({input:process.stdin,output:process.stdout}),A=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),$=A==="y"||A==="yes"}if(!$){console.log(m.dim(" aborted."));return}if(a.readArticle(c)?.content!==l.content){console.log(m.yellow(` ${c} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let b=[...new Set([...l.meta.related||[],...a.extractWikilinks(p)])];if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},p,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${c} patched.`))});var _y=H.command("contribute").description("queue sourced wiki patches from an agent's work since its last run (enable, disable)").option("--dir <path>","wiki directory").option("--agent <id>","contribute for this agent").option("--all","every agent with wiki.contribute.enabled in agentx.json").option("--since <time>","first run only: read work from this date or time (default: the last 24 hours)").option("--max-patches <n>","patches per agent per run (default: the agent's setting, else 30)").option("--max-cost <usd>","model spend per agent per run, in USD (default: the agent's setting, else wiki.contributions.maxCostUsd, else 0.5)").option("--max-items <n>","chat entries and tasks read per agent per run","60").option("--model <model>","model (default: the agent's setting, else wiki.contributions.model, else sonnet)").option("--db <path>","trace database with the agents' task runs",".agentx/db.sqlite").option("--dry-run","show the patches without queueing them or moving the cursor").option("--json","print the batches as JSON").action(async e=>{let{runContribution:t}=await import("./contributions-
|
|
575
|
-
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});lr.command("approve <id>").description("apply a held patch as it is").option("--dir <path>","wiki directory").action(async(e,t)=>{let{approveHeld:o}=await import("./contributions-
|
|
574
|
+
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${h} lines (${h-u>=0?"+":""}${h-u})`)),console.log(),console.log(p),console.log();let y=Um(l.content,p);if(y.length){for(let x of y)console.log(m.yellow(` ! ${x}`));if(n.commit&&!n.allowFactLoss){console.log(m.yellow(" not saved. If this change is intended, run again with --allow-fact-loss.")),process.exitCode=1;return}}if(!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let $=!!n.yes;if(!$){let x=s.createInterface({input:process.stdin,output:process.stdout}),A=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),$=A==="y"||A==="yes"}if(!$){console.log(m.dim(" aborted."));return}if(a.readArticle(c)?.content!==l.content){console.log(m.yellow(` ${c} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let b=[...new Set([...l.meta.related||[],...a.extractWikilinks(p)])];if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},p,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${c} patched.`))});var _y=H.command("contribute").description("queue sourced wiki patches from an agent's work since its last run (enable, disable)").option("--dir <path>","wiki directory").option("--agent <id>","contribute for this agent").option("--all","every agent with wiki.contribute.enabled in agentx.json").option("--since <time>","first run only: read work from this date or time (default: the last 24 hours)").option("--max-patches <n>","patches per agent per run (default: the agent's setting, else 30)").option("--max-cost <usd>","model spend per agent per run, in USD (default: the agent's setting, else wiki.contributions.maxCostUsd, else 0.5)").option("--max-items <n>","chat entries and tasks read per agent per run","60").option("--model <model>","model (default: the agent's setting, else wiki.contributions.model, else sonnet)").option("--db <path>","trace database with the agents' task runs",".agentx/db.sqlite").option("--dry-run","show the patches without queueing them or moving the cursor").option("--json","print the batches as JSON").action(async e=>{let{runContribution:t}=await import("./contributions-KHGGVSR6.js"),o=we(e.dir),n=ut(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-FZTWI3VG.js"),f=d();s=Object.fromEntries(Object.entries(f.agents||{}).map(([p,u])=>[p,u.wiki?.contribute])),r=f.wiki.contributions}catch{}let i=e.agent?[e.agent]:e.all?Object.keys(s).filter(d=>s[d]?.enabled).sort():[];if(i.length===0){console.log(m.yellow(e.all?" No agent has wiki.contribute.enabled. Turn one on with `agentx wiki contribute enable <agent>`.":" Name an agent with --agent <id>, or use --all.")),e.all||(process.exitCode=1);return}let a,c=q(process.cwd(),e.db);if(Ke(c)){let d=(await import("better-sqlite3")).default;a=new d(c,{readonly:!0})}else e.json||console.log(m.dim(` no trace database at ${c}; reading chat turns only`));let l=d=>async(f,p)=>{let u=q(n,"_tmp");Bt(u,{recursive:!0});let h=q(u,`contribute-${process.pid}-${Date.now()}.txt`);Ot(h,f);try{let{stdout:y}=await My(`cat '${h}' | claude -p - --output-format json --max-turns 1 --max-budget-usd ${p.toFixed(2)} --model ${d} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:$o(),timeout:18e4,maxBuffer:4194304});try{let $=JSON.parse(y);return{text:String($.result||$.content||""),costUsd:ic($).costUsd}}catch{return{text:y}}}finally{_l(h,{force:!0})}},g=[];try{for(let d of i){if(kn(o,d))continue;let f=s[d],p=e.model||f?.model||r.model||process.env.AGENTX_WIKI_CONTRIBUTE_MODEL||"sonnet";try{let u=await t(o,n,d,{model:p,call:l(p),db:a,since:e.since,dryRun:!!e.dryRun,maxPatches:e.maxPatches?parseInt(e.maxPatches):f?.maxPatches,maxCostUsd:e.maxCost?parseFloat(e.maxCost):f?.maxCostUsd??r.maxCostUsd,maxItems:parseInt(e.maxItems)});if(g.push(u),e.json)continue;let h=u.stoppedBy?m.yellow(` \xB7 stopped at ${u.stoppedBy}`):"";console.log(` ${m.cyan(d)}: ${u.patches.length} patch(es) from ${u.workIds.length} item(s) of work \xB7 $${u.costUsd.toFixed(4)}${h}${e.dryRun?m.dim(" \xB7 dry run, not queued"):""}`);for(let y of u.patches){let $=y.attribute?`${y.attribute}: ${y.previous?`${y.previous} \u2192 `:""}${y.value??""}`:y.summary??"";console.log(m.dim(` ${y.kind.padEnd(8)} ${y.page} \xB7 ${$} (${y.source}, ${y.checkedAt.slice(0,10)})`))}}catch(u){console.log(m.red(` ${d}: ${u.message?.slice(0,200)}`)),process.exitCode=1}}}finally{a?.close()}e.json?console.log(JSON.stringify(g,null,2)):!e.dryRun&&g.some(d=>d.patches.length)&&console.log(m.dim(" queued; `agentx wiki contributions merge` applies them."))});for(let[e,t]of[["enable",!0],["disable",!1]])_y.command(`${e} <agent>`).description(t?"turn on an agent's daily wiki contribution in agentx.json":"turn off an agent's daily wiki contribution").option("--max-cost <usd>","model spend per run, in USD").option("--max-patches <n>","patches per run").option("-c, --config <path>","path to agentx.json").action(async(o,n)=>{let{applyConfigMutation:s}=await import("./config-mutator-C5BMIBZO.js"),r=await s(i=>{let a=i.agents?.[o];if(!a)throw new Error(`no agent "${o}" in agentx.json`);a.wiki??={},a.wiki.contribute??={},a.wiki.contribute.enabled=t;let c={..._y.opts(),...n};c.maxCost&&(a.wiki.contribute.maxCostUsd=parseFloat(c.maxCost)),c.maxPatches&&(a.wiki.contribute.maxPatches=parseInt(c.maxPatches))},{configPath:n.config});if(!r.success){console.log(m.red(` \u2717 ${r.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${o}: daily wiki contribution ${t?"on":"off"}`)),t&&console.log(m.dim(" The daily jobs wiki-contribute and wiki-contribute-merge now show in `agentx schedule list`."))});var lr=H.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");lr.command("list",{isDefault:!0}).description("patches waiting for the merge, and what the last merge did").option("--dir <path>","wiki directory").option("--json").action(async e=>{let{listPendingBatches:t,latestReport:o,listHeld:n}=await import("./contributions-KHGGVSR6.js"),s=ut(e.dir),r=t(s),i=o(s),a=n(s);if(e.json){console.log(JSON.stringify({pending:r,lastMerge:i,held:a.length},null,2));return}console.log(),console.log(m.bold(` Waiting for the merge: ${r.reduce((c,l)=>c+l.patches.length,0)} patch(es) in ${r.length} batch(es)`));for(let c of r)console.log(m.dim(` ${c.agentId} \xB7 ${c.runAt.slice(0,16)} \xB7 ${c.patches.length} patch(es) \xB7 $${c.costUsd.toFixed(4)}`));i?(console.log(m.bold(` Last merge ${i.at.slice(0,16)}:`)+` ${i.applied.length} fact(s) applied, ${i.pagesUpdated.length} page(s) updated, ${i.pagesCreated.length} created, ${i.contradictions.length} contradiction(s), ${i.held.length} held`),i.duplicates.length&&console.log(m.yellow(` ${i.duplicates.length} subject(s) have more than one page: ${i.duplicates.slice(0,5).map(c=>c.title).join(", ")}${i.duplicates.length>5?", \u2026":""}`))):console.log(m.dim(" No merge has run yet.")),a.length&&console.log(m.yellow(` ${a.length} patch(es) held for a person: agentx wiki contributions held`)),console.log()});lr.command("merge").description("apply the queued patches: newest checked fact wins, fact-losing changes are held").option("--dir <path>","wiki directory").option("--dry-run","show what would change without writing").option("--json","print the report as JSON").action(async e=>{let{mergeContributions:t}=await import("./contributions-KHGGVSR6.js"),o=t(we(e.dir),ut(e.dir),{dryRun:!!e.dryRun,log:n=>console.error(n)});if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.batches.length===0){console.log(m.dim(" Nothing to merge.")),console.log();return}console.log(m.bold(` ${o.patches} patch(es) from ${o.agents.join(", ")}${o.dryRun?m.dim(" (dry run, nothing written)"):""}`)),console.log(` ${o.applied.length} fact(s) applied \xB7 ${o.pagesUpdated.length} page(s) updated \xB7 ${o.pagesCreated.length} page(s) created`);for(let n of o.pagesCreated)console.log(m.green(` + ${n}`));for(let n of o.pagesUpdated)console.log(m.dim(` ~ ${n}`));for(let n of o.contradictions)console.log(m.yellow(` ? ${n.page} \xB7 ${n.attribute}: ${n.by} reports "${n.value}" with an older check than the wiki's; a person is asked${n.questionId?` (${n.questionId})`:""}`));for(let n of o.held)console.log(m.yellow(` ! held ${n.id} \xB7 ${n.page}${n.attribute?` \xB7 ${n.attribute}`:""} from ${n.by}: ${n.reason}${n.lost?.length?` (${n.lost.slice(0,4).join(", ")})`:""}`));for(let n of o.duplicates.slice(0,10))console.log(m.yellow(` = ${n.title}: ${n.pages.join(" \xB7 ")}`));console.log()});lr.command("held").description("patches the merge held for a person, with the reason").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(async e=>{let{listHeld:t}=await import("./contributions-KHGGVSR6.js"),o=t(ut(e.dir),{all:!!e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&console.log(m.dim(" Nothing held."));for(let n of o){let s=n.patch,r=n.status==="held"?"":m.dim(` [${n.status}]`);console.log(` ${m.bold(n.id)}${r} \xB7 ${m.cyan(s.agentId)} \xB7 ${s.kind} \xB7 ${s.page}${s.attribute?` \xB7 ${s.attribute}`:""}${s.value?`: ${s.value}`:""}`),console.log(m.dim(` ${n.reason}${n.lost?.length?`: ${n.lost.join(", ")}`:""} \xB7 source: ${s.source}, checked ${s.checkedAt.slice(0,10)}`))}o.some(n=>n.status==="held")&&console.log(m.dim(`
|
|
575
|
+
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});lr.command("approve <id>").description("apply a held patch as it is").option("--dir <path>","wiki directory").action(async(e,t)=>{let{approveHeld:o}=await import("./contributions-KHGGVSR6.js"),n=o(we(t.dir),ut(t.dir),e,{by:process.env.USER||"operator"});if(!n.ok){console.log(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} applied${n.page?` to ${n.page}`:""}. The page's previous version is kept.`))});lr.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-KHGGVSR6.js"),n=o(ut(t.dir),e,{by:process.env.USER||"operator"});if(!n.ok){console.log(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected.`))});function dr(e,t,o){let n=t.trim(),s=e.listArticles(o),r=n.toLowerCase(),i=s.find(l=>l.meta.title.toLowerCase()===r);if(i)return i.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function CA(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
|
|
576
576
|
`)}function TA(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
|
|
577
577
|
|
|
578
578
|
${o}
|
|
@@ -627,17 +627,17 @@ Output (JSON array, one entry per input article, same order):
|
|
|
627
627
|
[
|
|
628
628
|
{"path": "path/to/article.md", "type": "project"},
|
|
629
629
|
...
|
|
630
|
-
]`}H.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=we(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()});H.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 t=e.dir||q(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await Ly(e.peer),s=n.map(r=>r.url);console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),s.length>0&&console.log(` Mesh: ${m.cyan(s.length+" peer(s)")} \u2014 ${s.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),Dm(t,o,e.agent,n,e.mode)});H.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:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:r,reportFields:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-
|
|
630
|
+
]`}H.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=we(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()});H.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 t=e.dir||q(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await Ly(e.peer),s=n.map(r=>r.url);console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),s.length>0&&console.log(` Mesh: ${m.cyan(s.length+" peer(s)")} \u2014 ${s.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),Dm(t,o,e.agent,n,e.mode)});H.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:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:r,reportFields:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-NU3UJC6C.js"),c=we(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),f=[];e:for(let y of l){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(f.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let x={...t(v.meta.type),...e.fields?r(v.meta.type):{}},A=await a(s,o({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),x,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!A){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let k=n(A.answers),S=e.fields?i(v.meta.type,A.answers):null;k.completeness>=d&&!(S&&!S.fit)||f.push({agent:y,type:v.meta.type??"?",score:k.completeness.toFixed(2),standsAlone:k.standsAlone.toFixed(2),gap:k.biggestGap,...S?{missing:S.missingCritical.join(",")||"-",cov:`${Math.round(S.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(f,null,2));return}if(f.length===0){console.log(m.green(" no articles below the threshold"));return}f.sort((y,$)=>parseFloat(y.score)-parseFloat($.score));let p=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=p.map(y=>Math.max(y.length,...f.map($=>String($[y]).length))),h=y=>y.map(($,b)=>String($).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(h(p)));for(let y of f)console.log(h(p.map($=>y[$])));if(e.fields){let y=f.filter($=>$.missing!=="-").length;console.log(m.dim(`
|
|
631
631
|
${f.length} article(s) flagged; ${y} 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(`
|
|
632
|
-
${f.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."))});H.command("query <question>").description("agentic wiki query \u2014 picks pages from their one-line summaries, reads live state at the source, then answers; walks the catalog + wikilink graph where no summaries exist").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to search first (default: the calling agent, else the first one with a catalog)").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--max-candidates <n>","candidates from selector (catalog method)","3").option("--max-hops <n>","wikilink hops from candidates (catalog method)","2").option("--max-articles <n>","cap on total articles walked (catalog method)","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").option("--own-only","search only the agent's own articles, not the shared wiki").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-
|
|
632
|
+
${f.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."))});H.command("query <question>").description("agentic wiki query \u2014 picks pages from their one-line summaries, reads live state at the source, then answers; walks the catalog + wikilink graph where no summaries exist").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to search first (default: the calling agent, else the first one with a catalog)").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--max-candidates <n>","candidates from selector (catalog method)","3").option("--max-hops <n>","wikilink hops from candidates (catalog method)","2").option("--max-articles <n>","cap on total articles walked (catalog method)","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").option("--own-only","search only the agent's own articles, not the shared wiki").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-5CPK6G2H.js"),{noteSourceFor:n}=await import("./query-settings-35GDM3HU.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await qy(t);if(!c)return;let l=we(t.dir),g=t.agent?[t.agent]:l.listAgents(),d=q(l.getBaseDir(),s),f=Date.now(),p=t.agent||process.env.AGENTX_AGENT_ID,u=p&&!t.ownOnly&&await jy()?p:null;for(let v of u?[]:g){let x=l.getAgentWiki(v),A=q(x.baseDir,"_index.md");try{if((await import("fs")).existsSync(A)){u=v;break}}catch{}}if(!u){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first.")),i(d,{at:new Date().toISOString(),agent:p||"",status:"no-catalog",source:"cli",wallMs:Date.now()-f}),process.exitCode=1;return}let h=u,y=l.getAgentWiki(h),$=t.ownOnly||!await jy()?void 0:l.sharedScope(h),b=await a(d,h,"cli",()=>o(e,y,h,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles),shared:$,method:c.method,summaries:c.summaries,notes:n(c,h)}));if(r(b.status)&&(process.exitCode=1),t.json){console.log(JSON.stringify(b,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${u} \xB7 status: ${b.status} \xB7 walked: ${b.walked.length}`)),console.log(),b.status!=="ok"){console.log(m.yellow(` (no answer) ${b.error||b.status}`));return}if(console.log(b.answer),console.log(),b.basis==="search"&&(console.log(m.dim(" No wiki page was used: the answer comes from a search at the source.")),console.log()),b.citations.length){console.log(m.dim(" Citations:"));for(let v of b.citations){let x=v.type?m.magenta(` [${v.type}]`):"";console.log(m.dim(` - ${v.title}${x} (${v.path})`))}console.log()}if(b.live?.length){console.log(m.dim(" Read live at the source:"));for(let v of b.live)console.log(m.dim(` - ${v.line}`));console.log()}if(t.trace&&b.trace){if(b.method==="summaries"&&console.log(m.dim(` method: summaries live reads: ${b.liveAsked??0} asked, ${b.live?.length??0} answered plan: ${b.trace.planMs??0}ms reads: ${b.trace.liveMs??0}ms`)),console.log(m.dim(` selector: ${b.trace.selectorMs}ms synthesis: ${b.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${b.candidates.map(v=>v.title).join(" | ")||"(none)"}`)),b.walked.length>b.candidates.length){let v=b.walked.filter(x=>!b.candidates.some(A=>A.path===x.path));console.log(m.dim(` followed: ${v.map(x=>`${x.title}@h${x.hop}`).join(" | ")}`))}console.log()}});H.command("score").description("score the wiki's answers to a question set; compare two reports").option("--dir <path>","wiki directory").option("--questions <file>","question set: JSON array or JSON lines of {id, question, expect: [facts]}").option("--agent <id>","ask as this agent (its own wiki first, then the shared wiki)").option("--own-only","search only the agent's own articles, to measure without the shared wiki").option("--out <file>","write the report as JSON to this file").option("--compare <files...>","compare two saved reports (before after) instead of running").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--json","print the report as JSON").action(async e=>{let{parseQuestionSet:t,buildReport:o,compareReports:n,runCost:s}=await import("./score-LNJ46A67.js"),r=A=>`${Math.round(A*100)}%`,i=A=>A===void 0?"?":`${(A/1e3).toFixed(1)}s`,a=A=>A===void 0?"?":`$${A.toFixed(3)}`,c=A=>`${i(A.meanMs)} and ${a(A.meanCostUsd)} per question${A.unpriced?` (${A.unpriced} without a cost)`:""}`;if(e.compare){if(e.compare.length!==2){console.log(m.red(" --compare takes two report files: before after")),process.exitCode=1;return}let[A,k]=e.compare.map(R=>JSON.parse(Nt(q(R),"utf-8"))),S=n(A,k);if(e.json){console.log(JSON.stringify(S,null,2));return}console.log(),console.log(m.bold(` ${r(S.before)} \u2192 ${r(S.after)}`)),console.log(m.dim(` before: ${c(S.cost.before)}`)),console.log(m.dim(` after: ${c(S.cost.after)}`)),S.changed==="unknown"?console.log(m.yellow(" ! A report records no settings, so what changed between the runs is unknown.")):(console.log(m.dim(` changed: ${S.changed.join("; ")||"nothing"}`)),S.changed.length>1&&console.log(m.yellow(" ! More than one setting changed: the difference can't be put down to one of them."))),(S.onlyBefore.length||S.onlyAfter.length)&&console.log(m.yellow(` ! The runs asked different questions. Only before: ${S.onlyBefore.join(", ")||"none"}. Only after: ${S.onlyAfter.join(", ")||"none"}.`));for(let R of S.deltas){if(R.before===R.after)continue;let O=R.after>R.before?m.green("\u25B2"):m.red("\u25BC");console.log(` ${O} ${R.id} ${r(R.before)} \u2192 ${r(R.after)} ${m.dim(R.question.slice(0,80))}`),R.gained.length&&console.log(m.green(` + ${R.gained.join(", ")}`)),R.lost.length&&console.log(m.red(` - ${R.lost.join(", ")}`))}console.log();return}if(!e.questions){console.log(m.red(" --questions <file> is required (or --compare before.json after.json).")),process.exitCode=1;return}let l=e.agent||process.env.AGENTX_AGENT_ID;if(!l){console.log(m.red(" --agent <id> is required: the score is for one agent's view of the wiki.")),process.exitCode=1;return}let g=t(Nt(q(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:f,CATALOG_SYNTH_MODEL:p}=await import("./query-5CPK6G2H.js"),{noteSourceFor:u}=await import("./query-settings-35GDM3HU.js"),{meteredModelCall:h}=await import("./model-call-J7JATTMW.js"),y=await qy(e);if(!y)return;let $=we(e.dir),b=!e.ownOnly,v=[];for(let A of g){let k={calls:0,usd:0,unpriced:0},S=Date.now(),R=await d(A.question,$.getAgentWiki(l),l,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:b?$.sharedScope(l):void 0,method:y.method,summaries:y.summaries,notes:u(y,l),call:h(k)}),O=Date.now()-S,N=R.method==="summaries"&&k.unpriced===0?k.usd:void 0;v.push({q:A,answer:R.answer||R.error||"",status:R.status,citations:R.citations.map(D=>D.path),method:R.method??"catalog",ms:O,costUsd:N}),e.json||process.stderr.write(m.dim(` ${A.id} ${R.status} ${i(O)} ${a(N)}
|
|
633
633
|
`))}let x=o({questions:e.questions,agent:l,shared:b,settings:{method:y.method,linkedPages:y.summaries.linkedPages,linkedChars:y.summaries.linkedChars,live:y.summaries.live.enabled,notes:y.notes.enabled,navigatorModel:e.selectorModel??y.summaries.navigatorModel,answerModel:e.synthModel??y.summaries.answerModel,catalogSelectorModel:e.selectorModel??f,catalogSynthModel:e.synthModel??p}},v);if(e.out&&Ot(q(e.out),`${JSON.stringify(x,null,2)}
|
|
634
634
|
`),e.json){console.log(JSON.stringify(x,null,2));return}console.log(),console.log(m.bold(` ${l}: ${r(x.score)} \xB7 ${x.full}/${x.results.length} questions fully answered${b?"":" (own articles only)"}`)),console.log(m.dim(` ${c(s(x))}`));for(let A of x.results){let k=A.missing.length===0?m.green("\u2713"):A.found.length?m.yellow("~"):m.red("\u2717");console.log(` ${k} ${A.id} ${r(A.score)} ${m.dim(A.question.slice(0,80))}`),A.missing.length&&console.log(m.dim(` missing: ${A.missing.join(", ")}`))}e.out&&console.log(m.dim(`
|
|
635
|
-
report saved to ${e.out}`)),console.log()});H.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,t)=>{let o=we(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));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()});H.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 t=we(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Ke(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new bo({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,f]of Object.entries(r.entries))i.set(d,f.path);if(i.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${i.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of o){let f=t.getAgentWiki(d),p=f.listArticles(d),u=t.getSharedStore().listEntries(),h=new Map(u.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let x=new Map;for(let k of v.meta.sources){let S=h.get(k);if(!S)continue;let R=String(S.meta?.sender??""),O=s.fingerprint({text:S.content,channel:S.source,sender:R}),N=i.get(O);if(!N?.length)continue;let D=N.join("/"),_=x.get(D);_?_.n++:x.set(D,{path:N,n:1})}if(x.size===0)continue;$++,l++;let A;for(let k of x.values())(!A||k.n>A.n)&&(A=k);A&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:A.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} 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()});H.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=we(e.dir),o=t.getSharedStore(),n=await Ly(e.peer?[e.peer]:void 0);if(n.length===0){console.log(m.dim(" No mesh peers configured")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(e.articles){let i=await Fy();if(!i){console.log(m.red(" No agents in this node's daemon config; run it where agentx.json is.")),process.exitCode=1;return}let{syncPeerArticles:a}=await import("./article-sync-4NOPOQU7.js");for(let c of n){console.log(),console.log(m.bold(` Copying articles from ${c.url}...`));try{let l=await a({hub:t,peer:c,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${l.node}`));for(let g of l.agents){if(g.skipped==="local"){console.log(m.dim(` ${g.agentId}: runs here, not copied`));continue}if(g.skipped){console.log(m.yellow(` ${g.agentId}: skipped (${g.skipped})`));continue}let d=[`${g.copied} ${e.dryRun?"to copy":"copied"}`,`${g.unchanged} unchanged`];g.removed&&d.push(`${g.removed} removed (gone on the peer)`),g.rejected&&d.push(`${g.rejected} refused`),console.log(` ${m.cyan(g.agentId)}: ${d.join(", ")}${g.error?m.red(` \u2014 stopped: ${g.error}`):""}`),g.error&&(process.exitCode=1)}}catch(l){console.log(m.red(` ${l.cause?.code==="ECONNREFUSED"?"Connection refused":l.message}`)),process.exitCode=1}}console.log();return}let s=new Set(o.listEntries().map(i=>i.id)),r=0;for(let{url:i,token:a}of n){console.log(),console.log(m.bold(` Syncing from ${i}...`));let c=a?{Authorization:`Bearer ${a}`}:{};try{let l=await fetch(`${i}/wiki/entries`,{headers:c,signal:AbortSignal.timeout(12e4)});if(!l.ok){console.log(m.red(` HTTP ${l.status}`));continue}let g=await l.json(),d=g.entries||[],f=g.nodeId||"unknown";console.log(m.dim(` Node: ${f} \u2014 ${d.length} entries`));let p=0;for(let u of d)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${f}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),p++);p>0?console.log(m.green(` ${p} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=p;try{let u=await fetch(`${i}/wiki/agents`,{headers:c,signal:AbortSignal.timeout(5e3)});if(u.ok){let h=await u.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.totalArticles} articles`))}}catch{}}catch(l){l.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${l.message}`))}}console.log(),r>0&&!e.dryRun?console.log(m.green(` ${r} entries synced.`)):r>0?console.log(m.dim(` ${r} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});H.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 t=e.dir||q(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ca(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);h+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Dl(c),articles:d.articles.length,entries:f.length,unabsorbed:p.length,uniqueTags:u.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["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 i){let g=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(f=>f[c])),d=s.filter(f=>f[c]===g).map(f=>f.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()});H.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,t)=>{let o=t.dir?q(process.cwd(),t.dir):q(process.cwd(),".agentx/wiki");Ke(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=q(o,".."),i=o.split("/").pop()||"wiki",a=["-C",r,"-czf",s];t.includeRaw||a.push("--exclude="+i+"/raw"),a.push(i),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=Ke(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${IA(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});H.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:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:r,ARTICLE_FIELDS_SEAT:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-FWF2HKWS.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=we(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),f=parseInt(e.limit),p=0,u=[];e:for(let k of d){let S=l.getAgentWiki(k);for(let R of S.listArticles(k)){if(p>=f)break e;let O=S.readArticle(R.path);if(!O||e.type&&O.meta.type!==e.type)continue;p++;let N=await a(i,n({title:O.meta.title,type:O.meta.type,body:O.content}),t(O.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:O.meta.type??"?"}});if(!N){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=o(O.meta.type,N.answers);for(let _ of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&_.needsHuman||(e.ask&&_.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:_.field,tier:_.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${_.label}?`}),u.push({tier:_.tier,need:_.field,how:_.needsHuman?m.yellow("ask"):_.sources.join("/"),uncertain:_.uncertain?"?":"",agent:k,article:O.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ut(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(k=>Math.max(k.length,...u.map(S=>$(S[k]).length))),v=(k,S)=>String(k)+" ".repeat(Math.max(0,b[S]-$(k).length));console.log(),console.log(m.bold(y.map((k,S)=>v(k,S)).join(" ")));for(let k of u)console.log(y.map((S,R)=>v(k[S],R)).join(" "));let x=u.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${x} can be closed by a lookup; ${u.length-x} need a person.`));let A=u[0]?.tier;if(A&&console.log(m.dim(` Start at ${A} \u2014 ${r[A]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),S=k[e.notifyTier]??k.pillar,R=g.filter(O=>(k[O.tier??"furniture"]??9)<=S);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:O}=await import("./config-VXXKMXHH.js"),N=O(),D=N?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let _=R.slice(0,10).map(K=>`\u2022 ${K.question}`).join(`
|
|
635
|
+
report saved to ${e.out}`)),console.log()});H.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,t)=>{let o=we(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));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()});H.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 t=we(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Ke(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new bo({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,f]of Object.entries(r.entries))i.set(d,f.path);if(i.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${i.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of o){let f=t.getAgentWiki(d),p=f.listArticles(d),u=t.getSharedStore().listEntries(),h=new Map(u.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let x=new Map;for(let k of v.meta.sources){let S=h.get(k);if(!S)continue;let R=String(S.meta?.sender??""),O=s.fingerprint({text:S.content,channel:S.source,sender:R}),N=i.get(O);if(!N?.length)continue;let D=N.join("/"),_=x.get(D);_?_.n++:x.set(D,{path:N,n:1})}if(x.size===0)continue;$++,l++;let A;for(let k of x.values())(!A||k.n>A.n)&&(A=k);A&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:A.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} 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()});H.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=we(e.dir),o=t.getSharedStore(),n=await Ly(e.peer?[e.peer]:void 0);if(n.length===0){console.log(m.dim(" No mesh peers configured")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(e.articles){let i=await Fy();if(!i){console.log(m.red(" No agents in this node's daemon config; run it where agentx.json is.")),process.exitCode=1;return}let{syncPeerArticles:a}=await import("./article-sync-4NOPOQU7.js");for(let c of n){console.log(),console.log(m.bold(` Copying articles from ${c.url}...`));try{let l=await a({hub:t,peer:c,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${l.node}`));for(let g of l.agents){if(g.skipped==="local"){console.log(m.dim(` ${g.agentId}: runs here, not copied`));continue}if(g.skipped){console.log(m.yellow(` ${g.agentId}: skipped (${g.skipped})`));continue}let d=[`${g.copied} ${e.dryRun?"to copy":"copied"}`,`${g.unchanged} unchanged`];g.removed&&d.push(`${g.removed} removed (gone on the peer)`),g.rejected&&d.push(`${g.rejected} refused`),console.log(` ${m.cyan(g.agentId)}: ${d.join(", ")}${g.error?m.red(` \u2014 stopped: ${g.error}`):""}`),g.error&&(process.exitCode=1)}}catch(l){console.log(m.red(` ${l.cause?.code==="ECONNREFUSED"?"Connection refused":l.message}`)),process.exitCode=1}}console.log();return}let s=new Set(o.listEntries().map(i=>i.id)),r=0;for(let{url:i,token:a}of n){console.log(),console.log(m.bold(` Syncing from ${i}...`));let c=a?{Authorization:`Bearer ${a}`}:{};try{let l=await fetch(`${i}/wiki/entries`,{headers:c,signal:AbortSignal.timeout(12e4)});if(!l.ok){console.log(m.red(` HTTP ${l.status}`));continue}let g=await l.json(),d=g.entries||[],f=g.nodeId||"unknown";console.log(m.dim(` Node: ${f} \u2014 ${d.length} entries`));let p=0;for(let u of d)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${f}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),p++);p>0?console.log(m.green(` ${p} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=p;try{let u=await fetch(`${i}/wiki/agents`,{headers:c,signal:AbortSignal.timeout(5e3)});if(u.ok){let h=await u.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.totalArticles} articles`))}}catch{}}catch(l){l.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${l.message}`))}}console.log(),r>0&&!e.dryRun?console.log(m.green(` ${r} entries synced.`)):r>0?console.log(m.dim(` ${r} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});H.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 t=e.dir||q(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ca(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);h+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Dl(c),articles:d.articles.length,entries:f.length,unabsorbed:p.length,uniqueTags:u.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["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 i){let g=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(f=>f[c])),d=s.filter(f=>f[c]===g).map(f=>f.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()});H.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,t)=>{let o=t.dir?q(process.cwd(),t.dir):q(process.cwd(),".agentx/wiki");Ke(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=q(o,".."),i=o.split("/").pop()||"wiki",a=["-C",r,"-czf",s];t.includeRaw||a.push("--exclude="+i+"/raw"),a.push(i),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=Ke(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${IA(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});H.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:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:r,ARTICLE_FIELDS_SEAT:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-NU3UJC6C.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=we(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),f=parseInt(e.limit),p=0,u=[];e:for(let k of d){let S=l.getAgentWiki(k);for(let R of S.listArticles(k)){if(p>=f)break e;let O=S.readArticle(R.path);if(!O||e.type&&O.meta.type!==e.type)continue;p++;let N=await a(i,n({title:O.meta.title,type:O.meta.type,body:O.content}),t(O.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:O.meta.type??"?"}});if(!N){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=o(O.meta.type,N.answers);for(let _ of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&_.needsHuman||(e.ask&&_.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:_.field,tier:_.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${_.label}?`}),u.push({tier:_.tier,need:_.field,how:_.needsHuman?m.yellow("ask"):_.sources.join("/"),uncertain:_.uncertain?"?":"",agent:k,article:O.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ut(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(k=>Math.max(k.length,...u.map(S=>$(S[k]).length))),v=(k,S)=>String(k)+" ".repeat(Math.max(0,b[S]-$(k).length));console.log(),console.log(m.bold(y.map((k,S)=>v(k,S)).join(" ")));for(let k of u)console.log(y.map((S,R)=>v(k[S],R)).join(" "));let x=u.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${x} can be closed by a lookup; ${u.length-x} need a person.`));let A=u[0]?.tier;if(A&&console.log(m.dim(` Start at ${A} \u2014 ${r[A]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),S=k[e.notifyTier]??k.pillar,R=g.filter(O=>(k[O.tier??"furniture"]??9)<=S);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:O}=await import("./config-FZTWI3VG.js"),N=O(),D=N?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let _=R.slice(0,10).map(K=>`\u2022 ${K.question}`).join(`
|
|
636
636
|
`),J=R.length>10?`
|
|
637
637
|
\u2026and ${R.length-10} more`:"",W=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
638
638
|
${_}${J}
|
|
639
639
|
|
|
640
|
-
agentx wiki questions`,X=N?.daemon?.port??N?.port??18800;try{let K=await fetch(`http://127.0.0.1:${X}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:W})});console.log(K.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${K.status}) \u2014 questions are still queued.`))}catch(K){console.log(m.yellow(` Push failed (${String(K?.message??K).slice(0,80)}) \u2014 questions are still queued.`))}}}}});H.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:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:i}=await import("./seat-FWF2HKWS.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=we(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),y=g(),$=c(d(p.getSharedStore().listEntries())),b=new Map($.map(N=>[N.name.toLowerCase().trim(),N])),v=0,x=0,A=[],k=!1;e:for(let N of u){let D=p.getAgentWiki(N);for(let _ of D.listArticles(N)){if(v>=h)break e;if(_.meta.type!=="person")continue;let J=D.readArticle(_.path);if(!J)continue;v++;let W=await i(s,n({title:J.meta.title,type:J.meta.type,body:J.content}),t(J.meta.type),{links:[{kind:"article",id:_.path}],features:{agent:N,op:"backfill"}});if(!W){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let K=o(J.meta.type,W.answers).missing.filter(I=>r.includes(I));if(K.length===0)continue;let{records:Ee,results:Be}=await a([{name:J.meta.title,type:"person"}],{sources:y}),P=b.get(J.meta.title.toLowerCase().trim());if(!k){for(let I of l(Be,y))console.log(m.yellow(` ! ${I.source} ${I.kind} \u2014 would supply ${I.provides.join(", ")}`)),console.log(m.dim(` ${I.hint}`));k=!0}let re=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([I,fe])=>[I,fe.value]))}]:[],...Ee]);if(re.length===0)continue;let{content:Te,edits:le}=f(J.content,re[0],K);if(le.length!==0){for(let I of le)A.push({agent:N,article:J.meta.title.slice(0,32),field:I.field,action:I.replaced?"replace":"add",got:`${I.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(_.path,J.meta,Te,N)?x++:console.log(m.red(` could not write ${_.path}`)))}}}if(e.json){console.log(JSON.stringify(A,null,2));return}if(A.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let S=["agent","article","field","action","got"],R=S.map(N=>Math.max(N.length,...A.map(D=>String(D[N]).length))),O=N=>N.map((D,_)=>String(D).padEnd(R[_])).join(" ");console.log(),console.log(m.bold(O(S)));for(let N of A)console.log(O(S.map(D=>N[D])));console.log(),e.apply?(console.log(m.green(` ${A.length} field(s) written across ${x} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${A.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});H.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:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ut(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,r)=>(o[s.tier??"furniture"]??9)-(o[r.tier??"furniture"]??9)),console.log();for(let s of n){let r=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${r} ${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`))});H.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,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:r}=await import("./article-fields-PITN4NHA.js"),i=new n(ut(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-P62U3FHT.js"),y=new h(ut(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=i.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),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(!r[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=we(o.dir,o.mode).getAgentWiki(l.agentId),f=d.readArticle(l.path);if(!f){console.log(m.yellow(` article gone: ${l.path}`));return}let p=s(f.content,l.field,`${t} (answered by operator)`);if(!p){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(l.path,f.meta,p.content,l.agentId);console.log(u?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});H.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:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:r}=await import("./seat-FWF2HKWS.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),p=we(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:y,backlog:$}=i(u,h),b=a(y,J=>J.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},x=[],A=0,k=Date.now();if(e.load){let{readFileSync:J}=await import("fs");x.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let J of e.load?[]:b){let W=await r(t,n(J),o,{features:{source:J.source??"",absorbed:J.absorbed}});if(!W){A++;continue}let X=W.answers;x.push({entry:J,verdict:s(W.answers,v),citeWorthy:X.citeWorthy?.noul})}if(x.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:J}=await import("fs");J(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let S=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(x,"seat","seat"),O=d(R,{minN:50}),N=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:S,calibration:O,failures:A,elapsed:N},null,2));return}let D=J=>`${(J*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${S.n} (${S.positives} kept by absorb, ${S.negatives} passed over)`),console.log(` recall ${D(S.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(S.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(S.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${S.lostPositives>0?m.yellow(`lost ${S.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in O)||!O.insufficient)&&console.log(` ECE ${O.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),S.lostPositives>0){let J=S.droppedBy;console.log(m.dim(` dropped by: type ${J.type} \xB7 worth ${J.worth} \xB7 durability ${J.durability} (a positive can fail several)`))}let _=S.positiveMeans;if(console.log(m.dim(` positives avg: worth ${_.worth.toFixed(2)} \xB7 durability ${_.durability.toFixed(2)} \xB7 typeConf ${_.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${N}s, ${A} 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 J=parseFloat(e.minRecall),{best:W,points:X}=g(x,{minRecall:J});if(console.log(),console.log(m.bold(` threshold sweep (${X.length} policies, recall floor ${D(J)})`)),W)console.log(` best: ${W.requireTyped?`typed & type>=${W.minType}`:"type gate OFF"} worth>=${W.minWorth} durability>=${W.minDurability}`),console.log(` recall ${D(W.recall)} \xB7 filtered ${D(W.filtered)} \xB7 precision ${D(W.precision)} \xB7 lost ${W.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(J)} recall \u2014 not even keeping everything typed.`));let K=X.slice().sort((Ee,Be)=>Be.recall-Ee.recall)[0];K&&console.log(m.dim(` Best recall available: ${D(K.recall)} at ${K.requireTyped?`type>=${K.minType}`:"type gate OFF"} worth>=${K.minWorth} dur>=${K.minDurability}, filtering ${D(K.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});H.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,t)=>{let o=q(process.cwd(),e);Ke(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?q(process.cwd(),t.dir):q(process.cwd(),".agentx/wiki");Ke(n)&&!t.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=q(n,".."),{mkdirSync:r}=await import("fs");r(s,{recursive:!0});let i=["-C",s,"-xzf",o];console.log(m.dim(` tar ${i.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",i,{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 IA(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"}_d();import{Command as jA}from"commander";import U from"chalk";import{resolve as ea}from"path";import{existsSync as _A}from"fs";ae();var ps=new jA().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");ps.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 t=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(U.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(U.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),r=new bo({baseDir:ea(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(U.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),c=r.loadNodes().nodes;console.log(),console.log(U.bold(` Graph review \u2014 ${i.length} pending`)),console.log(U.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,f=0;for(let u=0;u<i.length;u++){let h=i[u],y=Tr(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(y)} ... `);let $=DA(h,a,c),b=null;try{b=await PA(n,o,$,t.dashboard?.token)}catch(A){f++,console.log(U.red(`ERR ${A.message?.slice(0,80)}`));continue}if(!b||!b.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(x)),e.dryRun)l++;else try{MA(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(A){console.log(U.yellow(` (commit failed, staying pending: ${A.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(x)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(x||v)),d++)}console.log();let p=e.dryRun?"would":"did";console.log(U.dim(` Summary: ${p} approve ${l}, ${p} reject ${g}, ${d} skipped, ${f} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});ps.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 t=C();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=ea(process.cwd(),t.graph.baseDir);if(!_A(o)){console.log(U.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new bo({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(U.dim(" "),...a)});console.log(),console.log(U.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,c)=>c[1]-a[1]);i.length===0&&console.log(U.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});ps.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 t=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let r=new bo({baseDir:ea(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(S=>S.id));console.log(),console.log(U.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let S=await fetch(`${o}/graph/schema`,{headers:s});if(!S.ok)throw new Error(`schema HTTP ${S.status}`);l=(await S.json()).schema;let O=await fetch(`${o}/graph/nodes`,{headers:s});if(!O.ok)throw new Error(`nodes HTTP ${O.status}`);g=(await O.json()).nodes||[];let N=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!N.ok)throw new Error(`classifications HTTP ${N.status}`);d=(await N.json()).classifications||[]}catch(S){console.log(U.red(` fetch failed: ${S.message}`));return}let f=i.levels.map(S=>S.id).join(","),p=l?.levels?.map(S=>S.id).join(","),u=f===p;u?console.log(U.dim(` schema matches (${i.levels.length} levels)`)):(console.log(U.yellow(" \u26A0 schema levels differ:")),console.log(U.dim(` local: ${f}`)),console.log(U.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(U.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(l)):console.log(U.yellow(" keeping local schema; node import may fail if levels disagree")));let h=u?i:l,y=new Map;h.levels.forEach((S,R)=>y.set(S.id,R));let $=[...g].sort((S,R)=>(y.get(S.level)??99)-(y.get(R.level)??99)),b=0,v=0,x=0;for(let S of $){if(c.has(S.id)){v++;continue}if(e.dryRun){b++,c.add(S.id);continue}try{r.addNode({...S,createdBy:S.createdBy?`${S.createdBy} (sync)`:`sync:${o}`}),c.add(S.id),b++}catch(R){x++,console.log(U.yellow(` skip node ${S.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${x} failed`));let A=0,k=0;for(let S of d)if(!(!S.msgHash||!Array.isArray(S.path))){if(r.getFingerprint(S.msgHash)){k++;continue}if(e.dryRun){A++;continue}r.setFingerprint(S.msgHash,{path:S.path,leaf:S.leaf||{}}),A++}console.log(U.dim(` fingerprints: +${A} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` \u2713 pulled from ${o}`)),console.log()});function DA(e,t,o){let n={};for(let i of o)(n[i.level]||=[]).push(`${i.id}${i.axes?.name?` (${i.axes.name})`:""}`);let s=t.levels.map(i=>` ${i.id}: [${(n[i.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
640
|
+
agentx wiki questions`,X=N?.daemon?.port??N?.port??18800;try{let K=await fetch(`http://127.0.0.1:${X}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:W})});console.log(K.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${K.status}) \u2014 questions are still queued.`))}catch(K){console.log(m.yellow(` Push failed (${String(K?.message??K).slice(0,80)}) \u2014 questions are still queued.`))}}}}});H.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:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:i}=await import("./seat-NU3UJC6C.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=we(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),y=g(),$=c(d(p.getSharedStore().listEntries())),b=new Map($.map(N=>[N.name.toLowerCase().trim(),N])),v=0,x=0,A=[],k=!1;e:for(let N of u){let D=p.getAgentWiki(N);for(let _ of D.listArticles(N)){if(v>=h)break e;if(_.meta.type!=="person")continue;let J=D.readArticle(_.path);if(!J)continue;v++;let W=await i(s,n({title:J.meta.title,type:J.meta.type,body:J.content}),t(J.meta.type),{links:[{kind:"article",id:_.path}],features:{agent:N,op:"backfill"}});if(!W){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let K=o(J.meta.type,W.answers).missing.filter(I=>r.includes(I));if(K.length===0)continue;let{records:Ee,results:Be}=await a([{name:J.meta.title,type:"person"}],{sources:y}),P=b.get(J.meta.title.toLowerCase().trim());if(!k){for(let I of l(Be,y))console.log(m.yellow(` ! ${I.source} ${I.kind} \u2014 would supply ${I.provides.join(", ")}`)),console.log(m.dim(` ${I.hint}`));k=!0}let re=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([I,fe])=>[I,fe.value]))}]:[],...Ee]);if(re.length===0)continue;let{content:Te,edits:le}=f(J.content,re[0],K);if(le.length!==0){for(let I of le)A.push({agent:N,article:J.meta.title.slice(0,32),field:I.field,action:I.replaced?"replace":"add",got:`${I.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(_.path,J.meta,Te,N)?x++:console.log(m.red(` could not write ${_.path}`)))}}}if(e.json){console.log(JSON.stringify(A,null,2));return}if(A.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let S=["agent","article","field","action","got"],R=S.map(N=>Math.max(N.length,...A.map(D=>String(D[N]).length))),O=N=>N.map((D,_)=>String(D).padEnd(R[_])).join(" ");console.log(),console.log(m.bold(O(S)));for(let N of A)console.log(O(S.map(D=>N[D])));console.log(),e.apply?(console.log(m.green(` ${A.length} field(s) written across ${x} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${A.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});H.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:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ut(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,r)=>(o[s.tier??"furniture"]??9)-(o[r.tier??"furniture"]??9)),console.log();for(let s of n){let r=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${r} ${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`))});H.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,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:r}=await import("./article-fields-PITN4NHA.js"),i=new n(ut(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-P62U3FHT.js"),y=new h(ut(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=i.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),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(!r[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=we(o.dir,o.mode).getAgentWiki(l.agentId),f=d.readArticle(l.path);if(!f){console.log(m.yellow(` article gone: ${l.path}`));return}let p=s(f.content,l.field,`${t} (answered by operator)`);if(!p){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(l.path,f.meta,p.content,l.agentId);console.log(u?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});H.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:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:r}=await import("./seat-NU3UJC6C.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),p=we(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:y,backlog:$}=i(u,h),b=a(y,J=>J.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},x=[],A=0,k=Date.now();if(e.load){let{readFileSync:J}=await import("fs");x.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let J of e.load?[]:b){let W=await r(t,n(J),o,{features:{source:J.source??"",absorbed:J.absorbed}});if(!W){A++;continue}let X=W.answers;x.push({entry:J,verdict:s(W.answers,v),citeWorthy:X.citeWorthy?.noul})}if(x.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:J}=await import("fs");J(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let S=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(x,"seat","seat"),O=d(R,{minN:50}),N=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:S,calibration:O,failures:A,elapsed:N},null,2));return}let D=J=>`${(J*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${S.n} (${S.positives} kept by absorb, ${S.negatives} passed over)`),console.log(` recall ${D(S.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(S.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(S.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${S.lostPositives>0?m.yellow(`lost ${S.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in O)||!O.insufficient)&&console.log(` ECE ${O.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),S.lostPositives>0){let J=S.droppedBy;console.log(m.dim(` dropped by: type ${J.type} \xB7 worth ${J.worth} \xB7 durability ${J.durability} (a positive can fail several)`))}let _=S.positiveMeans;if(console.log(m.dim(` positives avg: worth ${_.worth.toFixed(2)} \xB7 durability ${_.durability.toFixed(2)} \xB7 typeConf ${_.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${N}s, ${A} 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 J=parseFloat(e.minRecall),{best:W,points:X}=g(x,{minRecall:J});if(console.log(),console.log(m.bold(` threshold sweep (${X.length} policies, recall floor ${D(J)})`)),W)console.log(` best: ${W.requireTyped?`typed & type>=${W.minType}`:"type gate OFF"} worth>=${W.minWorth} durability>=${W.minDurability}`),console.log(` recall ${D(W.recall)} \xB7 filtered ${D(W.filtered)} \xB7 precision ${D(W.precision)} \xB7 lost ${W.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(J)} recall \u2014 not even keeping everything typed.`));let K=X.slice().sort((Ee,Be)=>Be.recall-Ee.recall)[0];K&&console.log(m.dim(` Best recall available: ${D(K.recall)} at ${K.requireTyped?`type>=${K.minType}`:"type gate OFF"} worth>=${K.minWorth} dur>=${K.minDurability}, filtering ${D(K.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});H.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,t)=>{let o=q(process.cwd(),e);Ke(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?q(process.cwd(),t.dir):q(process.cwd(),".agentx/wiki");Ke(n)&&!t.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=q(n,".."),{mkdirSync:r}=await import("fs");r(s,{recursive:!0});let i=["-C",s,"-xzf",o];console.log(m.dim(` tar ${i.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",i,{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 IA(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"}_d();import{Command as jA}from"commander";import U from"chalk";import{resolve as ea}from"path";import{existsSync as _A}from"fs";ae();var ps=new jA().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");ps.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 t=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(U.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(U.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),r=new bo({baseDir:ea(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(U.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),c=r.loadNodes().nodes;console.log(),console.log(U.bold(` Graph review \u2014 ${i.length} pending`)),console.log(U.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,f=0;for(let u=0;u<i.length;u++){let h=i[u],y=Tr(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(y)} ... `);let $=DA(h,a,c),b=null;try{b=await PA(n,o,$,t.dashboard?.token)}catch(A){f++,console.log(U.red(`ERR ${A.message?.slice(0,80)}`));continue}if(!b||!b.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(x)),e.dryRun)l++;else try{MA(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(A){console.log(U.yellow(` (commit failed, staying pending: ${A.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(x)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(x||v)),d++)}console.log();let p=e.dryRun?"would":"did";console.log(U.dim(` Summary: ${p} approve ${l}, ${p} reject ${g}, ${d} skipped, ${f} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});ps.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 t=C();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=ea(process.cwd(),t.graph.baseDir);if(!_A(o)){console.log(U.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new bo({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(U.dim(" "),...a)});console.log(),console.log(U.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,c)=>c[1]-a[1]);i.length===0&&console.log(U.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});ps.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 t=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let r=new bo({baseDir:ea(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(S=>S.id));console.log(),console.log(U.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let S=await fetch(`${o}/graph/schema`,{headers:s});if(!S.ok)throw new Error(`schema HTTP ${S.status}`);l=(await S.json()).schema;let O=await fetch(`${o}/graph/nodes`,{headers:s});if(!O.ok)throw new Error(`nodes HTTP ${O.status}`);g=(await O.json()).nodes||[];let N=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!N.ok)throw new Error(`classifications HTTP ${N.status}`);d=(await N.json()).classifications||[]}catch(S){console.log(U.red(` fetch failed: ${S.message}`));return}let f=i.levels.map(S=>S.id).join(","),p=l?.levels?.map(S=>S.id).join(","),u=f===p;u?console.log(U.dim(` schema matches (${i.levels.length} levels)`)):(console.log(U.yellow(" \u26A0 schema levels differ:")),console.log(U.dim(` local: ${f}`)),console.log(U.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(U.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(l)):console.log(U.yellow(" keeping local schema; node import may fail if levels disagree")));let h=u?i:l,y=new Map;h.levels.forEach((S,R)=>y.set(S.id,R));let $=[...g].sort((S,R)=>(y.get(S.level)??99)-(y.get(R.level)??99)),b=0,v=0,x=0;for(let S of $){if(c.has(S.id)){v++;continue}if(e.dryRun){b++,c.add(S.id);continue}try{r.addNode({...S,createdBy:S.createdBy?`${S.createdBy} (sync)`:`sync:${o}`}),c.add(S.id),b++}catch(R){x++,console.log(U.yellow(` skip node ${S.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${x} failed`));let A=0,k=0;for(let S of d)if(!(!S.msgHash||!Array.isArray(S.path))){if(r.getFingerprint(S.msgHash)){k++;continue}if(e.dryRun){A++;continue}r.setFingerprint(S.msgHash,{path:S.path,leaf:S.leaf||{}}),A++}console.log(U.dim(` fingerprints: +${A} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` \u2713 pulled from ${o}`)),console.log()});function DA(e,t,o){let n={};for(let i of o)(n[i.level]||=[]).push(`${i.id}${i.axes?.name?` (${i.axes.name})`:""}`);let s=t.levels.map(i=>` ${i.id}: [${(n[i.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
641
641
|
`),r=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) ---",r,"","--- 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(`
|
|
642
642
|
`)}async function PA(e,t,o,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let r=new AbortController,i=setTimeout(()=>r.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:t,message:o,context:{channel:"a2a",sender:"graph-review"}}),signal:r.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 Cr((c?.content||"").toString())}finally{clearTimeout(i)}}function MA(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Pl(){let e=C();if(!e.graph?.baseDir)return console.log(U.red(" graph.baseDir is not configured")),null;let t=ea(process.cwd(),e.graph.baseDir);return{store:new bo({baseDir:t}),baseDir:t}}var Ml=ps.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Ml.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 t=Pl();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),r=new o(t.baseDir).load(),i=n(s,new Set(r.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(U.green(" nothing left unreviewed"));return}let a=t.store.loadNodes().nodes;console.log();for(let c of i){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):U.dim("cache");console.log(` ${U.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${U.bold(Tr(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(U.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(U.dim(` ${i.length} to check (${e.strategy}).`)),console.log(U.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Ml.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,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(U.red(" verdict must be correct | wrong | unsure"));return}let n=Pl();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),i=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(i.length===0){console.log(U.red(` no classification matching "${e}"`));return}if(i.length>1){console.log(U.red(` "${e}" matches ${i.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:i[0].msgHash,verdict:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(U.green(` ${t}: ${Tr(i[0].path,c)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(U.dim(` should have been: ${o.path}`))});Ml.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=Pl();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),r=new o(t.baseDir).load(),i=n(s,r);if(e.json){console.log(JSON.stringify(i,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${i.classifications}`),console.log(` reviewed ${i.reviewed} (${i.correct} correct \xB7 ${i.wrong} wrong \xB7 ${i.unsure} unsure)`),i.correct+i.wrong>0&&console.log(` accuracy ${a(i.accuracy)}`),console.log(` calibratable ${i.calibratable} ${U.dim("reviewed rows that carry a confidence")}`),i.byBin.length>0){console.log(),console.log(U.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of i.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?U.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),i.calibratable<100?console.log(U.dim(` ${100-i.calibratable} more labelled rows before a calibration report means anything.`)):console.log(U.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as BA}from"commander";import se from"chalk";import{Command as Wy}from"commander";import Se from"chalk";import{existsSync as LA}from"fs";import{resolve as FA}from"path";import qA from"better-sqlite3";function UA(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(Se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function WA(e){let t=FA(process.cwd(),e);return LA(t)||(console.log(Se.red(` No db at ${t}`)),process.exit(1)),new qA(t,{readonly:!0})}var By=new Wy().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(Os)).option("--max <n>","max clusters distilled per run",String(jr)).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(Se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=WA(e.path),o=await Og(t,{since:UA(e.since),agentId:e.agent,sessions:new Ud(process.cwd()),minOccurrences:Number(e.minOccurrences)||Os,max:Number(e.max)||jr,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(Se.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${Se.cyan(n.key)} ${Se.bold(`\xD7${n.count}`)} ${Se.dim(n.status)}`),n.sampleMessage&&console.log(Se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(Se.dim(`
|
|
643
643
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(Se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(Se.green(` \u2713 draft written: ${n.id}`)+Se.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(Se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(Se.yellow(` \u26A0 ${n}`));o.dryRun?console.log(Se.dim(`
|
|
@@ -708,7 +708,7 @@ ${e.body||""}`)}function xE(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
|
|
|
708
708
|
|
|
709
709
|
`))>=0;){let p=l.slice(0,f);l=l.slice(f+2),ME(p)}}}catch(i){console.error(pe.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function ME(e){let t="message",o="";for(let r of e.split(`
|
|
710
710
|
`))r.startsWith("event: ")?t=r.slice(7):r.startsWith("data: ")&&(o=r.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?pe.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=pe.cyan(n.phase?.padEnd(9)??"run"),i=pe.bold(n.workflowId??""),a=pe.dim((n.runId??"").slice(0,8)),c=n.nodeId?pe.yellow(n.nodeId):"",l=n.note?pe.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${c} ${l}`);break}case"task":{let r=pe.magenta(`task.${n.phase}`.padEnd(14)),i=pe.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?pe.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${pe.cyan(a)} ${c}`);break}case"signal":{let r=pe.green("signal".padEnd(9)),i=pe.bold(n.name),a=pe.dim(`(${n.scope})`),c=n.workflowId?pe.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"mesh":{let r=pe.blue("mesh".padEnd(9)),i=pe.bold(n.peer),a=n.healthy?pe.green("\u2713 healthy"):pe.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${pe.dim(n.delta??"")}`);break}case"channel":{let r=pe.yellow("channel".padEnd(9)),i=n.direction==="in"?pe.cyan("\u2190"):pe.magenta("\u2192"),a=pe.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?pe.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"status":{console.log(pe.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}ae();import{Command as LE}from"commander";import bs from"chalk";function FE(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}var Hw=new LE().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let a=C(e.config);t||(t=a.dashboard?.daemonUrl||""),o||(o=a.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(FE(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(bs.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(bs.red(` daemon unreachable at ${t}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let r=s.events??[];if(e.agent&&!s.subscriptions){console.log(bs.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log(bs.dim(" no events"));return}for(let a of r)console.log(` ${zd(a)} ${bs.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log(bs.dim(`
|
|
711
|
-
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as UE}from"commander";import fr from"chalk";import{spawn as WE}from"node:child_process";import{execFileSync as qE}from"node:child_process";function zw(e=()=>qE("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var Yw=new UE().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(fr.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-
|
|
711
|
+
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as UE}from"commander";import fr from"chalk";import{spawn as WE}from"node:child_process";import{execFileSync as qE}from"node:child_process";function zw(e=()=>qE("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var Yw=new UE().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(fr.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-OCLSGJYQ.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:zw();if(n?.ok){let{fetchAgents:l}=await import("./client-OCLSGJYQ.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||g[0].id;if(!g.some($=>$.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let f={};try{f=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let p=Object.fromEntries(g.map($=>[$.id,{name:`AgentX ${$.name||$.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...f,model:`agentx/${d}`,providers:{...f.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${o.baseUrl}/v1`},models:p}}})};console.error(fr.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:y}=await import("./opencode-launch-ECMEY2QZ.js");await y({agentId:d,env:u,cwd:process.cwd(),pool:h,spawnImpl:WE,log:$=>console.error(fr.dim($))});return}n&&!n.ok&&(console.error(fr.yellow(n.reason)),console.error(fr.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-6T6NVB7O.js"),{render:r}=await import("ink"),i=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await r(i.createElement(s,{conn:o,pollMs:a})).waitUntilExit()});import{Command as BE}from"commander";import ce from"chalk";import{randomUUID as Kw}from"crypto";import{createInterface as JE}from"node:readline/promises";import GE from"ora";import ua from"chalk";function Vw(e){console.error(),console.error(ua.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ua.dim(` ${e.why}`)),console.error(),console.error(` Use ${ua.cyan(e.instead)} instead.`),e.note&&console.error(ua.dim(` ${e.note}`)),console.error()}var Xw={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 Qw=new BE().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,t)=>{Vw({what:"agentx chat",...Xw});let o=Jm({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${Kw().slice(0,12)}`,i=[];try{i=await ni(o)}catch(g){console.error(ce.red(` cannot reach daemon at ${o.baseUrl}: ${g?.message||g}`)),console.error(ce.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(ce.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(g=>g.id===n)||(console.error(ce.red(` unknown agent: @${n}`)),console.error(ce.dim(` registered: ${i.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(ce.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-QZBJ4NHC.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}zE(o.baseUrl,n,r,s);let a=JE({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(ce.dim(`
|
|
712
712
|
bye`)),process.exit(0)});;){let g;try{g=(await a.question(ce.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(ce.dim(` @${n} chatId=${r} channel=${s}`));continue}if(g==="/clear"){r=`chat-cli:${Kw().slice(0,12)}`,console.log(ce.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await ni(o);for(let h of u){let y=h.id===n?ce.green("\u25CF"):ce.dim("\u25CB");console.log(` ${y} @${h.id} ${ce.dim(h.tier)} ${h.model??""}`)}}catch(u){console.error(ce.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(ce.red(" usage: /agent <id>"));continue}try{if(!(await ni(o)).find(y=>y.id===u)){console.log(ce.red(` unknown agent: @${u}`));continue}n=u,console.log(ce.dim(` now talking to @${n}`))}catch(h){console.error(ce.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(ce.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(ce.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=GE({text:`@${n}\u2026`,color:"cyan"}).start(),f=Date.now(),p=HE(n);try{let u=await Gm(o,n,g,{channel:s,chatId:r,onText:y=>{d.stop(),p.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),p.tool(y)}});d.stop();let h=Math.round((Date.now()-f)/100)/10;u.error?p.finishError(u.error):p.finish(h,u.usage)}catch(u){d.stop(),p.finishError(u?.message||String(u))}finally{c=!1}if(l){console.log(ce.dim(" bye"));return}}});function HE(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${ce.green(`@${e}`)}
|
|
713
713
|
`),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
|
|
714
714
|
`&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
|
|
@@ -805,7 +805,7 @@ Restart the daemon to activate.
|
|
|
805
805
|
dist/
|
|
806
806
|
*.log
|
|
807
807
|
.env
|
|
808
|
-
`}import{Command as MR}from"commander";import Ze from"chalk";import{writeFileSync as LR,mkdirSync as FR,existsSync as wa,readFileSync as $$,appendFileSync as b$}from"fs";import{resolve as xs,dirname as x$}from"path";import{homedir as ld}from"os";var S$=new MR().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
808
|
+
`}import{Command as MR}from"commander";import Ze from"chalk";import{writeFileSync as LR,mkdirSync as FR,existsSync as wa,readFileSync as $$,appendFileSync as b$}from"fs";import{resolve as xs,dirname as x$}from"path";import{homedir as ld}from"os";var S$=new MR().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-HFN24YLA.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=WR(o);break;case"bash":s=zR(o);break;case"fish":s=YR(o);break;default:console.error(Ze.red(`unsupported shell: ${n}`)),console.error(Ze.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?xs(String(e.output)):qR(n);FR(x$(r),{recursive:!0}),LR(r,s),console.log(Ze.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),UR(n,r,!!e.yes)});function qR(e){let t=ld();switch(e){case"zsh":return xs(t,".zsh","completions","_agentx");case"bash":return xs(t,".bash_completion.d","agentx.bash");case"fish":return xs(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function UR(e,t,o){if(e==="zsh"){let n=xs(ld(),".zshrc"),s=x$(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=wa(n)?$$(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ze.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&wa(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),b$(n,g.join(`
|
|
809
809
|
`)+`
|
|
810
810
|
`),console.log(Ze.green("\u2713 Patched ~/.zshrc")),console.log(Ze.dim("Reload your shell: exec zsh"));return}console.log(Ze.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ze.cyan(` ${r}`)),l&&console.log(Ze.cyan(` ${i}`)),console.log(),console.log(Ze.dim("Then reload: exec zsh")),console.log(Ze.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=xs(ld(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((wa(n)?$$(n,"utf-8"):"").includes(t)){console.log(Ze.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&wa(n)){b$(n,`
|
|
811
811
|
# agentx completion
|
|
@@ -821,4 +821,4 @@ ${VR({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
821
821
|
${o.url}`)}catch(t){console.error(As.red(` ${t.message}`)),process.exitCode=1}});vr.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",gd).action(async(e,t)=>{try{let o=await pd(t.models);if(!ud(t.model,o)){console.log(md(t.model,o)),process.exitCode=1;return}let n=e==="-"?await QR():await KR(e,"utf8"),s=JSON.parse(n),{version:r}=await Ir(),i=C$({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(As.red(` ${o.message}`)),process.exitCode=1}});async function QR(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function pU(){let e=await Ir(),t=new ZR().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=Tm(n);Om(s)&&Cm("cli",s)});for(let o of[Mp,Pp,gs,Jn,Zt,At,mm,en,mi,uo,po,Lo,iy,Mo,gi,Yw,jo,Af,Ef,Df,Zs,Hf,Kf,vf,eh,th,wh,vh,xh,Tt,$n,e$,Ws,Co,S$,vr])t.addCommand(o);for(let o of O$)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=O$.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,eC(o,74," "),""].join(`
|
|
822
822
|
`)}),t}var O$=[H,ps,ho,Jt,Gs,is,Ye,fo,Fo,hn,ys,ws,No,pt,Qn,Ei,Wi,fn,Bi,Gw,Hw,go,pr,Et,Hm,on,br,Tc,Wo,wt,Xn,Oc,aa,io,yo,m$,p$,Qw];function eC(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
|
|
823
823
|
`)}export{pU as buildProgram};
|
|
824
|
-
//# sourceMappingURL=program-
|
|
824
|
+
//# sourceMappingURL=program-HFN24YLA.js.map
|