agentix-cli 0.50.1 → 0.52.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-WG4ZZV4A.js} +346 -137
- package/dist/board-dashboard-WG4ZZV4A.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-WUDXUY7H.js → chunk-BNVF66YL.js} +3 -3
- package/dist/chunk-BNVF66YL.js.map +1 -0
- package/dist/{chunk-HHY3MSMN.js → chunk-CAA546XN.js} +2 -2
- package/dist/{chunk-X5K3HR4V.js → chunk-F7WY24UZ.js} +2 -2
- package/dist/{chunk-7WDJW37G.js → chunk-GUJB53QU.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-4BNQSUWV.js → chunk-KAFO5QZR.js} +2 -2
- package/dist/{chunk-ZQSB6IX4.js → chunk-KFALP5NO.js} +2 -2
- package/dist/{chunk-RP7GLXOA.js → chunk-NTG5ZXRI.js} +180 -179
- package/dist/chunk-NTG5ZXRI.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-JWLTI6NZ.js → chunk-UL4E2CV4.js} +163 -160
- package/dist/chunk-UL4E2CV4.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-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/processes-NNXSRQSV.js +2 -0
- package/dist/program-UXJWH5JG.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/chunk-WUDXUY7H.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/processes-CMTMB7LG.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-7WDJW37G.js.map → chunk-GUJB53QU.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-4BNQSUWV.js.map → chunk-KAFO5QZR.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-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/{processes-CMTMB7LG.js.map → processes-NNXSRQSV.js.map} +0 -0
- /package/dist/{program-RFAHI4SS.js.map → program-UXJWH5JG.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,34 +1,37 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
Computer-use helper \u2192 ${Me(
|
|
3
|
-
Agent \u2192 ${t}
|
|
4
|
-
Daemon \u2192 ${
|
|
5
|
-
Starts at login \u2192 ${
|
|
1
|
+
import{a as gc,b as Wn,g as mc}from"./chunk-KFALP5NO.js";import{a as uo,b as oc,f as So,i as qn,j as sc,k as ic,l as Qs,m as lc,o as dc}from"./chunk-BNVF66YL.js";import{a as rc,c as ac,d as cc}from"./chunk-Z3IP66SL.js";import{a as tc,c as nc}from"./chunk-CAA546XN.js";import{a as Us,b as Wr}from"./chunk-RKPAVWXF.js";import{a as mt}from"./chunk-GV7S5BAX.js";import{e as Nr}from"./chunk-GSX4NK2N.js";import{c as Rr}from"./chunk-SZDACK6O.js";import{$ as za,A as _a,B as Da,C as Pa,D as Yt,E as Js,F as _n,G as Ma,H as xo,I as La,J as Gs,K as Hs,L as Fa,M as Ua,N as Vt,O as Dn,P as qa,Q as Wa,R as Ba,S as Ja,T as ut,U as ft,V as Ga,W as Ha,X as Ce,Y as Pn,Z as Kt,_ as zs,a as Kr,aa as Mn,b as Xr,ba as Ln,ca as Ka,da as Ks,ea as Qa,fa as Fn,ga as ht,h as oa,ha as Un,i as zt,ia as Xs,j as jn,ja as Za,k as sa,ka as ec,l as ia,m as ra,n as aa,o as ya,p as wa,q as xa,r as Aa,s as Ta,t as Oa,u as Ia,v as ja,w as Bs,x as Ca,y as Na,z as Ra}from"./chunk-NTG5ZXRI.js";import{E as Ya,F as Ys,G as Va,H as Vs,V as io,X as Xa,k as ba,n as $a,u as ka,v as va}from"./chunk-YE2BUU3Z.js";import{a as Qr,d as Zr,e as ea}from"./chunk-QP6XNTBB.js";import{a as Ws,b as Cn,c as Nn,d as ca,e as la,f as da,i as ga,j as ma,k as pa,l as ua,o as Rn,q as fa,r as ha}from"./chunk-S7CVSKOX.js";import{a as ta,p as na}from"./chunk-WDQ3BPFS.js";import{a as Sa,b as Ea}from"./chunk-L53FTKEP.js";import{E as Ur,O as qr,h as Tr,q as Or,v as Ms,w as jr,y as vo}from"./chunk-YEV6W34S.js";import{b as Gt,c as dt,d as On,e as In,f as gt,g as Cr,h as Jo,i as Ht}from"./chunk-U67EG5IF.js";import{a as Ar}from"./chunk-N6EWZGIX.js";import{e as Mr,f as Fs,k as Lr}from"./chunk-WP6KLXTP.js";import{b as lt}from"./chunk-DP7RTNDM.js";import{a as qs,e as Br,f as Jr,h as Gr,i as Hr,k as zr,l as Yr,m as Vr}from"./chunk-F7WY24UZ.js";import{a as Ir,k as Pr}from"./chunk-V7XZN3MQ.js";import{f as _r,g as Dr,h as Ls}from"./chunk-76Z4VHDX.js";import{b as he,c as Ae,d as pt,e as Fr}from"./chunk-VMS3HVTT.js";import{h as Er}from"./chunk-DWADWDMU.js";import{a as Ps}from"./chunk-XZTR5MBJ.js";import{b as ko,d as Tn}from"./chunk-ROCUOXCW.js";import{b as ct,d as Sr}from"./chunk-2GIDVZ4H.js";import{a as Ds,b as mr,c as cg,d as En,e as pr,f as wr,g as dg,h as br,i as gg,m as at,n as kr,o as vr,s as xr,v as so,w as Jt}from"./chunk-JQR3NTHI.js";import{a as po,b as rt,e as fr,f as Bt}from"./chunk-72SZI2UW.js";import{a as $r,b as mg}from"./chunk-FX3D7YON.js";import{a as mo,b as ag}from"./chunk-7I7IEX4S.js";import{l as ur,m as R,n as An,p as re}from"./chunk-SRCXUZM2.js";import{g as hr,k as yr,l as lg}from"./chunk-RGDKHYY2.js";import{Command as pg}from"commander";var pc=new pg().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 Xr({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()});re();import{Command as ug}from"commander";import{execFileSync as ro}from"node:child_process";import{cpSync as uc,existsSync as ei,mkdirSync as Zs,mkdtempSync as fg,rmSync as hg,writeFileSync as fc}from"node:fs";import{dirname as hc,join as Me}from"node:path";import{homedir as Bn,release as yg,tmpdir as wg}from"node:os";import{setTimeout as bg}from"node:timers/promises";function Jn(){let e=ca(process.platform,process.arch,yg());if(e)throw new Error(e)}function Xt(){return`gui/${process.getuid()}/${Ws}`}function yt(){return Me(Bn(),"Library/LaunchAgents",`${Ws}.plist`)}async function yc(){try{ro("launchctl",["bootout",Xt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{return}await bg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function wc(){if(!ei(yt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{e=!1}e||ro("launchctl",["bootstrap",`gui/${process.getuid()}`,yt()],{stdio:"pipe"}),ro("launchctl",["kickstart",Xt()],{stdio:"pipe"})}function $g(){let e=ua();if(e&&ei(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 wt=new ug("desktop").description("install and control the macOS desktop assistant");wt.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=>{Jn();let o=R(),t=la(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=$g(),r=Me(Bn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Me(r,Cn)}
|
|
2
|
+
Computer-use helper \u2192 ${Me(r,Nn)}
|
|
3
|
+
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
|
+
Daemon \u2192 ${s}
|
|
5
|
+
Starts at login \u2192 ${yt()}`),e.dryRun)return;try{ro("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=ro("/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=fg(Me(wg(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){uc(Me(i,"apps",p),Me(c,p),{recursive:!0,filter:u=>!u.split("/").includes("build")});let f=p==="mac-helper"?ma(o.notifications.local.icon):[];ro("/bin/bash",[Me(c,p,"build.sh"),...f],{stdio:"inherit"})}let l=Me(Bn(),"Library/Logs/agentx-desktop.err.log"),g=ga({executable:Me(r,Cn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:pa(Bn()),cli:Me(i,"dist/cli.js"),node:process.execPath,log:l,path:da(a,process.env.AGENTX_VOICE_PATH)}),d=Me(c,"desktop.plist");fc(d,g,{mode:384}),ro("plutil",["-lint",d],{stdio:"pipe"}),await yc(),Zs(r,{recursive:!0});for(let[p,f,u]of[["mac-voice","AgentX Voice.app",Cn],["mac-helper",Nn,Nn]])uc(Me(c,p,"build",f),Me(r,u),{recursive:!0});Zs(hc(yt()),{recursive:!0}),Zs(hc(l),{recursive:!0}),fc(yt(),g,{mode:384}),wc(),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{
|
|
8
|
-
`)),{path:t,changed:l,events:a,guardInstalled:c}}function
|
|
9
|
-
`),{path:o,changed:r,events:i,guardInstalled:!1}}function
|
|
10
|
-
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await
|
|
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(;
|
|
12
|
-
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(
|
|
13
|
-
`);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let p=JSON.parse(d.slice(6)),
|
|
14
|
-
(${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(
|
|
15
|
-
`)),console.log(Ke.green(" \u2713 Created .env template"))),
|
|
7
|
+
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{hg(c,{recursive:!0,force:!0})}});wt.command("start").description("start the installed desktop assistant").action(()=>{Jn(),wc(),console.log("Desktop assistant started.")});wt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Jn(),await yc(),console.log("Desktop assistant stopped.")});wt.command("status").description("show the desktop login service status").action(()=>{Jn();try{console.log(ro("launchctl",["print",Xt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(ei(yt())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Ag}from"commander";import{open as Tg}from"fs/promises";import{existsSync as zn,mkdirSync as kg,readFileSync as Yn,writeFileSync as bc}from"fs";import{homedir as vg}from"os";import{dirname as xg,resolve as oi}from"path";var ti="/attach/",$c="/guard/check";function kc(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 Gn(e,o,t){let n={hooks:[{type:"command",command:kc(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Sg(e){return{SessionStart:[Gn("/attach/session-start",e,"")],UserPromptSubmit:[Gn("/attach/prompt",e)],Stop:[Gn("/attach/stop",e)],SessionEnd:[Gn("/attach/session-end",e)]}}function Eg(e){let o=kc("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Hn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Qt(){return oi(vg(),".claude/settings.json")}function Go(e=process.cwd()){for(let o of[e,oi(e,"..")]){let t=oi(o,"agentx.json");if(zn(t))try{let n=JSON.parse(Yn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function vc(e,o={}){let t=o.path??Qt(),n=o.withGuard!==!1,s={};if(zn(t))try{s=JSON.parse(Yn(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(Sg(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!Hn(f,ti)):[];r[g]=[...p,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Hn(d,$c)):[];r.PreToolUse=[...g,...Eg(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(kg(xg(t),{recursive:!0}),bc(t,`${JSON.stringify(s,null,2)}
|
|
8
|
+
`)),{path:t,changed:l,events:a,guardInstalled:c}}function xc(e={}){let o=e.path??Qt();if(!zn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Yn(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"?$c:ti;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Hn(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&&bc(o,`${JSON.stringify(t,null,2)}
|
|
9
|
+
`),{path:o,changed:r,events:i,guardInstalled:!1}}function Vn(e=Qt()){if(!zn(e))return!1;try{return!!JSON.parse(Yn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Hn(t,ti))}catch{return!1}}var Kn=new Ag("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Sc=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;async function Ec(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)}`)}Kn.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",Sc).action(async e=>{try{await Ec(e.url,"register",Zr.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}});Kn.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",Sc).action(async e=>{try{let o=await Tg(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 Ec(e.url,"ended",ea.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 $y}from"commander";import{Command as Pg}from"commander";re();import T from"chalk";import{existsSync as Mg,readFileSync as Lg}from"fs";re();import{Command as Og}from"commander";import oe from"chalk";import{spawn as Tc}from"child_process";import{existsSync as Ig,readFileSync as jg,unlinkSync as Cg}from"fs";import{resolve as ni}from"path";var si=e=>new Promise(o=>setTimeout(o,e));function ii(e){try{return process.kill(e,0),!0}catch{return!1}}async function bt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Ng(e){let o=await bt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await bt(`${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 Rg(e){for(let o of[ni(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(jg(o,"utf-8").trim(),10);if(Number.isFinite(t)&&ii(t))return t}catch{}return null}function _g(e){return new Promise(o=>{let t=Tc(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Oc=new Og("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 bt(`${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 bt(`${i}/daemon/restart`),c=a?.pid??Ca(s)??Rg(process.cwd()),l=a?.service??(c?Ia(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,p=process.getuid?.()===0,f=Ta(l,{isRoot:p,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?ja(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: ${Oa(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(` ${Ac(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 Aa({read:()=>Ng(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=ni(g,".agentx");try{Ea(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 Dg(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&&Cg(ni(u,Sa))}catch{}console.log(oe.red(` Step failed: ${Ac(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 bt(`${i}/health`);if(v&&typeof v.uptime=="number"&&v.uptime*1e3<=Date.now()-w+2e3){let A=await bt(`${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 si(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 Ac(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 Dg(e,o){switch(e.kind){case"exec":return await _g(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(;ii(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 si(500);return ii(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(;Bs(o.service)&&Date.now()-t<3e4;)await si(500);return!Bs(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Ig(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=Tc(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Fg(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 Pg().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(T.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(T.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(T.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(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${w}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(T.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 Fg(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Ug(i(process.cwd(),".env"))}catch{}await new Xs(e.config).start()});function Ug(e){if(!Mg(e))return;let o=Lg(e,"utf-8");for(let t of o.split(`
|
|
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(;Ic(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(T.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(Ic(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.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(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});Ve.addCommand(Oc);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(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${qg(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=R(e.config),n=An(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.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(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.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(T.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(T.dim(` Connecting to ${n}...`)),console.log(T.dim(` Press Ctrl+C to stop
|
|
12
|
+
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(T.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)),f=new Date(p.time).toLocaleTimeString(),u=p.message?.replace(/^\[agentx\]\s*/,"")||"";u.includes("executing")?console.log(`${T.dim(f)} ${T.cyan("\u25B6")} ${u}`):u.includes("completed")?console.log(`${T.dim(f)} ${T.green("\u2713")} ${u}`):u.includes("error")||u.includes("Error")?console.log(`${T.dim(f)} ${T.red("\u2717")} ${u}`):u.includes("Routing")?console.log(`${T.dim(f)} ${T.yellow("\u2192")} ${u}`):u.includes("mention")?console.log(`${T.dim(f)} ${T.magenta("@")} ${u}`):u.includes("Skipping")?console.log(`${T.dim(f)} ${T.dim("\u2298")} ${T.dim(u)}`):console.log(`${T.dim(f)} ${u}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(T.red(` Connection failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Diagnostic order:")),console.log(T.dim(" 1) agentx daemon status # is the daemon up?")),console.log(T.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(T.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(T.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(T.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(T.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(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
|
|
14
|
+
(${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.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(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.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(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.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(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});Ve.action(async e=>{await new Xs(e.config).start()});function qg(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 Ic(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as Wg}from"commander";import Ke from"chalk";import{existsSync as Zt,readFileSync as Bg,writeFileSync as jc,mkdirSync as Cc}from"fs";import{hostname as Nc}from"os";import{resolve as $t}from"path";var Rc=new Wg().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=$t(o,"agentx.json"),n=$t(o,".env"),s=$t(o,".agentx/sessions");if(console.log(),console.log(Ke.bold(" agentx init")),console.log(),Zt(t)&&!e.force){console.log(Ke.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[$t(o,"agentx.example.json"),$t(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Zt(c)){r=Bg(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Nc().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Nc(),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)),jc(t,r),console.log(Ke.green(" \u2713 Created agentx.json")),Zt(n)||(jc(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
15
|
+
`)),console.log(Ke.green(" \u2713 Created .env template"))),Zt(s)||(Cc(s,{recursive:!0}),console.log(Ke.green(" \u2713 Created .agentx/sessions/")));let a=$t(o,".claude");Zt(a)||(Cc(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 Jg}from"commander";import Ho from"chalk";import{spawn as Dc}from"child_process";import{existsSync as Gg}from"fs";import{dirname as Hg,resolve as zg}from"path";import{fileURLToPath as Yg}from"url";re();var Pc=new Jg().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=oc(),t=e.port?parseInt(e.port,10):Vg(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Ho.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Ho.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Ho.bold(` Opening ${n}`)),console.log(),await Xg(n).catch(()=>!1))console.log(Ho.dim(" Dashboard is already running.")),e.open!==!1&&_c(n);else{console.log(Ho.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Kg(),r=Dc(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&_c(n),await new Promise(a=>r.on("exit",()=>a()))}});function Vg(){try{return R().dashboard.port||4202}catch{return 4202}}function Kg(){let e=zg(Hg(Yg(import.meta.url)),"cli.js");return Gg(e)?e:process.argv[1]||e}async function Xg(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function _c(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Dc(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Ho.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Ho.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Qg}from"commander";import Te from"chalk";var en=new Qg().name("token").description("scoped API tokens for external access (mesh peers, integrations)");en.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 So,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(Te.bold(" Token created.")),console.log(),console.log(` id: ${Te.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Te.dim("never")}`),console.log(),console.log(Te.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Te.green.bold(s)}`),console.log(),console.log(Te.dim(" Use it via the Authorization header:")),console.log(Te.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});en.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new So().list();if(e.length===0){console.log(Te.dim(`
|
|
16
16
|
No tokens issued.
|
|
17
|
-
`));return}console.log();for(let o of e){let t=o.revokedAt?
|
|
17
|
+
`));return}console.log();for(let o of e){let t=o.revokedAt?Te.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Te.red("expired"):Te.green("active");console.log(` ${Te.cyan(o.id)} ${t} ${o.name}`),console.log(Te.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Te.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Te.red(` ${e.message}`)),process.exit(1)}});en.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new So().revoke(e);o||(console.log(Te.red(` Token ${e} not found.`)),process.exit(1)),console.log(Te.green(`
|
|
18
18
|
\u2713 Revoked ${e} (${o.name})
|
|
19
|
-
`))}catch(o){console.log(
|
|
20
|
-
|
|
19
|
+
`))}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});import{Command as Zg}from"commander";import Xe from"chalk";import{execFileSync as Mc}from"child_process";re();var on=new Zg().name("app").description("pair phones with the AgentX phone app and manage paired devices");on.command("pair").description("pair a phone \u2014 prints a QR code to scan with the phone's camera").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let o=tm(nm(),ri());if(o.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${o.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset",` tailscale serve --bg --set-path /app http://127.0.0.1:${ri()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${ri()}/api/app`].join(`
|
|
20
|
+
`));let t=(e.url?String(e.url):em()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(t))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${t}`);let{token:n,record:s}=new So().create({name:String(e.name),scopes:["app"]}),i=`${t}/app/pair#token=${n}`,{default:r}=await import("qrcode-terminal");console.log(),r.generate(i,{small:!0},a=>console.log(a)),console.log(" Scan with the phone's camera, then open the link."),console.log(` Device ${Xe.cyan(s.id)} (${s.name}) paired to ${t}.`),console.log(Xe.yellow(" \u26A0 Anyone who scans this code can use the app. Clear the terminal when done.")),t.startsWith("https://")||console.log(Xe.yellow(` \u26A0 ${t} is not HTTPS: the phone can't install the app or keep the session from there.`)),console.log()}catch(o){console.log(Xe.red(` ${o.message}`)),process.exit(1)}});on.command("devices").description("list paired phones").action(()=>{let e=new So().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Xe.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Xe.red("revoked"):Xe.green("active");console.log(` ${Xe.cyan(o.id)} ${t} ${o.name}`),console.log(Xe.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});on.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new So,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Xe.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Xe.green(`
|
|
21
|
+
\u2713 Unpaired ${e} (${t.name})
|
|
22
|
+
`))});function em(){let e;try{e=JSON.parse(Mc("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var om=new Set(["/app","/api/app"]);function tm(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!om.has(g)&&n.push(`${i}${a}`)}return n}function nm(){try{return JSON.parse(Mc("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function ri(){try{return R().dashboard.port||4202}catch{return 4202}}re();import{Command as co}from"commander";import h from"chalk";import Ne from"prompts";import{readFileSync as Ao,writeFileSync as kt,existsSync as ue,mkdirSync as ao,cpSync as ai,readdirSync as li}from"fs";import{resolve as G,join as Eo,dirname as sm}from"path";import{fileURLToPath as im}from"url";function ae(){let e=G(process.cwd(),"agentx.json");if(!ue(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ao(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 zo=new co().name("agent").description("manage agents \u2014 add, list, remove");zo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ae();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()});zo.command("add").description("add a new agent interactively").action(async()=>{let e=ae(),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:Eo(o.workspace,o.id);ao(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(sm(im(import.meta.url)),"../wiki/SKILL.md"),c=ue(r)?r:a;ue(c)&&(ao(G(t,".claude/skills/wiki"),{recursive:!0}),ai(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Le(e),console.log(h.green(`
|
|
23
|
+
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()});zo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ae();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)`))});zo.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=ae(),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 tn=new co().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");tn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ae().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
24
|
${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(`
|
|
25
|
+
`));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()});tn.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=ae();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`))});tn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ae(),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}`))});tn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ae().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)});zo.addCommand(tn);var Xn=new co().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Xn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ae();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()});Xn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ae(),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),ao(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 vt=new co().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");vt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});vt.command("add").description("add a cron job").action(async()=>{let e=ae(),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())});vt.command("enable <id>").description("enable a cron job").action(async e=>{let o=ae();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`))});vt.command("disable <id>").description("disable a cron job").action(async e=>{let o=ae();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 xt=new co().name("mesh").description("manage mesh peers \u2014 add, list, remove");xt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ae();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()});xt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ae(),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()}});xt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ae();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`)))});xt.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=ae();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 Yo=new co().name("skill").description("manage skills \u2014 add to agent(s), list");Yo.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=ae(),n=G(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(Eo(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);ao(c,{recursive:!0}),ue(Eo(n,"SKILL.md"))?ai(n,c,{recursive:!0}):n.endsWith(".md")&&ai(n,Eo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Yo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=ue(n)?li(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Yo.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=Ao(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||(ao(A,{recursive:!0}),kt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=Ao(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||kt(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()});Yo.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=ae().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=ae();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)});Yo.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=ae(),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
26
|
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
|
|
27
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var nn=new co().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");nn.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");ao(i,{recursive:!0}),ao(r,{recursive:!0});let a=li(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=Eo(i,d);if(ue(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let u=Ao(Eo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);kt(p,u),console.log(h.green(` + ${p}`)),c++}let g=Eo(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=Ao(s,"utf-8").replaceAll("example.",`${e}.`);kt(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()});nn.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
28
|
--- ${w} ---`)),console.log(y.split(`
|
|
26
29
|
`).slice(0,30).map(k=>` ${k}`).join(`
|
|
27
30
|
`)),y.split(`
|
|
28
31
|
`).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}
|
|
32
|
+
`).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}ao(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=Eo(p,w);if(ue(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}kt(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()});nn.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 di=new co().name("hook").description("manage hooks \u2014 add to agent workspace");di.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ae().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(Ao(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),ao(G(t.workspace,".claude"),{recursive:!0}),kt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var gi=new co().name("migrate").description("import configuration from OpenClaw or other tools");gi.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(Ao(n,"utf-8")),i=ue(G(process.cwd(),"agentx.json"))?ae():{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){ao(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(Ao(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
33
|
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
|
|
34
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var To=new co().name("config").description("validate and inspect configuration");To.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=An(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"))?li(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()});To.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 rm(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 ci(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}To.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(ci(g))});To.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=rm(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: ${ci(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ci(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})`)))});To.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.")))});To.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 am}from"commander";import Oo from"chalk";import{resolve as Io}from"path";import{existsSync as cm}from"fs";var fo=new am().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Vo(e){let o=Io(e,".agentx/db.sqlite");cm(o)||(console.log(Oo.red(` No SQLite at ${o}`)),console.log(Oo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Ar({path:o});return t||(console.log(Oo.red(` Could not open ${o}`)),console.log(Oo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Ko(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Oo.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])))}fo.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=Vo(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
35
|
SELECT agent_id, channel, status, duration_ms,
|
|
33
36
|
input_tokens, output_tokens,
|
|
34
37
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -37,7 +40,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
37
40
|
${t.length?"WHERE "+t.join(" AND "):""}
|
|
38
41
|
ORDER BY started_at DESC
|
|
39
42
|
LIMIT @limit
|
|
40
|
-
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});
|
|
43
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Ko(i,!!e.json)});fo.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Vo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
|
|
41
44
|
SELECT agent_id, reason, COUNT(*) AS n,
|
|
42
45
|
ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
|
|
43
46
|
MAX(last_turn_input_tokens) AS max_input_tokens
|
|
@@ -51,14 +54,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
51
54
|
${s}
|
|
52
55
|
ORDER BY rotated_at DESC
|
|
53
56
|
LIMIT @limit
|
|
54
|
-
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});
|
|
57
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});Ko(r,!!e.json)});fo.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Vo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
|
|
55
58
|
SELECT day, agent_id, model, tasks,
|
|
56
59
|
input_tokens AS in_tok, output_tokens AS out_tok,
|
|
57
60
|
cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
|
|
58
61
|
FROM usage_daily
|
|
59
62
|
${t.length?"WHERE "+t.join(" AND "):""}
|
|
60
63
|
ORDER BY day DESC, agent_id
|
|
61
|
-
`,i=o.prepare(s).all(n);
|
|
64
|
+
`,i=o.prepare(s).all(n);Ko(i,!!e.json)});fo.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Vo(Io(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
|
|
62
65
|
SELECT channel, kind, deciding_stage, COUNT(*) AS n
|
|
63
66
|
FROM route_traces
|
|
64
67
|
${s}
|
|
@@ -71,7 +74,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
71
74
|
${s}
|
|
72
75
|
ORDER BY at DESC
|
|
73
76
|
LIMIT @limit
|
|
74
|
-
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});
|
|
77
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});Ko(r,!!e.json)});fo.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Vo(Io(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
|
|
75
78
|
SELECT agent_id, channel, duration_ms,
|
|
76
79
|
substr(error, 1, 120) AS error,
|
|
77
80
|
started_at
|
|
@@ -79,12 +82,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
79
82
|
WHERE ${t.join(" AND ")}
|
|
80
83
|
ORDER BY started_at DESC
|
|
81
84
|
LIMIT @limit
|
|
82
|
-
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});
|
|
85
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Ko(i,!!e.json)});fo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Vo(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}));Ko(n,!!e.json)});fo.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=Vo(Io(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Oo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Oo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Ko(n,!!o.json)}catch(n){console.log(Oo.red(` ${n.message}`)),process.exit(1)}});import{Command as gm}from"commander";import z from"chalk";import{mkdtempSync as mm}from"fs";import{tmpdir as pm}from"os";import{resolve as Fc,join as Uc}from"path";import{existsSync as um}from"fs";import fm from"better-sqlite3";function Lc(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=lm(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=Pr(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:dm(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function lm(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function dm(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 jo=new gm().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function St(e){let o=Fc(e.cwd??process.cwd()),t=Fc(o,e.path??".agentx/intent/ledger.sqlite");um(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 fm(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 Xo(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 hm(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 Qn(e){if(!e)return;let o=hm(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}jo.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=St(e),t=Qn(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
86
|
SELECT COUNT(*) as n FROM intent_decisions d
|
|
84
87
|
LEFT JOIN intent_resolutions r
|
|
85
88
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
86
89
|
WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
|
|
87
|
-
`).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),
|
|
90
|
+
`).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),Xo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),Xo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),Xo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});jo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=St(e),t=Qn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
|
|
88
91
|
SELECT
|
|
89
92
|
datetime(ts/1000, 'unixepoch') AS at,
|
|
90
93
|
source,
|
|
@@ -98,7 +101,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
98
101
|
${i}
|
|
99
102
|
ORDER BY ts DESC
|
|
100
103
|
LIMIT @limit
|
|
101
|
-
`).all(s);
|
|
104
|
+
`).all(s);Xo(r,!!e.json)});jo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=St(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
|
|
102
105
|
SELECT
|
|
103
106
|
datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
|
|
104
107
|
e.source,
|
|
@@ -114,7 +117,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
114
117
|
WHERE ${t.join(" AND ")}
|
|
115
118
|
ORDER BY d.decided_at DESC
|
|
116
119
|
LIMIT @limit
|
|
117
|
-
`).all(n);
|
|
120
|
+
`).all(n);Xo(s,!!e.json)});jo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=St(e),t=Qn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
|
|
118
121
|
SELECT
|
|
119
122
|
datetime(ts/1000, 'unixepoch') AS at,
|
|
120
123
|
source,
|
|
@@ -125,7 +128,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
125
128
|
${i}
|
|
126
129
|
ORDER BY ts DESC
|
|
127
130
|
LIMIT @limit
|
|
128
|
-
`).all(s);
|
|
131
|
+
`).all(s);Xo(r,!!e.json)});jo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=St(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
|
|
129
132
|
FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(z.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((d,p)=>[`id${p}`,d])),l=t.prepare(`
|
|
130
133
|
SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
|
|
131
134
|
r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
|
|
@@ -134,21 +137,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
134
137
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
135
138
|
WHERE d.event_id IN (${a})
|
|
136
139
|
ORDER BY d.decided_at ASC
|
|
137
|
-
`).all(c);if(o.json){let d=i.map(p=>({event:p,decisions:l.filter(
|
|
140
|
+
`).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()});jo.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=St(e),t=Qn(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
141
|
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
139
142
|
FROM intent_events
|
|
140
143
|
${n.length?"WHERE "+n.join(" AND "):""}
|
|
141
144
|
ORDER BY ts ASC
|
|
142
145
|
${i}
|
|
143
|
-
`).all(s).map(
|
|
146
|
+
`).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
147
|
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
145
148
|
FROM intent_decisions
|
|
146
149
|
WHERE event_id IN (${c})
|
|
147
|
-
`).all(l).map(
|
|
150
|
+
`).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
151
|
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
149
152
|
FROM intent_resolutions
|
|
150
153
|
WHERE decision_event_id IN (${c})
|
|
151
|
-
`).all(l).map(
|
|
154
|
+
`).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=mm(Uc(pm(),"agentx-ledger-replay-")),f=new Ir({path:Uc(p,"target.sqlite")});try{let u=Lc(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`)),Xo(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()}});pr();lg();dg();gg();cg();kr();Bt();import{Command as ym}from"commander";import q from"chalk";import{existsSync as qc}from"fs";import{resolve as mi}from"path";import wm from"better-sqlite3";var qe=new ym().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Qe=".agentx/decisions/decisions.sqlite";function bm(e){return mi(mi(e.cwd??process.cwd()),e.path??Qe)}function go(e,o=!1){let t=bm(e);qc(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 En({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 lo(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 pi(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 ui(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:pi(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",Qe).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=go(e),t=pi(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
|
|
152
155
|
COUNT(*) AS calls,
|
|
153
156
|
SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
|
|
154
157
|
SUM(retries) AS retries,
|
|
@@ -158,16 +161,16 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
158
161
|
FROM decision_calls
|
|
159
162
|
WHERE ts >= ?
|
|
160
163
|
GROUP BY seat, mode, backend, model, structure_mode
|
|
161
|
-
ORDER BY calls DESC`).all(t);
|
|
164
|
+
ORDER BY calls DESC`).all(t);lo(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
|
|
162
165
|
FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
|
|
163
166
|
ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(q.bold(`
|
|
164
|
-
policy`)),
|
|
167
|
+
policy`)),lo(s,!1),console.log(q.dim(`
|
|
165
168
|
explored=1 means the policy wanted to skip and the expensive path ran anyway.
|
|
166
|
-
Those are the only rows in the skip region that can ever be graded.`))),o.close()});qe.command("calls").description("recent calls").option("--path <file>","store path",
|
|
169
|
+
Those are the only rows in the skip region that can ever be graded.`))),o.close()});qe.command("calls").description("recent calls").option("--path <file>","store path",Qe).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=go(e),t=["ts >= ?"],n=[pi(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
|
|
167
170
|
structure_mode AS structure, latency_ms AS ms, retries, truncated, error
|
|
168
171
|
FROM decision_calls WHERE ${t.join(" AND ")}
|
|
169
|
-
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));
|
|
170
|
-
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});qe.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",
|
|
172
|
+
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));lo(s,e.json),o.close()});qe.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Qe).option("--json").action((e,o)=>{let t=go(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(q.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}lo(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});qe.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Qe).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=go(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(q.green(` labeled ${e}.${o} = ${t}`)),s.close()});qe.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Qe).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=go(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));lo(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});qe.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Qe).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=go(e,!0),t=mi(process.cwd(),e.db);qc(t)||(console.log(q.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new wm(t,{readonly:!0});try{let s=Qr(n,o);console.log(q.green(` wrote ${s} label(s)`)),s===0&&console.log(q.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
|
|
173
|
+
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});qe.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Qe).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=go(e),t=o.gradedRows(ui(e)),n=yr(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(q.bold(`
|
|
171
174
|
${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(q.yellow(`
|
|
172
175
|
Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(q.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(q.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
|
|
173
176
|
accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+q.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${q.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${q.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${q.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
|
|
@@ -175,21 +178,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
175
178
|
skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(q.yellow(` Nothing in the skip region has been graded. Everything below describes
|
|
176
179
|
only the decisions this policy chose NOT to skip \u2014 it cannot tell you
|
|
177
180
|
what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(q.bold(`
|
|
178
|
-
reliability (equal-width bins)`)),
|
|
181
|
+
reliability (equal-width bins)`)),lo(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});qe.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Qe).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=go(e),t=o.gradedRows(ui(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=wr(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(q.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(q.bold(`
|
|
179
182
|
${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(q.dim(` Cross-validated, because more parameters always fit training data better.
|
|
180
|
-
`)),
|
|
183
|
+
`)),lo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(q.green(`
|
|
181
184
|
Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(q.dim(" that need different corrections."))):s.best==="temperature"?console.log(q.dim(`
|
|
182
185
|
One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(q.dim(`
|
|
183
|
-
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});qe.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",
|
|
186
|
+
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});qe.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Qe).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=go(e),t=o.gradedRows({...ui(e),labeledOnly:!0}),n=hr(t,Number(e.steps));if(n.length===0){console.log(q.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}lo(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});qe.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Qe).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{at();let o=go(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
|
|
184
187
|
WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
|
|
185
188
|
${e.call?"AND id = ?":""}
|
|
186
|
-
ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(q.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(q.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await
|
|
189
|
+
ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(q.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(q.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await br(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(q.bold(`
|
|
187
190
|
${e.seat} on ${i.backend} (${i.model})`)),console.log(q.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
|
|
188
|
-
`)),
|
|
191
|
+
`)),lo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?q.red("NO"):"yes"})),!1),console.log(`
|
|
189
192
|
mean stdev ${i.meanStdev.toFixed(4)}`),console.log(q.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(q.red(`
|
|
190
193
|
Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(q.dim(` not merely by how much. Usually a compound question: one name, several questions.
|
|
191
194
|
Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(q.green(`
|
|
192
|
-
Every question held its decision across all samples.`)),console.log(q.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});qe.command("backends").description("registered decision backends and what they claim").action(()=>{
|
|
195
|
+
Every question held its decision across all samples.`)),console.log(q.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});qe.command("backends").description("registered decision backends and what they claim").action(()=>{at();let e=mr().map(o=>{let t=Ds(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});lo(e,!1),console.log(q.dim(`
|
|
193
196
|
source where the numbers come from. "verbalized" means the model wrote them
|
|
194
197
|
into its answer; "logits" means they were read off its next-token
|
|
195
198
|
distribution. Logits are the model's actual posterior \u2014 verbalized
|
|
@@ -197,22 +200,22 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
197
200
|
calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
|
|
198
201
|
traffic. Reading real logits does not buy this: a posterior can be
|
|
199
202
|
confidently wrong. It comes from a recalibrator fitted on your own
|
|
200
|
-
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});qe.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{
|
|
203
|
+
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});qe.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{at();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=rt(s,"Which option fits this state?")}e.noul&&(o.verdict=po(String(e.noul))),Object.keys(o).length===0&&(console.log(q.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Ds(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Sm}from"commander";import O from"chalk";import{resolve as Yc}from"path";import{existsSync as Em}from"fs";import Am from"better-sqlite3";var Wc=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],$m=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Jc(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...$m,...Wc,"num_turns","injected_context"].map(d=>t.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];o.since!==void 0&&(i.push("started_at >= ?"),r.push(o.since)),o.agentId&&(i.push("agent_id = ?"),r.push(o.agentId));let a=i.join(" AND "),c=e.prepare(`
|
|
201
204
|
SELECT ${s} FROM task_traces WHERE ${a} ORDER BY started_at
|
|
202
205
|
`).all(...r),l=new Map,g=e.prepare(`
|
|
203
206
|
SELECT task_id, action FROM task_trace_steps
|
|
204
207
|
WHERE name = 'tool_use' AND action IS NOT NULL
|
|
205
208
|
AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
|
|
206
209
|
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,
|
|
208
|
-
`).slice(0,8);console.log(r.map(a=>` ${
|
|
210
|
+
`).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=oa({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=Wc.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:Mr(d.injected_context)}})}function fi(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function hi(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 Bc(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:hi(e.map(o=>o.tokens)),medianTurns:hi(e.map(o=>o.turns)),medianDurationMs:hi(e.map(o=>o.durationMs))}}function Gc(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 fi(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(fi));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=>fi(u).includes(g));p.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Bc(p),after:Bc(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Co from"chalk";function km(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function vm(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function xm(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function yi(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 Hc(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 ${km(o.medianTokens)}${t?yi(t.medianTokens,o.medianTokens):""}`,`turns ${xm(o.medianTurns)}${t?yi(t.medianTurns,o.medianTurns):""}`,`time ${vm(o.medianDurationMs)}${t?yi(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function zc(e,o){if(e.length===0)return[Co.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Co.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(`${Co.bold(s.agentId)} ${Co.cyan(s.cluster)}`),n=i),t.push(` ${Co.yellow(s.lesson)} ${Co.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Co.dim(Hc("before",s.before))),t.push(Hc("after",s.after,s.before))}return t.push(""),t.push(Co.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Et=new Sm().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function es(e){let o=Yc(e.cwd??process.cwd()),t=Yc(o,e.path??".agentx/db.sqlite");Em(t)||(console.log(O.red(` No db at ${t}`)),console.log(O.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Am(t,{readonly:!0})}catch(n){console.log(O.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(O.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Tm(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 Vc(e){if(!e)return;let o=Tm(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(O.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Om(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 wi(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}Et.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=es(e),t=Lr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Vc(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(O.dim(" (no traces)"));return}for(let n of t){let s=wi(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?O.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?O.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${O.dim(n.taskId)} ${s} ${O.bold(n.agentId)}${O.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${O.dim("\xB7")} ${i}${a} ${O.dim(Om(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});Et.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=es(o),n=Fs(t,e);if(n||(console.log(O.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Im(n.task,n.steps)});function Im(e,o){let t=wi(e.status)(e.status);if(console.log(O.bold(`Trace ${e.taskId}`)),console.log(` ${O.dim("agent")} ${e.agentId}`),console.log(` ${O.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${O.dim("workflow")} ${O.cyan(e.workflowRunId)}${n?O.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${O.dim("intent")} ${e.intentEventId} ${O.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${O.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${O.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${O.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${O.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${O.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${O.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(` ${O.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(` ${O.dim("lessons")} ${r.length?r.join(" "):O.dim("none")}`)}if(e.error&&console.log(` ${O.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${O.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(O.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(O.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?wi(n.status)(n.status):O.dim("\u2014"),i=n.action?O.cyan(n.action):"";if(console.log(` ${O.dim(`#${n.seq}`)} ${O.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?O.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
211
|
+
`).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
|
|
209
212
|
`)),n.inputSummary.split(`
|
|
210
|
-
`).length>8&&console.log(` ${
|
|
211
|
-
`).slice(0,8);console.log(r.map(a=>` ${
|
|
213
|
+
`).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
214
|
+
`).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2190")} ${a}`).join(`
|
|
212
215
|
`)),n.outputSummary.split(`
|
|
213
|
-
`).length>8&&console.log(` ${
|
|
214
|
-
error: ${d.error}`)),console.log(),console.log(
|
|
215
|
-
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${
|
|
216
|
+
`).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}Et.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=es(e),t=Math.max(1,parseInt(e.min,10)||2),n=Jc(o,{since:Vc(e.since),agentId:e.agent}),s=Gc(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of zc(s,{minSamples:t}))console.log(i)});Et.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=es(o),n=Fs(t,e);n||(console.log(O.red(` task not found: ${e}`)),console.log(O.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(O.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(O.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(O.bold(` replay ${O.cyan(e)}`)),console.log(O.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(O.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(O.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(O.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(O.bold(" INPUT (replayed verbatim)")),console.log(),Zn(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Zn(s.finalResponse):console.log(O.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(O.bold(` CURRENT OUTPUT ${O.dim(`status=${d.error?"error":"ok"} ${p}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Zn(d.content??"(empty reply)"),d.error&&console.log(O.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?O.dim(" outputs are identical"):O.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(O.green(` \u2713 replayed in ${p}ms`)),console.log(),Zn(d.content??"(empty reply)"),d.error&&console.log(O.red(`
|
|
217
|
+
error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Zn(e){let o=e.split(`
|
|
218
|
+
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${O.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${O.dim("\u2502")} ${O.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Rm}from"commander";import me from"chalk";import{existsSync as _m,mkdirSync as Dm,writeFileSync as Pm}from"fs";import{resolve as Qc,join as Xc,dirname as Mm}from"path";var jm=`# AgentX destructive-action guardrails \u2014 global policy
|
|
216
219
|
#
|
|
217
220
|
# This file + environments/*.yaml + agents/<id>.yaml are deep-merged
|
|
218
221
|
# (most specific wins). The built-in catalog (prisma / rm -rf / docker /
|
|
@@ -238,7 +241,7 @@ defaults:
|
|
|
238
241
|
# action: escalate
|
|
239
242
|
# severity: high
|
|
240
243
|
rules: []
|
|
241
|
-
`,
|
|
244
|
+
`,Cm=`# Production protected resources.
|
|
242
245
|
#
|
|
243
246
|
# The catalog rules reference \`target_in: production\`, so DECLARING this set is
|
|
244
247
|
# what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
|
|
@@ -260,7 +263,7 @@ protected_resources:
|
|
|
260
263
|
|
|
261
264
|
# Production-only rules beyond the catalog:
|
|
262
265
|
rules: []
|
|
263
|
-
`,
|
|
266
|
+
`,Nm=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
|
|
264
267
|
# this agent (the filename names it). coder agents never touch production.
|
|
265
268
|
rules:
|
|
266
269
|
- id: coder-no-prod
|
|
@@ -269,7 +272,7 @@ rules:
|
|
|
269
272
|
action: deny
|
|
270
273
|
severity: critical
|
|
271
274
|
message: "coder-agent is not permitted to run commands against production."
|
|
272
|
-
`,
|
|
275
|
+
`,Kc=[{relPath:"policy.yaml",content:jm},{relPath:"environments/production.yaml",content:Cm},{relPath:"agents/coder-agent.yaml",content:Nm}];var No=new Rm().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function bi(e){return e==="deny"?me.red:e==="escalate"||e==="ask"?me.yellow:e==="warn"?me.magenta:me.green}function os(e){return e.root?Qc(e.root):Pa()}No.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Da({root:os(e),agentId:e.agent,env:e.env}),process.exit(0)});No.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=os(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=_a({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Lm(s,i,r)});function Lm(e,o,t){let n=bi(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":me.dim(" (no rule matched)")}`),console.log(` enforced as ${bi(e.effectiveAction)(e.effectiveAction)} ${me.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${me.cyan(e.ruleId)}${e.severity?me.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${me.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${me.dim(`evaluated in ${t}ms`)}`),console.log()}No.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Tr({root:os(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(me.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=bi(t.verdict),i=t.effective_action!==t.verdict?me.dim(`->${t.effective_action}`):"";console.log(` ${me.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${me.cyan((t.agent_id??"?").padEnd(16))} ${me.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(me.dim(` target: ${t.resolved_target}`))}});No.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Xc(Qc(e.root),Na),t=0;for(let n of Kc){let s=Xc(o,n.relPath);if(_m(s)&&!e.force){console.log(me.dim(` skip (exists) ${n.relPath}`));continue}Dm(Mm(s),{recursive:!0}),Pm(s,n.content),console.log(me.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${me.cyan(o)}`),console.log(me.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(me.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});No.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(me.green(` daemon reloaded (${e.url})`)):console.log(me.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(me.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});No.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Ra(os(e),e.agent);console.log(JSON.stringify(o,null,2))});Jt();import{Command as Fm}from"commander";import{execFile as Um}from"child_process";import{promisify as qm}from"util";import{existsSync as Wm}from"fs";import Ze from"chalk";Bt();var rn="ui-element";function ts(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:sn(t.tried,80),screenChanged:t.changed,note:t.note?sn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Zc(t.role),label:sn(t.label,120),value:t.value?sn(t.value,80):null,enabled:t.enabled}))}}function ns(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Zc(t.role)}: ${sn(n,80)}`}return{target:rt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:po("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function ss(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function Zc(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function sn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var el=qm(Um),ol=new Fm().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{Wm(Ce)||(console.log(Ze.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Pn({max:Number(o.max)||40})}catch(d){console.log(Ze.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ze.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=Kt(t,n[0].id);d&&(console.log(Ze.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ze.bold(n[0].label)),await el(Ce,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await so(rn,ts({request:e,app:t.app,window:t.window,candidates:n}),ns(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ze.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${rn}.mode`)),process.exit(1));let i=ss(s.answers,n),r=Kt(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Ze.yellow(` nothing on screen matches "${e}"`)+Ze.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(p=>p.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${Ze.green("\u2192")} ${Ze.bold(g)} `+Ze.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await el(Ce,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as dp}from"commander";import We from"chalk";import{readFileSync as tl}from"fs";import{homedir as Bm}from"os";import{join as Jm}from"path";var nl=12e5,Gm="https://openrouter.ai/api/v1/chat/completions",Hm=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function zm(e={kind:"window"},o=nl,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return ht(e,{},n);try{return await ht(e,{untilStable:!0},n)}catch(s){if(s instanceof Qa)return ht(e,{},n);throw s}}var Ym=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
273
276
|
|
|
274
277
|
Report only what is visible in this image.
|
|
275
278
|
|
|
@@ -277,13 +280,13 @@ The failure that matters: an application that performs an action is on screen, a
|
|
|
277
280
|
|
|
278
281
|
State indicators are usually small and specific: a coloured dot, a pill or badge in the menu bar, an elapsed timer, a filled or highlighted toggle, a progress bar, a changed icon. If the question turns on such an indicator, say whether you can see it and what it looks like.
|
|
279
282
|
|
|
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
|
|
283
|
+
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 Vm(e,o,t,n){let s=Xm();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=tl(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
|
|
281
284
|
|
|
282
|
-
The image is the region ${
|
|
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
|
-
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(" "):
|
|
285
|
-
`);return}try{let{summary:s,backupPath:i}=
|
|
286
|
-
\u2713 ${s}`)),i&&console.log(
|
|
285
|
+
The image is the region ${Km(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Ym,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(Gm,{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 is(e,o={}){let t=Date.now(),n=await zm(o.region??{kind:"window"},o.maxPixels??nl,{settle:o.settle,screen:o.screen}),s=await Vm(e,n,o.model??Hm,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 Km(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 an;function Xm(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(an!==void 0)return an??void 0;try{let e=tl(Jm(Bm(),".agentx","openrouter-key.txt"),"utf-8").trim();an=e.length>0?e:null}catch{an=null}return an??void 0}import{execFile as Qm}from"child_process";import{promisify as Zm}from"util";var ep=Zm(Qm),op=["screencapture"],tp=["Screen Studio","OBS","QuickTime Player","Zoom"];async function il(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await np()),t}async function np(){let e=await sl(op);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 sl(tp);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 sl(e){let o=[];for(let t of e)try{let{stdout:n}=await ep("pgrep",["-x",t]),s=n.trim().split(`
|
|
286
|
+
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Jt();Bt();var rl="screen-state",al={observable:po("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:po("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 cl(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 ll(e){return{observable:e.observable.noul,holds:e.holds.noul}}var sp=.6,ip=.7,rp=.3;async function cn(e,o={}){let[t,n]=await Promise.all([is(e,o),il(e).catch(()=>[])]),s=o.observableFloor??sp,i=await so(rl,cl({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:lp(t),treeNote:o.treeNote,probes:n}),al,{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:cp(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=ll(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 (${rs(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=ip?"confirmed":a<=rp?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:ap(c,a,t),sighting:t,probes:n}}function ap(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${rs(o)}). ${n}`:e==="refuted"?`Not true (${rs(1-o)} it is false). ${n}`:`Inconclusive (${rs(o)}, between the thresholds). ${n}`}function cp(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 lp(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 rs=e=>`${Math.round(e*100)}%`;var dl=new dp().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 cn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?io():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 is(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?io():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: ${gp(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 gp(e){return e==="yes"?We.green(e):e==="no"?We.red(e):We.yellow(e)}import{Command as mp}from"commander";import eo from"chalk";import{spawn as pp}from"child_process";function Ro(e){console.log(eo.red(` ${e}`)),process.exit(1)}function gl(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?eo.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(eo.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function up(e){return new Promise(o=>{let t=pp(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var ln=new mp("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");ln.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=io(o.config),n;try{n=Fn(o.region,t)}catch(r){Ro(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Ro("--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 Un(()=>up(e),n,{out:o.out,untilStable:r},i);c||(console.log(eo.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),gl(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}gl(await ht(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Ro(r?.message??String(r))}});ln.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:${Go()}`).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||Ro(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(eo.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${eo.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Ro(`could not reach the daemon: ${n?.message??n}`)}});ln.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&&Ro(`--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)||Ro("--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=io(e.config);console.log(`
|
|
287
|
+
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(" "):eo.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":eo.dim("off")} ${eo.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
|
|
288
|
+
`);return}try{let{summary:s,backupPath:i}=uo(r=>{let a=Xa(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(eo.green(`
|
|
289
|
+
\u2713 ${s}`)),i&&console.log(eo.dim(` Backup: ${i}`)),console.log()}catch(s){Ro(s?.message??String(s))}});Jt();import{Command as yp}from"commander";import{execFile as bl}from"child_process";import{promisify as wp}from"util";import{existsSync as bp,readFileSync as $p,writeFileSync as $l,mkdirSync as kp}from"fs";import{homedir as vp}from"os";import{join as xp,dirname as Sp}from"path";import Re from"chalk";Bt();var $i="paste-transform";function ml(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function pl(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:po("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:rt(o,"What shape should this paste arrive in?")}}function ul(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var fp=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),hp=e=>/^https?:\/\/\S+$/i.test(e.trim()),ki=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
|
|
287
290
|
`);if(o.length<3)return null;let t=0;for(let n=0;n<o.length-1;n++){let s=o[n].trim(),i=o[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&t++}return t<2?null:e.split(/\n\s*\n/).map(n=>n.split(`
|
|
288
291
|
`).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
|
|
289
292
|
|
|
@@ -291,26 +294,26 @@ The image is the region ${qm(o)}.`},{type:"image_url",image_url:{url:`data:image
|
|
|
291
294
|
`).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
|
|
292
295
|
`)}},{id:"quote",criterion:"Prefix every line with a markdown blockquote marker. For quoting someone else's words into a document, an issue or a message.",label:"blockquote",apply:e=>{let o=e.split(`
|
|
293
296
|
`);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
|
|
294
|
-
`)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!
|
|
297
|
+
`)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!hp(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])fp.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
|
|
295
298
|
`)||o.length>90||o.length<3)return null;let t=o.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t!==o?t:null}},{id:"collapseSpace",criterion:"Collapse runs of whitespace and trim the ends, leaving one clean line. For text copied out of a web page that arrived padded with stray spaces, tabs and newlines.",label:"tidy whitespace",apply:e=>{let o=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
|
|
296
|
-
`).trim();return o===e?null:o}}];function
|
|
299
|
+
`).trim();return o===e?null:o}}];function fl(e){let o=[];for(let t of ki){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function hl(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
|
|
297
300
|
\u2026[${e.length-o} more characters]\u2026
|
|
298
|
-
${e.slice(-n)}`}function
|
|
299
|
-
`)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var
|
|
300
|
-
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),
|
|
301
|
-
(dry run \u2014 pass --apply to write it back)`))}var
|
|
301
|
+
${e.slice(-n)}`}function yl(e){let o=e.trim();return o.includes(`
|
|
302
|
+
`)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var vi=wp(bl),kl=new yp().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${ki.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=Ap();c===null&&(console.log(Re.yellow(" nothing to undo")),process.exit(2)),await xl(c),console.log(` ${Re.green("\u2192")} clipboard restored`);return}let o=await Tp();if(o||(console.log(Re.yellow(" clipboard is empty")),process.exit(2)),yl(o)){vl(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=fl(o),n=await Op();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Re.red(` "${e.as}" does not apply to this clipboard`)),console.log(Re.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await At(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await At(e,"asIs",o,o,"nothing else applies",0);return}let s=await so($i,ml({preview:hl(o),length:o.length,lineCount:o.split(`
|
|
303
|
+
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),pl(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await At(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${$i}.mode`,0);return}let i=ul(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await At(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await At(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await At(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function At(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(Ep(n),await xl(t)),vl(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await vi(Ce,["key","--name","v","--mod","command"]).catch(a=>{console.log(Re.red(` could not paste: ${a?.message??a}`))})}function vl(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Re.dim("\u2192")} ${Re.bold("unchanged")} ${Re.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Re.green("\u2192")} ${Re.bold(o.applied)} ${Re.dim(`\xB7 ${o.reason}`)}`),console.log(Re.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Re.dim(wl(o.original))),console.log(Re.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(wl(o.result)),!e.apply&&!e.paste&&console.log(Re.dim(`
|
|
304
|
+
(dry run \u2014 pass --apply to write it back)`))}var wl=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
|
|
302
305
|
`).map(t=>` ${t}`).join(`
|
|
303
|
-
`),
|
|
304
|
-
${n}`:n,a=await fetch(`${
|
|
305
|
-
`)}
|
|
306
|
-
${c.name} teaches: ${e}`)+
|
|
307
|
-
`));let g=
|
|
308
|
-
`)}function
|
|
309
|
-
`);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var
|
|
306
|
+
`),as=xp(vp(),".agentx","paste-undo.txt");function Ep(e){try{kp(Sp(as),{recursive:!0}),$l(as,e,{mode:384})}catch{}}function Ap(){try{let e=$p(as,"utf-8");return $l(as,"",{mode:384}),e.length?e:null}catch{return null}}async function Tp(){let{stdout:e}=await vi("pbpaste",[],{maxBuffer:16777216});return e}async function xl(e){await new Promise((o,t)=>{bl("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Op(){if(!bp(Ce))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await vi(Ce,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Ip(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Ip(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as jp}from"commander";import Fe from"chalk";re();function Sl(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await Un(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var Cp=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Np(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
|
|
307
|
+
${n}`:n,a=await fetch(`${Cp}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function Rp(e){let o;try{o=R(e.config).notifications.local}catch{o=void 0}let t=Rn(o);return e.sound||(t.sound=!1),e.banner||(t.banner=!1),{alert:fa(t),banner:t.banner}}var El=new jp().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new aa,n=ia(),{alert:s,banner:i}=Rp(o),r=s,a;if(o.proof&&!i)a=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let l=io(o.config),g=Sl(s,Fn("notifications",l),{settings:l});r=g.alert,a=g.proof}if(o.status){let l=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:l},null,2));return}console.log(` ${n.active?Fe.yellow("\u25D0"):Fe.green("\u25CB")} ${ra(n)} ${Fe.dim(`\xB7 ${n.reason}`)}`),console.log(` ${l.length} held`);for(let g of l.slice(0,8)){let d=new Date(g.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Fe.dim(` ${d} ${g.from}: ${g.message.slice(0,70)}`))}return}let c=Np(o.channel,o.chatId);if(o.flush){let l=await wa(c,{queue:t,alert:s});console.log(l?Fe.green(` delivered ${l} held notification(s)`):Fe.dim(" nothing was held"));return}e?.trim()||(console.log(Fe.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let l=await ya({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},c,{queue:t,alert:r,focus:n}),g=a?.();if(o.json){console.log(JSON.stringify(g?{...l,proof:g}:l,null,2));return}let d=l.delivered?Fe.green("\u2192"):Fe.yellow("\u23F8");console.log(` ${d} ${l.reason}`),l.held&&console.log(Fe.dim(" it will arrive with the others when Focus ends")),g?.shot&&console.log(` ${g.error?Fe.yellow("?"):Fe.green("\u2713")} banner: ${g.shot.path}${Fe.dim(` \xB7 ${g.shot.waitedMs}ms`)}`),g?.error&&console.log(Fe.yellow(` ${g.error}`))}catch(l){console.log(Fe.red(` ${l?.message??l}`)),await s(o.title,e.trim()),process.exit(1)}});Jt();kr();pr();Bt();import{Command as _p}from"commander";import{readFileSync as Dp}from"fs";var Al=new _p().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Dp(e.file,"utf8"):await Pp()}catch(r){Qo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Qo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Qo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Qo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Qo("spec needs at least one entry in `questions`");try{fr(t.questions)}catch(r){return Qo(r?.message??String(r))}let n=t.seat||e.seat;at(),process.env[xr(n)]="active";let s=null;if(e.record!==!1)try{s=new En({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
|
|
308
|
+
`)}vr({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await so(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Qo(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function Qo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Pp(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}Jt();import{Command as pu}from"commander";import{execFile as uu,spawn as ql}from"child_process";import{promisify as fu}from"util";import{existsSync as hu,statSync as yu}from"fs";import{join as Wl}from"path";import{tmpdir as wu}from"os";import X from"chalk";var Mp={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},Lp={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},Fp={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},xi=[Mp,Lp,Fp];re();re();import oo from"chalk";import{execFile as Up}from"child_process";import{promisify as qp}from"util";import{createInterface as Wp}from"readline";var Tl=qp(Up);function Bp(e){e.type==="step"?console.log(`${oo.cyan(` ${e.n}. ${e.action}`)}${e.target?oo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(oo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?oo.red(` failed: ${e.error}`):oo.dim(" done it")):e.type==="replanned"?console.log(oo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(oo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(oo.red(` error: ${e.error}`)):e.type==="end"&&console.log(oo.dim(` \xB7 ended (${e.reason})`))}async function Jp(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Tl("open",["-a",e]).catch(()=>{});try{let s=(await zs()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Ol(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=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Tl("open",["-a",o.app]),i=await Jp(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Dn(n,t.agents,!1),a=t.voice.listener??Ba,c=Mn(n,t.agents[n]),l=new Ha({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:zs,presence:new Ln(c,Ce,n),speech:new ut,model:ft({system:Ga(r.persona,a)}),act:za});l.on(Bp),console.log(oo.bold(`
|
|
309
|
+
${c.name} teaches: ${e}`)+oo.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
|
|
310
|
+
`));let g=Wp({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}re();import to from"chalk";import{execFile as su}from"child_process";import{existsSync as Ai,writeFileSync as iu}from"fs";import{homedir as ru}from"os";import{join as Fl,resolve as au}from"path";import{promisify as cu}from"util";var Ue={w:1e3,h:640},Si=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Cl=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Il=["none","semi","solid","fill","pattern"],Ei=180,Nl=48,Gp=["s","m","l","xl"],Hp=["draw","sans","serif","mono"];function Rl(){return[`You are an illustrator drawing on a tldraw canvas ${Ue.w} wide and ${Ue.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${Ei}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${Nl} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${Cl.join(", ")}.`,`color is one of: ${Si.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
|
|
311
|
+
`)}function Tt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Zo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var et=(e,o,t)=>Math.min(t,Math.max(o,e)),jl=e=>et(Zo(e)??1,.1,1),zp=/^#[0-9a-f]{6}$/i;function Yp(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Si.includes(t)&&typeof n=="string"&&zp.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Vp(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,Nl)){if(!Array.isArray(t))return null;let n=Zo(t[0]),s=Zo(t[1]);if(n===null||s===null)return null;o.push([et(n,0,Ue.w),et(s,0,Ue.h)])}return o.length>=2?o:null}function _l(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=Yp(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Tt(n.color,Si,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Vp(n.path),g=Tt(n.fill,Il,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:jl(n.opacity)}}let a=Zo(n.x),c=Zo(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:et(a,0,Ue.w-20),y:et(c,0,Ue.h-20),size:Tt(n.size,Gp,"l"),color:r,font:Tt(n.font,Hp,"draw")};if(typeof n.geo=="string"){let l=Zo(n.w),g=Zo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=et(a,0,Ue.w-4),p=et(c,0,Ue.h-4);return{kind:"geo",id:s,say:i,geo:Tt(n.geo,Cl,"rectangle"),x:d,y:p,w:Math.min(l,Ue.w-d),h:Math.min(g,Ue.h-p),color:r,fill:Tt(n.fill,Il,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:jl(n.opacity)}}return null}var cs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
|
|
312
|
+
`);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Kp=500,Xp=e=>`
|
|
310
313
|
editor.zoomToBounds({ x: 0, y: 0, w: ${Ue.w}, h: ${Ue.h} }, { inset: ${e}, immediate: true })
|
|
311
314
|
const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Ue.w}, y: 0 })
|
|
312
315
|
const chrome = window.outerHeight - window.innerHeight
|
|
313
|
-
return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Ue.w} }`;function
|
|
316
|
+
return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Ue.w} }`;function Dl(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function Pl(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function Qp(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Ml(e){return`const hex = ${JSON.stringify(e.colors)}
|
|
314
317
|
const tint = (h, t) => '#' + [1, 3, 5].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) * (1 - t) + 255 * t).toString(16).padStart(2, '0')).join('')
|
|
315
318
|
const th = editor.getTheme('default')
|
|
316
319
|
const colors = structuredClone(th.colors)
|
|
@@ -318,9 +321,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
|
|
|
318
321
|
if (colors[mode][name]) Object.assign(colors[mode][name], { solid: v, fill: v, pattern: v, linedFill: tint(v, 0.25), semi: tint(v, 0.75), noteFill: v })
|
|
319
322
|
}
|
|
320
323
|
editor.updateTheme({ ...th, colors })
|
|
321
|
-
return true`}function
|
|
324
|
+
return true`}function Zp(e,o){if(e.kind==="palette")return Ml(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
|
|
322
325
|
const el = ${JSON.stringify(e)}
|
|
323
|
-
const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(
|
|
326
|
+
const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Kp/10)}))
|
|
324
327
|
const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
|
|
325
328
|
const id = createShapeId(${t(e.id)})
|
|
326
329
|
editor.createShape({ id, type: 'geo', x: el.x, y: el.y, opacity: el.opacity, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill, dash: 'solid', size: 's' } })
|
|
@@ -360,55 +363,55 @@ return id`:`${n}
|
|
|
360
363
|
const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
|
|
361
364
|
const aid = typeof arrow === 'string' ? arrow : arrow?.id
|
|
362
365
|
if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
|
|
363
|
-
return aid ?? null`}function
|
|
364
|
-
${r.name} draws: ${e}`)+
|
|
365
|
-
`));let p=new AbortController;process.once("SIGINT",()=>p.abort());let
|
|
366
|
-
${
|
|
366
|
+
return aid ?? null`}function eu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[ho(s[0][0],s[0][1]),ho(i[0],i[1])]}if(e.kind==="geo")return[ho(e.x,e.y),ho(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Pl(e);return[ho(s.x,s.y+s.h/2),ho(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[ho(t.x+t.w/2,t.y+t.h/2),ho(n.x+n.w/2,n.y+n.h/2)]}var ho=(e,o)=>({x:e,y:o,w:0,h:0});async function Ll(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,Xp(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>=Ei)return;let $=_l(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 cs;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,Ml(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]=eu(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(Dl(l,C.x,C.y)),await s(250),o.presence.moveTo(Dl(l,j.x,j.y));try{await o.api.exec(t.docId,Zp(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"?Pl(x):x.kind==="path"?Qp(x.pts):ho(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let I=(x.say?r:0)-(i()-$);I>0&&await s(I)}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 ou}from"fs";import{homedir as tu}from"os";import{join as nu}from"path";var dn=nu(tu(),"Library","Application Support","tldraw","server.json"),ls=class{constructor(o=dn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=ou(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 lu=cu(su),du="claude-sonnet-5";function gu(e){e.type==="planned"?console.log(to.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${to.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${to.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(to.yellow(` skipped: ${e.line}`)):console.log(to.red(` error: ${e.error}`))}async function mu(){if(!Ai(dn)){await lu("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Ai(dn);e++)await new Promise(o=>setTimeout(o,500));if(!Ai(dn))throw new Error("tldraw offline did not start")}}async function Ul(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||du,i=au(o.out||Fl(ru(),"Documents")),r=Mn(n,t.agents[n]),a=ft({system:Rl(),model:s}),c=new Ln(r,Ce,n),l=new ls;try{await mu();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(to.bold(`
|
|
367
|
+
${r.name} draws: ${e}`)+to.dim(` (${s}, ${d.filePath})
|
|
368
|
+
`));let p=new AbortController;process.once("SIGINT",()=>p.abort());let f=await Ll(e,{api:l,presence:c,model:a},{docId:d.id,signal:p.signal},gu);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"):Fl(i,`agentx-draw-${g}.png`);iu(w,Buffer.from(u.slice(u.indexOf(",")+1),"base64")),console.log(to.bold(`
|
|
369
|
+
${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+to.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(to.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(to.dim(` ${d.filePath}
|
|
367
370
|
${w}
|
|
368
|
-
`))}finally{a.close(),c.close()}}var
|
|
371
|
+
`))}finally{a.close(),c.close()}}var Oi=fu(uu),Bl=new pu().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, "${xo}" 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 Ul(String(o.live),o):await Ol(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
372
|
lessons
|
|
370
|
-
`));for(let g of
|
|
371
|
-
`);return}let t
|
|
373
|
+
`));for(let g of xi)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
|
|
374
|
+
`);return}let t=xi.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),hu(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:ku(o.voice,o.agent);console.log(X.bold(`
|
|
372
375
|
${t.title}`)),console.log(X.dim(` ${t.appHint}
|
|
373
|
-
`));try{t.start&&(await
|
|
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
|
|
375
|
-
stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${w.reason}`)),console.log(X.dim(` screenshot: ${w.sighting.shot.path}`)),await
|
|
376
|
+
`));try{t.start&&(await Oi("/usr/bin/open",bu(t.start)),await _o(2e3),await ds(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=Wl(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=ql("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await _o(2e3));let r=o.hud===!1?null:ql(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})+`
|
|
377
|
+
`)}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 ds(d.before)}let p=o.speak===!1?Promise.resolve():xu(d.say,n),f=d.find?await $u(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 Oi(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 Ti(["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 _o(d.afterClickWaitMs??1500)}if(d.type){await ds(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:u}=await Ti(["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 ds(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:u}=await Ti(["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 _o((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await _o(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 cn(d.verify,u?{settle:!0,screen:io()}:{})}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(`
|
|
378
|
+
stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${w.reason}`)),console.log(X.dim(` screenshot: ${w.sighting.shot.path}`)),await _o(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 _o(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await _o(2500);try{let{size:g}=yu(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
379
|
`)),process.exitCode=3;return}console.log(X.green(`
|
|
377
380
|
done.
|
|
378
|
-
`))});function
|
|
379
|
-
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:
|
|
381
|
+
`))});function bu(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Wl(wu(),"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 ds(e){let o=await cn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Ti(e){try{let{stdout:o}=await Oi(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 $u(e,o=[]){try{let t=await Pn({max:45});if(t.candidates.length<2)return null;let n=await so(rn,ts({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),ns(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=ss(n.answers,t.candidates);return s.present<.5?null:Kt(t,s.id)}catch{return null}}function ku(e,o){if(e?.trim().toLowerCase()===xo)return{provider:"system",elevenlabs:Vt(),system:null,fallback:!0};let t=e?_n(e,Yt()):null;if(t)return{provider:"system",elevenlabs:Vt(),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]?Ua(La(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Vt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
|
|
382
|
+
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Vt(),system:null,fallback:!0}}}var vu=new ut;async function xu(e,o){o&&await vu.say({voice:o,text:e})}var _o=e=>new Promise(o=>setTimeout(o,e));re();import{Command as Jl}from"commander";import Be from"chalk";import{createInterface as Gl}from"readline";var Su=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Ot(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Su()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Eu(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 Hl(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 Au(e,o,t){let n=R(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Ot("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Wa(()=>n,()=>d),i.usePool(await qa(Ma()))}let r=e.map(d=>s[d]?Dn(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 Ja({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ut,listener:n.voice.listener,model:(d,p)=>ft({system:p})});l.on(Eu),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=Gl({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(` ${Hl(l.gaps)}`))}async function Tu(e,o,t){let n=await Ot("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=Gl({input:process.stdin});s.on("line",a=>{a.trim()&&Ot("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Ot("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Ot("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(` ${Hl(r)}`))}var zl=new Jl().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?Au:Tu)([e,o],s,n),process.exit(0)}catch(i){console.error(Be.red(` ${i?.message??i}`)),process.exit(1)}}),Yl=new Jl().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 Ot("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))});re();import{Command as Ou}from"commander";import Oe from"chalk";import{existsSync as Iu,readFileSync as ju,writeFileSync as Cu}from"fs";import{resolve as Vl}from"path";var gs=new Ou().name("voice").description("list installed system voices and pick each agent's voice");function Nu(e){let o=e?[e]:[Vl(process.cwd(),"agentx.json"),Vl(process.cwd(),".agentx/config.json")],t=o.find(n=>Iu(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Ru(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()===xo,y=w?null:_n(t,s,a??e?.voice?.locale),k=y?`system voice ${Gs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?xo: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?xo: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}}gs.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=Yt(),t;try{t=R(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Fa(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(Hs(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(Oe.yellow(`
|
|
380
383
|
No system voices found (system voices need macOS).
|
|
381
|
-
`));else{let r=e.all?
|
|
384
|
+
`));else{let r=e.all?Js(o,""):Js(o,n);console.log(Oe.bold(`
|
|
382
385
|
System voices${e.all?"":` (${n})`}, best first
|
|
383
|
-
`));for(let a of r){let c=a.siri?
|
|
384
|
-
More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(
|
|
386
|
+
`));for(let a of r){let c=a.siri?Oe.magenta("siri"):a.quality==="standard"?Oe.dim("standard"):Oe.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)} ${Oe.dim((a.gender??"").padEnd(7))} ${l?Oe.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Oe.dim(`
|
|
387
|
+
More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Oe.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Oe.bold(`
|
|
385
388
|
Agents
|
|
386
|
-
`));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=p=>p?
|
|
387
|
-
`),console.log(
|
|
388
|
-
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${
|
|
389
|
+
`));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=p=>p?Gs(p):Oe.dim("system default"),g=Object.entries(Hs(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,f])=>`${Oe.dim(`${p}:`)} ${l(f)}`).join(Oe.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Oe.dim("(default voice)")}`:`system ${l(i.get(r))}${g?Oe.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?Oe.dim(` (${a.voice.gender})`):""}`)}}console.log()});gs.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${xo}" 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=Nu(t.config),{raw:s,summary:i}=Ru(JSON.parse(ju(n,"utf8")),e,o,t,Yt());Cu(n,JSON.stringify(s,null,2)+`
|
|
390
|
+
`),console.log(Oe.green(` ${e}: ${i}`)),console.log(Oe.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Oe.red(` ${n.message}`)),process.exit(1)}});import{Command as _u}from"commander";import L from"chalk";var ot=new _u().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ii=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;function ji(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Ci(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 Ni(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 Kl(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function Du(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)} ${Kl(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}ot.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ms.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ii).action(async(e,o)=>{let t=ji(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)),jr(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${Ms.join(", ")}`)),process.exit(1)),Vn()||(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 Ci(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)} (${Kl(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: ${Ni(n)}`)),process.exit(1)}});ot.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",Ii).action(async e=>{let o=ji(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Ci(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: ${Ni(t)}`)),process.exit(1)}});ot.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ii).option("--json","raw JSON output").action(async e=>{let o=ji();try{let n=(await Ci(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Vn(),sessions:n},null,2));return}console.log(),console.log(Vn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(Qt())}`:`${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)Du(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
|
|
391
|
+
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${Ni(t)}`)),process.exit(1)}});ot.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||Go()),t=vc(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
392
|
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(`
|
|
393
|
+
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)}});ot.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=xc({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)}});re();import{Command as Pu}from"commander";import ye from"chalk";var ms=new Pu().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ql(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 Zl(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Xl(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 Mu(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}ms.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}=Ql(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Zl(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=Mu(r.state)(r.state.padEnd(9)),c=Xl(r.spawnedAt),l=r.lastTurnAt?Xl(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}`)}});ms.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}=Ql(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Zl(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 Lu}from"commander";import _e from"chalk";import{existsSync as Ri,rmSync as Fu}from"fs";import{resolve as _i}from"path";var It=new Lu().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 _r(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=_i(e.cwd,".agentx","rag");if(!Ri(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=>Ri(_i(o,s,"index.json")));if(n.length===0){console.log(_e.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ls(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=Dr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ls(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=_i(process.cwd(),".agentx","rag",e);if(!Ri(o)){console.log(_e.dim(` no index for ${e} \u2014 nothing to clear`));return}Fu(o,{recursive:!0,force:!0}),console.log(_e.green(` \u2713 cleared index for ${e}`))});re();import{Command as Uu}from"commander";import K from"chalk";import jt from"prompts";var tt=new Uu().name("backlog").description("manage the local backlog used by business workSource=backlog");function gn(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 Ya(n)}}function qu(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function Wu(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}tt.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}=gn(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(` ${Wu(n.status).padEnd(7)} ${qu(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()}`))});tt.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=gn(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=Va([o],i.source,n.config),a=await Vs(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}`))}});tt.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=gn(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 Vs(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}`))}});tt.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}=gn(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});tt.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=gn(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 jt({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"?Ju(o.config):Gu(o.config);y.length?(i=(await jt({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 jt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await jt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await jt({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 Hu(o.config,i,a):await zu(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=Ys({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 jt({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"?Bu(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ys(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 Bu(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ju(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 Gu(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 Hu(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 zu(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(ed)}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(ed):[]}function ed(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 Yu}from"commander";import W from"chalk";import{existsSync as Vu,readFileSync as Ku}from"fs";import{resolve as Xu}from"path";import Qu from"prompts";re();function od(e){let o=e||Xu(process.cwd(),"agentx.json");return Vu(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Ku(o,"utf-8"))}async function Zu(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 Qu([{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 yo=new Yu().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');yo.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: ${qs})`,qs).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){yo.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=Us(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=od(o.config),s=ur(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 Zu(o.notify,s),r=o.id||Wr(t.matched,o.agent),a=Jr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Br(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."))});yo.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=od(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=Hr(Gr(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]])yo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Vr(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."))});yo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!pt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Fr(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",zr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Yr,"reject an agent's pending create/delete request (drops the request)"]])yo.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."))});yo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Us(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 ef}from"commander";import ve from"chalk";var Do=new ef("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),of={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function td(){return{root:process.cwd()}}function Di(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function tf(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${of[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Di(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 ${Di(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}`:""}`))}Do.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=ka(td(),{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)tf(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 Pi(e,o,t){let n=qn(),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 va(td(),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}`))}Do.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)=>Pi(e,"yes",o));Do.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)=>Pi(e,"no",o));Do.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)=>Pi(e,"later",o));Do.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: ${ba.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=qn(),t=$a(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 ${Di(t.card.expires)}, then: ${t.card.if_silent}`))});Do.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=sc(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 ic(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=qn(),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 Af}from"commander";import Ct from"chalk";import te from"chalk";import pn from"prompts";import{readFileSync as nf,writeFileSync as sf,existsSync as rf}from"fs";import{resolve as nd}from"path";var af=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function cf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Mi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function sd(e=".env"){let o=nd(e);if(!rf(o))return[];let t=nf(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(af);i?n.push({kind:"kv",key:i[1],value:cf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function lf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Mi(o.value)}`:o.raw).join(`
|
|
391
394
|
`)+`
|
|
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.
|
|
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}}}}
|
|
395
|
+
`}function mn(e,o,t=".env"){let n=nd(t),s=sd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`})),sf(n,lf(s))}function Li(e,o=".env"){return sd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var id="https://t.me/BotFather";async function df(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 gf(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 rd(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${id}`)),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 pn({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,[id],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await pn({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 df(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 pn({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 pn({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`;mn(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=pt(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 pn({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 gf(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 Fi from"prompts";import{existsSync as qi,mkdirSync as mf,readdirSync as pf,readFileSync as ad}from"fs";import{resolve as Ui}from"path";var uf=".agentx/whatsapp-sessions";function ff(){let e=Ui(process.cwd(),".agentx/daemon.pid");if(!qi(e))return!1;try{let o=parseInt(ad(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function hf(e){if(!qi(e))return!1;try{return pf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function yf(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;mf(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 cd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),ff()){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 Fi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Ui(process.cwd(),"agentx.json");qi(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(ad(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||uf,s=Ui(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 Fi({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(hf(s)&&a){let{keep:l}=await Fi({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 yf(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 wf}from"crypto";import xe from"chalk";import ld from"prompts";var ps="agentx-mesh:",us="//join/";function bf(e){return Buffer.from(e,"utf-8").toString("base64url")}function $f(e){return Buffer.from(e,"base64url").toString("utf-8")}function kf(e){return`${ps}${us}${bf(JSON.stringify(e))}`}function vf(e){if(!e.startsWith(`${ps}${us}`))throw new Error(`Not a mesh invite link \u2014 expected ${ps}${us}\u2026`);let o=e.slice(ps.length+us.length),t=JSON.parse($f(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 xf(){return wf(32).toString("hex")}function Sf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ef(e){return e?.node?.name||e?.node?.id||"node"}async function dd(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=Li("MESH_TOKEN");r||(r=xf(),mn("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Sf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await ld({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=kf({url:a,token:r,name:Ef(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 gd(e,o={}){let t;try{t=vf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Li("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await ld({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))}mn("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=pt(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 Nt=new Af().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Nt.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 rd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Nt.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 cd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var md=Nt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");md.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 dd({url:e.url,configPath:e.config})});md.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 gd(e,{configPath:o.config})});Nt.action(()=>{console.log(),console.log(Ct.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ct.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ct.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ct.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ct.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ct.dim(" GitLab connect is the next slice.")),console.log()});re();import{Command as Tf}from"commander";import pe from"chalk";var un=new Tf().name("usage").description("token usage analysis and reporting");un.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}`))}});un.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?"))}});un.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-UXJWH5JG.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 Of}from"commander";import be from"chalk";import{readFileSync as If}from"fs";import{resolve as jf}from"path";re();var Po=new Of().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Po.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{Sr(jf(process.cwd(),".env"))}catch{}let o=Cf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-WG4ZZV4A.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 Cf(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.
|
|
396
|
+
`)),{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}}}}Po.command("list").description("list configured boards").action(()=>{try{let e=R();if(!e.boards?.length){console.log(be.dim(`
|
|
394
397
|
No boards configured.
|
|
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)}});
|
|
398
|
+
`));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)}});Po.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{fn(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)}});Po.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{fn(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 Wi=Po.command("column").description("manage a board's columns (add / remove / edit / list)");Wi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(If("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)}});Wi.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{fn(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)}});Wi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{fn(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)}});Po.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{fn(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 fn(e){let{summary:o,backupPath:t}=uo(n=>e(n));console.log(be.green(`
|
|
396
399
|
\u2713 ${o}
|
|
397
400
|
`)),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
|
|
401
|
+
`))}import{Command as Nf}from"commander";import m from"chalk";import{resolve as F,relative as pd,dirname as ud}from"path";import{execSync as nt}from"child_process";import{writeFileSync as st,mkdirSync as wo,readFileSync as hn,readdirSync as Rf,renameSync as fs,rmSync as _f,existsSync as ze}from"fs";function Se(e,o){return new Ps(yn(e),void 0,o||"graph")}function yn(e){return e||F(process.cwd(),".agentx/wiki")}function Ji(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Q=new Nf().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 [${Ji(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 ko({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
402
|
${$.content}
|
|
400
403
|
--- END ENTRY ---`).join(`
|
|
401
404
|
|
|
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(`
|
|
405
|
+
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:I,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}),ge=M(u);if(H.length>0||ge.length>0){let J=B(),{records:Ee,results:$e}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...ge,...Ee]);v=I(P);let He=[...ge.length>0?[`entries:${ge.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=ta(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${Ji(o)}`));let S=F(w.baseDir,"_tmp");wo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");st(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=nt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:ct({...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,I=[],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],ge=H==="{"?"}":"]",J=0,Ee=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===ge&&(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||[],I=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 Bo=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("+")} ${Bo}${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(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let P of I)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-2V2VGIT4.js"),He=new P(yn(e.dir)).add(I.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=Df(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 na({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 hs=Q.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ys(e){return e?F(e):F(process.cwd(),".agentx","wiki")}hs.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(ys(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}`))}});hs.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(ys(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
406
|
`).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>)`))}});
|
|
407
|
+
`)),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>)`))}});hs.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(ys(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`))});hs.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(ys(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 Df(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
408
|
`)||"_(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
409
|
|
|
407
410
|
${S.answer}
|
|
408
411
|
|
|
409
|
-
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),
|
|
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?
|
|
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
|
|
412
|
+
**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(`
|
|
413
|
+
`);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?hn(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":""}`)+`
|
|
414
|
+
`),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
415
|
${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
416
|
${m.dim("Anything else worth capturing?")}
|
|
414
417
|
${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(`
|
|
@@ -416,16 +419,16 @@ ${S.answer}
|
|
|
416
419
|
`),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(N=>`
|
|
417
420
|
Q: ${N.q}
|
|
418
421
|
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
|
-
`),A=F(a.baseDir,"_tmp");
|
|
420
|
-
`)){let fe=N.match(/^(\w+):\s*(.+)$/);fe&&(
|
|
421
|
-
`)){let
|
|
422
|
-
`)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:
|
|
423
|
-
`).length,B=
|
|
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)},
|
|
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=
|
|
426
|
-
`).length,w=
|
|
427
|
-
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${
|
|
428
|
-
`)}function
|
|
422
|
+
`),A=F(a.baseDir,"_tmp");wo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);st(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=nt(N,{env:ct({...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 I={};for(let N of j[1].split(`
|
|
423
|
+
`)){let fe=N.match(/^(\w+):\s*(.+)$/);fe&&(I[fe[1]]=fe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],B=I.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ge=`${{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: ${ge}`)),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:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.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`);st(fe,x);try{nt(`${N} '${fe}'`,{stdio:"inherit"});let Rs=hn(fe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Rs){let $o={};for(let Wt of Rs[1].split(`
|
|
424
|
+
`)){let _s=Wt.match(/^(\w+):\s*(.+)$/);_s&&($o[_s[1]]=_s[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Rs[2],$e={...$e,title:$o.title||$e.title,type:$o.type||$e.type,access:$o.access||$e.access,related:$o.related?$o.related.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:$o.tags?$o.tags.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ye){console.log(m.red(` editor failed: ${Ye.message}`));return}}if(!a.writeArticle(ge,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ge} 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 Bo=He.filter(N=>!ke.has(N.toLowerCase()));if(Bo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Bo.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=hn(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(ge=>`${ge.title} [${ge.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
425
|
+
`)),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 $=Mf(x.content,v,A,x.meta.title,x.meta.type),C=F(i.baseDir,"_tmp");wo(C,{recursive:!0});let j=F(C,`quiz-patch-${t().slice(0,8)}.txt`);st(j,$);let I="";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"`,ge=nt(H,{env:ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ee=JSON.parse(ge);I=String(Ee.result||Ee.content||"")}catch{I=ge}let J=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(I=J[1].trim()),I=I.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=x.content.split(`
|
|
426
|
+
`).length,B=I.split(`
|
|
427
|
+
`).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)},I,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}\``:""),"")}st(e.out,f.join(`
|
|
428
|
+
`)),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=yd(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{nt(`${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=yd(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=Pf(l.content,l.meta.title,l.meta.type,t),d=F(a.baseDir,"_tmp");wo(d,{recursive:!0});let p=F(d,`patch-${i().slice(0,8)}.txt`);st(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=nt(S,{env:ct({...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(`
|
|
429
|
+
`).length,w=f.split(`
|
|
430
|
+
`).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 yd(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 Pf(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(`
|
|
431
|
+
`)}function Mf(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
429
432
|
|
|
430
433
|
${t}
|
|
431
434
|
|
|
@@ -438,8 +441,8 @@ Incorporate it into the most relevant existing section, or create a short new se
|
|
|
438
441
|
${t}
|
|
439
442
|
|
|
440
443
|
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
|
|
444
|
+
`)}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;Bi(f,b=>{let v=pd(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=fd(hn(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)Bi(b.dir,v=>{let A=pd(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=fd(hn(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}`)),hd(p,b),g++):(wo(ud(j),{recursive:!0}),fs(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 I=F(p,"_versions",A.relPath.replace(/\.md$/,""));wo(I,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");fs(j,F(I,`${D}.md`))}wo(ud(j),{recursive:!0}),fs(b.absPath,j),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else hd(p,b),g++}catch(j){console.log(m.red(` ! ${S} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of u)try{_f(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 Bi(e,o){if(ze(e))for(let t of Rf(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?Bi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function fd(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
|
|
445
|
+
`)){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 hd(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));wo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");fs(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");wo(y,{recursive:!0});for(let k=0;k<u;k+=n){let b=p.slice(k,Math.min(k+n,u)),v=Ff(b),A=F(y,"migrate-prompt.txt");st(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"`,$=nt(x,{env:ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),C=JSON.parse($),I=String(C.result||C.content||"").match(/\[[\s\S]*\]/);if(!I)throw new Error("no JSON array in classifier response");S=JSON.parse(I[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=Lf($?.type);if(!$||!C){console.log(m.yellow(` ? ${x.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=g.extractWikilinks(x.content),I={...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,I,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 Lf(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 Ff(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
446
|
title: "${t.meta.title}"
|
|
444
447
|
tags: [${i}]
|
|
445
448
|
body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
|
|
@@ -479,48 +482,48 @@ Output (JSON array, one entry per input article, same order):
|
|
|
479
482
|
[
|
|
480
483
|
{"path": "path/to/article.md", "type": "project"},
|
|
481
484
|
...
|
|
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-
|
|
485
|
+
]`}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(),dc(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
486
|
${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(`
|
|
487
|
+
${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 ko({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}),I=r.get(j);if(!I?.length)continue;let D=I.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:I,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 Ps(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:Ji(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} (${Uf(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 I=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(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,I.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(yn(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"),I=j(),D=I?.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
488
|
`),M=C.length>10?`
|
|
486
489
|
\u2026and ${C.length-10} more`:"",H=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
487
490
|
${B}${M}
|
|
488
491
|
|
|
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(`
|
|
492
|
+
agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ge}/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(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of u){let D=f.getAgentWiki(I);for(let B of D.listArticles(I)){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:I,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:Bo}=p(M.content,He[0],J);if(Bo.length!==0){for(let N of Bo)S.push({agent:I,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,I)?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(I=>Math.max(I.length,...S.map(D=>String(D[I]).length))),j=I=>I.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let I of S)console.log(j($.map(D=>I[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(yn(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(yn(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 ge=H.answers;A.push({entry:M,verdict:s(H.answers,v),citeWorthy:ge.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}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:I},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(` ${I}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:ge}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${ge.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=ge.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 Uf(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"}mg();import{Command as qf}from"commander";import _ from"chalk";import{resolve as ws}from"path";import{existsSync as Wf}from"fs";re();var Rt=new qf().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Rt.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 ko({baseDir:ws(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=Tn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${_.cyan(w.msgHash.slice(0,8))} ${_.dim(y)} ... `);let k=Bf(w,a,c),b=null;try{b=await Jf(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{Gf(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()});Rt.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=ws(process.cwd(),o.graph.baseDir);if(!Wf(t)){console.log(_.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new ko({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()});Rt.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 ko({baseDir:ws(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 I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.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 Bf(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
493
|
`),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
|
-
`)}async function
|
|
492
|
-
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(
|
|
493
|
-
dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(
|
|
494
|
-
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),
|
|
495
|
-
`),i=await he(a=>{Ae(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Ae(a,"crons.procedure-extract.enabled",!1):o&&Ae(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(
|
|
494
|
+
`)}async function Jf(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 $r((c?.content||"").toString())}finally{clearTimeout(r)}}function Gf(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Gi(){let e=R();if(!e.graph?.baseDir)return console.log(_.red(" graph.baseDir is not configured")),null;let o=ws(process.cwd(),e.graph.baseDir);return{store:new ko({baseDir:o}),baseDir:o}}var Hi=Rt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Hi.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=Gi();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(Tn(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]"))});Hi.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=Gi();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}: ${Tn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(_.dim(` should have been: ${t.path}`))});Hi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Gi();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 Xf}from"commander";import Y from"chalk";import{Command as bd}from"commander";import ce from"chalk";import{existsSync as Hf}from"fs";import{resolve as zf}from"path";import Yf from"better-sqlite3";function Vf(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(ce.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Kf(e){let o=zf(process.cwd(),e);return Hf(o)||(console.log(ce.red(` No db at ${o}`)),process.exit(1)),new Yf(o,{readonly:!0})}var $d=new bd().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(zt)).option("--max <n>","max clusters distilled per run",String(jn)).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(ce.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Kf(e.path),t=await sa(o,{since:Vf(e.since),agentId:e.agent,sessions:new Or(process.cwd()),minOccurrences:Number(e.minOccurrences)||zt,max:Number(e.max)||jn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ce.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(` ${ce.cyan(n.key)} ${ce.bold(`\xD7${n.count}`)} ${ce.dim(n.status)}`),n.sampleMessage&&console.log(ce.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ce.dim(`
|
|
495
|
+
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ce.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ce.green(` \u2713 draft written: ${n.id}`)+ce.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ce.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ce.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ce.dim(`
|
|
496
|
+
dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(ce.dim(`
|
|
497
|
+
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),wd={hourly:"0 * * * *",daily:"0 3 * * *"},kd=new bd().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(zt)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?wd.hourly:e.daily?wd.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(ce.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(ce.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||zt,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${jn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
|
|
498
|
+
`),i=await he(a=>{Ae(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Ae(a,"crons.procedure-extract.enabled",!1):o&&Ae(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(ce.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(ce.green(` \u2713 ${r} procedure extraction: off`)):(console.log(ce.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(ce.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(ce.dim(" on-task counting: enabled")),console.log(ce.dim(` threshold: ${t} occurrences`))),console.log(ce.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var no=new Xf().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");no.addCommand($d);no.addCommand(kd);no.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new vo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});no.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new vo,t=e.steps?String(e.steps):`## Steps
|
|
496
499
|
|
|
497
500
|
1. (fill in)
|
|
498
501
|
|
|
499
502
|
## Notes
|
|
500
503
|
|
|
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)}});
|
|
504
|
+
`;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)}});no.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new vo,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()});no.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new vo;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)}});no.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new vo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});no.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new vo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});no.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 vo,n=Ur(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 eh}from"commander";import E from"chalk";import{resolve as Dt,basename as oh}from"path";import{existsSync as zi,readFileSync as Yi,writeFileSync as bs}from"fs";import B0 from"better-sqlite3";import{readFileSync as Qf}from"fs";import{resolve as _t,dirname as vd}from"path";import{fileURLToPath as Zf}from"url";var wn=[{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 xd(e){let o=vd(Zf(import.meta.url)),t=process.argv[1]?vd(process.argv[1]):"",n=[_t(o,`${e}.yaml`),_t(o,"workflows/templates",`${e}.yaml`),_t(o,"..","workflows/templates",`${e}.yaml`),_t(o,"../..","workflows/templates",`${e}.yaml`),t?_t(t,"workflows/templates",`${e}.yaml`):"",t?_t(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Qf(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
|
|
502
505
|
${n.join(`
|
|
503
|
-
`)}`)}var Je=new
|
|
504
|
-
`)}else
|
|
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
|
|
506
|
-
`;
|
|
506
|
+
`)}`)}var Je=new eh().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 Jo().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 Jo().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(Cr(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=Dt(process.cwd(),e);zi(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=Yi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?gt(r,{filePath:e}):JSON.parse(r),l=dt.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=On(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 In?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Jo().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 (${wn.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");wn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${wn.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 Jo;!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=xd(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=gt(s,{filePath:`${e}.yaml`}),c=dt.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=Dt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=gt(s,{filePath:`${e}.yaml`}),c=dt.parse(a);bs(r,JSON.stringify(c,null,2)+`
|
|
507
|
+
`)}else bs(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 wn)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=Dt(process.cwd(),e);zi(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=Yi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?gt(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof In?p.message:`parse error: ${p?.message??p}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=dt.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=On(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 Jo,l=s?oh(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Dt(c.baseDir,`${r.data.id}.${l}`);if(bs(g,s?n:JSON.stringify(r.data,null,2)+`
|
|
508
|
+
`),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 Ht({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=Dt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&zi(s)){let c=Yi(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?gt(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof In?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=dt.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=On(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 Jo,u=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=Dt(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)+`
|
|
509
|
+
`;bs(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 th({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function th(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}Sd(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)Sd(i)});function Sd(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 Ht({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 Ht({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 Ht({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 Ed}from"commander";import ne from"chalk";import it from"prompts";import{readFileSync as nh,existsSync as sh}from"fs";import{resolve as ih}from"path";var bn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Vi=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Ad={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 Td(){let e=ih(process.cwd(),"agentx.json");if(!sh(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(nh(e,"utf-8"))}function rh(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ne.yellow("\u26A0 no signing secret"):ne.green("\u2713 active"):ne.dim("disabled")}function ah(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Vi.has(e.source)?ne.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ne.cyan(e.id)} ${rh(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 bo=new Ed().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");bo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Td(),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
510
|
No webhooks registered. Add one with: agentx webhook add
|
|
508
|
-
`));return}console.log();for(let n of t)
|
|
511
|
+
`));return}console.log();for(let n of t)ah(n)});bo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${bn.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=Td(),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 it({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 it({type:"select",name:"source",message:"Source",choices:bn.map(u=>({title:`${u}${Vi.has(u)?" \u2713 wired":""}`,value:u,description:Ad[u]}))})).source),!bn.includes(a))throw new Error(`Source must be one of: ${bn.join(", ")}`);if(!c&&d&&(i?c=((await it({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await it({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 it({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await it({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"))});bo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await it({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 Od(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}"`))}}bo.command("enable <id>").description("enable a webhook entry").action(Od(!0));bo.command("disable <id>").description("disable a webhook entry").action(Od(!1));var $s=new Ed().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");$s.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}`))});$s.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}"`))});$s.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}`}`))});bo.addCommand($s);bo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=bn.map(t=>({source:t,wired:Vi.has(t),hint:Ad[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 ch}from"commander";import se from"chalk";re();function Pt(e){let{summary:o,backupPath:t}=uo(n=>e(n));console.log(se.green(`
|
|
509
512
|
\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
|
-
`))}function
|
|
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=
|
|
512
|
-
`))console.log(` ${s}`);console.log();let n=
|
|
513
|
+
`))}function ks(){try{return R().business||{}}catch{return{}}}var Mt=new ch().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Mt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ks();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 Ki=Mt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Ki.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ks(),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}`):""}`)});Ki.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);Pt(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}`:""})`))});Ki.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{Pt(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 Xi=Mt.command("project").description("manage business.projects \u2014 id, pm, client");Xi.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ks().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())});Xi.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)=>{Pt(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`})});Xi.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{Pt(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 Qi=Mt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Qi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ks().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:""}`)}});Qi.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)),Pt(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`})});Qi.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=>{Pt(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 lh}from"commander";import De from"chalk";re();var dh={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Zi(e){let o=dh[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function vs(){let o=R().business?.standup?.plansDir||".agentx/plans";return new Ka(o)}var Lt=new lh().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Lt.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=Zi(e),n=vs(),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(`
|
|
514
|
+
`):(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=Ks(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}`))}});Lt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=vs();if(e){let n=Zi(e),s=o.read(n);if(!s){console.log(De.dim(` No ${n} plan set.`));return}Id(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}Id(t.tier,t.date,t.content)});Lt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=vs().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)}`)});Lt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Zi(e),n=vs().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 Id(e,o,t){console.log(De.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
|
|
515
|
+
`))console.log(` ${s}`);console.log();let n=Ks(t);n.length&&console.log(De.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as gh}from"commander";import Z from"chalk";re();function mh(){try{return R().notifications||{}}catch{return{}}}function ph(){try{return R().channels?.ntfy}catch{return}}function $n(e){let{summary:o,backupPath:t}=uo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Z.green(`
|
|
513
516
|
\u2713 ${o}`)),t&&console.log(Z.dim(` Backup: ${t}`)),console.log(Z.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
514
|
-
`))}var
|
|
515
|
-
`))}catch(n){console.log(Z.red(` ${n?.message??n}`)),process.exit(1)}});
|
|
517
|
+
`))}var Mo=new gh().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Mo.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=mh();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=Rn(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 tc();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=Qs(ph());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()});Mo.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){$n(o=>(delete o.destination,"notifications destination cleared"));return}$n(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})`:""}`))});Mo.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";$n(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Mo.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)),$n(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});Mo.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{$n(n=>(n.local=ha(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.
|
|
518
|
+
`))}catch(n){console.log(Z.red(` ${n?.message??n}`)),process.exit(1)}});Mo.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}=uo(s=>{s.channels=s.channels||{},s.channels.ntfy=lc(s.channels.ntfy,o);let i=Qs(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
519
|
\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
|
|
520
|
+
`))}catch(t){console.log(Z.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as uh}from"commander";import Lo from"chalk";import{readdirSync as er,statSync as jd,unlinkSync as fh,rmSync as hh,existsSync as Cd}from"fs";import{resolve as Nd,join as Rd}from"path";var _d=[{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 or(e,o){if(!Cd(e))return[];let t=[];for(let n of er(e,{withFileTypes:!0})){let s=Rd(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...or(s,!0))}return t}var Ss=new uh().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Ss.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of _d){let t=Nd(process.cwd(),o.dir),n=or(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=jd(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(` ${Lo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${xs(s).padStart(10)} oldest=${r}`)}console.log(Lo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${xs(e).padStart(10)} total`)),console.log(),console.log(Lo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Ss.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(Lo.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(Lo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Lo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of _d){if(n&&r.dir!==n)continue;let a=Nd(process.cwd(),r.dir),c=or(a,!!r.recursive),l=0,g=0;for(let p of c)try{let f=jd(p);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{fh(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Dd(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Lo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${xs(g)})`),s+=l,i+=g}console.log(),console.log(Lo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${xs(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Dd(e){if(Cd(e))for(let o of er(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Rd(e,o.name);Dd(t);try{er(t).length===0&&hh(t,{recursive:!1})}catch{}}}function xs(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 yh}from"commander";import U from"chalk";var Fo=new yh().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Fo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new mt().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()});Fo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new mt().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()});Fo.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=wh(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=Nr.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 mt().save(s.data);console.log(U.green(`
|
|
518
521
|
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
|
|
519
|
-
`))});
|
|
522
|
+
`))});Fo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new mt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Fo.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 mt().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 Rr(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)}});Fo.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 wh(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}re();import{Command as bh}from"commander";import ee from"chalk";var Pd=new bh().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
523
|
|
|
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
|
|
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:${
|
|
524
|
+
`))>=0;){let f=l.slice(0,p);l=l.slice(p+2),$h(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function $h(e){let o="message",t="";for(let i of e.split(`
|
|
525
|
+
`))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 vh}from"commander";import Es from"chalk";import{spawn as xh}from"node:child_process";import{execFileSync as kh}from"node:child_process";function Md(e=()=>kh("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 Ld=new vh().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(Es.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:Md();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(Es.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=xh("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(Es.yellow(n.reason)),console.error(Es.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 Sh}from"commander";import V from"chalk";import{randomUUID as qd}from"crypto";import{createInterface as Eh}from"node:readline/promises";import Ah from"ora";import As from"chalk";function Fd(e){console.error(),console.error(As.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(As.dim(` ${e.why}`)),console.error(),console.error(` Use ${As.cyan(e.instead)} instead.`),e.note&&console.error(As.dim(` ${e.note}`)),console.error()}var Ud={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 Wd=new Sh().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)=>{Fd({what:"agentx chat",...Ud});let t=gc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${qd().slice(0,12)}`,r=[];try{r=await Wn(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}Oh(t.baseUrl,n,i,s);let a=Eh({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
|
|
526
|
+
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:${qd().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await Wn(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 Wn(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=Ah({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Th(n);try{let u=await mc(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 Th(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
|
|
524
527
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
525
528
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
526
529
|
`&&(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(`
|
|
@@ -535,17 +538,17 @@ agentx wiki questions`,de=O?.daemon?.port??O?.port??18800;try{let J=await fetch(
|
|
|
535
538
|
`))},finishError(r){o&&!t&&process.stdout.write(`
|
|
536
539
|
`),process.stdout.write(V.red(` \u2717 ${r}
|
|
537
540
|
|
|
538
|
-
`))}}}function bh(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as $h}from"commander";import ie from"chalk";import{readFileSync as kh}from"fs";import{existsSync as vh,readdirSync as xh}from"fs";import{resolve as Sh}from"path";var Es=["user","feedback","project","reference"],Lo=new $h().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Lo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!Es.includes(e.type)){console.error(ie.red(` --type must be one of: ${Es.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Eh();else try{o=kh(e.file,"utf-8")}catch(s){console.error(ie.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(ie.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new at().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(ie.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Lo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new at().list(e.agent);if(e.type){if(!Es.includes(e.type)){console.error(ie.red(` --type must be one of: ${Es.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(ie.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(ie.bold(` ${s.type}`)),n=s.type),console.log(` ${ie.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ie.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Lo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new at().get(o.agent,e);if(!n){console.error(ie.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ie.bold(`${n.type}/${n.name}`)+ie.dim(` (${n.description})`)),console.log(ie.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Lo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new at().remove(o.agent,e)){console.error(ie.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ie.green(` \u2713 memory "${e}" removed`))});Lo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new at().indexMarkdown(e.agent);if(!t){console.log(ie.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var As=Lo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Zi(e){if(e)return[e];let o=Sh(process.cwd(),".agentx/memory");return vh(o)?xh(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}As.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Bt;for(let t of Zi(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${ie.bold(t)} ${n||ie.dim("(none)")}`)}});As.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Bt,t=0;for(let n of Zi(e.agent))for(let s of o.held(n))t++,console.log(` ${ie.bold(n)} ${ie.cyan(s.id)} ${ie.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(ie.dim(" nothing held"))});for(let e of["approve","reject"])As.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new Bt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(ie.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ie.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});As.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new Bt,t=0;for(let n of Zi(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${ie.bold(n)} ${s}`),t+=s}console.log(e.apply?ie.green(` \u2713 deleted ${t} fact(s) containing credentials`):ie.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});async function Eh(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}ng();import er from"chalk";import{Command as Ah}from"commander";import{resolve as Ih}from"path";var Fd=new Ah().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(Ih(e.cwd)),e.stdio!==!1?await zr():(go.error("Only stdio transport is currently supported."),go.info(`Usage: ${er.green("agentx serve --stdio")} or configure in your MCP client.`),go.break(),go.info("Add to Claude Code:"),go.info(er.dim(" claude mcp add agentx -- npx agentx serve --stdio")),go.break(),go.info("Add to Cursor/MCP config:"),go.info(er.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Ka(o)}});import{Command as Th}from"commander";import ce from"chalk";import{spawn as or}from"child_process";import{mkdirSync as Oh,writeFileSync as Os,readFileSync as jh,readdirSync as Ch,rmSync as qd,openSync as Wd,existsSync as Is}from"fs";import{resolve as Nh,join as Pe}from"path";import{randomBytes as Rh}from"crypto";var Ud={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var Bd="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",_h="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Dh(e,o){return[{dir:Pe(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Ud,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:Pe(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:Pe(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function Ph(e,o,t){let n=Pe(e.dir,"workspaces",e.agentId);Oh(n,{recursive:!0}),Os(Pe(n,"CLAUDE.md"),`# ${e.agentName}
|
|
541
|
+
`))}}}function Oh(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Ih}from"commander";import ie from"chalk";import{readFileSync as jh}from"fs";import{existsSync as Ch,readdirSync as Nh}from"fs";import{resolve as Rh}from"path";var Ts=["user","feedback","project","reference"],Uo=new Ih().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Uo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!Ts.includes(e.type)){console.error(ie.red(` --type must be one of: ${Ts.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await _h();else try{o=jh(e.file,"utf-8")}catch(s){console.error(ie.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(ie.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new lt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(ie.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Uo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new lt().list(e.agent);if(e.type){if(!Ts.includes(e.type)){console.error(ie.red(` --type must be one of: ${Ts.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(ie.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(ie.bold(` ${s.type}`)),n=s.type),console.log(` ${ie.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ie.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Uo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new lt().get(o.agent,e);if(!n){console.error(ie.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ie.bold(`${n.type}/${n.name}`)+ie.dim(` (${n.description})`)),console.log(ie.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Uo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new lt().remove(o.agent,e)){console.error(ie.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ie.green(` \u2713 memory "${e}" removed`))});Uo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new lt().indexMarkdown(e.agent);if(!t){console.log(ie.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Os=Uo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function tr(e){if(e)return[e];let o=Rh(process.cwd(),".agentx/memory");return Ch(o)?Nh(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Os.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Gt;for(let t of tr(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${ie.bold(t)} ${n||ie.dim("(none)")}`)}});Os.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Gt,t=0;for(let n of tr(e.agent))for(let s of o.held(n))t++,console.log(` ${ie.bold(n)} ${ie.cyan(s.id)} ${ie.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(ie.dim(" nothing held"))});for(let e of["approve","reject"])Os.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new Gt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(ie.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ie.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Os.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new Gt,t=0;for(let n of tr(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${ie.bold(n)} ${s}`),t+=s}console.log(e.apply?ie.green(` \u2713 deleted ${t} fact(s) containing credentials`):ie.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});async function _h(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}ag();import nr from"chalk";import{Command as Dh}from"commander";import{resolve as Ph}from"path";var Bd=new Dh().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(Ph(e.cwd)),e.stdio!==!1?await Kr():(mo.error("Only stdio transport is currently supported."),mo.info(`Usage: ${nr.green("agentx serve --stdio")} or configure in your MCP client.`),mo.break(),mo.info("Add to Claude Code:"),mo.info(nr.dim(" claude mcp add agentx -- npx agentx serve --stdio")),mo.break(),mo.info("Add to Cursor/MCP config:"),mo.info(nr.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Za(o)}});import{Command as Mh}from"commander";import le from"chalk";import{spawn as sr}from"child_process";import{mkdirSync as Lh,writeFileSync as Cs,readFileSync as Fh,readdirSync as Uh,rmSync as Gd,openSync as Hd,existsSync as Is}from"fs";import{resolve as qh,join as Pe}from"path";import{randomBytes as Wh}from"crypto";var Jd={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var zd="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Bh="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Jh(e,o){return[{dir:Pe(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Jd,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:Pe(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:Pe(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function Gh(e,o,t){let n=Pe(e.dir,"workspaces",e.agentId);Lh(n,{recursive:!0}),Cs(Pe(n,"CLAUDE.md"),`# ${e.agentName}
|
|
539
542
|
|
|
540
543
|
${e.persona}
|
|
541
|
-
`),
|
|
544
|
+
`),Cs(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}};Cs(Pe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ir(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 rr(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 js(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
542
545
|
`).join(`
|
|
543
|
-
`)}`)}var
|
|
544
|
-
`,{mode:384})}console.log(),console.log(
|
|
546
|
+
`)}`)}var Yd=new Mh().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=qh(process.cwd(),".agentx-demo"),n=Jh(t,o),s=Pe(t,"mesh-token"),i=!!e.reuse&&Is(s)&&Is(Pe(n[0].dir,"agentx.json")),r=i?Fh(s,"utf8").trim():Wh(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Is(l))&&(console.error(le.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 Uh(t))Gd(Pe(t,f),{recursive:!0,force:!0});for(let f of n)Gh(f,n,r);Cs(s,r+`
|
|
547
|
+
`,{mode:384})}console.log(),console.log(le.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(le.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(le.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{Gd(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=Hd(Pe(y.dir,"daemon.log"),"a"),b=sr(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(le.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Pe(y.dir,"daemon.log")})`))}for(let y of n)await ir(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(le.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Hd(Pe(n[0].dir,"board.log"),"a"),k=sr(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 ir("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(le.green(" \u2713 dashboard up")),await ir("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(le.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: ${le.cyan(u)} (all three nodes via the mesh)`),console.log(le.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{sr(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(le.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),js("You \u2192 @cx (laptop-paris)",zd,le.cyan);let y=await rr(n[0].port,"/task",{agent:"cx",message:zd});js("@cx (laptop-paris)",y.content||"(no content)",le.green),console.log(),console.log(le.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await rr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Bh}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";js("@builder (vps-nyc)",b,le.yellow);let v=await rr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});js("@cx (laptop-paris)",v.content||"(no content)",le.green),console.log(),console.log(le.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(le.dim(` Worth your time? A star helps others find it: ${le.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(le.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(le.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(le.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(le.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(le.red(` Demo failed: ${f.message}`)),console.error(le.dim(` Node logs: ${n.map(u=>Pe(u.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Hh}from"commander";import{randomUUID as zh}from"crypto";import{readFileSync as Yh}from"fs";import{resolve as Vh}from"path";re();var Kd=new Hh().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??Yh(0,"utf8")).trim();t||Vd("no task given (pass it as an argument or on stdin)");let n=R(o.config?Vh(o.config):void 0),s=n.agents[o.agent];s||Vd(`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";Er(o.agent,s,l,i)}let r=new qr(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-${zh()}`,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
548
|
`):c.error?console.error(c.error):process.stdout.write(c.content+`
|
|
546
|
-
`),process.exit(c.error?1:0)});function
|
|
547
|
-
`}function
|
|
548
|
-
`}function
|
|
549
|
+
`),process.exit(c.error?1:0)});function Vd(e){console.error(`agentx exec: ${e}`),process.exit(1)}re();import{Command as Kh}from"commander";import Ie from"chalk";var qo=new Kh().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");qo.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 kn("/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(Ie.dim(" no chats cached yet"));return}console.log(),console.log(Ie.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ie.cyan("group"):Ie.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ie.dim(n.jid.padEnd(40))} ${Ie.dim(i)}`)}console.log()}catch(o){Ft(o)}});qo.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 kn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ie.dim(" no contacts cached yet"));return}console.log(),console.log(Ie.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} ${Ie.dim(i)} ${Ie.dim(n.jid)}`)}console.log()}catch(o){Ft(o)}});qo.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 cr("/whatsapp/ingest",o);ar(t,!!e.dryRun)}catch(o){Ft(o)}});qo.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 cr("/whatsapp/ingest",t);ar(n,!!o.dryRun)}catch(t){Ft(t)}});qo.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 cr("/whatsapp/ingest",t);ar(n,!!o.dryRun)}catch(t){Ft(t)}});qo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await kn("/whatsapp/state"),o=await kn("/whatsapp/chats"),t=await kn("/whatsapp/contacts");console.log(),console.log(Ie.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){Ft(e)}});function ar(e,o){if(console.log(),console.log(Ie.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(Ie.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ie.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ie.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ie.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ie.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Xd(){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 kn(e){let o=await fetch(`${Xd()}${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 cr(e,o){let t=await fetch(`${Xd()}${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 Ft(e){console.error(Ie.red(` ${e.message||e}`)),process.exit(1)}re();import{Command as Xh}from"commander";import de from"chalk";import{existsSync as Qh,mkdirSync as Qd,writeFileSync as vn}from"fs";import{join as Ut,resolve as Zh}from"path";var xn=new Xh().name("plugin").description("manage agentx plugins (Move B)");xn.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(de.dim(" No plugins configured.")),console.log(de.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(de.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${de.cyan(t)}`);console.log(),console.log(de.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(de.red(` ${e.message}`)),process.exitCode=1}});xn.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(de.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=Zh(o.cwd,t);Qh(n)&&!o.force&&(console.log(de.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Qd(n,{recursive:!0}),Qd(Ut(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;vn(Ut(n,"package.json"),ny(e,s)),vn(Ut(n,"tsconfig.json"),sy()),vn(Ut(n,"src/index.ts"),iy(e)),vn(Ut(n,"README.md"),ry(e,s)),vn(Ut(n,".gitignore"),ay()),console.log(),console.log(de.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(de.bold(" Next steps:")),console.log(de.dim(` cd ${t}`)),console.log(de.dim(" pnpm install")),console.log(de.dim(" pnpm build")),console.log(de.dim(" pnpm link --global # for local testing")),console.log(de.dim(" # then in your agentx project:")),console.log(de.dim(` pnpm link --global ${e}`)),console.log(de.dim(` agentx config set plugins[0] "${e}"`)),console.log(de.dim(" agentx plugin doctor")),console.log()});xn.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(de.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await ey(n);s.kind==="ok"?console.log(` ${de.green("\u2713")} ${de.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${de.red("\u2717")} ${de.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(de.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(de.red(` ${e.message}`)),process.exitCode=1}});async function ey(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=oy(o);if(!ty(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=xa.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 oy(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 ty(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ny(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)+`
|
|
550
|
+
`}function sy(){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)+`
|
|
551
|
+
`}function iy(e){return`// ${e} \u2014 AgentX plugin
|
|
549
552
|
//
|
|
550
553
|
// A plugin's default export is { manifest, setup }. The daemon calls
|
|
551
554
|
// setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
|
|
@@ -581,7 +584,7 @@ const plugin = {
|
|
|
581
584
|
}
|
|
582
585
|
|
|
583
586
|
export default plugin
|
|
584
|
-
`}function
|
|
587
|
+
`}function ry(e,o){return`# ${e}
|
|
585
588
|
|
|
586
589
|
${o}
|
|
587
590
|
|
|
@@ -608,19 +611,19 @@ agentx plugin doctor
|
|
|
608
611
|
\`\`\`
|
|
609
612
|
|
|
610
613
|
Restart the daemon to activate.
|
|
611
|
-
`}function
|
|
614
|
+
`}function ay(){return`node_modules/
|
|
612
615
|
dist/
|
|
613
616
|
*.log
|
|
614
617
|
.env
|
|
615
|
-
`}import{Command as
|
|
618
|
+
`}import{Command as cy}from"commander";import je from"chalk";import{writeFileSync as ly,mkdirSync as dy,existsSync as Ns,readFileSync as Zd,appendFileSync as eg}from"fs";import{resolve as qt,dirname as ng}from"path";import{homedir as dr}from"os";var sg=new cy().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-UXJWH5JG.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=py(t);break;case"bash":s=wy(t);break;case"fish":s=by(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?qt(String(e.output)):gy(n);dy(ng(i),{recursive:!0}),ly(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),my(n,i,!!e.yes)});function gy(e){let o=dr();switch(e){case"zsh":return qt(o,".zsh","completions","_agentx");case"bash":return qt(o,".bash_completion.d","agentx.bash");case"fish":return qt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function my(e,o,t){if(e==="zsh"){let n=qt(dr(),".zshrc"),s=ng(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ns(n)?Zd(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&&Ns(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),eg(n,g.join(`
|
|
616
619
|
`)+`
|
|
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=
|
|
620
|
+
`),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=qt(dr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ns(n)?Zd(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&&Ns(n)){eg(n,`
|
|
618
621
|
# agentx completion
|
|
619
622
|
${s}
|
|
620
|
-
`),console.log(je.green("\u2713 Patched ~/.bashrc")),console.log(je.dim("Reload your shell: exec bash"));return}console.log(je.dim("Add this to ~/.bashrc:")),console.log(je.cyan(` ${s}`)),console.log(),console.log(je.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(je.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ge(e){return e._name||e.name()||""}function
|
|
621
|
-
`)}function
|
|
622
|
-
`)}function
|
|
623
|
-
`)}function
|
|
624
|
-
`)}),o}var
|
|
625
|
-
`)}export{
|
|
626
|
-
//# sourceMappingURL=chunk-
|
|
623
|
+
`),console.log(je.green("\u2713 Patched ~/.bashrc")),console.log(je.dim("Reload your shell: exec bash"));return}console.log(je.dim("Add this to ~/.bashrc:")),console.log(je.cyan(` ${s}`)),console.log(),console.log(je.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(je.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ge(e){return e._name||e.name()||""}function Wo(e){return e.commands.filter(o=>{let t=Ge(o);return!(!t||t==="help")})}function Sn(e){return e.options.filter(o=>!o.hidden)}function py(e){let o=[];return o.push("#compdef agentx"),o.push(""),ig(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
|
|
624
|
+
`)}function og(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function ig(e,o,t){let n=Wo(e),i=Sn(e).map(hy).filter(c=>!!c),r=og(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(yy).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=og([...o,Ge(c)]);t.push(` (${Ge(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)ig(c,[...o,Ge(c)],t)}function uy(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function fy(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function hy(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=uy(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function yy(e){let o=fy(e.description()||"");return`'${Ge(e)}[${o}]'`}function wy(e){let o=Wo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ge).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Wo(n).map(Ge),i=tg(n);if(t.push(` ${Ge(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Wo(n)){let a=tg(r);t.push(` ${Ge(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
|
|
625
|
+
`)}function tg(e){let o=[];for(let t of Sn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function by(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of Wo(e)){let n=gr(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ge(t)}" -d "${n}"`)}o.push("");for(let t of Sn(e)){let n=lr(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Wo(e)){let n=Ge(t);o.push(`# ${n}`);for(let s of Sn(t)){let i=lr(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Wo(t)){let i=gr(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Wo(t).map(Ge).join(" ")}" -a "${Ge(s)}" -d "${i}"`);for(let r of Sn(s)){let a=lr(r,[`__fish_seen_subcommand_from ${Ge(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
|
|
626
|
+
`)}function gr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function lr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=gr(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 YA(){let e=await ec(),o=new $y().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=ac(n);cc(s)&&rc("cli",s)});for(let t of[Pc,Rc,Nt,wt,on,Ve,nc,zo,Xn,yo,Do,ot,Kn,Ld,No,ol,dl,ln,kl,El,Al,Bl,zl,Yl,gs,un,Bd,en,To,sg])o.addCommand(t);for(let t of rg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=rg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,ky(t,74," "),""].join(`
|
|
627
|
+
`)}),o}var rg=[Q,Rt,Uo,no,nn,It,Je,bo,Po,tt,Mt,Lt,jo,qe,Et,ms,Pd,fo,xt,pc,Yo,xn,di,Fo,vt,gi,Ss,Mo,qo,Yd,Kd,Wd];function ky(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(`
|
|
628
|
+
`)}export{YA as a};
|
|
629
|
+
//# sourceMappingURL=chunk-UL4E2CV4.js.map
|