agentix-cli 0.50.1 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +67 -14
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +20 -3
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +24 -31
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +16 -2
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +173 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +62 -15
- package/dist/{App-TDUUFVDV.js → App-QVNQ5BQK.js} +2 -2
- package/dist/{ChatApp-IOWDXM3R.js → ChatApp-CC57XC23.js} +2 -2
- package/dist/{agent-KRLAT3YJ.js → agent-ILH6ANOM.js} +2 -2
- package/dist/{board-dashboard-VA4VSCMQ.js → board-dashboard-XPPBRPQE.js} +114 -114
- package/dist/board-dashboard-XPPBRPQE.js.map +1 -0
- package/dist/{chunk-ZWGRRFJI.js → chunk-2KQTE4XI.js} +2 -2
- package/dist/{chunk-A6IV2VQY.js → chunk-6HAZ6YWI.js} +2 -2
- package/dist/{chunk-HHY3MSMN.js → chunk-CAA546XN.js} +2 -2
- package/dist/{chunk-X5K3HR4V.js → chunk-F7WY24UZ.js} +2 -2
- package/dist/{chunk-FDYGTQVW.js → chunk-H2TWRZC2.js} +2 -2
- package/dist/{chunk-F2PEUQW4.js → chunk-JQR3NTHI.js} +2 -2
- package/dist/{chunk-ZQSB6IX4.js → chunk-KFALP5NO.js} +2 -2
- package/dist/{chunk-JWLTI6NZ.js → chunk-LBMZP7TG.js} +57 -57
- package/dist/chunk-LBMZP7TG.js.map +1 -0
- package/dist/{chunk-2BRX2EMT.js → chunk-PSDCRZZM.js} +2 -2
- package/dist/{chunk-BVRUDRCM.js → chunk-QP6XNTBB.js} +2 -2
- package/dist/{chunk-AVJRATR5.js → chunk-ROCUOXCW.js} +2 -2
- package/dist/{chunk-FULEQYM6.js → chunk-S7CVSKOX.js} +2 -2
- package/dist/chunk-S7CVSKOX.js.map +1 -0
- package/dist/{chunk-XSFXAJDA.js → chunk-SRCXUZM2.js} +4 -4
- package/dist/{chunk-XSFXAJDA.js.map → chunk-SRCXUZM2.js.map} +1 -1
- package/dist/chunk-U67EG5IF.js +19 -0
- package/dist/chunk-U67EG5IF.js.map +1 -0
- package/dist/{chunk-RP7GLXOA.js → chunk-UBRMOTBH.js} +181 -180
- package/dist/chunk-UBRMOTBH.js.map +1 -0
- package/dist/chunk-V7XZN3MQ.js +123 -0
- package/dist/chunk-V7XZN3MQ.js.map +1 -0
- package/dist/{chunk-WW6KNRIR.js → chunk-VMS3HVTT.js} +2 -2
- package/dist/{chunk-WUDXUY7H.js → chunk-WCMQRSVU.js} +2 -2
- package/dist/{chunk-5KCOH5FQ.js → chunk-WDQ3BPFS.js} +2 -2
- package/dist/{chunk-ZN7637EF.js → chunk-XZTR5MBJ.js} +2 -2
- package/dist/chunk-YE2BUU3Z.js +28 -0
- package/dist/chunk-YE2BUU3Z.js.map +1 -0
- package/dist/{chunk-ZKDWQJVS.js → chunk-YEV6W34S.js} +55 -55
- package/dist/{chunk-ZKDWQJVS.js.map → chunk-YEV6W34S.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/client-I7GAAM3T.js +2 -0
- package/dist/{config-I4GWI22T.js → config-TVW7UCKG.js} +2 -2
- package/dist/config-mutator-JHM53P5A.js +2 -0
- package/dist/doctor-CXFMV6PT.js +2 -0
- package/dist/index.d.ts +256 -6
- package/dist/index.js +1 -1
- package/dist/program-ZCFMO4ZD.js +2 -0
- package/dist/{promote-EDEG2HQR.js → promote-4T64VW5K.js} +2 -2
- package/dist/query-6IKL52WT.js +2 -0
- package/dist/registry-E4QUXHMQ.js +2 -0
- package/dist/{request-planner-JDBXFNQ4.js → request-planner-BRLDCYU5.js} +2 -2
- package/dist/{review-candidates-EBP5CFOB.js → review-candidates-QWW5PDUU.js} +2 -2
- package/dist/{routing-Q2EOZ3VW.js → routing-DP6S7OJL.js} +2 -2
- package/dist/schedule-tool-TPJ6GR47.js +2 -0
- package/dist/scheduler-7QPG6OTY.js +2 -0
- package/dist/{seat-LV3STEXI.js → seat-3KUNRM5Z.js} +2 -2
- package/dist/{select-5NHY4T5A.js → select-ILXHYJGD.js} +2 -2
- package/dist/{tool-2RKPJWDG.js → tool-SF3BCY55.js} +2 -2
- package/dist/wiki-WETANN3W.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-VA4VSCMQ.js.map +0 -1
- package/dist/chunk-FULEQYM6.js.map +0 -1
- package/dist/chunk-JUJ3TCOE.js +0 -19
- package/dist/chunk-JUJ3TCOE.js.map +0 -1
- package/dist/chunk-JWLTI6NZ.js.map +0 -1
- package/dist/chunk-JY7POTMB.js +0 -123
- package/dist/chunk-JY7POTMB.js.map +0 -1
- package/dist/chunk-KH6L7GDO.js +0 -28
- package/dist/chunk-KH6L7GDO.js.map +0 -1
- package/dist/chunk-RP7GLXOA.js.map +0 -1
- package/dist/client-PC7OEKSK.js +0 -2
- package/dist/config-mutator-3RFKH3OV.js +0 -2
- package/dist/doctor-OG6DK52Y.js +0 -2
- package/dist/program-RFAHI4SS.js +0 -2
- package/dist/query-P5LMGXVS.js +0 -2
- package/dist/registry-GJLY5J5E.js +0 -2
- package/dist/schedule-tool-N2Z5E6AR.js +0 -2
- package/dist/scheduler-WTPERNYJ.js +0 -2
- package/dist/wiki-XQMJ2FPU.js +0 -2
- /package/dist/{App-TDUUFVDV.js.map → App-QVNQ5BQK.js.map} +0 -0
- /package/dist/{ChatApp-IOWDXM3R.js.map → ChatApp-CC57XC23.js.map} +0 -0
- /package/dist/{agent-KRLAT3YJ.js.map → agent-ILH6ANOM.js.map} +0 -0
- /package/dist/{chunk-ZWGRRFJI.js.map → chunk-2KQTE4XI.js.map} +0 -0
- /package/dist/{chunk-A6IV2VQY.js.map → chunk-6HAZ6YWI.js.map} +0 -0
- /package/dist/{chunk-HHY3MSMN.js.map → chunk-CAA546XN.js.map} +0 -0
- /package/dist/{chunk-X5K3HR4V.js.map → chunk-F7WY24UZ.js.map} +0 -0
- /package/dist/{chunk-FDYGTQVW.js.map → chunk-H2TWRZC2.js.map} +0 -0
- /package/dist/{chunk-F2PEUQW4.js.map → chunk-JQR3NTHI.js.map} +0 -0
- /package/dist/{chunk-ZQSB6IX4.js.map → chunk-KFALP5NO.js.map} +0 -0
- /package/dist/{chunk-2BRX2EMT.js.map → chunk-PSDCRZZM.js.map} +0 -0
- /package/dist/{chunk-BVRUDRCM.js.map → chunk-QP6XNTBB.js.map} +0 -0
- /package/dist/{chunk-AVJRATR5.js.map → chunk-ROCUOXCW.js.map} +0 -0
- /package/dist/{chunk-WW6KNRIR.js.map → chunk-VMS3HVTT.js.map} +0 -0
- /package/dist/{chunk-WUDXUY7H.js.map → chunk-WCMQRSVU.js.map} +0 -0
- /package/dist/{chunk-5KCOH5FQ.js.map → chunk-WDQ3BPFS.js.map} +0 -0
- /package/dist/{chunk-ZN7637EF.js.map → chunk-XZTR5MBJ.js.map} +0 -0
- /package/dist/{client-PC7OEKSK.js.map → client-I7GAAM3T.js.map} +0 -0
- /package/dist/{config-I4GWI22T.js.map → config-TVW7UCKG.js.map} +0 -0
- /package/dist/{config-mutator-3RFKH3OV.js.map → config-mutator-JHM53P5A.js.map} +0 -0
- /package/dist/{doctor-OG6DK52Y.js.map → doctor-CXFMV6PT.js.map} +0 -0
- /package/dist/{program-RFAHI4SS.js.map → program-ZCFMO4ZD.js.map} +0 -0
- /package/dist/{promote-EDEG2HQR.js.map → promote-4T64VW5K.js.map} +0 -0
- /package/dist/{query-P5LMGXVS.js.map → query-6IKL52WT.js.map} +0 -0
- /package/dist/{registry-GJLY5J5E.js.map → registry-E4QUXHMQ.js.map} +0 -0
- /package/dist/{request-planner-JDBXFNQ4.js.map → request-planner-BRLDCYU5.js.map} +0 -0
- /package/dist/{review-candidates-EBP5CFOB.js.map → review-candidates-QWW5PDUU.js.map} +0 -0
- /package/dist/{routing-Q2EOZ3VW.js.map → routing-DP6S7OJL.js.map} +0 -0
- /package/dist/{schedule-tool-N2Z5E6AR.js.map → schedule-tool-TPJ6GR47.js.map} +0 -0
- /package/dist/{scheduler-WTPERNYJ.js.map → scheduler-7QPG6OTY.js.map} +0 -0
- /package/dist/{seat-LV3STEXI.js.map → seat-3KUNRM5Z.js.map} +0 -0
- /package/dist/{select-5NHY4T5A.js.map → select-ILXHYJGD.js.map} +0 -0
- /package/dist/{tool-2RKPJWDG.js.map → tool-SF3BCY55.js.map} +0 -0
- /package/dist/{wiki-XQMJ2FPU.js.map → wiki-WETANN3W.js.map} +0 -0
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{a as cc,b as Un,g as lc}from"./chunk-
|
|
2
|
-
Computer-use helper \u2192 ${Me(
|
|
3
|
-
Agent \u2192 ${t}
|
|
4
|
-
Daemon \u2192 ${
|
|
5
|
-
Starts at login \u2192 ${ft()}`),e.dryRun)return;try{io("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let
|
|
1
|
+
import{a as cc,b as Un,g as lc}from"./chunk-KFALP5NO.js";import{a as po,b as Qa,f as Ln,i as Fn,j as oc,k as tc,l as Ks,m as rc,o as ac}from"./chunk-WCMQRSVU.js";import{a as nc,c as sc,d as ic}from"./chunk-Z3IP66SL.js";import{a as Za,c as ec}from"./chunk-CAA546XN.js";import{a as Ls,b as Fr}from"./chunk-RKPAVWXF.js";import{a as dt}from"./chunk-GV7S5BAX.js";import{e as Or}from"./chunk-GSX4NK2N.js";import{c as jr}from"./chunk-SZDACK6O.js";import{$ as Ja,A as Ca,B as Na,C as Ra,D as Ht,E as Ws,F as Cn,G as _a,H as vo,I as Da,J as Bs,K as Js,L as Pa,M as Ma,N as zt,O as Nn,P as La,Q as Fa,R as Ua,S as qa,T as mt,U as pt,V as Wa,W as Ba,X as Ce,Y as Rn,Z as Yt,_ as Gs,a as zr,aa as _n,b as Yr,ba as Dn,ca as za,da as Ys,ea as Va,fa as Pn,ga as ut,h as Qr,ha as Mn,i as Gt,ia as Vs,j as In,ja as Ka,k as oa,ka as Xa,l as ta,m as na,n as sa,o as ua,p as fa,q as $a,r as xa,s as Sa,t as Ea,u as Aa,v as Ia,w as qs,x as Ta,y as Oa,z as ja}from"./chunk-UBRMOTBH.js";import{E as Ga,F as Hs,G as Ha,H as zs,V as so,X as Ya,k as ha,n as ya,u as wa,v as ba}from"./chunk-YE2BUU3Z.js";import{a as Vr,d as Kr,e as Xr}from"./chunk-QP6XNTBB.js";import{a as Us,b as Tn,c as On,d as ia,e as ra,f as aa,i as ca,j as la,k as da,l as ga,o as jn,q as ma,r as pa}from"./chunk-S7CVSKOX.js";import{a as Zr,p as ea}from"./chunk-WDQ3BPFS.js";import{a as ka,b as va}from"./chunk-L53FTKEP.js";import{E as Mr,O as Lr,h as Sr,q as Er,v as Ds,w as Ir,y as ko}from"./chunk-YEV6W34S.js";import{b as Bt,c as ct,d as En,e as An,f as lt,g as Tr,h as Wo,i as Jt}from"./chunk-U67EG5IF.js";import{a as xr}from"./chunk-N6EWZGIX.js";import{e as _r,f as Ms,k as Dr}from"./chunk-WP6KLXTP.js";import{b as at}from"./chunk-DP7RTNDM.js";import{a as Fs,e as Ur,f as qr,h as Wr,i as Br,k as Jr,l as Gr,m as Hr}from"./chunk-F7WY24UZ.js";import{a as Ar,k as Rr}from"./chunk-V7XZN3MQ.js";import{f as Cr,g as Nr,h as Ps}from"./chunk-76Z4VHDX.js";import{b as he,c as Ae,d as gt,e as Pr}from"./chunk-VMS3HVTT.js";import{h as vr}from"./chunk-DWADWDMU.js";import{a as _s}from"./chunk-XZTR5MBJ.js";import{b as $o,d as Sn}from"./chunk-ROCUOXCW.js";import{b as rt,d as kr}from"./chunk-2GIDVZ4H.js";import{a as Rs,b as lr,c as sg,d as vn,e as dr,f as fr,g as rg,h as hr,i as ag,m as it,n as wr,o as br,s as $r,v as no,w as Wt}from"./chunk-JQR3NTHI.js";import{a as mo,b as st,e as mr,f as qt}from"./chunk-72SZI2UW.js";import{a as yr,b as cg}from"./chunk-FX3D7YON.js";import{a as go,b as ng}from"./chunk-7I7IEX4S.js";import{l as gr,m as R,n as xn,p as ge}from"./chunk-SRCXUZM2.js";import{g as pr,k as ur,l as ig}from"./chunk-RGDKHYY2.js";import{Command as lg}from"commander";var dc=new lg().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 Yr({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()});ge();import{Command as dg}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as gc,existsSync as Qs,mkdirSync as Xs,mkdtempSync as gg,rmSync as mg,writeFileSync as mc}from"node:fs";import{dirname as pc,join as Me}from"node:path";import{homedir as qn,release as pg,tmpdir as ug}from"node:os";import{setTimeout as fg}from"node:timers/promises";function Wn(){let e=ia(process.platform,process.arch,pg());if(e)throw new Error(e)}function Vt(){return`gui/${process.getuid()}/${Us}`}function ft(){return Me(qn(),"Library/LaunchAgents",`${Us}.plist`)}async function uc(){try{io("launchctl",["bootout",Vt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{io("launchctl",["print",Vt()],{stdio:"pipe"})}catch{return}await fg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function fc(){if(!Qs(ft()))throw new Error("Run agentx desktop install first.");let e=!0;try{io("launchctl",["print",Vt()],{stdio:"pipe"})}catch{e=!1}e||io("launchctl",["bootstrap",`gui/${process.getuid()}`,ft()],{stdio:"pipe"}),io("launchctl",["kickstart",Vt()],{stdio:"pipe"})}function hg(){let e=ga();if(e&&Qs(Me(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 ht=new dg("desktop").description("install and control the macOS desktop assistant");ht.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=>{Wn();let o=R(),t=ra(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=hg(),r=Me(qn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Me(r,Tn)}
|
|
2
|
+
Computer-use helper \u2192 ${Me(r,On)}
|
|
3
|
+
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
|
+
Daemon \u2192 ${s}
|
|
5
|
+
Starts at login \u2192 ${ft()}`),e.dryRun)return;try{io("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let a=null;try{a=io("/bin/sh",["-c","command -v ffmpeg"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{}!a&&!process.env.AGENTX_VOICE_PATH&&console.warn("ffmpeg was not found. Local Whisper transcription needs it: install ffmpeg (for example brew install ffmpeg), then rerun this install.");let c=gg(Me(ug(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){gc(Me(i,"apps",p),Me(c,p),{recursive:!0,filter:u=>!u.split("/").includes("build")});let f=p==="mac-helper"?la(o.notifications.local.icon):[];io("/bin/bash",[Me(c,p,"build.sh"),...f],{stdio:"inherit"})}let l=Me(qn(),"Library/Logs/agentx-desktop.err.log"),g=ca({executable:Me(r,Tn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:da(qn()),cli:Me(i,"dist/cli.js"),node:process.execPath,log:l,path:aa(a,process.env.AGENTX_VOICE_PATH)}),d=Me(c,"desktop.plist");mc(d,g,{mode:384}),io("plutil",["-lint",d],{stdio:"pipe"}),await uc(),Xs(r,{recursive:!0});for(let[p,f,u]of[["mac-voice","AgentX Voice.app",Tn],["mac-helper",On,On]])gc(Me(c,p,"build",f),Me(r,u),{recursive:!0});Xs(pc(ft()),{recursive:!0}),Xs(pc(l),{recursive:!0}),mc(ft(),g,{mode:384}),fc(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
|
|
6
6
|
Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
|
|
7
|
-
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{mg(
|
|
7
|
+
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{mg(c,{recursive:!0,force:!0})}});ht.command("start").description("start the installed desktop assistant").action(()=>{Wn(),fc(),console.log("Desktop assistant started.")});ht.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Wn(),await uc(),console.log("Desktop assistant stopped.")});ht.command("status").description("show the desktop login service status").action(()=>{Wn();try{console.log(io("launchctl",["print",Vt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Qs(ft())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as vg}from"commander";import{open as xg}from"fs/promises";import{existsSync as Gn,mkdirSync as yg,readFileSync as Hn,writeFileSync as hc}from"fs";import{homedir as wg}from"os";import{dirname as bg,resolve as Zs}from"path";var ei="/attach/",yc="/guard/check";function wc(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function Bn(e,o,t){let n={hooks:[{type:"command",command:wc(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function $g(e){return{SessionStart:[Bn("/attach/session-start",e,"")],UserPromptSubmit:[Bn("/attach/prompt",e)],Stop:[Bn("/attach/stop",e)],SessionEnd:[Bn("/attach/session-end",e)]}}function kg(e){let o=wc("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Jn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Kt(){return Zs(wg(),".claude/settings.json")}function Bo(e=process.cwd()){for(let o of[e,Zs(e,"..")]){let t=Zs(o,"agentx.json");if(Gn(t))try{let n=JSON.parse(Hn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function bc(e,o={}){let t=o.path??Kt(),n=o.withGuard!==!1,s={};if(Gn(t))try{s=JSON.parse(Hn(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries($g(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!Jn(f,ei)):[];r[g]=[...p,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Jn(d,yc)):[];r.PreToolUse=[...g,...kg(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(yg(bg(t),{recursive:!0}),hc(t,`${JSON.stringify(s,null,2)}
|
|
8
8
|
`)),{path:t,changed:l,events:a,guardInstalled:c}}function $c(e={}){let o=e.path??Kt();if(!Gn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Hn(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?yc:ei;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Jn(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&hc(o,`${JSON.stringify(t,null,2)}
|
|
9
9
|
`),{path:o,changed:r,events:i,guardInstalled:!1}}function zn(e=Kt()){if(!Gn(e))return!1;try{return!!JSON.parse(Hn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Jn(t,ei))}catch{return!1}}var Yn=new vg("monitor").description("Register external CLI sessions and report ended runs to the briefing"),kc=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Bo()}`;async function vc(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Yn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",kc).action(async e=>{try{await vc(e.url,"register",Kr.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Yn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",kc).action(async e=>{try{let o=await xg(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
|
|
10
|
-
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await vc(e.url,"ended",Xr.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as gy}from"commander";import{Command as Ng}from"commander";ge();import I from"chalk";import{existsSync as Rg,readFileSync as _g}from"fs";ge();import{Command as Sg}from"commander";import oe from"chalk";import{spawn as Sc}from"child_process";import{existsSync as Eg,readFileSync as Ag,unlinkSync as Ig}from"fs";import{resolve as oi}from"path";var ti=e=>new Promise(o=>setTimeout(o,e));function ni(e){try{return process.kill(e,0),!0}catch{return!1}}async function yt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Tg(e){let o=await yt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await yt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Og(e){for(let o of[oi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Ag(o,"utf-8").trim(),10);if(Number.isFinite(t)&&ni(t))return t}catch{}return null}function jg(e){return new Promise(o=>{let t=Sc(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Ec=new Sg("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=R(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await yt(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await yt(`${i}/daemon/restart`),c=a?.pid??Ta(s)??Og(process.cwd()),l=a?.service??(c?Aa(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,p=process.getuid?.()===0,
|
|
10
|
+
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await vc(e.url,"ended",Xr.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as gy}from"commander";import{Command as Ng}from"commander";ge();import I from"chalk";import{existsSync as Rg,readFileSync as _g}from"fs";ge();import{Command as Sg}from"commander";import oe from"chalk";import{spawn as Sc}from"child_process";import{existsSync as Eg,readFileSync as Ag,unlinkSync as Ig}from"fs";import{resolve as oi}from"path";var ti=e=>new Promise(o=>setTimeout(o,e));function ni(e){try{return process.kill(e,0),!0}catch{return!1}}async function yt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Tg(e){let o=await yt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await yt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Og(e){for(let o of[oi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Ag(o,"utf-8").trim(),10);if(Number.isFinite(t)&&ni(t))return t}catch{}return null}function jg(e){return new Promise(o=>{let t=Sc(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Ec=new Sg("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=R(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await yt(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await yt(`${i}/daemon/restart`),c=a?.pid??Ta(s)??Og(process.cwd()),l=a?.service??(c?Aa(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,p=process.getuid?.()===0,f=Sa(l,{isRoot:p,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?Ia(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${oe.bold(r.node?.name||r.node?.id||i)}${c?oe.dim(` (PID ${c})`):""}`),console.log(` Run by: ${Ea(l)}`),f.ok||(console.log(oe.red(` ${f.reason}`)),console.log(oe.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(oe.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(oe.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(oe.dim(" Would run:"));for(let v of f.steps)console.log(oe.dim(` ${xc(v,c)}`));console.log();return}if(e.whenIdle){let v=Number(e.timeout),A=Math.max(1,Number(e.interval)||5);(!Number.isFinite(v)||v<0)&&(console.log(oe.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await xa({read:()=>Tg(i),intervalMs:A*1e3,timeoutMs:v*6e4,onCheck:$=>{$!==S&&$!==null&&$>0&&console.log(oe.dim(` Waiting: ${$} task(s) running...`)),S=$}});if(x.outcome==="unreachable"&&(console.log(oe.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(oe.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let $=x.inflight??"some";e.abortOnTimeout&&(console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Restarting anyway:`)),console.log(oe.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(oe.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let u=oi(g,".agentx");try{va(u,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let w=Date.now(),y=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(oe.dim(" Restarting..."));for(let v of f.steps){if(await Cg(v,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:y,service:l})||v.kind==="exec"&&v.mayFail)continue;let S=v===f.steps[0];try{S&&Ig(oi(u,ka))}catch{}console.log(oe.red(` Step failed: ${xc(v,c)}`)),console.log(S?oe.dim(` The daemon is still running. Restart it with: ${f.manual}`):oe.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let v=await yt(`${i}/health`);if(v&&typeof v.uptime=="number"&&v.uptime*1e3<=Date.now()-w+2e3){let A=await yt(`${i}/daemon/restart`);console.log(oe.green(` Daemon is back${A?.pid?` (PID ${A.pid})`:""} after ${Math.round((Date.now()-w)/1e3)}s.`)),console.log();return}await ti(1e3)}console.log(oe.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(oe.dim(` Start it with: ${f.manual}`)),console.log(oe.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function xc(e,o){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${o??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function Cg(e,o){switch(e.kind){case"exec":return await jg(e.argv)===0;case"sigterm":if(!o.pid)return!1;try{return process.kill(o.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!o.pid)return!0;let t=Date.now(),n=!1;for(;ni(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(oe.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await ti(500);return ni(o.pid)?(console.log(oe.yellow(` The old daemon (PID ${o.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(o.service.kind!=="launchd")return!0;let t=Date.now();for(;qs(o.service)&&Date.now()-t<3e4;)await ti(500);return!qs(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Eg(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=Sc(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Dg(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var Ve=new Ng().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ve.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:p}=await import("fs"),f=process.argv[1];(!f||!p(f))&&(console.error(I.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(I.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let u=[f,"daemon","start"];e.config&&u.push("-c",e.config),e.port&&u.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(I.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,u,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(I.green(`Daemon started in background (PID: ${k.pid})`)),console.log(I.dim(` Logs: tail -f ${w}`)),console.log(I.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(I.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(I.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Dg(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Pg(i(process.cwd(),".env"))}catch{}await new Vs(e.config).start()});function Pg(e){if(!Rg(e))return;let o=_g(e,"utf-8");for(let t of o.split(`
|
|
11
11
|
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Ve.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-ZAF7RW25.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;Ac(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(I.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(Ac(a)){console.log(I.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(I.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(I.green("Daemon stopped"))}catch{console.log(I.yellow("No daemon process found"))}});Ve.addCommand(Ec);Ve.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=R(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(I.bold(` ${r.node.name}`)+I.dim(` (${r.node.id})`)),console.log(I.green(" Status: running")+I.dim(` \u2014 uptime ${Mg(r.uptime)}`)),console.log(),console.log(I.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?I.yellow(` [${c.active} active]`):"",g=c.errors>0?I.red(` (${c.errors} errors)`):"";console.log(` ${I.cyan(c.name)} ${I.dim(`(${c.tier})`)}${l}${g}`),console.log(I.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(I.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?I.green("\u25CF"):I.dim("\u25CB"),g=c.nextRun?I.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(I.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?I.green("\u25CF"):I.red("\u25CF"),g=c.skills?.length?I.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${I.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(I.red(" Daemon is not running")),console.log(I.dim(" Start with: agentx daemon start"));else try{let t=R(e.config),n=xn(t);if(console.log(),console.log(I.bold(` ${t.node.name}`)+I.dim(` (${t.node.id})`)),console.log(I.yellow(" Status: stopped")),console.log(I.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(I.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(I.red(` ${t.message}`))}}});Ve.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(I.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Ve.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(R(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(I.dim(` Connecting to ${n}...`)),console.log(I.dim(` Press Ctrl+C to stop
|
|
12
12
|
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(I.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
|
|
13
|
-
`);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let p=JSON.parse(d.slice(6)),
|
|
13
|
+
`);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let p=JSON.parse(d.slice(6)),f=new Date(p.time).toLocaleTimeString(),u=p.message?.replace(/^\[agentx\]\s*/,"")||"";u.includes("executing")?console.log(`${I.dim(f)} ${I.cyan("\u25B6")} ${u}`):u.includes("completed")?console.log(`${I.dim(f)} ${I.green("\u2713")} ${u}`):u.includes("error")||u.includes("Error")?console.log(`${I.dim(f)} ${I.red("\u2717")} ${u}`):u.includes("Routing")?console.log(`${I.dim(f)} ${I.yellow("\u2192")} ${u}`):u.includes("mention")?console.log(`${I.dim(f)} ${I.magenta("@")} ${u}`):u.includes("Skipping")?console.log(`${I.dim(f)} ${I.dim("\u2298")} ${I.dim(u)}`):console.log(`${I.dim(f)} ${u}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(I.red(` Connection failed: ${s.message}`)),console.log(I.dim(" Is the daemon running? Diagnostic order:")),console.log(I.dim(" 1) agentx daemon status # is the daemon up?")),console.log(I.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(I.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(I.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(I.dim(" to see the error in the foreground."))}});Ve.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=R(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(I.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(I.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(I.dim(`
|
|
14
14
|
(${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(I.red(` Failed: ${s.message}`)),console.log(I.dim(" Is the daemon running? Try: agentx daemon status"))}});Ve.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(I.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(I.green(" \u2713 Tests passed"))}catch{console.log(I.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(I.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(I.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(I.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(I.green(" \u2713 Build complete")))}console.log(I.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(I.green(" \u2713 Deploy complete")),o.restart){console.log(I.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(I.green(" Remote daemon restarted"))}}catch(i){console.log(I.red(` Deploy failed: ${i.message}`))}});Ve.action(async e=>{await new Vs(e.config).start()});function Mg(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}function Ac(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as Lg}from"commander";import Ke from"chalk";import{existsSync as Xt,readFileSync as Fg,writeFileSync as Ic,mkdirSync as Tc}from"fs";import{hostname as Oc}from"os";import{resolve as wt}from"path";var jc=new Lg().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=wt(o,"agentx.json"),n=wt(o,".env"),s=wt(o,".agentx/sessions");if(console.log(),console.log(Ke.bold(" agentx init")),console.log(),Xt(t)&&!e.force){console.log(Ke.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[wt(o,"agentx.example.json"),wt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Xt(c)){r=Fg(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Oc().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Oc(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),Ic(t,r),console.log(Ke.green(" \u2713 Created agentx.json")),Xt(n)||(Ic(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
15
15
|
`)),console.log(Ke.green(" \u2713 Created .env template"))),Xt(s)||(Tc(s,{recursive:!0}),console.log(Ke.green(" \u2713 Created .agentx/sessions/")));let a=wt(o,".claude");Xt(a)||(Tc(a,{recursive:!0}),console.log(Ke.green(" \u2713 Created .claude/"))),console.log(),console.log(Ke.bold(" Next steps:")),console.log(` 1. Edit ${Ke.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Ke.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Ke.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Ke.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Ug}from"commander";import Jo from"chalk";import{spawn as Nc}from"child_process";import{existsSync as qg}from"fs";import{dirname as Wg,resolve as Bg}from"path";import{fileURLToPath as Jg}from"url";ge();var Rc=new Ug().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=Qa(),t=e.port?parseInt(e.port,10):Gg(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Jo.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Jo.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Jo.bold(` Opening ${n}`)),console.log(),await zg(n).catch(()=>!1))console.log(Jo.dim(" Dashboard is already running.")),e.open!==!1&&Cc(n);else{console.log(Jo.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Hg(),r=Nc(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Cc(n),await new Promise(a=>r.on("exit",()=>a()))}});function Gg(){try{return R().dashboard.port||4202}catch{return 4202}}function Hg(){let e=Bg(Wg(Jg(import.meta.url)),"cli.js");return qg(e)?e:process.argv[1]||e}async function zg(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function Cc(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Nc(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Jo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Jo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Yg}from"commander";import Ie from"chalk";var Qt=new Yg().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Qt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new Ln,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ie.bold(" Token created.")),console.log(),console.log(` id: ${Ie.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ie.dim("never")}`),console.log(),console.log(Ie.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ie.green.bold(s)}`),console.log(),console.log(Ie.dim(" Use it via the Authorization header:")),console.log(Ie.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});Qt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Ln().list();if(e.length===0){console.log(Ie.dim(`
|
|
16
16
|
No tokens issued.
|
|
@@ -19,16 +19,16 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
19
19
|
`))}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});ge();import{Command as ao}from"commander";import h from"chalk";import Ne from"prompts";import{readFileSync as So,writeFileSync as bt,existsSync as ue,mkdirSync as ro,cpSync as si,readdirSync as ri}from"fs";import{resolve as G,join as xo,dirname as Vg}from"path";import{fileURLToPath as Kg}from"url";function re(){let e=G(process.cwd(),"agentx.json");if(!ue(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(So(e,"utf-8"))}function Le(e){return he(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Go=new ao().name("agent").description("manage agents \u2014 add, list, remove");Go.command("list").alias("ls").description("list configured agents").action(()=>{let e=re();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Go.command("add").description("add a new agent interactively").action(async()=>{let e=re(),o=await Ne([{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:G(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:xo(o.workspace,o.id);ro(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(Vg(Kg(import.meta.url)),"../wiki/SKILL.md"),c=ue(r)?r:a;ue(c)&&(ro(G(t,".claude/skills/wiki"),{recursive:!0}),si(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Le(e),console.log(h.green(`
|
|
20
20
|
Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Go.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=re();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Le(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Go.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=re(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Le(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Zt=new ao().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Zt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=re().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
21
21
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
22
|
-
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Zt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=re();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-I4GWI22T.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ne({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(u=>({title:u,value:u}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ne({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Ne({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"}]});p.scheme==="tokenEnv"?a=((await Ne({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await Ne({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[u,...f]=p.split("=");u&&(g[u.trim()]=f.join("=").trim())}else if(n){let p=await Ne({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let u of String(p.metadata).split(",")){let[f,...w]=u.split("=");f&&(g[f.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Le(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Zt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=re(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Le(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Zt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=re().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Go.addCommand(Zt);var Vn=new ao().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Vn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=re();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Vn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=re(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ne({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 Ne([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Le(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ne([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Le(e),ro(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ne([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Le(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var $t=new ao().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");$t.command("list").alias("ls").description("list cron jobs").action(()=>{let e=re();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});$t.command("add").description("add a cron job").action(async()=>{let e=re(),o=Object.keys(e.agents||{}),t=await Ne([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Le(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});$t.command("enable <id>").description("enable a cron job").action(async e=>{let o=re();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Le(o),console.log(h.green(` Cron "${e}" enabled`))});$t.command("disable <id>").description("disable a cron job").action(async e=>{let o=re();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Le(o),console.log(h.green(` Cron "${e}" disabled`))});var kt=new ao().name("mesh").description("manage mesh peers \u2014 add, list, remove");kt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=re();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});kt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=re(),o=await Ne([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Le(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});kt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=re();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Le(o),console.log(h.green(` Peer "${e}" removed`)))});kt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=re();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Le(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Ho=new ao().name("skill").description("manage skills \u2014 add to agent(s), list");Ho.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=re(),n=G(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(xo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ne({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);ro(c,{recursive:!0}),ue(xo(n,"SKILL.md"))?si(n,c,{recursive:!0}):n.endsWith(".md")&&si(n,xo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ho.command("list").alias("ls").description("list skills per agent").action(()=>{let e=re();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=ue(n)?ri(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ho.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=So(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=R()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,u=0,f=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=G(v,".claude/skills",e),S=G(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(ro(A,{recursive:!0}),bt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=So(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let C=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||bt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),u++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${u}, ${f} already current, ${w} skipped.`)),o.dryRun&&(p>0||u>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ho.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let u=re().agents?.[e.workspace];u||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(u.workspace))}else if(e.allWorkspaces){let p=re();for(let u of Object.values(p.agents||{}))u?.workspace&&i.push(G(u.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let u of d)p[u.verdict]++;console.log();for(let u of d){let f=u.verdict==="PASS"?h.green("PASS "):u.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(u.name)}${u.skill?.path?h.dim(` (${u.skill.path})`):""}`);for(let w of u.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Ho.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=re(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-5NHY4T5A.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
22
|
+
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Zt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=re();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-TVW7UCKG.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ne({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ne({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Ne({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"}]});p.scheme==="tokenEnv"?a=((await Ne({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await Ne({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Ne({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Le(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Zt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=re(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Le(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Zt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=re().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Go.addCommand(Zt);var Vn=new ao().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Vn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=re();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Vn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=re(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ne({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 Ne([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Le(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ne([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Le(e),ro(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ne([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Le(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var $t=new ao().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");$t.command("list").alias("ls").description("list cron jobs").action(()=>{let e=re();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});$t.command("add").description("add a cron job").action(async()=>{let e=re(),o=Object.keys(e.agents||{}),t=await Ne([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Le(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});$t.command("enable <id>").description("enable a cron job").action(async e=>{let o=re();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Le(o),console.log(h.green(` Cron "${e}" enabled`))});$t.command("disable <id>").description("disable a cron job").action(async e=>{let o=re();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Le(o),console.log(h.green(` Cron "${e}" disabled`))});var kt=new ao().name("mesh").description("manage mesh peers \u2014 add, list, remove");kt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=re();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});kt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=re(),o=await Ne([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Le(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});kt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=re();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Le(o),console.log(h.green(` Peer "${e}" removed`)))});kt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=re();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Le(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Ho=new ao().name("skill").description("manage skills \u2014 add to agent(s), list");Ho.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=re(),n=G(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(xo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ne({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);ro(c,{recursive:!0}),ue(xo(n,"SKILL.md"))?si(n,c,{recursive:!0}):n.endsWith(".md")&&si(n,xo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ho.command("list").alias("ls").description("list skills per agent").action(()=>{let e=re();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=ue(n)?ri(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ho.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=So(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=R()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=G(v,".claude/skills",e),S=G(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(ro(A,{recursive:!0}),bt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=So(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let C=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||bt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ho.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=re().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let p=re();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Ho.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=re(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-ILXHYJGD.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
23
23
|
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
|
|
24
|
-
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var en=new ao().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");en.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");ue(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");ro(i,{recursive:!0}),ro(r,{recursive:!0});let a=ri(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=xo(i,d);if(ue(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let
|
|
24
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var en=new ao().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");en.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");ue(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");ro(i,{recursive:!0}),ro(r,{recursive:!0});let a=ri(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=xo(i,d);if(ue(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let u=So(xo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);bt(p,u),console.log(h.green(` + ${p}`)),c++}let g=xo(r,`${e}.yaml`);if(ue(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(ue(s)){let d=So(s,"utf-8").replaceAll("example.",`${e}.`);bt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});en.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=G(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),p=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
|
|
25
25
|
--- ${w} ---`)),console.log(y.split(`
|
|
26
26
|
`).slice(0,30).map(k=>` ${k}`).join(`
|
|
27
27
|
`)),y.split(`
|
|
28
28
|
`).length>30&&console.log(h.dim(` \u2026 (${y.split(`
|
|
29
|
-
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}ro(p,{recursive:!0});let
|
|
29
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}ro(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=xo(p,w);if(ue(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}bt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});en.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(G(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var ai=new ao().name("hook").description("manage hooks \u2014 add to agent workspace");ai.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=re().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=ue(n)?JSON.parse(So(n,"utf-8")):{},i=await Ne([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),ro(G(t.workspace,".claude"),{recursive:!0}),bt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var ci=new ao().name("migrate").description("import configuration from OpenClaw or other tools");ci.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ue(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(So(n,"utf-8")),i=ue(G(process.cwd(),"agentx.json"))?re():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){ro(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.js");y(u,i.agents[u])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let p=G(n,"../cron/jobs.json");if(ue(p)){let f=JSON.parse(So(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
|
|
30
30
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Le(i),console.log(h.green(`
|
|
31
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Eo=new ao().name("config").description("validate and inspect configuration");Eo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=R(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=xn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(G(r,".claude")),c=ue(G(r,"CLAUDE.md")),l=ue(G(r,".claude/settings.json")),g=ue(G(r,".claude/skills"))?ri(G(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Eo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=R(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Xg(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function ii(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Eo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-
|
|
31
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Eo=new ao().name("config").description("validate and inspect configuration");Eo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=R(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=xn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(G(r,".claude")),c=ue(G(r,"CLAUDE.md")),l=ue(G(r,".claude/settings.json")),g=ue(G(r,".claude/skills"))?ri(G(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Eo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=R(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Xg(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function ii(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Eo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-JHM53P5A.js"),{expandEnvVars:r}=await import("./config-TVW7UCKG.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(ii(g))});Eo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-JHM53P5A.js"),r=Xg(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${ii(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ii(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Eo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-JHM53P5A.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Eo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=R(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Qg}from"commander";import Ao from"chalk";import{resolve as Io}from"path";import{existsSync as Zg}from"fs";var uo=new Qg().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function zo(e){let o=Io(e,".agentx/db.sqlite");Zg(o)||(console.log(Ao.red(` No SQLite at ${o}`)),console.log(Ao.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=xr({path:o});return t||(console.log(Ao.red(` Could not open ${o}`)),console.log(Ao.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Yo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ao.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}uo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=zo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
|
|
32
32
|
SELECT agent_id, channel, status, duration_ms,
|
|
33
33
|
input_tokens, output_tokens,
|
|
34
34
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -79,7 +79,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
79
79
|
WHERE ${t.join(" AND ")}
|
|
80
80
|
ORDER BY started_at DESC
|
|
81
81
|
LIMIT @limit
|
|
82
|
-
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Yo(i,!!e.json)});uo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=zo(Io(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Yo(n,!!e.json)});uo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=zo(Io(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Ao.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Ao.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Yo(n,!!o.json)}catch(n){console.log(Ao.red(` ${n.message}`)),process.exit(1)}});import{Command as tm}from"commander";import z from"chalk";import{mkdtempSync as nm}from"fs";import{tmpdir as sm}from"os";import{resolve as Dc,join as Pc}from"path";import{existsSync as im}from"fs";import rm from"better-sqlite3";function _c(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(
|
|
82
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Yo(i,!!e.json)});uo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=zo(Io(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Yo(n,!!e.json)});uo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=zo(Io(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Ao.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Ao.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Yo(n,!!o.json)}catch(n){console.log(Ao.red(` ${n.message}`)),process.exit(1)}});import{Command as tm}from"commander";import z from"chalk";import{mkdtempSync as nm}from"fs";import{tmpdir as sm}from"os";import{resolve as Dc,join as Pc}from"path";import{existsSync as im}from"fs";import rm from"better-sqlite3";function _c(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(u){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${u?.message??u}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=em(l),p={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=Rr(e,p,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:om(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function em(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function om(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var To=new tm().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function vt(e){let o=Dc(e.cwd??process.cwd()),t=Dc(o,e.path??".agentx/intent/ledger.sqlite");im(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new rm(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Vo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function am(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Kn(e){if(!e)return;let o=am(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}To.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=vt(e),t=Kn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
|
|
83
83
|
SELECT COUNT(*) as n FROM intent_decisions d
|
|
84
84
|
LEFT JOIN intent_resolutions r
|
|
85
85
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
@@ -134,21 +134,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
134
134
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
135
135
|
WHERE d.event_id IN (${a})
|
|
136
136
|
ORDER BY d.decided_at ASC
|
|
137
|
-
`).all(c);if(o.json){let d=i.map(p=>({event:p,decisions:l.filter(
|
|
137
|
+
`).all(c);if(o.json){let d=i.map(p=>({event:p,decisions:l.filter(f=>f.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let p=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(p)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(u=>u.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let u of f){let w=u.outcome==="dispatched"?z.green(u.outcome):u.outcome==="dropped"?z.dim(u.outcome):z.yellow(u.outcome),y=u.agent_id?z.cyan(u.agent_id):z.dim("-"),k=u.reason?z.dim(` \u2014 ${u.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(u.decided_by)} \u2192 ${w} ${y}${k}`),u.resolution_status){let b=u.resolution_status==="ok"?z.green(u.resolution_status):z.red(u.resolution_status),v=u.duration_ms?`${(u.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(v)}`)}else u.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});To.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=vt(e),t=Kn(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
|
|
138
138
|
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
139
139
|
FROM intent_events
|
|
140
140
|
${n.length?"WHERE "+n.join(" AND "):""}
|
|
141
141
|
ORDER BY ts ASC
|
|
142
142
|
${i}
|
|
143
|
-
`).all(s).map(
|
|
143
|
+
`).all(s).map(u=>({id:u.id,ts:u.ts,source:u.source,sourceEventId:u.source_event_id,project:u.project,subject:u.subject,intent:u.intent,rawJson:u.raw_json}));if(r.length===0){console.log(z.dim(" (no events match filter)"));return}let a=new Set(r.map(u=>u.id)),c=r.map((u,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((u,w)=>[`id${w}`,u.id])),g=o.prepare(`
|
|
144
144
|
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
145
145
|
FROM intent_decisions
|
|
146
146
|
WHERE event_id IN (${c})
|
|
147
|
-
`).all(l).map(
|
|
147
|
+
`).all(l).map(u=>({eventId:u.event_id,decidedAt:u.decided_at,decidedBy:u.decided_by,agentId:u.agent_id,outcome:u.outcome,reason:u.reason})),d=o.prepare(`
|
|
148
148
|
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
149
149
|
FROM intent_resolutions
|
|
150
150
|
WHERE decision_event_id IN (${c})
|
|
151
|
-
`).all(l).map(
|
|
151
|
+
`).all(l).map(u=>({decisionEventId:u.decision_event_id,decisionDecidedBy:u.decision_decided_by,resolvedAt:u.resolved_at,status:u.status,durationMs:u.duration_ms,resultSummary:u.result_summary})),p=nm(Pc(sm(),"agentx-ledger-replay-")),f=new Ar({path:Pc(p,"target.sqlite")});try{let u=_c(f,r,g,d);if(e.json){console.log(JSON.stringify(u,null,2));return}console.log(z.bold(`Replayed ${u.eventsCount} events, ${u.decisionsCount} decisions, ${d.length} resolutions`)),u.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${u.divergences.length} divergences`)),Vo(u.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});dr();ig();rg();ag();sg();wr();qt();import{Command as cm}from"commander";import q from"chalk";import{existsSync as Mc}from"fs";import{resolve as li}from"path";import lm from"better-sqlite3";var qe=new cm().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Xe=".agentx/decisions/decisions.sqlite";function dm(e){return li(li(e.cwd??process.cwd()),e.path??Xe)}function lo(e,o=!1){let t=dm(e);Mc(t)||(console.log(q.red(` No decision store at ${t}`)),console.log(q.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new vn({path:t,readonly:!o})}catch(n){console.log(q.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(q.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function co(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(q.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(q.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function di(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function gi(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:di(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}qe.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Xe).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=lo(e),t=di(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
|
|
152
152
|
COUNT(*) AS calls,
|
|
153
153
|
SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
|
|
154
154
|
SUM(retries) AS retries,
|
|
@@ -204,13 +204,13 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
204
204
|
WHERE name = 'tool_use' AND action IS NOT NULL
|
|
205
205
|
AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
|
|
206
206
|
ORDER BY task_id, seq
|
|
207
|
-
`).all(...r);for(let d of g){let p=l.get(d.task_id)??[];p.push(d.action),l.set(d.task_id,p)}return c.map(d=>{let p=d.task_id,
|
|
207
|
+
`).all(...r);for(let d of g){let p=l.get(d.task_id)??[];p.push(d.action),l.set(d.task_id,p)}return c.map(d=>{let p=d.task_id,f=d.agent_id,u=Qr({taskId:p,agentId:f,channel:d.channel??"unknown",chatId:d.chat_id??"",startedAt:d.started_at,userMessage:(d.original_message??d.message_preview??"").trim(),userTurns:[],actions:l.get(p)??[],actionSummaries:[]}),w=Lc.map(y=>d[y]).filter(y=>typeof y=="number");return{taskId:p,agentId:f,cluster:u,startedAt:d.started_at,ok:d.status==="ok",tokens:w.length>0?w.reduce((y,k)=>y+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:_r(d.injected_context)}})}function mi(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function pi(e){let o=e.filter(n=>n!==null).sort((n,s)=>n-s);if(o.length===0)return null;let t=Math.floor(o.length/2);return o.length%2?o[t]:(o[t-1]+o[t])/2}function Fc(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:pi(e.map(o=>o.tokens)),medianTurns:pi(e.map(o=>o.turns)),medianDurationMs:pi(e.map(o=>o.durationMs))}}function qc(e,o={}){let t=Math.max(1,o.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of mi(r)){let g=`${r.agentId}\0${l}`;n.set(g,Math.min(n.get(g)??1/0,r.startedAt))}let a=`${r.agentId}\0${r.cluster}`,c=s.get(a)??[];c.push(r),s.set(a,c)}let i=[];for(let r of s.values()){let{agentId:a,cluster:c}=r[0],l=new Set(r.flatMap(mi));for(let g of l){let d=n.get(`${a}\0${g}`),p=r.filter(u=>u.injected!==null&&u.startedAt<d),f=r.filter(u=>mi(u).includes(g));p.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Fc(p),after:Fc(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Oo from"chalk";function mm(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function pm(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function um(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function ui(e,o){if(e==null||o==null||e===0)return"";let t=Math.round((o-e)/e*100);return t===0?" (=)":` (${t>0?"+":""}${t}%)`}function Wc(e,o,t){let n=`${Math.round(o.successRate*100)}%`,s=t?` (${o.successRate>=t.successRate?"+":""}${Math.round((o.successRate-t.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(o.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${mm(o.medianTokens)}${t?ui(t.medianTokens,o.medianTokens):""}`,`turns ${um(o.medianTurns)}${t?ui(t.medianTurns,o.medianTurns):""}`,`time ${pm(o.medianDurationMs)}${t?ui(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function Bc(e,o){if(e.length===0)return[Oo.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Oo.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let t=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&t.push(""),t.push(`${Oo.bold(s.agentId)} ${Oo.cyan(s.cluster)}`),n=i),t.push(` ${Oo.yellow(s.lesson)} ${Oo.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Oo.dim(Wc("before",s.before))),t.push(Wc("after",s.after,s.before))}return t.push(""),t.push(Oo.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var xt=new fm().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Qn(e){let o=Jc(e.cwd??process.cwd()),t=Jc(o,e.path??".agentx/db.sqlite");hm(t)||(console.log(T.red(` No db at ${t}`)),console.log(T.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new ym(t,{readonly:!0})}catch(n){console.log(T.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(T.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function wm(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Gc(e){if(!e)return;let o=wm(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(T.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function bm(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function fi(e){return e==="ok"?T.green:e==="error"||e==="timeout"?T.red:e==="in-flight"?T.yellow:T.dim}xt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Qn(e),t=Dr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Gc(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(T.dim(" (no traces)"));return}for(let n of t){let s=fi(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?T.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?T.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${T.dim(n.taskId)} ${s} ${T.bold(n.agentId)}${T.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${T.dim("\xB7")} ${i}${a} ${T.dim(bm(n.startedAt))}`),n.error&&console.log(` ${T.red("error:")} ${n.error}`)}});xt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Qn(o),n=Ms(t,e);if(n||(console.log(T.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}$m(n.task,n.steps)});function $m(e,o){let t=fi(e.status)(e.status);if(console.log(T.bold(`Trace ${e.taskId}`)),console.log(` ${T.dim("agent")} ${e.agentId}`),console.log(` ${T.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${T.dim("workflow")} ${T.cyan(e.workflowRunId)}${n?T.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${T.dim("intent")} ${e.intentEventId} ${T.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${T.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${T.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${T.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${T.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${T.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${T.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.numTurns!=null&&console.log(` ${T.dim("turns")} ${e.numTurns}`),e.injectedContext){let{memory:n,procedures:s,wiki:i}=e.injectedContext,r=[...n.map(a=>`memory:${a}`),...s.map(a=>`procedure:${a}`),...i?["wiki"]:[]];console.log(` ${T.dim("lessons")} ${r.length?r.join(" "):T.dim("none")}`)}if(e.error&&console.log(` ${T.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${T.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(T.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(T.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?fi(n.status)(n.status):T.dim("\u2014"),i=n.action?T.cyan(n.action):"";if(console.log(` ${T.dim(`#${n.seq}`)} ${T.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?T.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
208
208
|
`).slice(0,8);console.log(r.map(a=>` ${T.dim("\u2192")} ${a}`).join(`
|
|
209
209
|
`)),n.inputSummary.split(`
|
|
210
210
|
`).length>8&&console.log(` ${T.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
211
211
|
`).slice(0,8);console.log(r.map(a=>` ${T.dim("\u2190")} ${a}`).join(`
|
|
212
212
|
`)),n.outputSummary.split(`
|
|
213
|
-
`).length>8&&console.log(` ${T.dim("\u2026")}`)}n.error&&console.log(` ${T.red("error:")} ${n.error}`)}}xt.command("lessons").description("compare repeated tasks before and after each lesson (memory, procedure, wiki) was used").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","only this agent").option("--since <duration>","only tasks newer than (e.g. 7d, 30d)","30d").option("--min <n>","minimum tasks on each side of a lesson","2").option("--json","emit JSON").action(e=>{let o=Qn(e),t=Math.max(1,parseInt(e.min,10)||2),n=Uc(o,{since:Gc(e.since),agentId:e.agent}),s=qc(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of Bc(s,{minSamples:t}))console.log(i)});xt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Qn(o),n=Ms(t,e);n||(console.log(T.red(` task not found: ${e}`)),console.log(T.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(T.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(T.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(T.bold(` replay ${T.cyan(e)}`)),console.log(T.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(T.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(
|
|
213
|
+
`).length>8&&console.log(` ${T.dim("\u2026")}`)}n.error&&console.log(` ${T.red("error:")} ${n.error}`)}}xt.command("lessons").description("compare repeated tasks before and after each lesson (memory, procedure, wiki) was used").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","only this agent").option("--since <duration>","only tasks newer than (e.g. 7d, 30d)","30d").option("--min <n>","minimum tasks on each side of a lesson","2").option("--json","emit JSON").action(e=>{let o=Qn(e),t=Math.max(1,parseInt(e.min,10)||2),n=Uc(o,{since:Gc(e.since),agentId:e.agent}),s=qc(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of Bc(s,{minSamples:t}))console.log(i)});xt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Qn(o),n=Ms(t,e);n||(console.log(T.red(` task not found: ${e}`)),console.log(T.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(T.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(T.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(T.bold(` replay ${T.cyan(e)}`)),console.log(T.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(T.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(T.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let d=await g.json().catch(()=>({})),p=Date.now()-l;if(g.ok||(console.log(T.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(T.bold(" INPUT (replayed verbatim)")),console.log(),Xn(i),console.log(),console.log(T.bold(` ORIGINAL OUTPUT ${T.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Xn(s.finalResponse):console.log(T.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(T.bold(` CURRENT OUTPUT ${T.dim(`status=${d.error?"error":"ok"} ${p}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Xn(d.content??"(empty reply)"),d.error&&console.log(T.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?T.dim(" outputs are identical"):T.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(T.green(` \u2713 replayed in ${p}ms`)),console.log(),Xn(d.content??"(empty reply)"),d.error&&console.log(T.red(`
|
|
214
214
|
error: ${d.error}`)),console.log(),console.log(T.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Xn(e){let o=e.split(`
|
|
215
215
|
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${T.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${T.dim("\u2502")} ${T.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Sm}from"commander";import me from"chalk";import{existsSync as Em,mkdirSync as Am,writeFileSync as Im}from"fs";import{resolve as Yc,join as zc,dirname as Tm}from"path";var km=`# AgentX destructive-action guardrails \u2014 global policy
|
|
216
216
|
#
|
|
@@ -279,7 +279,7 @@ State indicators are usually small and specific: a coloured dot, a pill or badge
|
|
|
279
279
|
|
|
280
280
|
Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function Um(e,o,t,n){let s=Wm();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Qc(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
|
|
281
281
|
|
|
282
|
-
The image is the region ${qm(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Fm,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),l;try{l=await fetch(Pm,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let
|
|
282
|
+
The image is the region ${qm(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Fm,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),l;try{l=await fetch(Pm,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let u=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${u.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(d.function.arguments),f=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function ns(e,o={}){let t=Date.now(),n=await Lm(o.region??{kind:"window"},o.maxPixels??Zc,{settle:o.settle,screen:o.screen}),s=await Um(e,n,o.model??Mm,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function qm(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var nn;function Wm(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(nn!==void 0)return nn??void 0;try{let e=Qc(Dm(_m(),".agentx","openrouter-key.txt"),"utf-8").trim();nn=e.length>0?e:null}catch{nn=null}return nn??void 0}import{execFile as Bm}from"child_process";import{promisify as Jm}from"util";var Gm=Jm(Bm),Hm=["screencapture"],zm=["Screen Studio","OBS","QuickTime Player","Zoom"];async function ol(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Ym()),t}async function Ym(){let e=await el(Hm);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await el(zm);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function el(e){let o=[];for(let t of e)try{let{stdout:n}=await Gm("pgrep",["-x",t]),s=n.trim().split(`
|
|
283
283
|
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Wt();qt();var tl="screen-state",nl={observable:mo("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:mo("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function sl(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function il(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Vm=.6,Km=.7,Xm=.3;async function sn(e,o={}){let[t,n]=await Promise.all([ns(e,o),ol(e).catch(()=>[])]),s=o.observableFloor??Vm,i=await no(tl,sl({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:ep(t),treeNote:o.treeNote,probes:n}),nl,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Zm(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=il(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${ss(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Km?"confirmed":a<=Xm?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Qm(c,a,t),sighting:t,probes:n}}function Qm(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${ss(o)}). ${n}`:e==="refuted"?`Not true (${ss(1-o)} it is false). ${n}`:`Inconclusive (${ss(o)}, between the thresholds). ${n}`}function Zm(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function ep(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var ss=e=>`${Math.round(e*100)}%`;var rl=new op().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--settle","wait for the region to stop moving before capturing it").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(We.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await sn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?so():void 0});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?We.green("\u2713"):s.outcome==="refuted"?We.red("\u2717"):We.yellow("?");console.log(` ${i} ${We.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(We.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(We.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await ns(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?so():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${We.bold(n.observation)}`),n.evidence&&console.log(We.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${tp(n.reading)}`),console.log(We.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(We.red(` ${n?.message??n}`)),process.exit(1)}});function tp(e){return e==="yes"?We.green(e):e==="no"?We.red(e):We.yellow(e)}import{Command as np}from"commander";import Ze from"chalk";import{spawn as sp}from"child_process";function Co(e){console.log(Ze.red(` ${e}`)),process.exit(1)}function al(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?Ze.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(Ze.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function ip(e){return new Promise(o=>{let t=sp(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var rn=new np("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");rn.command("capture").description("capture a region, optionally waiting for it to change or settle, or around a command").argument("[command...]","run this after arming; capture what it changes (put it after --)").option("--region <name|x,y,w,h>","window, screen, menubar, notifications, a name from screen.regions, or x,y,w,h","window").option("--until-changed","wait for the region to change first").option("--until-stable","wait for the region to stop changing").option("--max-pixels <n>","pixel budget for this capture (default screen.maxPixels)").option("--out <path>","where to write the PNG").option("-c, --config <path>","agentx.json to read screen settings from").option("--json","print the result as JSON").action(async(e,o)=>{let t=so(o.config),n;try{n=Pn(o.region,t)}catch(r){Co(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Co("--max-pixels must be a whole number above 0");let i={settings:t,maxPixels:s};try{if(e.length){let r=o.untilStable||!o.untilChanged,{result:a,shot:c,error:l}=await Mn(()=>ip(e),n,{out:o.out,untilStable:r},i);c||(console.log(Ze.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),al(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}al(await ut(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Co(r?.message??String(r))}});rn.command("recent").description("frames from the daemon's in-memory screen buffer (screen.buffer must be on)").option("--seconds <n>","how far back (default screen.buffer.seconds)").option("--url <url>","daemon URL",process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Bo()}`).option("--json","print the result as JSON").action(async e=>{let o=process.env.MESH_TOKEN,t=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${t}`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||Co(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(Ze.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${Ze.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Co(`could not reach the daemon: ${n?.message??n}`)}});rn.command("config").description("show or change screen capture settings (agentx.json `screen`)").option("--max-pixels <n>","pixel budget for a captured frame").option("--timeout <ms>","longest a capture waits").option("--interval <ms>","time between samples while waiting").option("--threshold <0-1>","difference that counts as a change").option("--stable-ms <ms>","how long a region must hold still to be stable").option("--region <name=x,y,w,h>","add or change a named region",(e,o)=>[...o,e],[]).option("--remove-region <name>","remove a named region",(e,o)=>[...o,e],[]).option("--buffer <state>","on | off: keep recent frames in memory").option("--buffer-seconds <n>","how many seconds the buffer keeps").option("--buffer-fps <n>","samples per second").option("--buffer-region <name|x,y,w,h>","region the buffer watches").option("--buffer-max-pixels <n>","pixel budget per buffered frame").option("-c, --config <path>","agentx.json to read and change (default: ./agentx.json)").action(e=>{let o={};e.maxPixels!==void 0&&(o.maxPixels=e.maxPixels),e.timeout!==void 0&&(o.timeoutMs=e.timeout),e.interval!==void 0&&(o.intervalMs=e.interval),e.threshold!==void 0&&(o.changeThreshold=e.threshold),e.stableMs!==void 0&&(o.stableMs=e.stableMs);let t={};for(let s of e.region){let i=s.indexOf("=");i<1&&Co(`--region wants name=x,y,w,h, got "${s}"`),t[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)t[s]=null;Object.keys(t).length&&(o.regions=t);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||Co("--buffer must be on|off"),n.enabled=s==="on"}if(e.bufferSeconds!==void 0&&(n.seconds=e.bufferSeconds),e.bufferFps!==void 0&&(n.fps=e.bufferFps),e.bufferRegion!==void 0&&(n.region=e.bufferRegion),e.bufferMaxPixels!==void 0&&(n.maxPixels=e.bufferMaxPixels),Object.keys(n).length&&(o.buffer=n),Object.keys(o).length===0){let s=so(e.config);console.log(`
|
|
284
284
|
maxPixels ${s.maxPixels}`),console.log(` wait timeout ${s.timeoutMs}ms \xB7 every ${s.intervalMs}ms \xB7 change > ${s.changeThreshold} \xB7 stable ${s.stableMs}ms`);let i=Object.entries(s.regions).map(([a,c])=>`${a}=${c.x},${c.y},${c.width},${c.height}`);console.log(` regions ${i.length?i.join(" "):Ze.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":Ze.dim("off")} ${Ze.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
|
|
285
285
|
`);return}try{let{summary:s,backupPath:i}=po(r=>{let a=Ya(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(Ze.green(`
|
|
@@ -360,55 +360,55 @@ return id`:`${n}
|
|
|
360
360
|
const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
|
|
361
361
|
const aid = typeof arrow === 'string' ? arrow : arrow?.id
|
|
362
362
|
if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
|
|
363
|
-
return aid ?? null`}function Gp(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[fo(s[0][0],s[0][1]),fo(i[0],i[1])]}if(e.kind==="geo")return[fo(e.x,e.y),fo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Nl(e);return[fo(s.x,s.y+s.h/2),fo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[fo(t.x+t.w/2,t.y+t.h/2),fo(n.x+n.w/2,n.y+n.h/2)]}var fo=(e,o)=>({x:e,y:o,w:0,h:0});async function _l(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Wp(60)),g=new Set,d=new Map,p=[],
|
|
363
|
+
return aid ?? null`}function Gp(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[fo(s[0][0],s[0][1]),fo(i[0],i[1])]}if(e.kind==="geo")return[fo(e.x,e.y),fo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Nl(e);return[fo(s.x,s.y+s.h/2),fo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[fo(t.x+t.w/2,t.y+t.h/2),fo(n.x+n.w/2,n.y+n.h/2)]}var fo=(e,o)=>({x:e,y:o,w:0,h:0});async function _l(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Wp(60)),g=new Set,d=new Map,p=[],f=!1,u=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},v=x=>{if(g.size>=vi)return;let $=jl(x,g);if(!$){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add($.id),w??=i()-c,p.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let x=new rs;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))x.push($).forEach(v);x.flush().forEach(v)}catch($){y=$?.message??String($)}finally{u=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=p.shift();if(!x){if(f)break;await new Promise(D=>{k=D});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let $=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,Rl(x))}catch(D){n({type:"error",error:`palette: ${D?.message??D}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-$});continue}let[C,j]=Gp(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(Cl(l,C.x,C.y)),await s(250),o.presence.moveTo(Cl(l,j.x,j.y));try{await o.api.exec(t.docId,Jp(x,a))}catch(D){n({type:"error",error:`${x.id}: ${D?.message??D}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?Nl(x):x.kind==="path"?Bp(x.pts):fo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let O=(x.say?r:0)-(i()-$);O>0&&await s(O)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:u}}import{readFileSync as Hp}from"fs";import{homedir as zp}from"os";import{join as Yp}from"path";var an=Yp(zp(),"Library","Application Support","tldraw","server.json"),as=class{constructor(o=an,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Hp(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var eu=Zp(Vp),ou="claude-sonnet-5";function tu(e){e.type==="planned"?console.log(oo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${oo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${oo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(oo.yellow(` skipped: ${e.line}`)):console.log(oo.red(` error: ${e.error}`))}async function nu(){if(!xi(an)){await eu("open",["-a","tldraw offline"]);for(let e=0;e<40&&!xi(an);e++)await new Promise(o=>setTimeout(o,500));if(!xi(an))throw new Error("tldraw offline did not start")}}async function Pl(e,o){let t=R(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||ou,i=Qp(o.out||Dl(Xp(),"Documents")),r=_n(n,t.agents[n]),a=pt({system:Ol(),model:s}),c=new Dn(r,Ce,n),l=new as;try{await nu();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(oo.bold(`
|
|
364
364
|
${r.name} draws: ${e}`)+oo.dim(` (${s}, ${d.filePath})
|
|
365
|
-
`));let p=new AbortController;process.once("SIGINT",()=>p.abort());let
|
|
366
|
-
${
|
|
365
|
+
`));let p=new AbortController;process.once("SIGINT",()=>p.abort());let f=await _l(e,{api:l,presence:c,model:a},{docId:d.id,signal:p.signal},tu);await l.exec(d.id,"await helpers.saveDoc(); return true");let u=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Dl(i,`agentx-draw-${g}.png`);Kp(w,Buffer.from(u.slice(u.indexOf(",")+1),"base64")),console.log(oo.bold(`
|
|
366
|
+
${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+oo.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let y=a.lastUsage;y&&console.log(oo.dim(` tokens: ${y.inputTokens} in, ${y.outputTokens} out, ${y.cacheReadTokens} cache read, ${y.cacheWriteTokens} cache write; cost ${y.costUsd===null?"not reported":`$${y.costUsd.toFixed(4)}`}`)),console.log(oo.dim(` ${d.filePath}
|
|
367
367
|
${w}
|
|
368
368
|
`))}finally{a.close(),c.close()}}var Ei=ru(iu),Fl=new su().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${vo}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await Pl(String(o.live),o):await Sl(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
|
|
369
369
|
lessons
|
|
370
370
|
`));for(let g of $i)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
|
|
371
371
|
`);return}let t=$i.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),au(Ce)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:mu(o.voice,o.agent);console.log(X.bold(`
|
|
372
372
|
${t.title}`)),console.log(X.dim(` ${t.appHint}
|
|
373
|
-
`));try{t.start&&(await Ei("/usr/bin/open",du(t.start)),await No(2e3),await cs(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Ll(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Ml("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await No(2e3));let r=o.hud===!1?null:Ml(Ce,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,p,
|
|
374
|
-
`)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await cs(d.before)}let p=o.speak===!1?Promise.resolve():uu(d.say,n),
|
|
373
|
+
`));try{t.start&&(await Ei("/usr/bin/open",du(t.start)),await No(2e3),await cs(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Ll(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Ml("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await No(2e3));let r=o.hud===!1?null:Ml(Ce,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,p,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:p,avoid:f})+`
|
|
374
|
+
`)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await cs(d.before)}let p=o.speak===!1?Promise.resolve():uu(d.say,n),f=d.find?await gu(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await p,new Error(`Could not find "${d.find}"; stopped before acting`);if(await p,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Ei(Ce,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:u,changed:w}=await Si(["click"]);if(u)throw new Error(u);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:u??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await No(d.afterClickWaitMs??1500)}if(d.type){await cs(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:u}=await Si(["type","--text",d.type]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(d.key){await cs(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:u}=await Si(["key","--name",d.key]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:u}),new Error(u)}if(!f&&!d.type&&!d.key?await No((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await No(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u=!!(d.click||d.type||d.key),w;try{w=await sn(d.verify,u?{settle:!0,screen:so()}:{})}catch(y){w=null,console.log(X.yellow(` ? could not check: ${y?.message??y}`))}if(!w&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(w){let y=w.outcome==="confirmed"?X.green("\u2713"):w.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${y} ${X.dim(w.reason)}`),!w.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(X.red(`
|
|
375
375
|
stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${w.reason}`)),console.log(X.dim(` screenshot: ${w.sighting.shot.path}`)),await No(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await No(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await No(2500);try{let{size:g}=cu(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(X.red(` lesson stopped before the end.
|
|
376
376
|
`)),process.exitCode=3;return}console.log(X.green(`
|
|
377
377
|
done.
|
|
378
378
|
`))});function du(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Ll(lu(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function cs(e){let o=await sn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Si(e){try{let{stdout:o}=await Ei(Ce,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function gu(e,o=[]){try{let t=await Rn({max:45});if(t.candidates.length<2)return null;let n=await no(tn,es({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),os(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=ts(n.answers,t.candidates);return s.present<.5?null:Yt(t,s.id)}catch{return null}}function mu(e,o){if(e?.trim().toLowerCase()===vo)return{provider:"system",elevenlabs:zt(),system:null,fallback:!0};let t=e?Cn(e,Ht()):null;if(t)return{provider:"system",elevenlabs:zt(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=R(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Ma(Da(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:zt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
|
|
379
|
-
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:zt(),system:null,fallback:!0}}}var pu=new mt;async function uu(e,o){o&&await pu.say({voice:o,text:e})}var No=e=>new Promise(o=>setTimeout(o,e));ge();import{Command as Ul}from"commander";import Be from"chalk";import{createInterface as ql}from"readline";var fu=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function At(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(fu()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function hu(e){e.type==="line"?console.log(`${Be.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Be.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Be.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Be.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Be.dim(" \xB7 hushed")):e.type==="error"?console.log(Be.red(` error: ${e.error}`)):e.type==="end"&&console.log(Be.dim(` \xB7 ended (${e.reason})`))}function Wl(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function yu(e,o,t){let n=R(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await At("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Fa(()=>n,()=>d),i.usePool(await La(_a()))}let r=e.map(d=>s[d]?Nn(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new qa({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new mt,listener:n.voice.listener,model:(d,p)=>pt({system:p})});l.on(hu),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Be.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=ql({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Be.dim(` ${Wl(l.gaps)}`))}async function wu(e,o,t){let n=await At("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=ql({input:process.stdin});s.on("line",a=>{a.trim()&&At("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void At("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await At("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Be.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Be.dim(` ${Wl(r)}`))}var Bl=new Ul().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?yu:wu)([e,o],s,n),process.exit(0)}catch(i){console.error(Be.red(` ${i?.message??i}`)),process.exit(1)}}),Jl=new Ul().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Be.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await At("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Be.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ge();import{Command as bu}from"commander";import Te from"chalk";import{existsSync as $u,readFileSync as ku,writeFileSync as vu}from"fs";import{resolve as Gl}from"path";var ls=new bu().name("voice").description("list installed system voices and pick each agent's voice");function xu(e){let o=e?[e]:[Gl(process.cwd(),"agentx.json"),Gl(process.cwd(),".agentx/config.json")],t=o.find(n=>$u(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Su(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},
|
|
379
|
+
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:zt(),system:null,fallback:!0}}}var pu=new mt;async function uu(e,o){o&&await pu.say({voice:o,text:e})}var No=e=>new Promise(o=>setTimeout(o,e));ge();import{Command as Ul}from"commander";import Be from"chalk";import{createInterface as ql}from"readline";var fu=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function At(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(fu()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function hu(e){e.type==="line"?console.log(`${Be.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Be.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Be.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Be.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Be.dim(" \xB7 hushed")):e.type==="error"?console.log(Be.red(` error: ${e.error}`)):e.type==="end"&&console.log(Be.dim(` \xB7 ended (${e.reason})`))}function Wl(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function yu(e,o,t){let n=R(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await At("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Fa(()=>n,()=>d),i.usePool(await La(_a()))}let r=e.map(d=>s[d]?Nn(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new qa({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new mt,listener:n.voice.listener,model:(d,p)=>pt({system:p})});l.on(hu),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Be.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=ql({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Be.dim(` ${Wl(l.gaps)}`))}async function wu(e,o,t){let n=await At("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=ql({input:process.stdin});s.on("line",a=>{a.trim()&&At("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void At("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await At("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Be.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Be.dim(` ${Wl(r)}`))}var Bl=new Ul().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?yu:wu)([e,o],s,n),process.exit(0)}catch(i){console.error(Be.red(` ${i?.message??i}`)),process.exit(1)}}),Jl=new Ul().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Be.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await At("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Be.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ge();import{Command as bu}from"commander";import Te from"chalk";import{existsSync as $u,readFileSync as ku,writeFileSync as vu}from"fs";import{resolve as Gl}from"path";var ls=new bu().name("voice").description("list installed system voices and pick each agent's voice");function xu(e){let o=e?[e]:[Gl(process.cwd(),"agentx.json"),Gl(process.cwd(),".agentx/config.json")],t=o.find(n=>$u(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Su(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===vo,y=w?null:Cn(t,s,a??e?.voice?.locale),k=y?`system voice ${Bs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?vo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)p(w?vo:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let u=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:u}}ls.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Ht(),t;try{t=R(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Pa(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Js(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Te.yellow(`
|
|
380
380
|
No system voices found (system voices need macOS).
|
|
381
381
|
`));else{let r=e.all?Ws(o,""):Ws(o,n);console.log(Te.bold(`
|
|
382
382
|
System voices${e.all?"":` (${n})`}, best first
|
|
383
383
|
`));for(let a of r){let c=a.siri?Te.magenta("siri"):a.quality==="standard"?Te.dim("standard"):Te.green(a.quality),l=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Te.dim((a.gender??"").padEnd(7))} ${l?Te.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Te.dim(`
|
|
384
384
|
More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Te.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Te.bold(`
|
|
385
385
|
Agents
|
|
386
|
-
`));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=p=>p?Bs(p):Te.dim("system default"),g=Object.entries(Js(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,
|
|
386
|
+
`));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=p=>p?Bs(p):Te.dim("system default"),g=Object.entries(Js(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,f])=>`${Te.dim(`${p}:`)} ${l(f)}`).join(Te.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Te.dim("(default voice)")}`:`system ${l(i.get(r))}${g?Te.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?Te.dim(` (${a.voice.gender})`):""}`)}}console.log()});ls.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${vo}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=xu(t.config),{raw:s,summary:i}=Su(JSON.parse(ku(n,"utf8")),e,o,t,Ht());vu(n,JSON.stringify(s,null,2)+`
|
|
387
387
|
`),console.log(Te.green(` ${e}: ${i}`)),console.log(Te.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Te.red(` ${n.message}`)),process.exit(1)}});import{Command as Eu}from"commander";import L from"chalk";var Zo=new Eu().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ai=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Bo()}`;function Ii(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Ti(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function Oi(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:o}function Hl(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function Au(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=o?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(t)} ${Hl(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Zo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ds.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ai).action(async(e,o)=>{let t=Ii(o.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),Ir(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${Ds.join(", ")}`)),process.exit(1)),zn()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Ti(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${Hl(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(L.red(`Bind failed: ${Oi(n)}`)),process.exit(1)}});Zo.command("detach").description("stop wearing an identity in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ai).action(async e=>{let o=Ii(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Ti(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(L.red(`Detach failed: ${Oi(t)}`)),process.exit(1)}});Zo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ai).option("--json","raw JSON output").action(async e=>{let o=Ii();try{let n=(await Ti(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:zn(),sessions:n},null,2));return}console.log(),console.log(zn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(Kt())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let r of s)Au(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
|
|
388
388
|
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${Oi(t)}`)),process.exit(1)}});Zo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Bo()),t=bc(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(t.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(t.path)}`),console.log(L.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
|
|
389
389
|
settings \u2014 without this an attached production identity would be less
|
|
390
|
-
guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Zo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=$c({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as Iu}from"commander";import ye from"chalk";var ds=new Iu().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Yl(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=R(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Vl(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function zl(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Tu(e){return e==="busy"?ye.magenta:e==="warm-hot"?ye.green:e==="warm-cold"?ye.cyan:e==="idle"?ye.yellow:e==="dead"?ye.red:ye.dim}ds.command("list").description("list every live persistent claude process").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)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Yl(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Vl(t)})}catch(r){console.log(ye.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ye.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ye.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ye.dim(" (no processes)"));return}for(let r of i){let a=Tu(r.state)(r.state.padEnd(9)),c=zl(r.spawnedAt),l=r.lastTurnAt?zl(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ye.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?ye.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ye.dim("sess=\u2014"),p=r.pendingTaskId?ye.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ye.bold(r.key.agentId)}${ye.dim(":"+r.key.channel+":"+r.key.chatId)} ${ye.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${p}`),r.deadReason&&console.log(` ${ye.red("dead:")} ${r.deadReason}`)}});ds.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").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)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Yl(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Vl(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ye.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ye.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ye.red(` ${a}`)),process.exit(1)}console.log(ye.green(` killed ${e}:${o}:${t}`))});import{Command as Ou}from"commander";import _e from"chalk";import{existsSync as ji,rmSync as ju}from"fs";import{resolve as Ci}from"path";var It=new Ou().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");It.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,o,t)=>{o.length===0&&(console.log(_e.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Cr(e,o,{verbose:n}),r=Date.now()-s;console.log(_e.green(` \u2713 indexed ${i.docs} doc(s) for ${_e.bold(e)} in ${r}ms`)),console.log(_e.dim(` \u2192 ${i.path}`))});It.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Ci(e.cwd,".agentx","rag");if(!ji(o)){console.log(_e.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ji(Ci(o,s,"index.json")));if(n.length===0){console.log(_e.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ps(s);console.log(` ${_e.bold(s)} ${i.docs} doc(s) ${_e.dim(i.path)}`)}});It.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,o,t)=>{let n=parseInt(t.k,10)||5,s=Nr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ps(e);i.exists?console.log(_e.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(_e.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${_e.bold(i.title)} ${_e.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${_e.dim(i.path)}`),console.log(` ${_e.dim(i.snippet.slice(0,200))}`)});It.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Ci(process.cwd(),".agentx","rag",e);if(!ji(o)){console.log(_e.dim(` no index for ${e} \u2014 nothing to clear`));return}ju(o,{recursive:!0,force:!0}),console.log(_e.green(` \u2713 cleared index for ${e}`))});ge();import{Command as Cu}from"commander";import K from"chalk";import Tt from"prompts";var et=new Cu().name("backlog").description("manage the local backlog used by business workSource=backlog");function cn(e){let o=R(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ga(n)}}function Nu(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function Ru(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}et.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:o}=cn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${Ru(n.status).padEnd(7)} ${Nu(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});et.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=cn(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Ha([o],i.source,n.config),a=await zs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});et.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,o)=>{let t=cn(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await zs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});et.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=cn(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});et.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 o=cn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.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=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Tt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Du(o.config):Pu(o.config);y.length?(i=(await Tt({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,i==="__CUSTOM__"&&(i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Tt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Mu(o.config,i,a):await Lu(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Hs({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),u=(await Tt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!u.length){console.log(K.dim(" nothing selected"));return}let f=u.map(y=>{let k={type:s,host:s==="gitlab"?_u(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Hs(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(f);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function _u(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Du(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Pu(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Mu(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.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 Lu(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Kl)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Kl):[]}function Kl(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Fu}from"commander";import W from"chalk";import{existsSync as Uu,readFileSync as qu}from"fs";import{resolve as Wu}from"path";import Bu from"prompts";ge();function Xl(e){let o=e||Wu(process.cwd(),"agentx.json");return Uu(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(qu(o,"utf-8"))}async function Ju(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Bu([{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||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var ho=new Fu().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ho.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("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Fs})`,Fs).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,o)=>{if(!e){ho.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Ls(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Xl(o.config),s=gr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Ju(o.notify,s),r=o.id||Fr(t.matched,o.agent),a=qr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await he(d=>Ae(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.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 t=Xl(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Br(Wr(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])ho.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Hr(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!gt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Pr(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",Jr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Gr,"reject an agent's pending create/delete request (drops the request)"]])ho.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ls(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Gu}from"commander";import ve from"chalk";var Ro=new Gu("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Hu={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Ql(){return{root:process.cwd()}}function Ni(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function zu(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${Hu[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Ni(e.snoozed_until)})`):""}`),console.log(` ${ve.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ve.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(ve.yellow(` Expires ${Ni(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ve.dim(` ${e.detail}`)),e.source&&console.log(ve.dim(` ${e.source}`)),console.log(ve.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Ro.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 o=wa(Ql(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ve.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ve.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)zu(t),console.log();console.log(ve.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Ri(e,o,t){let n=Fn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ve.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await ba(Ql(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(ve.red(` ${i.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 ${i.message}`))}Ro.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").action((e,o)=>Ri(e,"yes",o));Ro.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,o)=>Ri(e,"no",o));Ro.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,o)=>Ri(e,"later",o));Ro.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: ${ha.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").action(e=>{let o=Fn(),t=ya(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(ve.red(` ${t.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 card:${t.card.id} raised; expires ${Ni(t.card.expires)}, then: ${t.card.if_silent}`))});Ro.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("--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').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=oc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(ve.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await tc(o);if(!a.success){console.error(ve.red(` ${a.error}`)),process.exitCode=1;return}console.log(ve.green(" \u2713 saved")+(a.reloaded?ve.dim(" (daemon reloaded)"):""))}let i=Fn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as yf}from"commander";import Ot from"chalk";import te from"chalk";import dn from"prompts";import{readFileSync as Yu,writeFileSync as Vu,existsSync as Ku}from"fs";import{resolve as Zl}from"path";var Xu=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Qu(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function _i(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ed(e=".env"){let o=Zl(e);if(!Ku(o))return[];let t=Yu(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Xu);i?n.push({kind:"kv",key:i[1],value:Qu(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Zu(e){return e.map(o=>o.kind==="kv"?`${o.key}=${_i(o.value)}`:o.raw).join(`
|
|
390
|
+
guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Zo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=$c({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as Iu}from"commander";import ye from"chalk";var ds=new Iu().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Yl(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=R(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Vl(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function zl(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Tu(e){return e==="busy"?ye.magenta:e==="warm-hot"?ye.green:e==="warm-cold"?ye.cyan:e==="idle"?ye.yellow:e==="dead"?ye.red:ye.dim}ds.command("list").description("list every live persistent claude process").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)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Yl(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Vl(t)})}catch(r){console.log(ye.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ye.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ye.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ye.dim(" (no processes)"));return}for(let r of i){let a=Tu(r.state)(r.state.padEnd(9)),c=zl(r.spawnedAt),l=r.lastTurnAt?zl(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ye.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?ye.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ye.dim("sess=\u2014"),p=r.pendingTaskId?ye.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ye.bold(r.key.agentId)}${ye.dim(":"+r.key.channel+":"+r.key.chatId)} ${ye.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${p}`),r.deadReason&&console.log(` ${ye.red("dead:")} ${r.deadReason}`)}});ds.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").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)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Yl(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Vl(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ye.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ye.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ye.red(` ${a}`)),process.exit(1)}console.log(ye.green(` killed ${e}:${o}:${t}`))});import{Command as Ou}from"commander";import _e from"chalk";import{existsSync as ji,rmSync as ju}from"fs";import{resolve as Ci}from"path";var It=new Ou().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");It.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,o,t)=>{o.length===0&&(console.log(_e.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Cr(e,o,{verbose:n}),r=Date.now()-s;console.log(_e.green(` \u2713 indexed ${i.docs} doc(s) for ${_e.bold(e)} in ${r}ms`)),console.log(_e.dim(` \u2192 ${i.path}`))});It.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Ci(e.cwd,".agentx","rag");if(!ji(o)){console.log(_e.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ji(Ci(o,s,"index.json")));if(n.length===0){console.log(_e.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ps(s);console.log(` ${_e.bold(s)} ${i.docs} doc(s) ${_e.dim(i.path)}`)}});It.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,o,t)=>{let n=parseInt(t.k,10)||5,s=Nr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ps(e);i.exists?console.log(_e.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(_e.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${_e.bold(i.title)} ${_e.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${_e.dim(i.path)}`),console.log(` ${_e.dim(i.snippet.slice(0,200))}`)});It.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Ci(process.cwd(),".agentx","rag",e);if(!ji(o)){console.log(_e.dim(` no index for ${e} \u2014 nothing to clear`));return}ju(o,{recursive:!0,force:!0}),console.log(_e.green(` \u2713 cleared index for ${e}`))});ge();import{Command as Cu}from"commander";import K from"chalk";import Tt from"prompts";var et=new Cu().name("backlog").description("manage the local backlog used by business workSource=backlog");function cn(e){let o=R(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ga(n)}}function Nu(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function Ru(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}et.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:o}=cn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${Ru(n.status).padEnd(7)} ${Nu(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});et.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=cn(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Ha([o],i.source,n.config),a=await zs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});et.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,o)=>{let t=cn(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await zs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});et.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=cn(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});et.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 o=cn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.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=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Tt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Du(o.config):Pu(o.config);y.length?(i=(await Tt({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,i==="__CUSTOM__"&&(i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Tt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Mu(o.config,i,a):await Lu(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Hs({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Tt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let k={type:s,host:s==="gitlab"?_u(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Hs(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function _u(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Du(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Pu(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Mu(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.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 Lu(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Kl)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Kl):[]}function Kl(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Fu}from"commander";import W from"chalk";import{existsSync as Uu,readFileSync as qu}from"fs";import{resolve as Wu}from"path";import Bu from"prompts";ge();function Xl(e){let o=e||Wu(process.cwd(),"agentx.json");return Uu(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(qu(o,"utf-8"))}async function Ju(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Bu([{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||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var ho=new Fu().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ho.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("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Fs})`,Fs).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,o)=>{if(!e){ho.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Ls(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Xl(o.config),s=gr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Ju(o.notify,s),r=o.id||Fr(t.matched,o.agent),a=qr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await he(d=>Ae(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.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 t=Xl(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Br(Wr(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])ho.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Hr(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!gt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Pr(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",Jr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Gr,"reject an agent's pending create/delete request (drops the request)"]])ho.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ls(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Gu}from"commander";import ve from"chalk";var Ro=new Gu("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Hu={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Ql(){return{root:process.cwd()}}function Ni(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function zu(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${Hu[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Ni(e.snoozed_until)})`):""}`),console.log(` ${ve.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ve.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(ve.yellow(` Expires ${Ni(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ve.dim(` ${e.detail}`)),e.source&&console.log(ve.dim(` ${e.source}`)),console.log(ve.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Ro.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 o=wa(Ql(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ve.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ve.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)zu(t),console.log();console.log(ve.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Ri(e,o,t){let n=Fn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ve.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await ba(Ql(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(ve.red(` ${i.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 ${i.message}`))}Ro.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").action((e,o)=>Ri(e,"yes",o));Ro.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,o)=>Ri(e,"no",o));Ro.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,o)=>Ri(e,"later",o));Ro.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: ${ha.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").action(e=>{let o=Fn(),t=ya(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(ve.red(` ${t.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 card:${t.card.id} raised; expires ${Ni(t.card.expires)}, then: ${t.card.if_silent}`))});Ro.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("--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').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=oc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(ve.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await tc(o);if(!a.success){console.error(ve.red(` ${a.error}`)),process.exitCode=1;return}console.log(ve.green(" \u2713 saved")+(a.reloaded?ve.dim(" (daemon reloaded)"):""))}let i=Fn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as yf}from"commander";import Ot from"chalk";import te from"chalk";import dn from"prompts";import{readFileSync as Yu,writeFileSync as Vu,existsSync as Ku}from"fs";import{resolve as Zl}from"path";var Xu=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Qu(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function _i(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ed(e=".env"){let o=Zl(e);if(!Ku(o))return[];let t=Yu(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Xu);i?n.push({kind:"kv",key:i[1],value:Qu(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Zu(e){return e.map(o=>o.kind==="kv"?`${o.key}=${_i(o.value)}`:o.raw).join(`
|
|
391
391
|
`)+`
|
|
392
|
-
`}function ln(e,o,t=".env"){let n=Zl(t),s=ed(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`})),Vu(n,Zu(s))}function Di(e,o=".env"){return ed(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var od="https://t.me/BotFather";async function ef(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function of(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function td(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${od}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[od],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await dn({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"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await ef(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await dn({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(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await dn({type:"text",name:"account",message:`Account "${p}" 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),p||(console.log(te.red(" Aborted")),process.exit(1));let u=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ln(u,t.trim()),process.env[u]=t.trim();let f=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${u}}`,agentBinding:g});let v=gt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(f.success||(console.log(te.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${u}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await of(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Pi from"prompts";import{existsSync as Li,mkdirSync as tf,readdirSync as nf,readFileSync as nd}from"fs";import{resolve as Mi}from"path";var sf=".agentx/whatsapp-sessions";function rf(){let e=Mi(process.cwd(),".agentx/daemon.pid");if(!Li(e))return!1;try{let o=parseInt(nd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function af(e){if(!Li(e))return!1;try{return nf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function cf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;tf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(u.qr,{small:!0})}catch{o(` QR: ${u.qr}`)}o("")}if(u.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function sd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),rf()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Pi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Mi(process.cwd(),"agentx.json");Li(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(nd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||sf,s=Mi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Pi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(af(s)&&a){let{keep:l}=await Pi({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(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await cf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as lf}from"crypto";import xe from"chalk";import id from"prompts";var gs="agentx-mesh:",ms="//join/";function df(e){return Buffer.from(e,"utf-8").toString("base64url")}function gf(e){return Buffer.from(e,"base64url").toString("utf-8")}function mf(e){return`${gs}${ms}${df(JSON.stringify(e))}`}function pf(e){if(!e.startsWith(`${gs}${ms}`))throw new Error(`Not a mesh invite link \u2014 expected ${gs}${ms}\u2026`);let o=e.slice(gs.length+ms.length),t=JSON.parse(gf(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function uf(){return lf(32).toString("hex")}function ff(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function hf(e){return e?.node?.name||e?.node?.id||"node"}async function rd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Di("MESH_TOKEN");r||(r=uf(),ln("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ff(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await id({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=mf({url:a,token:r,name:hf(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ad(e,o={}){let t;try{t=pf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Di("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await id({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}ln("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=gt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var jt=new yf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");jt.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 td({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});jt.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 sd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var cd=jt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");cd.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 rd({url:e.url,configPath:e.config})});cd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ad(e,{configPath:o.config})});jt.action(()=>{console.log(),console.log(Ot.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ot.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ot.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ot.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ot.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ot.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as wf}from"commander";import pe from"chalk";var gn=new wf().name("usage").description("token usage analysis and reporting");gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});gn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});gn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-RFAHI4SS.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let u of d.commands??[]){let f=p?`${p} ${u.name()}`:u.name();c.push(f),l(u,f)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.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(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as bf}from"commander";import be from"chalk";import{readFileSync as $f}from"fs";import{resolve as kf}from"path";ge();var _o=new bf().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");_o.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{kr(kf(process.cwd(),".env"))}catch{}let o=vf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-VA4VSCMQ.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function vf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
392
|
+
`}function ln(e,o,t=".env"){let n=Zl(t),s=ed(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`})),Vu(n,Zu(s))}function Di(e,o=".env"){return ed(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var od="https://t.me/BotFather";async function ef(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function of(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function td(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${od}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[od],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await dn({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"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await ef(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await dn({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(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await dn({type:"text",name:"account",message:`Account "${p}" 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),p||(console.log(te.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ln(f,t.trim()),process.env[f]=t.trim();let u=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=gt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(te.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${f}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await of(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Pi from"prompts";import{existsSync as Li,mkdirSync as tf,readdirSync as nf,readFileSync as nd}from"fs";import{resolve as Mi}from"path";var sf=".agentx/whatsapp-sessions";function rf(){let e=Mi(process.cwd(),".agentx/daemon.pid");if(!Li(e))return!1;try{let o=parseInt(nd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function af(e){if(!Li(e))return!1;try{return nf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function cf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;tf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function sd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),rf()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Pi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Mi(process.cwd(),"agentx.json");Li(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(nd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||sf,s=Mi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Pi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(af(s)&&a){let{keep:l}=await Pi({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(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await cf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as lf}from"crypto";import xe from"chalk";import id from"prompts";var gs="agentx-mesh:",ms="//join/";function df(e){return Buffer.from(e,"utf-8").toString("base64url")}function gf(e){return Buffer.from(e,"base64url").toString("utf-8")}function mf(e){return`${gs}${ms}${df(JSON.stringify(e))}`}function pf(e){if(!e.startsWith(`${gs}${ms}`))throw new Error(`Not a mesh invite link \u2014 expected ${gs}${ms}\u2026`);let o=e.slice(gs.length+ms.length),t=JSON.parse(gf(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function uf(){return lf(32).toString("hex")}function ff(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function hf(e){return e?.node?.name||e?.node?.id||"node"}async function rd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Di("MESH_TOKEN");r||(r=uf(),ln("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ff(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await id({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=mf({url:a,token:r,name:hf(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ad(e,o={}){let t;try{t=pf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Di("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await id({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}ln("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=gt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var jt=new yf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");jt.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 td({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});jt.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 sd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var cd=jt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");cd.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 rd({url:e.url,configPath:e.config})});cd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ad(e,{configPath:o.config})});jt.action(()=>{console.log(),console.log(Ot.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ot.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ot.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ot.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ot.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ot.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as wf}from"commander";import pe from"chalk";var gn=new wf().name("usage").description("token usage analysis and reporting");gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});gn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});gn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-ZCFMO4ZD.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.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(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as bf}from"commander";import be from"chalk";import{readFileSync as $f}from"fs";import{resolve as kf}from"path";ge();var _o=new bf().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");_o.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{kr(kf(process.cwd(),".env"))}catch{}let o=vf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-XPPBRPQE.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function vf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
393
393
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}_o.command("list").description("list configured boards").action(()=>{try{let e=R();if(!e.boards?.length){console.log(be.dim(`
|
|
394
394
|
No boards configured.
|
|
395
395
|
`));return}console.log();for(let o of e.boards){console.log(` ${be.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(be.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(be.dim(` primary label: ${o.primaryToolLabel}`)),console.log(be.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});_o.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{mn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});_o.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});var Fi=_o.command("column").description("manage a board's columns (add / remove / edit / list)");Fi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse($f("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(be.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Fi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{mn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(be.red(` ${n.message}`)),process.exit(1)}});Fi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});_o.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{mn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});function mn(e){let{summary:o,backupPath:t}=po(n=>e(n));console.log(be.green(`
|
|
396
396
|
\u2713 ${o}
|
|
397
397
|
`)),t&&console.log(be.dim(` Backup: ${t}`)),console.log(be.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
398
|
-
`))}import{Command as xf}from"commander";import m from"chalk";import{resolve as F,relative as ld,dirname as dd}from"path";import{execSync as ot}from"child_process";import{writeFileSync as tt,mkdirSync as yo,readFileSync as pn,readdirSync as Sf,renameSync as ps,rmSync as Ef,existsSync as ze}from"fs";function Se(e,o){return new _s(un(e),void 0,o||"graph")}function un(e){return e||F(process.cwd(),".agentx/wiki")}function qi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Q=new xf().name("wiki").description("wiki knowledge base management");Q.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 o=e.mode,t=Se(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${qi(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),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}`),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 r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});Q.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(e=>{let o=Se(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Q.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").action(async e=>{let o=e.mode,t=Se(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=F(process.cwd(),".agentx/graph");return ze(p)?new $o({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[u
|
|
398
|
+
`))}import{Command as xf}from"commander";import m from"chalk";import{resolve as F,relative as ld,dirname as dd}from"path";import{execSync as ot}from"child_process";import{writeFileSync as tt,mkdirSync as yo,readFileSync as pn,readdirSync as Sf,renameSync as ps,rmSync as Ef,existsSync as ze}from"fs";function Se(e,o){return new _s(un(e),void 0,o||"graph")}function un(e){return e||F(process.cwd(),".agentx/wiki")}function qi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Q=new xf().name("wiki").description("wiki knowledge base management");Q.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 o=e.mode,t=Se(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${qi(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),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}`),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 r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});Q.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(e=>{let o=Se(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Q.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").action(async e=>{let o=e.mode,t=Se(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=F(process.cwd(),".agentx/graph");return ze(p)?new $o({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[f,u]of Object.entries(p.entries))r.set(f,u.path)}catch{}let a,c=p=>{let f=p.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let u=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:u});return r.get(w)},l=(p,f)=>{let u=new Map;for(let y of p){let k=f.find(S=>S.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let v=b.join("/"),A=u.get(v);A?A.n++:u.set(v,{path:b,n:1})}if(u.size===0)return;let w;for(let y of u.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let p of n){let f=typeof e.since=="string"?e.since.trim():"",u=t.getUnabsorbedEntries(p).filter($=>!f||($.date??"")>=f).slice(0,s);if(u.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${u.length} entries to absorb`));for(let $ of u.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(u.length>3&&console.log(m.dim(` ... and ${u.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=u.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
|
|
399
399
|
${$.content}
|
|
400
400
|
--- END ENTRY ---`).join(`
|
|
401
401
|
|
|
402
|
-
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:O,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let H=$(f.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),de=M(f);if(H.length>0||de.length>0){let J=B(),{records:Ee,results:$e}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...de,...Ee]);v=O(P);let He=[...de.length>0?[`entries:${de.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${He.length?` (${He.join(" ")})`:""}`));for(let ke of D($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=Zr(o,p,k,y.articles,b,f.length,v);console.log(m.dim(` Mode: ${qi(o)}`));let S=F(w.baseDir,"_tmp");yo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");tt(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=ot(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:rt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,O=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],de=H==="{"?"}":"]",J=0,Ee=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===de&&(J--,J===0)){Ee=P+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=C.slice(M,Ee);try{let P=JSON.parse($e);Array.isArray(P)?j=P:(j=P.articles||[],O=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let P of j){let He=new Date().toISOString().slice(0,10),ke=l(P.sources||[],f);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:He,lastUpdated:He,sources:P.sources||[],graphPath:ke},P.content,p);let qo=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${qo}${P.path}: ${P.title}${m.dim(N)}`);let fe=(P.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let P of O)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-2V2VGIT4.js"),He=new P(un(e.dir)).add(O.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));He.added>0&&console.log(m.dim(` queued ${He.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Q.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Af(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-EBP5CFOB.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(f=>f.trim()).filter(Boolean)});let p=i.filter(f=>(f.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let u=i[0];u&&(u.occurrences??1)>1&&console.log(m.dim(` most recurrent (${u.occurrences} sessions): ${u.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let u=c(p,{since:Date.now()-(o??6048e5)}),f=l(u,{minSessions:a});console.log(m.dim(` ${u.length} failed run(s) in window \u2192 ${f.length} failure(s) seen in ${a}+ sessions`));let w=f[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...f]}finally{p.close()}}}let r=await ea({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var us=Q.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function fs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}us.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(fs(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});us.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(fs(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
402
|
+
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:O,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let H=$(u.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),de=M(u);if(H.length>0||de.length>0){let J=B(),{records:Ee,results:$e}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...de,...Ee]);v=O(P);let He=[...de.length>0?[`entries:${de.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${He.length?` (${He.join(" ")})`:""}`));for(let ke of D($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=Zr(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${qi(o)}`));let S=F(w.baseDir,"_tmp");yo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");tt(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=ot(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:rt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,O=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],de=H==="{"?"}":"]",J=0,Ee=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===de&&(J--,J===0)){Ee=P+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=C.slice(M,Ee);try{let P=JSON.parse($e);Array.isArray(P)?j=P:(j=P.articles||[],O=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let P of j){let He=new Date().toISOString().slice(0,10),ke=l(P.sources||[],u);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:He,lastUpdated:He,sources:P.sources||[],graphPath:ke},P.content,p);let qo=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${qo}${P.path}: ${P.title}${m.dim(N)}`);let fe=(P.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let P of O)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-2V2VGIT4.js"),He=new P(un(e.dir)).add(O.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));He.added>0&&console.log(m.dim(` queued ${He.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Q.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Af(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-QWW5PDUU.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(o??6048e5)}),u=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let w=u[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...u]}finally{p.close()}}}let r=await ea({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var us=Q.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function fs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}us.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(fs(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});us.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(fs(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
403
403
|
`).map(s=>` ${s}`).join(`
|
|
404
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});us.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-
|
|
404
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});us.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-4T64VW5K.js"),n=t(fs(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});us.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-4T64VW5K.js"),n=t(fs(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Af(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Q.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",F(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-6IKL52WT.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Se(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.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 ${p.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<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
405
405
|
`)||"_(none returned)_",A;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
|
|
406
406
|
|
|
407
407
|
${S.answer}
|
|
408
408
|
|
|
409
|
-
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),
|
|
409
|
+
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),u.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=u.join(`
|
|
410
410
|
`);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Q.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-S6NHM5C3.js"),s=e.answers?pn(e.answers,"utf-8").split(/\r?\n/).filter(N=>N.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=Se(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(N){console.log(m.red(` can't open wiki for agent "${e.agent}": ${N.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async N=>{if(s){let fe=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${fe.slice(0,80)}${fe.length>80?"\u2026":""}`)+`
|
|
411
|
-
`),fe.trim()}return(await c.question(N)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await l(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}p.has(N)?d=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),d="concept")}let
|
|
411
|
+
`),fe.trim()}return(await c.question(N)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await l(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}p.has(N)?d=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),d="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},u=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${u.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<u.length;N++){let fe=u[N],Ye=await l(` ${m.dim(`[${N+1}/${u.length}]`)} ${fe}
|
|
412
412
|
${m.green(">")} `);if(Ye==="/abort"){y=!0;break}if(Ye==="/done")break;Ye!=="/skip"&&Ye&&w.push({q:fe,a:Ye})}if(!y){let N=await l(`
|
|
413
413
|
${m.dim("Anything else worth capturing?")}
|
|
414
414
|
${m.green(">")} `);N&&N!=="/abort"&&N!=="/done"&&w.push({q:"Anything else worth capturing?",a:N})}if(y||w.length===0){console.log(m.yellow(`
|
|
@@ -418,13 +418,13 @@ Q: ${N.q}
|
|
|
418
418
|
A: ${N.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(`
|
|
419
419
|
`),A=F(a.baseDir,"_tmp");yo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);tt(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let N=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=ot(N,{env:rt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ye=JSON.parse(fe);x=String(Ye.result||Ye.content||"")}catch{x=fe}}catch(N){console.log(m.red(` synthesis failed: ${N.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let $=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(x=$[1].trim());let C=x.indexOf("---");C>0&&(x=x.slice(C));let j=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let O={};for(let N of j[1].split(`
|
|
420
420
|
`)){let fe=N.match(/^(\w+):\s*(.+)$/);fe&&(O[fe[1]]=fe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],B=O.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),de=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${M}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${de}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Ee=D,$e={title:B,type:O.type||d,related:O.related?O.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:O.tags?O.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:O.access||"public",created:O.created||new Date().toISOString().slice(0,10),lastUpdated:O.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let N=process.env.EDITOR||"vi",fe=F(A,`draft-${t().slice(0,8)}.md`);tt(fe,x);try{ot(`${N} '${fe}'`,{stdio:"inherit"});let Cs=pn(fe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Cs){let bo={};for(let Ut of Cs[1].split(`
|
|
421
|
-
`)){let Ns=Ut.match(/^(\w+):\s*(.+)$/);Ns&&(bo[Ns[1]]=Ns[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Cs[2],$e={...$e,title:bo.title||$e.title,type:bo.type||$e.type,access:bo.access||$e.access,related:bo.related?bo.related.replace(/^\[|\]$/g,"").split(",").map(Ut=>Ut.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:bo.tags?bo.tags.replace(/^\[|\]$/g,"").split(",").map(Ut=>Ut.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ye){console.log(m.red(` editor failed: ${Ye.message}`));return}}if(!a.writeArticle(de,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${de} saved.`));let He=a.extractWikilinks(Ee),ke=new Map;for(let N of a.listArticles(e.agent))ke.set(N.meta.title.toLowerCase(),!0);let qo=He.filter(N=>!ke.has(N.toLowerCase()));if(qo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of qo.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Q.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-
|
|
422
|
-
`)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:
|
|
421
|
+
`)){let Ns=Ut.match(/^(\w+):\s*(.+)$/);Ns&&(bo[Ns[1]]=Ns[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Cs[2],$e={...$e,title:bo.title||$e.title,type:bo.type||$e.type,access:bo.access||$e.access,related:bo.related?bo.related.replace(/^\[|\]$/g,"").split(",").map(Ut=>Ut.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:bo.tags?bo.tags.replace(/^\[|\]$/g,"").split(",").map(Ut=>Ut.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ye){console.log(m.red(` editor failed: ${Ye.message}`));return}}if(!a.writeArticle(de,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${de} saved.`));let He=a.extractWikilinks(Ee),ke=new Map;for(let N of a.listArticles(e.agent))ke.set(N.meta.title.toLowerCase(),!0);let qo=He.filter(N=>!ke.has(N.toLowerCase()));if(qo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of qo.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Q.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-6IKL52WT.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Se(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=pn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],p=0;for(let f=0;f<l;f++){let u,w;if(r){let H=r[f];if(!H)break;u=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.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 H=y.citations.map(de=>`${de.title} [${de.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
422
|
+
`)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=Tf(x.content,v,A,x.meta.title,x.meta.type),C=F(i.baseDir,"_tmp");yo(C,{recursive:!0});let j=F(C,`quiz-patch-${t().slice(0,8)}.txt`);tt(j,$);let O="";try{let H=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,de=ot(H,{env:rt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ee=JSON.parse(de);O=String(Ee.result||Ee.content||"")}catch{O=de}let J=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(O=J[1].trim()),O=O.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=x.content.split(`
|
|
423
423
|
`).length,B=O.split(`
|
|
424
|
-
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},O,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${p} patches applied.`)),e.out){let
|
|
425
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Q.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,o,t)=>{let n=Se(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=pd(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" 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 r=F(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ot(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(
|
|
426
|
-
`).length,w=
|
|
427
|
-
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${
|
|
424
|
+
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},O,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<d.length;u++){let w=d[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}tt(e.out,f.join(`
|
|
425
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Q.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,o,t)=>{let n=Se(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=pd(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" 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 r=F(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ot(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...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 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});Q.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").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Se(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=pd(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=If(l.content,l.meta.title,l.meta.type,t),d=F(a.baseDir,"_tmp");yo(d,{recursive:!0});let p=F(d,`patch-${i().slice(0,8)}.txt`);tt(p,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=ot(S,{env:rt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let C=JSON.parse(x);f=String(C.result||C.content||"")}catch{f=x}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=l.content.split(`
|
|
426
|
+
`).length,w=f.split(`
|
|
427
|
+
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${w} lines (${w-u>=0?"+":""}${w-u})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=x==="y"||x==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(S=>!b.includes(S));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function pd(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.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 If(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"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(`
|
|
428
428
|
`)}function Tf(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
429
429
|
|
|
430
430
|
${t}
|
|
@@ -438,8 +438,8 @@ Incorporate it into the most relevant existing section, or create a short new se
|
|
|
438
438
|
${t}
|
|
439
439
|
|
|
440
440
|
Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${t}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[o]||`Make a minimal edit per: ${t}`,"","## 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 edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
|
|
441
|
-
`)}Q.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?F(e.dir):F(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let p=F(s,"agents",d);if(!ze(p))continue;let
|
|
442
|
-
`)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function md(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));yo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ps(o.absPath,F(t,`${n}.md`))}Q.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),p=d.filter(k=>!k.meta.type);if(r+=d.length,a+=p.length,p.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let
|
|
441
|
+
`)}Q.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?F(e.dir):F(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let p=F(s,"agents",d);if(!ze(p))continue;let f=F(p,i),u=r.map(b=>({mode:b,dir:F(p,b)})).filter(b=>ze(b.dir));if(u.length===0)continue;let w=new Map;Ui(f,b=>{let v=ld(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=gd(pn(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of u)Ui(b.dir,v=>{let A=ld(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=gd(pn(v,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=u.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),S;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),C=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${x} ${m.dim(b.mode+"/")}${C}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let j=F(f,b.relPath);ze(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),md(p,b),g++):(yo(dd(j),{recursive:!0}),ps(b.absPath,j),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let j=F(f,A.relPath);if(ze(j)){let O=F(p,"_versions",A.relPath.replace(/\.md$/,""));yo(O,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");ps(j,F(O,`${D}.md`))}yo(dd(j),{recursive:!0}),ps(b.absPath,j),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else md(p,b),g++}catch(j){console.log(m.red(` ! ${S} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of u)try{Ef(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Ui(e,o){if(ze(e))for(let t of Sf(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?Ui(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function gd(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
|
|
442
|
+
`)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function md(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));yo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ps(o.absPath,F(t,`${n}.md`))}Q.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),p=d.filter(k=>!k.meta.type);if(r+=d.length,a+=p.length,p.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),u=Math.min(p.length,f);if(u===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${u}/${p.length} untyped articles`));let w=g.baseDir,y=F(w,"_tmp");yo(y,{recursive:!0});for(let k=0;k<u;k+=n){let b=p.slice(k,Math.min(k+n,u)),v=jf(b),A=F(y,"migrate-prompt.txt");tt(A,v);let S;try{let x=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=ot(x,{env:rt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),C=JSON.parse($),O=String(C.result||C.content||"").match(/\[[\s\S]*\]/);if(!O)throw new Error("no JSON array in classifier response");S=JSON.parse(O[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let $=S.find(M=>M.path===x.path),C=Of($?.type);if(!$||!C){console.log(m.yellow(` ? ${x.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=g.extractWikilinks(x.content),O={...x.meta,type:C.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.length>3?", \u2026":""}`):"",B=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${B} ${x.path}${D}`),i&&(g.writeArticle(x.path,O,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Of(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function jf(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
|
|
443
443
|
title: "${t.meta.title}"
|
|
444
444
|
tags: [${i}]
|
|
445
445
|
body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
|
|
@@ -479,14 +479,14 @@ Output (JSON array, one entry per input article, same order):
|
|
|
479
479
|
[
|
|
480
480
|
{"path": "path/to/article.md", "type": "project"},
|
|
481
481
|
...
|
|
482
|
-
]`}Q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(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()});Q.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-
|
|
482
|
+
]`}Q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(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()});Q.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-TVW7UCKG.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),ac(o,t,e.agent,n,e.mode)});Q.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-3KUNRM5Z.js"),c=Se(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||p.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
|
|
483
483
|
${p.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(`
|
|
484
|
-
${p.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."))});Q.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-P5LMGXVS.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Q.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});Q.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new $o({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),u=p.listArticles(d),f=o.getSharedStore().listEntries(),w=new Map(f.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of u){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),O=r.get(j);if(!O?.length)continue;let D=O.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:O,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(u.length)} articles \xB7 ${y} eligible \xB7 ${k} 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()});Q.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-I4GWI22T.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let u=await p.json();for(let f of u.agents||[])f.totalEntries>0&&console.log(m.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Q.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new _s(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),u=l.getUnabsorbedEntries(t),f=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])f.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:qi(c),articles:d.articles.length,entries:p.length,unabsorbed:u.length,uniqueTags:f.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.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()});Q.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Cf(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Q.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-LV3STEXI.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),u=0,f=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let C of $.listArticles(x)){if(u>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;u++;let O=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:x,type:j.meta.type??"?"}});if(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,O.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),f.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(un(e.dir)).add(g)),e.json){console.log(JSON.stringify(f,null,2));return}if(f.length===0){console.log(m.green(` ${u} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...f.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of f)console.log(y.map(($,C)=>v(x[$],C)).join(" "));let A=f.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${f.length} gap(s) across ${u} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${f.length-A} need a person.`));let S=f[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,C=g.filter(j=>(x[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-I4GWI22T.js"),O=j(),D=O?.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 B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
484
|
+
${p.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."))});Q.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-6IKL52WT.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Q.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});Q.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new $o({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),f=p.listArticles(d),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),O=r.get(j);if(!O?.length)continue;let D=O.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:O,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} 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()});Q.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-TVW7UCKG.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Q.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new _s(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:qi(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.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()});Q.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Cf(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Q.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-3KUNRM5Z.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let C of $.listArticles(x)){if(f>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let O=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:x,type:j.meta.type??"?"}});if(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,O.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),u.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(un(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...u.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of u)console.log(y.map(($,C)=>v(x[$],C)).join(" "));let A=u.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,C=g.filter(j=>(x[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-TVW7UCKG.js"),O=j(),D=O?.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 B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
485
485
|
`),M=C.length>10?`
|
|
486
486
|
\u2026and ${C.length-10} more`:"",H=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
487
487
|
${B}${M}
|
|
488
488
|
|
|
489
|
-
agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(`http://127.0.0.1:${de}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Q.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-LV3STEXI.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),u=Se(e.dir,e.mode),f=e.agent?[e.agent]:u.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(u.getSharedStore().listEntries())),b=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),v=0,A=0,S=[],x=!1;e:for(let O of f){let D=u.getAgentWiki(O);for(let B of D.listArticles(O)){if(v>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;v++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:O,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!x){for(let N of l($e,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));x=!0}let He=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,fe])=>[N,fe.value]))}]:[],...Ee]);if(He.length===0)continue;let{content:ke,edits:qo}=p(M.content,He[0],J);if(qo.length!==0){for(let N of qo)S.push({agent:O,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,ke,O)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(O=>Math.max(O.length,...S.map(D=>String(D[O]).length))),j=O=>O.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let O of S)console.log(j($.map(D=>O[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Q.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(un(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Q.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(un(t.dir));if(t.dismiss){let u=r.resolve(e,"dismissed");console.log(u?m.dim(` dismissed: ${u.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Q.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-LV3STEXI.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),u=Se(e.dir,"graph").getSharedStore(),f=u.listEntries(),w=new Set(u.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(f,w),b=a(y,M=>M.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},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){S++;continue}let de=H.answers;A.push({entry:M,verdict:s(H.answers,v),citeWorthy:de.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:O},null,2));return}let D=M=>`${(M*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${O}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let M=parseFloat(e.minRecall),{best:H,points:de}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${de.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.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(M)} recall \u2014 not even keeping everything typed.`));let J=de.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Q.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Cf(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"}cg();import{Command as Nf}from"commander";import _ from"chalk";import{resolve as hs}from"path";import{existsSync as Rf}from"fs";ge();var Ct=new Nf().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Ct.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(_.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(_.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new $o({baseDir:hs(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(_.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(_.bold(` Graph review \u2014 ${r.length} pending`)),console.log(_.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let f=0;f<r.length;f++){let w=r[f],y=Sn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${_.cyan(w.msgHash.slice(0,8))} ${_.dim(y)} ... `);let k=_f(w,a,c),b=null;try{b=await Df(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(_.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(_.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(_.green("APPROVE")+" "+_.dim(A)),e.dryRun)l++;else try{Pf(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(_.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(_.red("REJECT")+" "+_.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(_.yellow("SKIP")+" "+_.dim(A||v)),d++)}console.log();let u=e.dryRun?"would":"did";console.log(_.dim(` Summary: ${u} approve ${l}, ${u} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Ct.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=R();if(!o.graph){console.log(_.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=hs(process.cwd(),o.graph.baseDir);if(!Rf(t)){console.log(_.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new $o({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(_.dim(" "),...a)});console.log(),console.log(_.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(_.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Ct.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new $o({baseDir:hs(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(_.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let O=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch($){console.log(_.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),u=l?.levels?.map($=>$.id).join(","),f=p===u;f?console.log(_.dim(` schema matches (${r.levels.length} levels)`)):(console.log(_.yellow(" \u26A0 schema levels differ:")),console.log(_.dim(` local: ${p}`)),console.log(_.dim(` peer: ${u}`)),a.length===0&&!e.dryRun?(console.log(_.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(_.yellow(" keeping local schema; node import may fail if levels disagree")));let w=f?r:l,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(_.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(_.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(_.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` \u2713 pulled from ${t}`)),console.log()});function _f(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
489
|
+
agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(`http://127.0.0.1:${de}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Q.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-3KUNRM5Z.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Se(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),v=0,A=0,S=[],x=!1;e:for(let O of u){let D=f.getAgentWiki(O);for(let B of D.listArticles(O)){if(v>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;v++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:O,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!x){for(let N of l($e,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));x=!0}let He=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,fe])=>[N,fe.value]))}]:[],...Ee]);if(He.length===0)continue;let{content:ke,edits:qo}=p(M.content,He[0],J);if(qo.length!==0){for(let N of qo)S.push({agent:O,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,ke,O)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(O=>Math.max(O.length,...S.map(D=>String(D[O]).length))),j=O=>O.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let O of S)console.log(j($.map(D=>O[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Q.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(un(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Q.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(un(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Q.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-3KUNRM5Z.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Se(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,M=>M.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},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){S++;continue}let de=H.answers;A.push({entry:M,verdict:s(H.answers,v),citeWorthy:de.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:O},null,2));return}let D=M=>`${(M*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${O}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let M=parseFloat(e.minRecall),{best:H,points:de}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${de.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.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(M)} recall \u2014 not even keeping everything typed.`));let J=de.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Q.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Cf(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"}cg();import{Command as Nf}from"commander";import _ from"chalk";import{resolve as hs}from"path";import{existsSync as Rf}from"fs";ge();var Ct=new Nf().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Ct.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(_.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(_.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new $o({baseDir:hs(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(_.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(_.bold(` Graph review \u2014 ${r.length} pending`)),console.log(_.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=Sn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${_.cyan(w.msgHash.slice(0,8))} ${_.dim(y)} ... `);let k=_f(w,a,c),b=null;try{b=await Df(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(_.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(_.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(_.green("APPROVE")+" "+_.dim(A)),e.dryRun)l++;else try{Pf(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(_.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(_.red("REJECT")+" "+_.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(_.yellow("SKIP")+" "+_.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(_.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Ct.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=R();if(!o.graph){console.log(_.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=hs(process.cwd(),o.graph.baseDir);if(!Rf(t)){console.log(_.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new $o({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(_.dim(" "),...a)});console.log(),console.log(_.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(_.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Ct.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new $o({baseDir:hs(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(_.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let O=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch($){console.log(_.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(_.dim(` schema matches (${r.levels.length} levels)`)):(console.log(_.yellow(" \u26A0 schema levels differ:")),console.log(_.dim(` local: ${p}`)),console.log(_.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(_.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(_.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:l,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(_.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(_.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(_.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` \u2713 pulled from ${t}`)),console.log()});function _f(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
490
490
|
`),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
|
|
491
491
|
`)}async function Df(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return yr((c?.content||"").toString())}finally{clearTimeout(r)}}function Pf(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Wi(){let e=R();if(!e.graph?.baseDir)return console.log(_.red(" graph.baseDir is not configured")),null;let o=hs(process.cwd(),e.graph.baseDir);return{store:new $o({baseDir:o}),baseDir:o}}var Bi=Ct.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Bi.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=Wi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(_.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):_.dim("cache");console.log(` ${_.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${_.bold(Sn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(_.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(_.dim(` ${r.length} to check (${e.strategy}).`)),console.log(_.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Bi.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(_.red(" verdict must be correct | wrong | unsure"));return}let n=Wi();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(_.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(_.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(_.green(` ${o}: ${Sn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(_.dim(` should have been: ${t.path}`))});Bi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Wi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${_.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(_.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?_.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(_.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(_.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as Wf}from"commander";import Y from"chalk";import{Command as fd}from"commander";import ae from"chalk";import{existsSync as Mf}from"fs";import{resolve as Lf}from"path";import Ff from"better-sqlite3";function Uf(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(ae.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function qf(e){let o=Lf(process.cwd(),e);return Mf(o)||(console.log(ae.red(` No db at ${o}`)),process.exit(1)),new Ff(o,{readonly:!0})}var hd=new fd().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(Gt)).option("--max <n>","max clusters distilled per run",String(In)).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(ae.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=qf(e.path),t=await oa(o,{since:Uf(e.since),agentId:e.agent,sessions:new Er(process.cwd()),minOccurrences:Number(e.minOccurrences)||Gt,max:Number(e.max)||In,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ae.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${ae.cyan(n.key)} ${ae.bold(`\xD7${n.count}`)} ${ae.dim(n.status)}`),n.sampleMessage&&console.log(ae.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ae.dim(`
|
|
492
492
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ae.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ae.green(` \u2713 draft written: ${n.id}`)+ae.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ae.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ae.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ae.dim(`
|
|
@@ -501,11 +501,11 @@ agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(
|
|
|
501
501
|
`;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});to.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new ko,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});to.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new ko;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});to.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new ko;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});to.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new ko;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});to.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new ko,n=Mr(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as Gf}from"commander";import E from"chalk";import{resolve as Rt,basename as Hf}from"path";import{existsSync as Ji,readFileSync as Gi,writeFileSync as ys}from"fs";import T0 from"better-sqlite3";import{readFileSync as Bf}from"fs";import{resolve as Nt,dirname as wd}from"path";import{fileURLToPath as Jf}from"url";var fn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function bd(e){let o=wd(Jf(import.meta.url)),t=process.argv[1]?wd(process.argv[1]):"",n=[Nt(o,`${e}.yaml`),Nt(o,"workflows/templates",`${e}.yaml`),Nt(o,"..","workflows/templates",`${e}.yaml`),Nt(o,"../..","workflows/templates",`${e}.yaml`),t?Nt(t,"workflows/templates",`${e}.yaml`):"",t?Nt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Bf(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
|
|
502
502
|
${n.join(`
|
|
503
503
|
`)}`)}var Je=new Gf().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Je.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Wo().list();if(!o.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Je.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new Wo().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Tr(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Je.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Rt(process.cwd(),e);Ji(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=Gi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?lt(r,{filePath:e}):JSON.parse(r),l=ct.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=En(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof An?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Wo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Je.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${fn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");fn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${fn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Wo;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=bd(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=lt(s,{filePath:`${e}.yaml`}),c=ct.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=Rt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=lt(s,{filePath:`${e}.yaml`}),c=ct.parse(a);ys(r,JSON.stringify(c,null,2)+`
|
|
504
|
-
`)}else ys(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Je.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of fn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Je.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=Rt(process.cwd(),e);Ji(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=Gi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?lt(n,{filePath:e}):JSON.parse(n)}catch(p){let
|
|
505
|
-
`),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(d,{method:"POST"});p.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Je.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new Jt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Je.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Rt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ji(s)){let c=Gi(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?lt(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof An?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=ct.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=En(d.data);if(p.length){console.log(E.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let
|
|
506
|
-
`;ys(y,k),n=
|
|
504
|
+
`)}else ys(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Je.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of fn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Je.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=Rt(process.cwd(),e);Ji(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=Gi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?lt(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof An?p.message:`parse error: ${p?.message??p}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=ct.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=En(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new Wo,l=s?Hf(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Rt(c.baseDir,`${r.data.id}.${l}`);if(ys(g,s?n:JSON.stringify(r.data,null,2)+`
|
|
505
|
+
`),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(d,{method:"POST"});p.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Je.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new Jt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Je.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Rt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ji(s)){let c=Gi(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?lt(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof An?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=ct.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=En(d.data);if(p.length){console.log(E.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let f=new Wo,u=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=Rt(f.baseDir,`${u}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...d.data,id:u},null,2)+`
|
|
506
|
+
`;ys(y,k),n=u,console.log(E.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await zf({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function zf(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?E.green:a==="error"?E.red:E.cyan,l=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${E.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${E.dim("run finished:")} ${c.status}`),console.log(E.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Je.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}$d(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)$d(i)});function $d(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}Je.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Jt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});Je.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Jt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});Je.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Jt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as kd}from"commander";import ne from"chalk";import nt from"prompts";import{readFileSync as Yf,existsSync as Vf}from"fs";import{resolve as Kf}from"path";var hn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Hi=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),vd={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function xd(){let e=Kf(process.cwd(),"agentx.json");if(!Vf(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Yf(e,"utf-8"))}function Xf(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ne.yellow("\u26A0 no signing secret"):ne.green("\u2713 active"):ne.dim("disabled")}function Qf(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Hi.has(e.source)?ne.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ne.cyan(e.id)} ${Xf(e)}`),console.log(` ${ne.dim(e.source)} \u2192 ${ne.bold(e.agentId)}${n}`),console.log(` POST ${ne.dim(t)}`),e.secretEnv&&console.log(` secret: ${ne.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ne.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ne.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ne.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var wo=new kd().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");wo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=xd(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ne.dim(`
|
|
507
507
|
No webhooks registered. Add one with: agentx webhook add
|
|
508
|
-
`));return}console.log();for(let n of t)Qf(n)});wo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${hn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=xd(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(
|
|
508
|
+
`));return}console.log();for(let n of t)Qf(n)});wo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${hn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=xd(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await nt({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&d&&(a=(await nt({type:"select",name:"source",message:"Source",choices:hn.map(u=>({title:`${u}${Hi.has(u)?" \u2713 wired":""}`,value:u,description:vd[u]}))})).source),!hn.includes(a))throw new Error(`Source must be one of: ${hn.join(", ")}`);if(!c&&d&&(i?c=((await nt({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await nt({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await nt({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await nt({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await he(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let u={id:r,source:a,agentId:c,enabled:!0};l&&(u.secretEnv=l),g&&(u.description=g),i&&(u.node=i),f.webhooks.push(u)});if(!p.success)throw new Error(p.error);console.log(ne.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(ne.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ne.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});wo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await nt({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await he(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(ne.green(`\u2713 removed webhook "${e}"`))});function Sd(e){return async o=>{let t=await he(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(ne.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}wo.command("enable <id>").description("enable a webhook entry").action(Sd(!0));wo.command("disable <id>").description("disable a webhook entry").action(Sd(!1));var ws=new kd().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");ws.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await he(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(ne.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});ws.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await he(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(ne.green(`\u2713 removed trigger ${o} from "${e}"`))});ws.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await he(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(ne.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});wo.addCommand(ws);wo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=hn.map(t=>({source:t,wired:Hi.has(t),hint:vd[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ne.green("\u2713 wired"):ne.dim("inbound-only");console.log(` ${ne.cyan(t.source.padEnd(8))} ${n} ${ne.dim(t.hint)}`)}console.log(),console.log(ne.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ne.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Zf}from"commander";import se from"chalk";ge();function _t(e){let{summary:o,backupPath:t}=po(n=>e(n));console.log(se.green(`
|
|
509
509
|
\u2713 ${o}`)),t&&console.log(se.dim(` Backup: ${t}`)),console.log(se.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
510
510
|
`))}function bs(){try{return R().business||{}}catch{return{}}}var Dt=new Zf().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Dt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=bs();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(se.yellow(" business block not enabled (or missing).")),console.log(se.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(se.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(se.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?se.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?se.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${se.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(se.bold(` Projects (${n.length})`)),n.length===0)console.log(se.dim(" (empty)"));else for(let r of n){let a=r.pm?se.dim(` \xB7 pm=${r.pm}`):"",c=r.client?se.dim(` \xB7 client=${r.client}`):"";console.log(` ${se.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(se.bold(` Contact map (${s.length})`)),s.length===0)console.log(se.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${se.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?se.dim(` (${r.displayName})`):""}`)}console.log()});var zi=Dt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");zi.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=bs(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(se.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${se.cyan(n)} ${s.role}${s.reportsTo?se.dim(` \u2192 ${s.reportsTo}`):""}`)});zi.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);_t(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});zi.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{_t(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Yi=Dt.command("project").description("manage business.projects \u2014 id, pm, client");Yi.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=bs().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(se.dim(" no projects"));return}for(let n of t)console.log(` ${se.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Yi.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{_t(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Yi.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{_t(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var Vi=Dt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Vi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=bs().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(se.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${se.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Vi.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(se.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),_t(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});Vi.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{_t(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as eh}from"commander";import De from"chalk";ge();var oh={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ki(e){let o=oh[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function $s(){let o=R().business?.standup?.plansDir||".agentx/plans";return new za(o)}var Pt=new eh().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Pt.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Ki(e),n=$s(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
|
|
511
511
|
`):(console.error(De.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(De.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Ys(s);if(r.length){console.log(De.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(De.dim(` \u2022 ${a}`))}});Pt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=$s();if(e){let n=Ki(e),s=o.read(n);if(!s){console.log(De.dim(` No ${n} plan set.`));return}Ed(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(De.yellow(" No plan set at any tier.")),console.log(De.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(De.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Ed(t.tier,t.date,t.content)});Pt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=$s().list(parseInt(e.limit,10)||20);if(!t.length){console.log(De.dim(" No plans yet."));return}for(let n of t)console.log(` ${De.cyan(n.tier.padEnd(5))} ${De.bold(n.date.padEnd(11))} ${De.dim(n.path)}`)});Pt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Ki(e),n=$s().read(o);if(!n){console.log(De.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(De.green(` \u2713 ${o} plan cleared (${n.path})`))});function Ed(e,o,t){console.log(De.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
|
|
@@ -514,13 +514,13 @@ agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(
|
|
|
514
514
|
`))}var Do=new th().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Do.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=nh();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let i=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Z.cyan(o.destination.channel+":"+o.destination.chatId)}${Z.dim(i)}`)}else console.log(` destination ${Z.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Z.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Z.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Z.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Z.dim("off")}`);let n=jn(o.local);if(console.log(` local.banner ${n.banner?"on":Z.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:Z.dim("off")}`),console.log(` local.icon ${n.icon??Z.dim("AgentX logo")}`),n.banner){let i=await Za();i.state!=="unsupported"&&(console.log(` local.helper ${i.state==="ready"?i.message:Z.yellow(i.message)}`),i.fix&&console.log(` ${Z.dim("Fix: "+i.fix)}`))}let s=Ks(sh());console.log(` ntfy ${s.enabled?"on":Z.dim("off")} ${Z.dim(`${s.server} \xB7 topic ${s.topicSet?"set":"unset"} \xB7 token ${s.tokenSet?"set":"unset"}`)}`),console.log()});Do.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){yn(o=>(delete o.destination,"notifications destination cleared"));return}yn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});Do.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Z.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Z.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";yn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Do.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Z.red(" threshold must be a non-negative integer")),process.exit(1)),yn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});Do.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(Z.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(Z.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{yn(n=>(n.local=pa(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(Z.dim(` Run agentx desktop install to put the new icon on the helper.
|
|
515
515
|
`))}catch(n){console.log(Z.red(` ${n?.message??n}`)),process.exit(1)}});Do.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Z.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=po(s=>{s.channels=s.channels||{},s.channels.ntfy=rc(s.channels.ntfy,o);let i=Ks(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(Z.green(`
|
|
516
516
|
\u2713 ${t}`)),n&&console.log(Z.dim(` Backup: ${n}`)),console.log(Z.dim(` Restart the daemon for a channel change to take effect.
|
|
517
|
-
`))}catch(t){console.log(Z.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as ih}from"commander";import Po from"chalk";import{readdirSync as Xi,statSync as Ad,unlinkSync as rh,rmSync as ah,existsSync as Id}from"fs";import{resolve as Td,join as Od}from"path";var jd=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Qi(e,o){if(!Id(e))return[];let t=[];for(let n of Xi(e,{withFileTypes:!0})){let s=Od(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Qi(s,!0))}return t}var vs=new ih().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");vs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of jd){let t=Td(process.cwd(),o.dir),n=Qi(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Ad(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Po.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ks(s).padStart(10)} oldest=${r}`)}console.log(Po.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ks(e).padStart(10)} total`)),console.log(),console.log(Po.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});vs.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Po.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Po.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Po.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of jd){if(n&&r.dir!==n)continue;let a=Td(process.cwd(),r.dir),c=Qi(a,!!r.recursive),l=0,g=0;for(let p of c)try{let
|
|
517
|
+
`))}catch(t){console.log(Z.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as ih}from"commander";import Po from"chalk";import{readdirSync as Xi,statSync as Ad,unlinkSync as rh,rmSync as ah,existsSync as Id}from"fs";import{resolve as Td,join as Od}from"path";var jd=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Qi(e,o){if(!Id(e))return[];let t=[];for(let n of Xi(e,{withFileTypes:!0})){let s=Od(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Qi(s,!0))}return t}var vs=new ih().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");vs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of jd){let t=Td(process.cwd(),o.dir),n=Qi(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Ad(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Po.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ks(s).padStart(10)} oldest=${r}`)}console.log(Po.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ks(e).padStart(10)} total`)),console.log(),console.log(Po.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});vs.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Po.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Po.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Po.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of jd){if(n&&r.dir!==n)continue;let a=Td(process.cwd(),r.dir),c=Qi(a,!!r.recursive),l=0,g=0;for(let p of c)try{let f=Ad(p);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{rh(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Cd(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Po.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ks(g)})`),s+=l,i+=g}console.log(),console.log(Po.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ks(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Cd(e){if(Id(e))for(let o of Xi(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Od(e,o.name);Cd(t);try{Xi(t).length===0&&ah(t,{recursive:!1})}catch{}}}function ks(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"}import{Command as ch}from"commander";import U from"chalk";var Mo=new ch().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Mo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new dt().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Mo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new dt().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Mo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=lh(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Or.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new dt().save(s.data);console.log(U.green(`
|
|
518
518
|
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
|
|
519
519
|
`))});Mo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new dt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Mo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new dt().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await jr(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Mo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function lh(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}ge();import{Command as dh}from"commander";import ee from"chalk";var Nd=new dh().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=R(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(ee.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(ee.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ee.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
520
520
|
|
|
521
|
-
`))>=0;){let
|
|
522
|
-
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as ph}from"commander";import xs from"chalk";import{spawn as uh}from"node:child_process";import{execFileSync as mh}from"node:child_process";function Rd(e=()=>mh("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var _d=new ph().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(xs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-
|
|
523
|
-
bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Md().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let
|
|
521
|
+
`))>=0;){let f=l.slice(0,p);l=l.slice(p+2),gh(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function gh(e){let o="message",t="";for(let i of e.split(`
|
|
522
|
+
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as ph}from"commander";import xs from"chalk";import{spawn as uh}from"node:child_process";import{execFileSync as mh}from"node:child_process";function Rd(e=()=>mh("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var _d=new ph().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(xs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-I7GAAM3T.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Rd();if(n?.ok){let{fetchAgents:l}=await import("./client-I7GAAM3T.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${d}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(xs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=uh("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(xs.yellow(n.reason)),console.error(xs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-QVNQ5BQK.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as fh}from"commander";import V from"chalk";import{randomUUID as Md}from"crypto";import{createInterface as hh}from"node:readline/promises";import yh from"ora";import Ss from"chalk";function Dd(e){console.error(),console.error(Ss.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ss.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ss.cyan(e.instead)} instead.`),e.note&&console.error(Ss.dim(` ${e.note}`)),console.error()}var Pd={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 Ld=new fh().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Dd({what:"agentx chat",...Pd});let t=cc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Md().slice(0,12)}`,r=[];try{r=await Un(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.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-CC57XC23.js"),p=(await import("react")).default;await g(p.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}bh(t.baseUrl,n,i,s);let a=hh({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
|
|
523
|
+
bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Md().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await Un(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await Un(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=yh({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=wh(n);try{let u=await lc(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){d.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(l){console.log(V.dim(" bye"));return}}});function wh(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
|
|
524
524
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
525
525
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
526
526
|
`&&(t=!0)}},tool(r){if(i(),r.status==="start"&&r.name){let a=r.id||`${r.name}:${s.size}`;if(s.has(a))return;s.add(a),t||(process.stdout.write(`
|
|
@@ -540,8 +540,8 @@ agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(
|
|
|
540
540
|
${e.persona}
|
|
541
541
|
`),Os(Pe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};Os(Pe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function tr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function nr(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function Ts(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
542
542
|
`).join(`
|
|
543
|
-
`)}`)}var Jd=new Th().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=Nh(process.cwd(),".agentx-demo"),n=Dh(t,o),s=Pe(t,"mesh-token"),i=!!e.reuse&&Is(s)&&Is(Pe(n[0].dir,"agentx.json")),r=i?jh(s,"utf8").trim():Rh(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Is(l))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Is(t))for(let
|
|
544
|
-
`,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=
|
|
543
|
+
`)}`)}var Jd=new Th().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=Nh(process.cwd(),".agentx-demo"),n=Dh(t,o),s=Pe(t,"mesh-token"),i=!!e.reuse&&Is(s)&&Is(Pe(n[0].dir,"agentx.json")),r=i?jh(s,"utf8").trim():Rh(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Is(l))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Is(t))for(let f of Ch(t))qd(Pe(t,f),{recursive:!0,force:!0});for(let f of n)Ph(f,n,r);Os(s,r+`
|
|
544
|
+
`,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let u of c)try{u.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{qd(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let y of n){let k=Wd(Pe(y.dir,"daemon.log"),"a"),b=or(process.execPath,[l,"daemon","start","-c",Pe(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Pe(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ce.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Pe(y.dir,"daemon.log")})`))}for(let y of n)await tr(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ce.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Wd(Pe(n[0].dir,"board.log"),"a"),k=or(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await tr("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ce.green(" \u2713 dashboard up")),await tr("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ce.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let u=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ce.cyan(u)} (all three nodes via the mesh)`),console.log(ce.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{or(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Ts("You \u2192 @cx (laptop-paris)",Bd,ce.cyan);let y=await nr(n[0].port,"/task",{agent:"cx",message:Bd});Ts("@cx (laptop-paris)",y.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await nr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:_h}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";Ts("@builder (vps-nyc)",b,ce.yellow);let v=await nr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Ts("@cx (laptop-paris)",v.content||"(no content)",ce.green),console.log(),console.log(ce.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(ce.dim(` Worth your time? A star helps others find it: ${ce.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ce.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ce.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(ce.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ce.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ce.red(` Demo failed: ${f.message}`)),console.error(ce.dim(` Node logs: ${n.map(u=>Pe(u.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Mh}from"commander";import{randomUUID as Lh}from"crypto";import{readFileSync as Fh}from"fs";import{resolve as Uh}from"path";ge();var Hd=new Mh().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??Fh(0,"utf8")).trim();t||Gd("no task given (pass it as an argument or on stdin)");let n=R(o.config?Uh(o.config):void 0),s=n.agents[o.agent];s||Gd(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";vr(o.agent,s,l,i)}let r=new Lr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Lh()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
|
|
545
545
|
`):c.error?console.error(c.error):process.stdout.write(c.content+`
|
|
546
546
|
`),process.exit(c.error?1:0)});function Gd(e){console.error(`agentx exec: ${e}`),process.exit(1)}ge();import{Command as qh}from"commander";import Oe from"chalk";var Fo=new qh().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Fo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await wn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no chats cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Oe.cyan("group"):Oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Oe.dim(n.jid.padEnd(40))} ${Oe.dim(i)}`)}console.log()}catch(o){Mt(o)}});Fo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await wn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no contacts cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Oe.dim(i)} ${Oe.dim(n.jid)}`)}console.log()}catch(o){Mt(o)}});Fo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await ir("/whatsapp/ingest",o);sr(t,!!e.dryRun)}catch(o){Mt(o)}});Fo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await ir("/whatsapp/ingest",t);sr(n,!!o.dryRun)}catch(t){Mt(t)}});Fo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await ir("/whatsapp/ingest",t);sr(n,!!o.dryRun)}catch(t){Mt(t)}});Fo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await wn("/whatsapp/state"),o=await wn("/whatsapp/chats"),t=await wn("/whatsapp/contacts");console.log(),console.log(Oe.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){Mt(e)}});function sr(e,o){if(console.log(),console.log(Oe.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Oe.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Oe.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Oe.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Oe.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function zd(){try{let e=R(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function wn(e){let o=await fetch(`${zd()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function ir(e,o){let t=await fetch(`${zd()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function Mt(e){console.error(Oe.red(` ${e.message||e}`)),process.exit(1)}ge();import{Command as Wh}from"commander";import le from"chalk";import{existsSync as Bh,mkdirSync as Yd,writeFileSync as bn}from"fs";import{join as Lt,resolve as Jh}from"path";var $n=new Wh().name("plugin").description("manage agentx plugins (Move B)");$n.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=R().plugins??[];if(console.log(),o.length===0){console.log(le.dim(" No plugins configured.")),console.log(le.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(le.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${le.cyan(t)}`);console.log(),console.log(le.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(le.red(` ${e.message}`)),process.exitCode=1}});$n.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(le.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=Jh(o.cwd,t);Bh(n)&&!o.force&&(console.log(le.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Yd(n,{recursive:!0}),Yd(Lt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;bn(Lt(n,"package.json"),Yh(e,s)),bn(Lt(n,"tsconfig.json"),Vh()),bn(Lt(n,"src/index.ts"),Kh(e)),bn(Lt(n,"README.md"),Xh(e,s)),bn(Lt(n,".gitignore"),Qh()),console.log(),console.log(le.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(le.bold(" Next steps:")),console.log(le.dim(` cd ${t}`)),console.log(le.dim(" pnpm install")),console.log(le.dim(" pnpm build")),console.log(le.dim(" pnpm link --global # for local testing")),console.log(le.dim(" # then in your agentx project:")),console.log(le.dim(` pnpm link --global ${e}`)),console.log(le.dim(` agentx config set plugins[0] "${e}"`)),console.log(le.dim(" agentx plugin doctor")),console.log()});$n.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=R().plugins??[];if(console.log(),o.length===0){console.log(le.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Gh(n);s.kind==="ok"?console.log(` ${le.green("\u2713")} ${le.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${le.red("\u2717")} ${le.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(le.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(le.red(` ${e.message}`)),process.exitCode=1}});async function Gh(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Hh(o);if(!zh(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=$a.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function Hh(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function zh(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Yh(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
|
|
547
547
|
`}function Vh(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
|
|
@@ -612,7 +612,7 @@ Restart the daemon to activate.
|
|
|
612
612
|
dist/
|
|
613
613
|
*.log
|
|
614
614
|
.env
|
|
615
|
-
`}import{Command as Zh}from"commander";import je from"chalk";import{writeFileSync as ey,mkdirSync as oy,existsSync as js,readFileSync as Vd,appendFileSync as Kd}from"fs";import{resolve as Ft,dirname as Zd}from"path";import{homedir as ar}from"os";var eg=new Zh().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-
|
|
615
|
+
`}import{Command as Zh}from"commander";import je from"chalk";import{writeFileSync as ey,mkdirSync as oy,existsSync as js,readFileSync as Vd,appendFileSync as Kd}from"fs";import{resolve as Ft,dirname as Zd}from"path";import{homedir as ar}from"os";var eg=new Zh().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-ZCFMO4ZD.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=sy(t);break;case"bash":s=ly(t);break;case"fish":s=dy(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ft(String(e.output)):ty(n);oy(Zd(i),{recursive:!0}),ey(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),ny(n,i,!!e.yes)});function ty(e){let o=ar();switch(e){case"zsh":return Ft(o,".zsh","completions","_agentx");case"bash":return Ft(o,".bash_completion.d","agentx.bash");case"fish":return Ft(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ny(e,o,t){if(e==="zsh"){let n=Ft(ar(),".zshrc"),s=Zd(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=js(n)?Vd(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&js(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Kd(n,g.join(`
|
|
616
616
|
`)+`
|
|
617
617
|
`),console.log(je.green("\u2713 Patched ~/.zshrc")),console.log(je.dim("Reload your shell: exec zsh"));return}console.log(je.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(je.cyan(` ${i}`)),l&&console.log(je.cyan(` ${r}`)),console.log(),console.log(je.dim("Then reload: exec zsh")),console.log(je.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ft(ar(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((js(n)?Vd(n,"utf-8"):"").includes(o)){console.log(je.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&js(n)){Kd(n,`
|
|
618
618
|
# agentx completion
|
|
@@ -623,4 +623,4 @@ ${s}
|
|
|
623
623
|
`)}function cr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function rr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=cr(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function NA(){let e=await Xa(),o=new gy().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=sc(n);ic(s)&&nc("cli",s)});for(let t of[Rc,jc,jt,ht,Ve,ec,Go,Vn,ho,Ro,Zo,Yn,_d,jo,Xc,rl,rn,yl,kl,vl,Fl,Bl,Jl,ls,gn,Fd,Qt,Eo,eg])o.addCommand(t);for(let t of tg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=tg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,my(t,74," "),""].join(`
|
|
624
624
|
`)}),o}var tg=[Q,Ct,Lo,to,en,It,Je,wo,_o,et,Dt,Pt,To,qe,xt,ds,Nd,uo,kt,dc,Ho,$n,ai,Mo,$t,ci,vs,Do,Fo,Jd,Hd,Ld];function my(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
625
625
|
`)}export{NA as a};
|
|
626
|
-
//# sourceMappingURL=chunk-
|
|
626
|
+
//# sourceMappingURL=chunk-LBMZP7TG.js.map
|