agentix-cli 0.29.0 → 0.30.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/dist/{agent-LS4CZPJ6.js → agent-SPE7Q7MD.js} +2 -2
- package/dist/{board-dashboard-6QQCKFB3.js → board-dashboard-K4DM32SO.js} +2 -2
- package/dist/{chunk-LNWX4MPX.js → chunk-42DCRKUD.js} +130 -129
- package/dist/chunk-42DCRKUD.js.map +1 -0
- package/dist/chunk-45BLFNDG.js +170 -0
- package/dist/chunk-45BLFNDG.js.map +1 -0
- package/dist/{chunk-SBCZLZG3.js → chunk-AUNDQPDR.js} +2 -2
- package/dist/chunk-DWADWDMU.js +96 -0
- package/dist/chunk-DWADWDMU.js.map +1 -0
- package/dist/{chunk-3QVOWDHZ.js → chunk-EL3J74N2.js} +2 -2
- package/dist/{chunk-AE2LDMZU.js → chunk-GK7XAM3D.js} +2 -2
- package/dist/chunk-GK7XAM3D.js.map +1 -0
- package/dist/{chunk-OTXDKKEU.js → chunk-GUBMLV34.js} +134 -122
- package/dist/chunk-GUBMLV34.js.map +1 -0
- package/dist/{chunk-Z2Y24ETP.js → chunk-IVQO43U2.js} +2 -2
- package/dist/{chunk-F5AEXRPR.js → chunk-MGNJWBVP.js} +2 -2
- package/dist/{chunk-6F2IKJ2F.js → chunk-Q7CZIRBB.js} +2 -2
- package/dist/{chunk-UYSNGBDT.js → chunk-UU4WOZNR.js} +2 -2
- package/dist/{chunk-JIOLJIBM.js → chunk-V4HURNMX.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +161 -155
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/program-DWZAI4GY.js +2 -0
- package/dist/query-3HXGBKGM.js +2 -0
- package/dist/registry-EJRWAJYG.js +2 -0
- package/dist/{request-planner-BKT6RZKX.js → request-planner-BCOXUAPA.js} +2 -2
- package/dist/{review-candidates-F3OFYTCZ.js → review-candidates-O2PS7L3B.js} +2 -2
- package/dist/routing-5K7PGHPL.js +2 -0
- package/dist/{seat-ZVHXNAEN.js → seat-FZRNRAHQ.js} +2 -2
- package/dist/{select-L7C52URW.js → select-SOJYFAMI.js} +2 -2
- package/dist/wiki-34XVI32N.js +2 -0
- package/dist/workspace-setup-G6KGWPHY.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-67Q4DCPS.js +0 -54
- package/dist/chunk-67Q4DCPS.js.map +0 -1
- package/dist/chunk-AE2LDMZU.js.map +0 -1
- package/dist/chunk-I3SIXTJO.js +0 -44
- package/dist/chunk-I3SIXTJO.js.map +0 -1
- package/dist/chunk-LNWX4MPX.js.map +0 -1
- package/dist/chunk-OTXDKKEU.js.map +0 -1
- package/dist/chunk-XPXO5K4L.js +0 -164
- package/dist/chunk-XPXO5K4L.js.map +0 -1
- package/dist/program-I4J63BQ7.js +0 -2
- package/dist/query-R7EI3VGX.js +0 -2
- package/dist/registry-UJIJBLUR.js +0 -2
- package/dist/routing-S5WSFIAD.js +0 -2
- package/dist/wiki-5YQI4YKM.js +0 -2
- package/dist/workspace-setup-B3F3TUDE.js +0 -2
- /package/dist/{agent-LS4CZPJ6.js.map → agent-SPE7Q7MD.js.map} +0 -0
- /package/dist/{board-dashboard-6QQCKFB3.js.map → board-dashboard-K4DM32SO.js.map} +0 -0
- /package/dist/{chunk-SBCZLZG3.js.map → chunk-AUNDQPDR.js.map} +0 -0
- /package/dist/{chunk-3QVOWDHZ.js.map → chunk-EL3J74N2.js.map} +0 -0
- /package/dist/{chunk-Z2Y24ETP.js.map → chunk-IVQO43U2.js.map} +0 -0
- /package/dist/{chunk-F5AEXRPR.js.map → chunk-MGNJWBVP.js.map} +0 -0
- /package/dist/{chunk-6F2IKJ2F.js.map → chunk-Q7CZIRBB.js.map} +0 -0
- /package/dist/{chunk-UYSNGBDT.js.map → chunk-UU4WOZNR.js.map} +0 -0
- /package/dist/{chunk-JIOLJIBM.js.map → chunk-V4HURNMX.js.map} +0 -0
- /package/dist/{program-I4J63BQ7.js.map → program-DWZAI4GY.js.map} +0 -0
- /package/dist/{query-R7EI3VGX.js.map → query-3HXGBKGM.js.map} +0 -0
- /package/dist/{registry-UJIJBLUR.js.map → registry-EJRWAJYG.js.map} +0 -0
- /package/dist/{request-planner-BKT6RZKX.js.map → request-planner-BCOXUAPA.js.map} +0 -0
- /package/dist/{review-candidates-F3OFYTCZ.js.map → review-candidates-O2PS7L3B.js.map} +0 -0
- /package/dist/{routing-S5WSFIAD.js.map → routing-5K7PGHPL.js.map} +0 -0
- /package/dist/{seat-ZVHXNAEN.js.map → seat-FZRNRAHQ.js.map} +0 -0
- /package/dist/{select-L7C52URW.js.map → select-SOJYFAMI.js.map} +0 -0
- /package/dist/{wiki-5YQI4YKM.js.map → wiki-34XVI32N.js.map} +0 -0
- /package/dist/{workspace-setup-B3F3TUDE.js.map → workspace-setup-G6KGWPHY.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as hr,b as nn,g as fr}from"./chunk-DI7FMCDK.js";import{b as dr}from"./chunk-JKYMXLYL.js";import{a as Yo,b as lr,f as tn,j as ur}from"./chunk-Q7CZIRBB.js";import{a as gr,c as mr,d as pr}from"./chunk-UCQ2N3KO.js";import{a as zo}from"./chunk-GV7S5BAX.js";import{e as Ii}from"./chunk-GSX4NK2N.js";import{c as Ci}from"./chunk-SZDACK6O.js";import{A as ts,B as ns,C as ar,D as cr,a as Li,b as Mi,h as Wi,i as Bi,j as kt,k as on,l as Ji,m as Hi,n as Gi,o as zi,p as Yi,q as Ki,r as Xi,s as Vi,t as Qi,u as Zi,v as er,w as or,x as tr,y as nr,z as rr}from"./chunk-GUBMLV34.js";import{i as sr,j as es,k as ir,l as os}from"./chunk-F6CNF7V3.js";import{a as Ui,d as Fi,e as qi}from"./chunk-EL3J74N2.js";import{m as Si,o as Jo,q as Vn,r as Ai,t as lo,z as Pi}from"./chunk-45BLFNDG.js";import{b as Ho,c as Zt,d as en,e as Go,f as Oi,g as Ao,h as $t}from"./chunk-IVQO43U2.js";import{d as Zn,f as _i}from"./chunk-4BR7D2OU.js";import{a as Ni}from"./chunk-M4AMWP3H.js";import{a as Ei,e as Ti}from"./chunk-4KXBUORV.js";import{f as ji,g as Ri,h as Qn}from"./chunk-76Z4VHDX.js";import{a as de,b as we,c as Oo,d as Di}from"./chunk-SC5DIKBB.js";import{b as co,d as Qt,f as Xn}from"./chunk-AUNDQPDR.js";import{b as Bo,c as xi}from"./chunk-EVWEG3VD.js";import{a as Kn,b as gi,c as Mc,d as Xt,e as mi,f as yi,g as Fc,h as wi,i as qc,m as Wo,n as $i,o as ki,s as vi,v as Ye,w as bt}from"./chunk-MGNJWBVP.js";import{a as bi,b as Wc}from"./chunk-AJONZWLT.js";import{a as to,b as qo,e as ui,f as wt}from"./chunk-F4HZTZHW.js";import{a as oo,b as Lc}from"./chunk-L2WSPY6S.js";import{f as pi,g as W,h as Vt,j as Oe}from"./chunk-GMNKJXTR.js";import{g as hi,k as fi,l as Uc}from"./chunk-BH3GTCZ6.js";import{a as Pc}from"./chunk-FIOB3MEX.js";import{Command as Bc}from"commander";var yr=new Bc().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 Mi({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Oe();import{Command as Hc}from"commander";import{execFileSync as no}from"node:child_process";import{cpSync as xr,existsSync as cs,mkdirSync as rs,mkdtempSync as Gc,readFileSync as zc,rmSync as Yc,writeFileSync as Sr}from"node:fs";import{dirname as as,join as Ie,resolve as Er}from"node:path";import{homedir as an,release as Kc,tmpdir as Xc}from"node:os";import{fileURLToPath as Vc}from"node:url";import{setTimeout as Qc}from"node:timers/promises";import{existsSync as Jc}from"node:fs";import{join as wr}from"node:path";var sn="tn.acme.agentx.voice",rn="AgentX Desktop.app",vt="AgentX Helper.app";function br(e,o,t){return e!=="darwin"||o!=="arm64"||Number(t.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function $r(e,o){if(o&&!Object.hasOwn(e,o))throw new Error(`Unknown agent: ${o}. Run agentx agent list.`);let t=o||Object.keys(e)[0];if(!t)throw new Error("No agents configured. Run agentx setup first.");return t}function ss(e){return`'${e.replace(/'/g,"'\\''")}'`}function kr(e){let o=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),t={AGENTX_VOICE_AGENT:e.agent,AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${ss(e.cwd)} && ${ss(e.node)} ${ss(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
|
-
<key>Label</key><string>${
|
|
4
|
+
<key>Label</key><string>${sn}</string>
|
|
5
5
|
<key>ProgramArguments</key><array><string>${o(e.executable)}</string></array>
|
|
6
6
|
<key>WorkingDirectory</key><string>${o(e.cwd)}</string>
|
|
7
7
|
<key>EnvironmentVariables</key><dict>${Object.entries(t).map(([n,s])=>`<key>${n}</key><string>${o(s)}</string>`).join("")}</dict>
|
|
@@ -9,37 +9,37 @@ import{a as mr,b as on,g as pr}from"./chunk-DI7FMCDK.js";import{b as ar}from"./c
|
|
|
9
9
|
<key>ProcessType</key><string>Interactive</string>
|
|
10
10
|
<key>StandardErrorPath</key><string>${o(e.log)}</string>
|
|
11
11
|
</dict></plist>
|
|
12
|
-
`}function
|
|
12
|
+
`}function is(e){return wr(e,"Applications",vt,"Contents/MacOS/agentx-mac-helper")}function vr(e,o,t){if(t)return t;let n=is(o);return Jc(n)?n:wr(e,"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper")}function cn(){let e=br(process.platform,process.arch,Kc());if(e)throw new Error(e)}function xt(){return`gui/${process.getuid()}/${sn}`}function Ko(){return Ie(an(),"Library/LaunchAgents",`${sn}.plist`)}async function Ar(){try{no("launchctl",["bootout",xt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{no("launchctl",["print",xt()],{stdio:"pipe"})}catch{return}await Qc(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Or(){if(!cs(Ko()))throw new Error("Run agentx desktop install first.");let e=!0;try{no("launchctl",["print",xt()],{stdio:"pipe"})}catch{e=!1}e||no("launchctl",["bootstrap",`gui/${process.getuid()}`,Ko()],{stdio:"pipe"}),no("launchctl",["kickstart",xt()],{stdio:"pipe"})}function Zc(){let e=as(Vc(import.meta.url));for(let o of[Er(e,".."),Er(e,"../.."),process.cwd()])try{if(JSON.parse(zc(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&cs(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Xo=new Hc("desktop").description("install and control the macOS desktop assistant");Xo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{cn();let o=W(),t=$r(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Zc(),i=Ie(an(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,rn)}
|
|
13
13
|
Computer-use helper \u2192 ${Ie(i,vt)}
|
|
14
14
|
Agent \u2192 ${t}
|
|
15
15
|
Daemon \u2192 ${n}
|
|
16
|
-
Starts at login \u2192 ${Ko()}`),e.dryRun)return;try{no("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=
|
|
16
|
+
Starts at login \u2192 ${Ko()}`),e.dryRun)return;try{no("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=Gc(Ie(Xc(),"agentx-desktop-"));try{for(let d of["mac-helper","mac-voice"])xr(Ie(s,"apps",d),Ie(r,d),{recursive:!0,filter:g=>!g.split("/").includes("build")}),no("/bin/bash",[Ie(r,d,"build.sh")],{stdio:"inherit"});let a=Ie(an(),"Library/Logs/agentx-desktop.err.log"),c=kr({executable:Ie(i,rn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:is(an()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),l=Ie(r,"desktop.plist");Sr(l,c,{mode:384}),no("plutil",["-lint",l],{stdio:"pipe"}),await Ar(),rs(i,{recursive:!0});for(let[d,g,p]of[["mac-voice","AgentX Voice.app",rn],["mac-helper",vt,vt]])xr(Ie(r,d,"build",g),Ie(i,p),{recursive:!0});rs(as(Ko()),{recursive:!0}),rs(as(a),{recursive:!0}),Sr(Ko(),c,{mode:384}),Or(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
|
|
17
17
|
Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
|
|
18
|
-
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{
|
|
19
|
-
`)),{path:t,changed:l,events:a,guardInstalled:c}}function
|
|
20
|
-
`),{path:o,changed:r,events:i,guardInstalled:!1}}function
|
|
21
|
-
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await
|
|
22
|
-
`)){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}}Ke.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);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.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(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Ke.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=W(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(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${
|
|
18
|
+
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Yc(r,{recursive:!0,force:!0})}});Xo.command("start").description("start the installed desktop assistant").action(()=>{cn(),Or(),console.log("Desktop assistant started.")});Xo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{cn(),await Ar(),console.log("Desktop assistant stopped.")});Xo.command("status").description("show the desktop login service status").action(()=>{cn();try{console.log(no("launchctl",["print",xt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(cs(Ko())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as il}from"commander";import{open as rl}from"fs/promises";import{existsSync as gn,mkdirSync as el,readFileSync as mn,writeFileSync as Ir}from"fs";import{homedir as ol}from"os";import{dirname as tl,resolve as ls}from"path";var ds="/attach/",Cr="/guard/check";function jr(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 ln(e,o,t){let n={hooks:[{type:"command",command:jr(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function nl(e){return{SessionStart:[ln("/attach/session-start",e,"")],UserPromptSubmit:[ln("/attach/prompt",e)],Stop:[ln("/attach/stop",e)],SessionEnd:[ln("/attach/session-end",e)]}}function sl(e){let o=jr("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function dn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function St(){return ls(ol(),".claude/settings.json")}function Et(e=process.cwd()){for(let o of[e,ls(e,"..")]){let t=ls(o,"agentx.json");if(gn(t))try{let n=JSON.parse(mn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Rr(e,o={}){let t=o.path??St(),n=o.withGuard!==!1,s={};if(gn(t))try{s=JSON.parse(mn(t,"utf-8"))}catch(d){throw new Error(`${t} is not valid JSON (${d?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[d,g]of Object.entries(nl(e))){let p=Array.isArray(r[d])?r[d].filter(u=>!dn(u,ds)):[];r[d]=[...p,...g],a.push(d)}let c=!1;if(n){let d=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(g=>!dn(g,Cr)):[];r.PreToolUse=[...d,...sl(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(el(tl(t),{recursive:!0}),Ir(t,`${JSON.stringify(s,null,2)}
|
|
19
|
+
`)),{path:t,changed:l,events:a,guardInstalled:c}}function Tr(e={}){let o=e.path??St();if(!gn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(mn(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"?Cr:ds;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(d=>!dn(d,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&&Ir(o,`${JSON.stringify(t,null,2)}
|
|
20
|
+
`),{path:o,changed:r,events:i,guardInstalled:!1}}function pn(e=St()){if(!gn(e))return!1;try{return!!JSON.parse(mn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>dn(t,ds))}catch{return!1}}var un=new il("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Nr=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Et()}`;async function _r(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)}`)}un.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",Nr).action(async e=>{try{await _r(e.url,"register",Fi.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}});un.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",Nr).action(async e=>{try{let o=await rl(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]
|
|
21
|
+
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await _r(e.url,"ended",qi.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 Qp}from"commander";import{Command as al}from"commander";Oe();import O from"chalk";import{existsSync as cl,readFileSync as ll}from"fs";async function dl(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 Ke=new al().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ke.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:d,writeFileSync:g,existsSync:p}=await import("fs"),u=process.argv[1];(!u||!p(u))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${u||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let h=[u,"daemon","start"];e.config&&h.push("-c",e.config),e.port&&h.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=d(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let $=l(process.execPath,h,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),g("/tmp/agentx-daemon.pid",String($.pid)),console.log(O.green(`Daemon started in background (PID: ${$.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.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 d=!1;try{process.kill(l,0),d=!0}catch{}d&&await dl(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{gl(i(process.cwd(),".env"))}catch{}await new ns(e.config).start()});function gl(e){if(!cl(e))return;let o=ll(e,"utf-8");for(let t of o.split(`
|
|
22
|
+
`)){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}}Ke.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);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.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(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Ke.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=W(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(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${ml(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?O.yellow(` [${c.active} active]`):"",d=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${l}${d}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),d=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${d}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?O.green("\u25CF"):O.red("\u25CF"),d=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${O.dim(c.peerUrl)}${d}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=W(e.config),n=Vt(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.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(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});Ke.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(O.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"})});Ke.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(W(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
|
|
23
23
|
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.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 d=a.split(`
|
|
24
|
-
`);a=d.pop()||"";for(let g of d)if(g.startsWith("data: "))try{let
|
|
25
|
-
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ke.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(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.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(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Ke.action(async e=>{await new
|
|
26
|
-
`)),console.log(Be.green(" \u2713 Created .env template"))),At(s)||(
|
|
24
|
+
`);a=d.pop()||"";for(let g of d)if(g.startsWith("data: "))try{let p=JSON.parse(g.slice(6)),u=new Date(p.time).toLocaleTimeString(),h=p.message?.replace(/^\[agentx\]\s*/,"")||"";h.includes("executing")?console.log(`${O.dim(u)} ${O.cyan("\u25B6")} ${h}`):h.includes("completed")?console.log(`${O.dim(u)} ${O.green("\u2713")} ${h}`):h.includes("error")||h.includes("Error")?console.log(`${O.dim(u)} ${O.red("\u2717")} ${h}`):h.includes("Routing")?console.log(`${O.dim(u)} ${O.yellow("\u2192")} ${h}`):h.includes("mention")?console.log(`${O.dim(u)} ${O.magenta("@")} ${h}`):h.includes("Skipping")?console.log(`${O.dim(u)} ${O.dim("\u2298")} ${O.dim(h)}`):console.log(`${O.dim(u)} ${h}`)}catch{}else g.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Ke.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=W(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(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let g=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(g,null,2)):g.error?console.log(O.red(` Error: ${g.error}`)):(console.log(),console.log(g.content||g.response||"No response"),g.duration&&console.log(O.dim(`
|
|
25
|
+
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ke.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(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.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(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Ke.action(async e=>{await new ns(e.config).start()});function ml(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`}import{Command as pl}from"commander";import Be from"chalk";import{existsSync as At,readFileSync as ul,writeFileSync as Dr,mkdirSync as Pr}from"fs";import{hostname as Lr}from"os";import{resolve as Vo}from"path";var Mr=new pl().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Vo(o,"agentx.json"),n=Vo(o,".env"),s=Vo(o,".agentx/sessions");if(console.log(),console.log(Be.bold(" agentx init")),console.log(),At(t)&&!e.force){console.log(Be.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Vo(o,"agentx.example.json"),Vo(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(At(c)){r=ul(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Lr().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Lr(),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)),Dr(t,r),console.log(Be.green(" \u2713 Created agentx.json")),At(n)||(Dr(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
26
|
+
`)),console.log(Be.green(" \u2713 Created .env template"))),At(s)||(Pr(s,{recursive:!0}),console.log(Be.green(" \u2713 Created .agentx/sessions/")));let a=Vo(o,".claude");At(a)||(Pr(a,{recursive:!0}),console.log(Be.green(" \u2713 Created .claude/"))),console.log(),console.log(Be.bold(" Next steps:")),console.log(` 1. Edit ${Be.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Be.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Be.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Be.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as hl}from"commander";import Io from"chalk";import{spawn as Fr}from"child_process";import{existsSync as fl}from"fs";import{dirname as yl,resolve as wl}from"path";import{fileURLToPath as bl}from"url";Oe();var qr=new hl().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=lr(),t=e.port?parseInt(e.port,10):$l(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Io.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Io.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Io.bold(` Opening ${n}`)),console.log(),await vl(n).catch(()=>!1))console.log(Io.dim(" Dashboard is already running.")),e.open!==!1&&Ur(n);else{console.log(Io.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=kl(),r=Fr(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Ur(n),await new Promise(a=>r.on("exit",()=>a()))}});function $l(){try{return W().dashboard.port||4202}catch{return 4202}}function kl(){let e=wl(yl(bl(import.meta.url)),"cli.js");return fl(e)?e:process.argv[1]||e}async function vl(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function Ur(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Fr(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Io.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Io.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as xl}from"commander";import ve from"chalk";var Ot=new xl().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ot.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 tn,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(ve.bold(" Token created.")),console.log(),console.log(` id: ${ve.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||ve.dim("never")}`),console.log(),console.log(ve.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${ve.green.bold(s)}`),console.log(),console.log(ve.dim(" Use it via the Authorization header:")),console.log(ve.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Ot.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new tn().list();if(e.length===0){console.log(ve.dim(`
|
|
27
27
|
No tokens issued.
|
|
28
|
-
`));return}console.log();for(let o of e){let t=o.revokedAt?ve.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?ve.red("expired"):ve.green("active");console.log(` ${ve.cyan(o.id)} ${t} ${o.name}`),console.log(ve.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(ve.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ve.red(` ${e.message}`)),process.exit(1)}});Ot.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new
|
|
28
|
+
`));return}console.log();for(let o of e){let t=o.revokedAt?ve.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?ve.red("expired"):ve.green("active");console.log(` ${ve.cyan(o.id)} ${t} ${o.name}`),console.log(ve.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(ve.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ve.red(` ${e.message}`)),process.exit(1)}});Ot.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new tn().revoke(e);o||(console.log(ve.red(` Token ${e} not found.`)),process.exit(1)),console.log(ve.green(`
|
|
29
29
|
\u2713 Revoked ${e} (${o.name})
|
|
30
|
-
`))}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Oe();import{Command as
|
|
31
|
-
Agent "${o.id}" added`)),console.log(
|
|
30
|
+
`))}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Oe();import{Command as Ve}from"commander";import f from"chalk";import Ae from"prompts";import{readFileSync as mo,writeFileSync as Qo,existsSync as ge,mkdirSync as Xe,cpSync as gs,readdirSync as ps}from"fs";import{resolve as J,join as go,dirname as Sl}from"path";import{fileURLToPath as El}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(mo(e,"utf-8"))}function _e(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(f.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(f.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(f.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Co=new Ve().name("agent").description("manage agents \u2014 add, list, remove");Co.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${f.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(f.dim(` workspace: ${t.workspace}`)),n&&console.log(f.dim(` mentions: ${n}`))}console.log()});Co.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Ae([{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:J(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:go(o.workspace,o.id);Xe(J(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-G6KGWPHY.js"),i=s(o.id,n,"19900",(...l)=>{console.log(f.dim(` ${l.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(Sl(El(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Xe(J(t,".claude/skills/wiki"),{recursive:!0}),gs(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await _e(e),console.log(f.green(`
|
|
31
|
+
Agent "${o.id}" added`)),console.log(f.dim(` Workspace: ${t}`)),console.log(f.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Co.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(f.red(` Agent "${e}" not found`));return}delete o.agents[e],await _e(o),console.log(f.green(` Agent "${e}" removed from config (workspace preserved)`))});Co.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=ne(),n=t.agents?.[e];if(n||(console.log(f.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(f.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):f.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":f.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||f.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(f.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(f.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(f.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(f.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(f.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await _e(t),console.log(f.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(f.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var It=new Ve().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");It.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(f.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(f.dim(`
|
|
32
32
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
33
|
-
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)?a.push(process.env[g]?h.green(`${d}:${g}=set`):h.yellow(`${d}:${g}=UNSET`)):d==="auth"&&g==="keyring"?a.push(h.dim("auth:keyring")):d==="sessionDir"&&typeof g=="string"&&a.push(h.dim(`sessionDir:${g}`));let l=Object.entries(i.metadata??{}).map(([d,g])=>`${d}=${g}`).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()});It.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=ne();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-ORSGLVRW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ae({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ae({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Ae({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await Ae({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Ae({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let d={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[p,...f]=u.split("=");p&&(d[p.trim()]=f.join("=").trim())}else if(n){let u=await Ae({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let p of String(u.metadata).split(",")){let[f,...w]=p.split("=");f&&(d[f.trim()]=w.join("=").trim())}}let g={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),g.tokenEnv=a),c==="keyring"&&(g.auth="keyring"),l&&(g.sessionDir=l),Object.keys(g).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:g,metadata:d,enabled:!0}),await Ne(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`))});It.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),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 Ne(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});It.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().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[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)&&!process.env[g]&&l.push(`${d}: env var ${g} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let d of l)console.log(` ${h.dim(d)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Co.addCommand(It);var pn=new Xe().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");pn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();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()});pn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),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 Ae({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 Ae([{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 Ne(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ae([{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 Ae([{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 Ne(e),Ve(J(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 Ae([{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 Ae([{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 Ne(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 Zo=new Xe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Zo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();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()});Zo.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Ae([{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 Ne(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Zo.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await Ne(o),console.log(h.green(` Cron "${e}" enabled`))});Zo.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Ne(o),console.log(h.green(` Cron "${e}" disabled`))});var et=new Xe().name("mesh").description("manage mesh peers \u2014 add, list, remove");et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();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()});et.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Ae([{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 Ne(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});et.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Ne(o),console.log(h.green(` Peer "${e}" removed`)))});et.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();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 Ne(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 jo=new Xe().name("skill").description("manage skills \u2014 add to agent(s), list");jo.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=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(mo(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 Ae({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=J(a.workspace,".claude/skills",s);Ve(c,{recursive:!0}),ge(mo(n,"SKILL.md"))?cs(n,c,{recursive:!0}):n.endsWith(".md")&&cs(n,mo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});jo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?ds(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});jo.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]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find(k=>ge(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=po(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=W()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let d=Object.entries(l.agents||{}),g=o.agent?d.filter(([k])=>k===o.agent):d;if(g.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,p=0,f=0,w=0;for(let[k,b]of g){let x=b.workspace;if(!x||!ge(x)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let A=J(x,".claude/skills",e),v=J(A,"SKILL.md");if(!ge(v)){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||(Ve(A,{recursive:!0}),Qo(v,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let E=po(v,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let T=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Qo(v,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${T} \u2192 v${c}`)}`),p++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${p}, ${f} already current, ${w} skipped.`)),o.dryRun&&(u>0||p>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});jo.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-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let p=ne().agents?.[e.workspace];p||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(p.workspace))}else if(e.allWorkspaces){let u=ne();for(let p of Object.values(u.agents||{}))p?.workspace&&i.push(J(p.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,d]=await Promise.all([n(r),s(r)]),g=t({skills:c,references:l,recipes:d});if(e.json)console.log(JSON.stringify(g.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let p of g)u[p.verdict]++;console.log();for(let p of g){let f=p.verdict==="PASS"?h.green("PASS "):p.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(p.name)}${p.skill?.path?h.dim(` (${p.skill.path})`):""}`);for(let w of p.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(g.some(u=>u.verdict==="FAILING")?1:0)});jo.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=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([d])=>d===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-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-L7C52URW.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(`
|
|
34
|
-
shortlist (lexical -> judged)`));for(let d of l.shortlist.slice(0,6)){let g=d.p===void 0?" - ":d.p.toFixed(2);console.log(
|
|
35
|
-
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Ct=new
|
|
33
|
+
`));return}console.log(),console.log(f.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)?a.push(process.env[g]?f.green(`${d}:${g}=set`):f.yellow(`${d}:${g}=UNSET`)):d==="auth"&&g==="keyring"?a.push(f.dim("auth:keyring")):d==="sessionDir"&&typeof g=="string"&&a.push(f.dim(`sessionDir:${g}`));let l=Object.entries(i.metadata??{}).map(([d,g])=>`${d}=${g}`).join(" ");console.log(` ${r?f.cyan(i.kind.padEnd(14)):f.dim(i.kind.padEnd(14))} ${f.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${f.dim(l)}`),r||console.log(` ${f.dim("(disabled)")}`)}console.log()});It.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=ne();t.agents?.[e]||(console.log(f.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-ORSGLVRW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ae({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(u=>({title:u,value:u}))})).kind||"").trim()),i||(console.log(f.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ae({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(f.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 Ae({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 Ae({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 Ae({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let d={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[u,...h]=p.split("=");u&&(d[u.trim()]=h.join("=").trim())}else if(n){let p=await Ae({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[h,...w]=u.split("=");h&&(d[h.trim()]=w.join("=").trim())}}let g={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(f.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),g.tokenEnv=a),c==="keyring"&&(g.auth="keyring"),l&&(g.sessionDir=l),Object.keys(g).length||(console.log(f.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(f.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:g,metadata:d,enabled:!0}),await _e(t),console.log(f.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(f.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});It.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(f.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(f.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await _e(t),console.log(f.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});It.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(f.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(f.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)&&!process.env[g]&&l.push(`${d}: env var ${g} is unset`);if(l.length){r+=1,console.log(` ${f.red("\u2717")} ${a.kind} "${a.label}"`);for(let d of l)console.log(` ${f.dim(d)}`)}else console.log(` ${f.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Co.addCommand(It);var hn=new Ve().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");hn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(f.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${f.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(f.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(f.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(f.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(f.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(f.dim(" GitLab: disabled"));console.log()});hn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(f.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 Ae({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 Ae([{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(f.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(f.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 _e(e),console.log(f.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ae([{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 Ae([{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 _e(e),Xe(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(f.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(f.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ae([{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 Ae([{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 _e(e),console.log(f.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(f.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(f.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(f.dim(` Secret token: ${s.webhookSecret}`)),console.log(f.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(f.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Zo=new Ve().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Zo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?f.green("\u25CF"):f.dim("\u25CB");console.log(` ${n} ${f.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(f.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(f.dim(" No cron jobs configured")),console.log()});Zo.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Ae([{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 _e(e),console.log(f.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Zo.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(f.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await _e(o),console.log(f.green(` Cron "${e}" enabled`))});Zo.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(f.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await _e(o),console.log(f.green(` Cron "${e}" disabled`))});var et=new Ve().name("mesh").description("manage mesh peers \u2014 add, list, remove");et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(f.dim(" Mesh: disabled"));else{console.log(f.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=f.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=f.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${f.cyan(o.name)} ${f.dim(o.url)} ${t}`)}}console.log()});et.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Ae([{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(f.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(f.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 _e(e),console.log(f.green(` Peer "${o.name}" added`)),console.log()}});et.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await _e(o),console.log(f.green(` Peer "${e}" removed`)))});et.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();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(f.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(f.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(f.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await _e(o),console.log(f.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(f.dim(" Restart the daemon for the new cadence to take effect."))});var jo=new Ve().name("skill").description("manage skills \u2014 add to agent(s), list");jo.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=ne(),n=J(e);if(!ge(n)){console.log(f.red(` Skill not found: ${n}`));return}let s=ge(go(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 Ae({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(f.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);Xe(c,{recursive:!0}),ge(go(n,"SKILL.md"))?gs(n,c,{recursive:!0}):n.endsWith(".md")&&gs(n,go(c,"SKILL.md")),console.log(f.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});jo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?ps(n).filter(i=>!i.startsWith(".")):[];console.log(` ${f.cyan(o)}: ${s.length?s.join(", "):f.dim("(none)")}`)}console.log()});jo.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]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find($=>ge($));if(!i){console.log(f.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(f.dim(` ${$}`));return}let r=mo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=W()}catch($){console.log(f.red(` Can't load agentx.json: ${$.message}`));return}let d=Object.entries(l.agents||{}),g=o.agent?d.filter(([$])=>$===o.agent):d;if(g.length===0){console.log(f.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(f.bold(` Skill sync \u2014 ${e}`)),console.log(f.dim(` Source: ${i}`)),console.log(f.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(f.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,u=0,h=0,w=0;for(let[$,b]of g){let v=b.workspace;if(!v||!ge(v)){console.log(` ${f.yellow("\u2717")} ${$.padEnd(22)} ${f.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=J(v,".claude/skills",e),x=J(A,"SKILL.md");if(!ge(x)){if(!o.allWorkspaces){console.log(` ${f.dim("\xB7")} ${$.padEnd(22)} ${f.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Xe(A,{recursive:!0}),Qo(x,r)),console.log(` ${f.green("+")} ${$.padEnd(22)} ${f.dim("\u2192 seeded v"+c)}`),p++;continue}let E=mo(x,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${f.dim("=")} ${$.padEnd(22)} ${f.dim("up to date (v"+c+")")}`),h++;continue}let T=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Qo(x,r),console.log(` ${f.yellow("\u21BB")} ${$.padEnd(22)} ${f.dim(`v${T} \u2192 v${c}`)}`),u++}console.log();let y=o.dryRun?"would":"did";console.log(f.dim(` Summary: ${y} seed ${p}, ${y} update ${u}, ${h} already current, ${w} skipped.`)),o.dryRun&&(p>0||u>0)&&console.log(f.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});jo.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-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let u=ne().agents?.[e.workspace];u||(console.log(f.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(u.workspace))}else if(e.allWorkspaces){let p=ne();for(let u of Object.values(p.agents||{}))u?.workspace&&i.push(J(u.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,d]=await Promise.all([n(r),s(r)]),g=t({skills:c,references:l,recipes:d});if(e.json)console.log(JSON.stringify(g.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 g)p[u.verdict]++;console.log();for(let u of g){let h=u.verdict==="PASS"?f.green("PASS "):u.verdict==="REVIEW"?f.yellow("REVIEW "):f.red("FAILING");console.log(` ${h} ${f.bold(u.name)}${u.skill?.path?f.dim(` (${u.skill.path})`):""}`);for(let w of u.reasons)console.log(` ${f.dim("\xB7")} ${w}`)}console.log(),console.log(` ${f.green(`${p.PASS} PASS`)} ${f.yellow(`${p.REVIEW} REVIEW`)} ${f.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(g.some(p=>p.verdict==="FAILING")?1:0)});jo.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=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([d])=>d===o.agent)??[]:n[0]??[];i||(console.log(f.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-SOJYFAMI.js"),c=await r(i.workspace);if(c.length===0){console.log(f.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(` ${f.green("\u2192")} ${f.bold(l.skill.frontmatter.name)} ${f.dim(`\xB7 ${l.reason}`)}`),console.log(` ${f.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${f.yellow("\xB7")} no skill for this ${f.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(f.dim(`
|
|
34
|
+
shortlist (lexical -> judged)`));for(let d of l.shortlist.slice(0,6)){let g=d.p===void 0?" - ":d.p.toFixed(2);console.log(f.dim(` ${d.lexical.toFixed(2)} -> ${g} ${d.name}`))}}l.judged||console.log(f.dim(`
|
|
35
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Ct=new Ve().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Ct.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(f.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(f.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");Xe(i,{recursive:!0}),Xe(r,{recursive:!0});let a=ps(n).filter(g=>g.endsWith(".yaml")||g.endsWith(".yml")),c=0,l=0;for(let g of a){let p=go(i,g);if(ge(p)&&!o.force){console.log(f.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let h=mo(go(n,g),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Qo(p,h),console.log(f.green(` + ${p}`)),c++}let d=go(r,`${e}.yaml`);if(ge(d)&&!o.force)console.log(f.dim(` skip ${d} (exists; --force to overwrite)`)),l++;else if(ge(s)){let g=mo(s,"utf-8").replaceAll("example.",`${e}.`);Qo(d,g),console.log(f.green(` + ${d}`)),c++}console.log(),console.log(f.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(f.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(f.dim(" 2. agentx skill audit # verify references resolve")),console.log(f.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Ct.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(f.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(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(f.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(f.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(f.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 d=s(c,e),g=J(o.referencesCwd||o.cwd),p=J(g,".agentx/references",e);if(!o.write){console.log(),console.log(f.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(d))console.log(f.cyan(`
|
|
36
36
|
--- ${w} ---`)),console.log(y.split(`
|
|
37
|
-
`).slice(0,30).map(
|
|
37
|
+
`).slice(0,30).map($=>` ${$}`).join(`
|
|
38
38
|
`)),y.split(`
|
|
39
|
-
`).length>30&&console.log(
|
|
40
|
-
`).length-30} more lines truncated in preview)`));console.log(),console.log(
|
|
41
|
-
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await
|
|
42
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var
|
|
39
|
+
`).length>30&&console.log(f.dim(` \u2026 (${y.split(`
|
|
40
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(f.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}Xe(p,{recursive:!0});let u=0,h=0;for(let[w,y]of Object.entries(d)){let $=go(p,w);if(ge($)&&!o.force){console.log(f.dim(` skip ${$} (exists; --force to overwrite)`)),h++;continue}Qo($,y),console.log(f.green(` + ${$}`)),u++}console.log(),console.log(f.dim(` ${u} written, ${h} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(f.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Ct.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-4ZGTK7LD.js"),t=await o(J(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(f.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(` ${f.cyan(s.id)} ${f.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(f.dim(` ${i}`))}console.log(),console.log(f.dim(` ${n.length} reference(s) loaded.`)),console.log()});var us=new Ve().name("hook").description("manage hooks \u2014 add to agent workspace");us.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(f.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(mo(n,"utf-8")):{},i=await Ae([{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),Xe(J(t.workspace,".claude"),{recursive:!0}),Qo(n,JSON.stringify(s,null,2)),console.log(f.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var hs=new Ve().name("migrate").description("import configuration from OpenClaw or other tools");hs.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,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let u of t)if(u&&ge(u)){n=u;break}if(!n){console.log(f.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(f.dim(` Reading: ${n}`));let s=JSON.parse(mo(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{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 u of a)u.match?.channel==="telegram"&&(c[u.match.accountId]=u.agentId);r.find(u=>u.id==="main"||u.default)&&(c.default="main");let l=0;for(let u of r){if(u.workspace?.startsWith("/data"))continue;let h=u.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=u.groupChat?.mentionPatterns||[];if(w.some(y=>y===h)||w.push(h),i.agents[h]={name:u.name,workspace:u.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:u.id==="main"?2:1,systemPrompt:`You are ${u.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){Xe(J(u.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(h,i.agents[h])}}console.log(` ${f.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let d=s.channels?.telegram?.accounts||{},g=0;for(let[u,h]of Object.entries(d)){if(!h.botToken)continue;let y=c[u]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[u]={token:h.botToken,agentBinding:y},i.channels.telegram.enabled=!0,g++}console.log(` ${f.green(g)} Telegram accounts imported`);let p=J(n,"../cron/jobs.json");if(ge(p)){let u=JSON.parse(mo(p,"utf-8")),h=0;for(let w of u.jobs||[]){let y=w.name||w.id,$=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:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},h++}console.log(` ${f.green(h)} cron jobs imported`)}o.dryRun?(console.log(f.yellow(`
|
|
41
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await _e(i),console.log(f.green(`
|
|
42
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var po=new Ve().name("config").description("validate and inspect configuration");po.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=W(e.config);console.log(f.green(" \u2713 Config valid")),console.log(f.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(f.dim(` Bind: ${o.node.bind}`)),console.log(f.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(f.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(f.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(f.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(f.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Vt(o);if(n.length){console.log(),console.log(f.yellow(" Warnings:"));for(let s of n)console.log(f.yellow(` \u26A0 ${s}`))}else console.log(f.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),l=ge(J(r,".claude/settings.json")),d=ge(J(r,".claude/skills"))?ps(J(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,g=[a?f.green("\u2713"):f.red("\u2717"),".claude",c?f.green("\u2713"):f.yellow("\u25CB"),"CLAUDE.md",l?f.green("\u2713"):f.yellow("\u25CB"),"settings",`${d} skills`];console.log(` ${f.cyan(s)}: ${g.join(" ")}`)}}catch(o){console.log(f.red(` \u2717 ${o.message}`))}console.log()});po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=W(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(f.red(o.message))}});function Al(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 ms(e){return e===void 0?f.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}po.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-JB3S2E7H.js"),{expandEnvVars:r}=await import("./config-ORSGLVRW.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(f.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),d=i(l,e);o.json?console.log(JSON.stringify(d)):console.log(ms(d))});po.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-JB3S2E7H.js"),r=Al(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(f.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(f.yellow(` (dry-run) ${f.cyan(e)} would become: ${ms(c)}`)):(console.log(f.green(` \u2713 ${f.cyan(e)} = ${ms(c)}`)),a.reloaded?console.log(f.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(f.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});po.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-JB3S2E7H.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(f.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(f.dim(` (no-op) ${f.cyan(e)} was not set`));return}o.dryRun?console.log(f.yellow(` (dry-run) ${f.cyan(e)} would be removed`)):(console.log(f.green(` \u2713 ${f.cyan(e)} removed`)),i.reloaded&&console.log(f.dim(" Daemon hot-reloaded.")))});po.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 g=W(e.config);o=!!g.business?.enabled,t=(g.business?.projects??[]).length}catch(g){n=g?.message??String(g)}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(f.bold(" Governance flags")),console.log(),n&&(console.log(f.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?f.green:s==="shadow"?f.cyan:s==="off"?f.dim:f.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":f.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let d=a?f.green("active"):r?f.yellow("env=true but business.enabled=false \u2192 inactive"):f.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${d}`),console.log(f.dim(` business.enabled ${o?f.green("true"):f.dim("false")}`)),console.log(f.dim(` business.projects[] ${t}`)),console.log(),console.log(f.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(f.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Ol}from"commander";import uo from"chalk";import{resolve as ho}from"path";import{existsSync as Il}from"fs";var so=new Ol().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ro(e){let o=ho(e,".agentx/db.sqlite");Il(o)||(console.log(uo.red(` No SQLite at ${o}`)),console.log(uo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Ni({path:o});return t||(console.log(uo.red(` Could not open ${o}`)),console.log(uo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function To(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(uo.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])))}so.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=Ro(ho(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=`
|
|
43
43
|
SELECT agent_id, channel, status, duration_ms,
|
|
44
44
|
input_tokens, output_tokens,
|
|
45
45
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -90,12 +90,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
90
90
|
WHERE ${t.join(" AND ")}
|
|
91
91
|
ORDER BY started_at DESC
|
|
92
92
|
LIMIT @limit
|
|
93
|
-
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});To(i,!!e.json)});so.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(ho(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}));To(n,!!e.json)});so.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=Ro(ho(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(
|
|
93
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});To(i,!!e.json)});so.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(ho(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}));To(n,!!e.json)});so.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=Ro(ho(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(uo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(uo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();To(n,!!o.json)}catch(n){console.log(uo.red(` ${n.message}`)),process.exit(1)}});import{Command as Rl}from"commander";import G from"chalk";import{mkdtempSync as Tl}from"fs";import{tmpdir as Nl}from"os";import{resolve as Br,join as Jr}from"path";import{existsSync as _l}from"fs";import Dl from"better-sqlite3";function Wr(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(h){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${h?.message??h}`})}continue}let l=c.decision,d=s.get(l.eventId);if(!d){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 g=Cl(l),p={id:d.id,ts:d.ts,source:d.source,sourceEventId:d.sourceEventId,project:d.project,subject:d.subject,intent:d.intent,rawJson:d.rawJson},u=Ti(e,p,g,()=>l.decidedAt);a+=1,(u.outcome!==l.outcome||u.agentId!==l.agentId)&&r.push({eventId:d.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:u.agentId,outcome:u.outcome},reason:jl(l,u)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Cl(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function jl(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 fo=new Rl().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function ot(e){let o=Br(e.cwd??process.cwd()),t=Br(o,e.path??".agentx/intent/ledger.sqlite");_l(t)||(console.log(G.red(` No ledger at ${t}`)),console.log(G.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 Dl(t,{readonly:!0})}catch(n){console.log(G.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(G.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function No(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(G.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 Pl(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 fn(e){if(!e)return;let o=Pl(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(G.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}fo.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=ot(e),t=fn(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,d=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),g=o.prepare(`
|
|
94
94
|
SELECT COUNT(*) as n FROM intent_decisions d
|
|
95
95
|
LEFT JOIN intent_resolutions r
|
|
96
96
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
97
97
|
WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
|
|
98
|
-
`).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:d,inFlight:g},null,2));return}console.log(G.bold("Events by source")),No(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),No(c,!1),console.log(),console.log(G.bold(`Divergences: ${l}`)),No(d,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${g}`))});
|
|
98
|
+
`).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:d,inFlight:g},null,2));return}console.log(G.bold("Events by source")),No(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),No(c,!1),console.log(),console.log(G.bold(`Divergences: ${l}`)),No(d,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${g}`))});fo.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=ot(e),t=fn(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(`
|
|
99
99
|
SELECT
|
|
100
100
|
datetime(ts/1000, 'unixepoch') AS at,
|
|
101
101
|
source,
|
|
@@ -109,7 +109,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
109
109
|
${i}
|
|
110
110
|
ORDER BY ts DESC
|
|
111
111
|
LIMIT @limit
|
|
112
|
-
`).all(s);No(r,!!e.json)});
|
|
112
|
+
`).all(s);No(r,!!e.json)});fo.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=ot(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(`
|
|
113
113
|
SELECT
|
|
114
114
|
datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
|
|
115
115
|
e.source,
|
|
@@ -125,7 +125,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
125
125
|
WHERE ${t.join(" AND ")}
|
|
126
126
|
ORDER BY d.decided_at DESC
|
|
127
127
|
LIMIT @limit
|
|
128
|
-
`).all(n);No(s,!!e.json)});
|
|
128
|
+
`).all(n);No(s,!!e.json)});fo.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=ot(e),t=fn(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(`
|
|
129
129
|
SELECT
|
|
130
130
|
datetime(ts/1000, 'unixepoch') AS at,
|
|
131
131
|
source,
|
|
@@ -136,8 +136,8 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
136
136
|
${i}
|
|
137
137
|
ORDER BY ts DESC
|
|
138
138
|
LIMIT @limit
|
|
139
|
-
`).all(s);No(r,!!e.json)});
|
|
140
|
-
FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.dim(` (no events for ${n}:${s})`));return}let r=i.map(g=>g.id),a=r.map((g,
|
|
139
|
+
`).all(s);No(r,!!e.json)});fo.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=ot(o),n=null,s=null;if(o.bySubject){let g=e.indexOf(":");g<0&&(console.log(G.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,g),s=e.slice(g+1)}else{let g=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);g||(console.log(G.red(` no event with id ${e}`)),process.exit(1)),n=g.project,s=g.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.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
|
|
140
|
+
FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.dim(` (no events for ${n}:${s})`));return}let r=i.map(g=>g.id),a=r.map((g,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((g,p)=>[`id${p}`,g])),l=t.prepare(`
|
|
141
141
|
SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
|
|
142
142
|
r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
|
|
143
143
|
FROM intent_decisions d
|
|
@@ -145,21 +145,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
145
145
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
146
146
|
WHERE d.event_id IN (${a})
|
|
147
147
|
ORDER BY d.decided_at ASC
|
|
148
|
-
`).all(c);if(o.json){let g=i.map(
|
|
148
|
+
`).all(c);if(o.json){let g=i.map(p=>({event:p,decisions:l.filter(u=>u.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:g},null,2));return}let d=new Set;for(let g of l)g.outcome==="dispatched"&&g.agent_id&&d.add(g.agent_id);console.log(),console.log(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.dim(` ${i.length} event(s), ${l.length} decision(s), ${d.size} distinct agent(s) dispatched`)),console.log();for(let g of i){let p=new Date(g.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${G.dim(p)} ${G.bold(g.id)} ${G.dim(`(${g.source}/${g.intent})`)}`);let u=l.filter(h=>h.event_id===g.id);if(u.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let h of u){let w=h.outcome==="dispatched"?G.green(h.outcome):h.outcome==="dropped"?G.dim(h.outcome):G.yellow(h.outcome),y=h.agent_id?G.cyan(h.agent_id):G.dim("-"),$=h.reason?G.dim(` \u2014 ${h.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(h.decided_by)} \u2192 ${w} ${y}${$}`),h.resolution_status){let b=h.resolution_status==="ok"?G.green(h.resolution_status):G.red(h.resolution_status),v=h.duration_ms?`${(h.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(v)}`)}else h.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});fo.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=ot(e),t=fn(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(`
|
|
149
149
|
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
150
150
|
FROM intent_events
|
|
151
151
|
${n.length?"WHERE "+n.join(" AND "):""}
|
|
152
152
|
ORDER BY ts ASC
|
|
153
153
|
${i}
|
|
154
|
-
`).all(s).map(
|
|
154
|
+
`).all(s).map(h=>({id:h.id,ts:h.ts,source:h.source,sourceEventId:h.source_event_id,project:h.project,subject:h.subject,intent:h.intent,rawJson:h.raw_json}));if(r.length===0){console.log(G.dim(" (no events match filter)"));return}let a=new Set(r.map(h=>h.id)),c=r.map((h,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((h,w)=>[`id${w}`,h.id])),d=o.prepare(`
|
|
155
155
|
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
156
156
|
FROM intent_decisions
|
|
157
157
|
WHERE event_id IN (${c})
|
|
158
|
-
`).all(l).map(
|
|
158
|
+
`).all(l).map(h=>({eventId:h.event_id,decidedAt:h.decided_at,decidedBy:h.decided_by,agentId:h.agent_id,outcome:h.outcome,reason:h.reason})),g=o.prepare(`
|
|
159
159
|
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
160
160
|
FROM intent_resolutions
|
|
161
161
|
WHERE decision_event_id IN (${c})
|
|
162
|
-
`).all(l).map(
|
|
162
|
+
`).all(l).map(h=>({decisionEventId:h.decision_event_id,decisionDecidedBy:h.decision_decided_by,resolvedAt:h.resolved_at,status:h.status,durationMs:h.duration_ms,resultSummary:h.result_summary})),p=Tl(Jr(Nl(),"agentx-ledger-replay-")),u=new Ei({path:Jr(p,"target.sqlite")});try{let h=Wr(u,r,d,g);if(e.json){console.log(JSON.stringify(h,null,2));return}console.log(G.bold(`Replayed ${h.eventsCount} events, ${h.decisionsCount} decisions, ${g.length} resolutions`)),h.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${h.divergences.length} divergences`)),No(h.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{u.close()}});mi();Uc();Fc();qc();Mc();$i();wt();import{Command as Ll}from"commander";import U from"chalk";import{existsSync as Hr}from"fs";import{resolve as fs}from"path";import Ml from"better-sqlite3";var De=new Ll().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Je=".agentx/decisions/decisions.sqlite";function Ul(e){return fs(fs(e.cwd??process.cwd()),e.path??Je)}function Ze(e,o=!1){let t=Ul(e);Hr(t)||(console.log(U.red(` No decision store at ${t}`)),console.log(U.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 Xt({path:t,readonly:!o})}catch(n){console.log(U.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(U.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Qe(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(U.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(U.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function ys(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 ws(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:ys(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}De.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Je).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=Ze(e),t=ys(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
|
|
163
163
|
COUNT(*) AS calls,
|
|
164
164
|
SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
|
|
165
165
|
SUM(retries) AS retries,
|
|
@@ -174,11 +174,11 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
174
174
|
ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(U.bold(`
|
|
175
175
|
policy`)),Qe(s,!1),console.log(U.dim(`
|
|
176
176
|
explored=1 means the policy wanted to skip and the expensive path ran anyway.
|
|
177
|
-
Those are the only rows in the skip region that can ever be graded.`))),o.close()});
|
|
177
|
+
Those are the only rows in the skip region that can ever be graded.`))),o.close()});De.command("calls").description("recent calls").option("--path <file>","store path",Je).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ze(e),t=["ts >= ?"],n=[ys(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,
|
|
178
178
|
structure_mode AS structure, latency_ms AS ms, retries, truncated, error
|
|
179
179
|
FROM decision_calls WHERE ${t.join(" AND ")}
|
|
180
|
-
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Qe(s,e.json),o.close()});
|
|
181
|
-
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});
|
|
180
|
+
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Qe(s,e.json),o.close()});De.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Je).option("--json").action((e,o)=>{let t=Ze(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(U.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}Qe(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()});De.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Je).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=Ze(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(U.green(` labeled ${e}.${o} = ${t}`)),s.close()});De.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Je).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ze(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));Qe(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});De.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Je).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=Ze(e,!0),t=fs(process.cwd(),e.db);Hr(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Ml(t,{readonly:!0});try{let s=Ui(n,o);console.log(U.green(` wrote ${s} label(s)`)),s===0&&console.log(U.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
|
|
181
|
+
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});De.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows(ws(e)),n=fi(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(U.bold(`
|
|
182
182
|
${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(U.yellow(`
|
|
183
183
|
Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(U.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(U.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
|
|
184
184
|
accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+U.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${U.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${U.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${U.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
|
|
@@ -186,21 +186,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
186
186
|
skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(U.yellow(` Nothing in the skip region has been graded. Everything below describes
|
|
187
187
|
only the decisions this policy chose NOT to skip \u2014 it cannot tell you
|
|
188
188
|
what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
|
|
189
|
-
reliability (equal-width bins)`)),Qe(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()});
|
|
189
|
+
reliability (equal-width bins)`)),Qe(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()});De.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows(ws(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=yi(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(U.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(U.bold(`
|
|
190
190
|
${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(U.dim(` Cross-validated, because more parameters always fit training data better.
|
|
191
191
|
`)),Qe(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(U.green(`
|
|
192
192
|
Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(U.dim(" that need different corrections."))):s.best==="temperature"?console.log(U.dim(`
|
|
193
193
|
One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(U.dim(`
|
|
194
|
-
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});
|
|
194
|
+
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});De.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows({...ws(e),labeledOnly:!0}),n=hi(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}Qe(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()});De.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Je).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=>{Wo();let o=Ze(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
|
|
195
195
|
WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
|
|
196
196
|
${e.call?"AND id = ?":""}
|
|
197
|
-
ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.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
|
|
197
|
+
ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.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 wi(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(U.bold(`
|
|
198
198
|
${e.seat} on ${i.backend} (${i.model})`)),console.log(U.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
|
|
199
199
|
`)),Qe(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?U.red("NO"):"yes"})),!1),console.log(`
|
|
200
200
|
mean stdev ${i.meanStdev.toFixed(4)}`),console.log(U.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(U.red(`
|
|
201
201
|
Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(U.dim(` not merely by how much. Usually a compound question: one name, several questions.
|
|
202
202
|
Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(U.green(`
|
|
203
|
-
Every question held its decision across all samples.`)),console.log(U.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()});
|
|
203
|
+
Every question held its decision across all samples.`)),console.log(U.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()});De.command("backends").description("registered decision backends and what they claim").action(()=>{Wo();let e=gi().map(o=>{let t=Kn(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});Qe(e,!1),console.log(U.dim(`
|
|
204
204
|
source where the numbers come from. "verbalized" means the model wrote them
|
|
205
205
|
into its answer; "logits" means they were read off its next-token
|
|
206
206
|
distribution. Logits are the model's actual posterior \u2014 verbalized
|
|
@@ -208,15 +208,15 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
208
208
|
calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
|
|
209
209
|
traffic. Reading real logits does not buy this: a posterior can be
|
|
210
210
|
confidently wrong. It comes from a recalibrator fitted on your own
|
|
211
|
-
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});
|
|
211
|
+
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});De.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=>{Wo();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=qo(s,"Which option fits this state?")}e.noul&&(o.verdict=to(String(e.noul))),Object.keys(o).length===0&&(console.log(U.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Kn(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Fl}from"commander";import I from"chalk";import{resolve as Gr}from"path";import{existsSync as ql}from"fs";import Wl from"better-sqlite3";var jt=new Fl().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function $s(e){let o=Gr(e.cwd??process.cwd()),t=Gr(o,e.path??".agentx/db.sqlite");ql(t)||(console.log(I.red(` No db at ${t}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Wl(t,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Bl(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 Jl(e){if(!e)return;let o=Bl(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Hl(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 bs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}jt.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=$s(e),t=_i(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Jl(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(I.dim(" (no traces)"));return}for(let n of t){let s=bs(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim(Hl(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});jt.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=$s(o),n=Zn(t,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Gl(n.task,n.steps)});function Gl(e,o){let t=bs(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?bs(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
212
212
|
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
|
|
213
213
|
`)),n.inputSummary.split(`
|
|
214
214
|
`).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
215
215
|
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
|
|
216
216
|
`)),n.outputSummary.split(`
|
|
217
|
-
`).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}jt.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
|
|
218
|
-
error: ${g.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function
|
|
219
|
-
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as
|
|
217
|
+
`).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}jt.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=$s(o),n=Zn(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.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(),d;try{d=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(u){console.log(I.red(` daemon unreachable at ${a}: ${u.message||u}`)),process.exit(1)}let g=await d.json().catch(()=>({})),p=Date.now()-l;if(d.ok||(console.log(I.red(` replay failed (${d.status}): ${g.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),yn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?yn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${g.error?"error":"ok"} ${p}ms tokens=in:${g.usage?.inputTokens??0}/out:${g.usage?.outputTokens??0}`)}`)),console.log(),yn(g.content??"(empty reply)"),g.error&&console.log(I.red(` error: ${g.error}`)),console.log();let u=(s.finalResponse??"").trim()===(g.content??"").trim();s.finalResponse&&(console.log(u?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${p}ms`)),console.log(),yn(g.content??"(empty reply)"),g.error&&console.log(I.red(`
|
|
218
|
+
error: ${g.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function yn(e){let o=e.split(`
|
|
219
|
+
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Xl}from"commander";import ce from"chalk";import{existsSync as Vl,mkdirSync as Ql,writeFileSync as Zl}from"fs";import{resolve as Kr,join as Yr,dirname as ed}from"path";var zl=`# AgentX destructive-action guardrails \u2014 global policy
|
|
220
220
|
#
|
|
221
221
|
# This file + environments/*.yaml + agents/<id>.yaml are deep-merged
|
|
222
222
|
# (most specific wins). The built-in catalog (prisma / rm -rf / docker /
|
|
@@ -242,7 +242,7 @@ defaults:
|
|
|
242
242
|
# action: escalate
|
|
243
243
|
# severity: high
|
|
244
244
|
rules: []
|
|
245
|
-
`,
|
|
245
|
+
`,Yl=`# Production protected resources.
|
|
246
246
|
#
|
|
247
247
|
# The catalog rules reference \`target_in: production\`, so DECLARING this set is
|
|
248
248
|
# what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
|
|
@@ -264,7 +264,7 @@ protected_resources:
|
|
|
264
264
|
|
|
265
265
|
# Production-only rules beyond the catalog:
|
|
266
266
|
rules: []
|
|
267
|
-
`,
|
|
267
|
+
`,Kl=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
|
|
268
268
|
# this agent (the filename names it). coder agents never touch production.
|
|
269
269
|
rules:
|
|
270
270
|
- id: coder-no-prod
|
|
@@ -273,7 +273,7 @@ rules:
|
|
|
273
273
|
action: deny
|
|
274
274
|
severity: critical
|
|
275
275
|
message: "coder-agent is not permitted to run commands against production."
|
|
276
|
-
`,Jr=[{relPath:"policy.yaml",content:Hl},{relPath:"environments/production.yaml",content:Gl},{relPath:"agents/coder-agent.yaml",content:zl}];var wo=new Yl().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function ws(e){return e==="deny"?ae.red:e==="escalate"||e==="ask"?ae.yellow:e==="warn"?ae.magenta:ae.green}function hn(e){return e.root?Gr(e.root):er()}wo.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 Zi({root:hn(e),agentId:e.agent,env:e.env}),process.exit(0)});wo.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=hn(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Qi({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}Zl(s,i,r)});function Zl(e,o,t){let n=ws(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ae.dim(" (no rule matched)")}`),console.log(` enforced as ${ws(e.effectiveAction)(e.effectiveAction)} ${ae.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ae.cyan(e.ruleId)}${e.severity?ae.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ae.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ae.dim(`evaluated in ${t}ms`)}`),console.log()}wo.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=Xi({root:hn(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(ae.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=ws(t.verdict),i=t.effective_action!==t.verdict?ae.dim(`->${t.effective_action}`):"";console.log(` ${ae.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ae.cyan((t.agent_id??"?").padEnd(16))} ${ae.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ae.dim(` target: ${t.resolved_target}`))}});wo.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=Hr(Gr(e.root),Ki),t=0;for(let n of Jr){let s=Hr(o,n.relPath);if(Kl(s)&&!e.force){console.log(ae.dim(` skip (exists) ${n.relPath}`));continue}Vl(Ql(s),{recursive:!0}),Xl(s,n.content),console.log(ae.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ae.cyan(o)}`),console.log(ae.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ae.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});wo.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(ae.green(` daemon reloaded (${e.url})`)):console.log(ae.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ae.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});wo.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=Vi(hn(e),e.agent);console.log(JSON.stringify(o,null,2))});bt();import{Command as ad}from"commander";import{execFile as cd}from"child_process";import{promisify as ld}from"util";import{existsSync as dd}from"fs";import He from"chalk";wt();var Tt="ui-element";function yn(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:Rt(t.tried,80),screenChanged:t.changed,note:t.note?Rt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:zr(t.role),label:Rt(t.label,120),value:t.value?Rt(t.value,80):null,enabled:t.enabled}))}}function wn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${zr(t.role)}: ${Rt(n,80)}`}return{target:qo(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:to("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 bn(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 zr(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Rt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{homedir as td}from"node:os";import{execFile as nd}from"child_process";import{promisify as sd}from"util";import{existsSync as id}from"fs";var ed=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText)/;function od(e){let o=new Map(e.map(i=>[i.id,i])),t=new Set(e.filter(i=>i.role==="AXWebArea").map(i=>i.id));if(t.size===0)return e;let n=i=>{let r=i;for(let a=0;r&&a<64;a++){if(t.has(r.id))return!0;if(r.parent<0)return!1;r=o.get(r.parent)}return!1},s=e.filter(n);return s.length>=2?s:e}function Yr(e,o=60){let t=n=>/^AX(TextField|TextArea|SearchField|ComboBox)/.test(n)?0:/^AX(Button|MenuItem|MenuButton|PopUpButton|CheckBox|RadioButton|Tab|Link)/.test(n)?1:/^AX(Row|Cell|Slider|Disclosure|Toolbar)/.test(n)?2:3;return od(e).filter(n=>ed.test(n.role)).filter(n=>n.width>=1&&n.height>=1).map((n,s)=>({e:n,i:s})).sort((n,s)=>t(n.e.role)-t(s.e.role)||n.i-s.i).map(({e:n})=>n).slice(0,o).map((n,s)=>({id:n.id,role:n.role,label:(n.label||n.value||"").trim()||`${n.role.replace(/^AX/,"")} ${s+1}`,value:n.value??null,enabled:n.enabled}))}var Kr=sd(nd),xe=br(process.cwd(),td(),process.env.AGENTX_MAC_HELPER),rd=6;async function $n(e={}){if(!id(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:o}=await Kr(xe,["read","--max","400"]),t=JSON.parse(o),n=Yr(t.elements,e.max??60),s=new Map;if(!(e.ocr!==!1&&n.length<rd))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:r}=await Kr(xe,["ocr"],{maxBuffer:8388608}),a=JSON.parse(r),c=Math.max(0,...t.elements.map(d=>d.id))+1,l=[];for(let d of a.hits){if(d.confidence<.5||d.text.length<2)continue;let g=c++;if(s.set(g,{x:d.x,y:d.y,width:d.width,height:d.height}),l.push({id:g,role:"OCRText",label:d.text,value:null,enabled:!0}),l.length>=(e.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...l],elements:t.elements,usedOCR:l.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function Nt(e,o){let t=e.elements.find(n=>n.id===o);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:e.ocrRects.get(o)??null}var Vr=ld(cd),Xr=new ad().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)=>{dd(xe)||(console.log(He.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await $n({max:Number(o.max)||40})}catch(g){console.log(He.red(` could not read the screen: ${g?.message??g}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(He.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let g=Nt(t,n[0].id);g&&(console.log(He.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+He.bold(n[0].label)),await Vr(xe,["point","--x",String(g.x),"--y",String(g.y),"--w",String(g.width),"--h",String(g.height),"--label",n[0].label]));return}let s=await Ye(Tt,yn({request:e,app:t.app,window:t.window,candidates:n}),wn(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(He.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Tt}.mode`)),process.exit(1));let i=bn(s.answers,n),r=Nt(t,i.id),a=n.find(g=>g.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(He.yellow(` nothing on screen matches "${e}"`)+He.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(g=>({...g,label:n.find(u=>u.id===g.id)?.label}))},null,2));return}let d=a;console.log(` ${He.green("\u2192")} ${He.bold(d)} `+He.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Vr(xe,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",d])});import{Command as Pd}from"commander";import De from"chalk";import{execFile as gd}from"child_process";import{promisify as md}from"util";import{existsSync as pd,readFileSync as bs}from"fs";import{homedir as ud,tmpdir as fd}from"os";import{join as Qr}from"path";var hd=md(gd),Zr=12e5,yd="https://openrouter.ai/api/v1/chat/completions",wd=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function bd(e={kind:"window"},o=Zr){if(!pd(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Qr(fd(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let{stdout:s}=await hd(xe,n),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=bs(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var $d=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
276
|
+
`,zr=[{relPath:"policy.yaml",content:zl},{relPath:"environments/production.yaml",content:Yl},{relPath:"agents/coder-agent.yaml",content:Kl}];var yo=new Xl().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function ks(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function wn(e){return e.root?Kr(e.root):nr()}yo.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 tr({root:wn(e),agentId:e.agent,env:e.env}),process.exit(0)});yo.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=wn(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=or({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}od(s,i,r)});function od(e,o,t){let n=ks(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${ks(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}yo.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=er({root:wn(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(ce.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=ks(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});yo.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=Yr(Kr(e.root),Qi),t=0;for(let n of zr){let s=Yr(o,n.relPath);if(Vl(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}Ql(ed(s),{recursive:!0}),Zl(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});yo.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(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});yo.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=Zi(wn(e),e.agent);console.log(JSON.stringify(o,null,2))});bt();import{Command as ld}from"commander";import{execFile as dd}from"child_process";import{promisify as gd}from"util";import{existsSync as md}from"fs";import He from"chalk";wt();var Tt="ui-element";function bn(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:Rt(t.tried,80),screenChanged:t.changed,note:t.note?Rt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Xr(t.role),label:Rt(t.label,120),value:t.value?Rt(t.value,80):null,enabled:t.enabled}))}}function $n(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Xr(t.role)}: ${Rt(n,80)}`}return{target:qo(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:to("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 kn(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 Xr(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Rt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{homedir as sd}from"node:os";import{execFile as id}from"child_process";import{promisify as rd}from"util";import{existsSync as ad}from"fs";var td=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText)/;function nd(e){let o=new Map(e.map(i=>[i.id,i])),t=new Set(e.filter(i=>i.role==="AXWebArea").map(i=>i.id));if(t.size===0)return e;let n=i=>{let r=i;for(let a=0;r&&a<64;a++){if(t.has(r.id))return!0;if(r.parent<0)return!1;r=o.get(r.parent)}return!1},s=e.filter(n);return s.length>=2?s:e}function Vr(e,o=60){let t=n=>/^AX(TextField|TextArea|SearchField|ComboBox)/.test(n)?0:/^AX(Button|MenuItem|MenuButton|PopUpButton|CheckBox|RadioButton|Tab|Link)/.test(n)?1:/^AX(Row|Cell|Slider|Disclosure|Toolbar)/.test(n)?2:3;return nd(e).filter(n=>td.test(n.role)).filter(n=>n.width>=1&&n.height>=1).map((n,s)=>({e:n,i:s})).sort((n,s)=>t(n.e.role)-t(s.e.role)||n.i-s.i).map(({e:n})=>n).slice(0,o).map((n,s)=>({id:n.id,role:n.role,label:(n.label||n.value||"").trim()||`${n.role.replace(/^AX/,"")} ${s+1}`,value:n.value??null,enabled:n.enabled}))}var Qr=rd(id),xe=vr(process.cwd(),sd(),process.env.AGENTX_MAC_HELPER),cd=6;async function vn(e={}){if(!ad(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:o}=await Qr(xe,["read","--max","400"]),t=JSON.parse(o),n=Vr(t.elements,e.max??60),s=new Map;if(!(e.ocr!==!1&&n.length<cd))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:r}=await Qr(xe,["ocr"],{maxBuffer:8388608}),a=JSON.parse(r),c=Math.max(0,...t.elements.map(d=>d.id))+1,l=[];for(let d of a.hits){if(d.confidence<.5||d.text.length<2)continue;let g=c++;if(s.set(g,{x:d.x,y:d.y,width:d.width,height:d.height}),l.push({id:g,role:"OCRText",label:d.text,value:null,enabled:!0}),l.length>=(e.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...l],elements:t.elements,usedOCR:l.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function Nt(e,o){let t=e.elements.find(n=>n.id===o);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:e.ocrRects.get(o)??null}var Zr=gd(dd),ea=new ld().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)=>{md(xe)||(console.log(He.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await vn({max:Number(o.max)||40})}catch(g){console.log(He.red(` could not read the screen: ${g?.message??g}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(He.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let g=Nt(t,n[0].id);g&&(console.log(He.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+He.bold(n[0].label)),await Zr(xe,["point","--x",String(g.x),"--y",String(g.y),"--w",String(g.width),"--h",String(g.height),"--label",n[0].label]));return}let s=await Ye(Tt,bn({request:e,app:t.app,window:t.window,candidates:n}),$n(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(He.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Tt}.mode`)),process.exit(1));let i=kn(s.answers,n),r=Nt(t,i.id),a=n.find(g=>g.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(He.yellow(` nothing on screen matches "${e}"`)+He.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(g=>({...g,label:n.find(p=>p.id===g.id)?.label}))},null,2));return}let d=a;console.log(` ${He.green("\u2192")} ${He.bold(d)} `+He.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Zr(xe,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",d])});import{Command as Md}from"commander";import Pe from"chalk";import{execFile as pd}from"child_process";import{promisify as ud}from"util";import{existsSync as hd,readFileSync as vs}from"fs";import{homedir as fd,tmpdir as yd}from"os";import{join as oa}from"path";var wd=ud(pd),ta=12e5,bd="https://openrouter.ai/api/v1/chat/completions",$d=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function kd(e={kind:"window"},o=ta){if(!hd(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",oa(yd(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let s=await wd(xe,n).then(a=>a.stdout,a=>{if(typeof a?.stdout=="string"&&a.stdout.trim().startsWith("{"))return a.stdout;throw a}),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=vs(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var vd=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
277
277
|
|
|
278
278
|
Report only what is visible in this image.
|
|
279
279
|
|
|
@@ -281,10 +281,10 @@ The failure that matters: an application that performs an action is on screen, a
|
|
|
281
281
|
|
|
282
282
|
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.
|
|
283
283
|
|
|
284
|
-
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
|
|
284
|
+
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 xd(e,o,t,n){let s=Ed();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=vs(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
|
|
285
285
|
|
|
286
|
-
The image is the region ${
|
|
287
|
-
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}bt();wt();var
|
|
286
|
+
The image is the region ${Sd(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:vd,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(bd,{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 h=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${h.slice(0,300)}`)}let d=await l.json(),g=d?.choices?.[0]?.message?.tool_calls?.[0];if(!g?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(g.function.arguments),u=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:u,model:typeof d.model=="string"?d.model:t,usage:{inputTokens:d?.usage?.prompt_tokens??0,outputTokens:d?.usage?.completion_tokens??0}}}async function xn(e,o={}){let t=Date.now(),n=await kd(o.region??{kind:"window"},o.maxPixels??ta),s=await xd(e,n,o.model??$d,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 Sd(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 _t;function Ed(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(_t!==void 0)return _t??void 0;try{let e=vs(oa(fd(),".agentx","openrouter-key.txt"),"utf-8").trim();_t=e.length>0?e:null}catch{_t=null}return _t??void 0}import{execFile as Ad}from"child_process";import{promisify as Od}from"util";var Id=Od(Ad),Cd=["screencapture"],jd=["Screen Studio","OBS","QuickTime Player","Zoom"];async function sa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Rd()),t}async function Rd(){let e=await na(Cd);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 na(jd);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 na(e){let o=[];for(let t of e)try{let{stdout:n}=await Id("pgrep",["-x",t]),s=n.trim().split(`
|
|
287
|
+
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}bt();wt();var ia="screen-state",ra={observable:to("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:to("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 aa(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 ca(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Td=.6,Nd=.7,_d=.3;async function Dt(e,o={}){let[t,n]=await Promise.all([xn(e,o),sa(e).catch(()=>[])]),s=o.observableFloor??Td,i=await Ye(ia,aa({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Ld(t),treeNote:o.treeNote,probes:n}),ra,{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:Pd(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=ca(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 (${Sn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Nd?"confirmed":a<=_d?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Dd(c,a,t),sighting:t,probes:n}}function Dd(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Sn(o)}). ${n}`:e==="refuted"?`Not true (${Sn(1-o)} it is false). ${n}`:`Inconclusive (${Sn(o)}, between the thresholds). ${n}`}function Pd(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 Ld(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 Sn=e=>`${Math.round(e*100)}%`;var la=new Md().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("--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(Pe.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 Dt(e,{region:t,model:o.model});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"?Pe.green("\u2713"):s.outcome==="refuted"?Pe.red("\u2717"):Pe.yellow("?");console.log(` ${i} ${Pe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Pe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Pe.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 xn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Pe.bold(n.observation)}`),n.evidence&&console.log(Pe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Ud(n.reading)}`),console.log(Pe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Pe.red(` ${n?.message??n}`)),process.exit(1)}});function Ud(e){return e==="yes"?Pe.green(e):e==="no"?Pe.red(e):Pe.yellow(e)}bt();import{Command as Wd}from"commander";import{execFile as ya}from"child_process";import{promisify as Bd}from"util";import{existsSync as Jd,readFileSync as Hd,writeFileSync as wa,mkdirSync as Gd}from"fs";import{homedir as zd}from"os";import{join as Yd,dirname as Kd}from"path";import Ce from"chalk";wt();var xs="paste-transform";function da(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function ga(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:to("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:qo(o,"What shape should this paste arrive in?")}}function ma(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 Fd=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"]),qd=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ss=[{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(`
|
|
288
288
|
`);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(`
|
|
289
289
|
`).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
|
|
290
290
|
|
|
@@ -292,67 +292,67 @@ The image is the region ${vd(o)}.`},{type:"image_url",image_url:{url:`data:image
|
|
|
292
292
|
`).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
|
|
293
293
|
`)}},{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(`
|
|
294
294
|
`);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
|
|
295
|
-
`)}},{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(!
|
|
295
|
+
`)}},{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(!qd(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Fd.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(`
|
|
296
296
|
`)||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,`
|
|
297
|
-
`).trim();return o===e?null:o}}];function
|
|
297
|
+
`).trim();return o===e?null:o}}];function pa(e){let o=[];for(let t of Ss){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function ua(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
|
|
298
298
|
\u2026[${e.length-o} more characters]\u2026
|
|
299
|
-
${e.slice(-n)}`}function
|
|
300
|
-
`)||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
|
|
301
|
-
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),
|
|
302
|
-
(dry run \u2014 pass --apply to write it back)`))}var
|
|
299
|
+
${e.slice(-n)}`}function ha(e){let o=e.trim();return o.includes(`
|
|
300
|
+
`)||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 Es=Bd(ya),ba=new Wd().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 (${Ss.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=Vd();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await ka(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await Qd();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),ha(o)){$a(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=pa(o),n=await Zd();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await tt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await tt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ye(xs,da({preview:ua(o),length:o.length,lineCount:o.split(`
|
|
301
|
+
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),ga(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await tt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${xs}.mode`,0);return}let i=ma(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await tt(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 tt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await tt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function tt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(Xd(n),await ka(t)),$a(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Es(xe,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function $a(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ce.dim("\u2192")} ${Ce.bold("unchanged")} ${Ce.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ce.green("\u2192")} ${Ce.bold(o.applied)} ${Ce.dim(`\xB7 ${o.reason}`)}`),console.log(Ce.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ce.dim(fa(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(fa(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
|
|
302
|
+
(dry run \u2014 pass --apply to write it back)`))}var fa=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
|
|
303
303
|
`).map(t=>` ${t}`).join(`
|
|
304
|
-
`),
|
|
305
|
-
${n}`:n,a=await fetch(`${
|
|
306
|
-
`)}
|
|
304
|
+
`),En=Yd(zd(),".agentx","paste-undo.txt");function Xd(e){try{Gd(Kd(En),{recursive:!0}),wa(En,e,{mode:384})}catch{}}function Vd(){try{let e=Hd(En,"utf-8");return wa(En,"",{mode:384}),e.length?e:null}catch{return null}}async function Qd(){let{stdout:e}=await Es("pbpaste",[],{maxBuffer:16777216});return e}async function ka(e){await new Promise((o,t)=>{ya("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Zd(){if(!Jd(xe))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Es(xe,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:eg(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function eg(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 og}from"commander";import Ge from"chalk";var tg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function ng(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
|
|
305
|
+
${n}`:n,a=await fetch(`${tg}/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)}`)}}var va=new og().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","Secretary").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("--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 zi,n=Hi(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ge.yellow("\u25D0"):Ge.green("\u25CB")} ${Gi(n)} ${Ge.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ge.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=ng(o.channel,o.chatId);if(o.flush){let r=await Ki(i,{queue:t,sound:s});console.log(r?Ge.green(` delivered ${r} held notification(s)`):Ge.dim(" nothing was held"));return}e?.trim()||(console.log(Ge.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await Yi({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ge.green("\u2192"):Ge.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ge.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ge.red(` ${r?.message??r}`)),s!==!1&&Xi(),process.exit(1)}});bt();$i();mi();wt();import{Command as sg}from"commander";import{readFileSync as ig}from"fs";var xa=new sg().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?ig(e.file,"utf8"):await rg()}catch(r){_o(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return _o("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return _o(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return _o("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return _o("spec needs at least one entry in `questions`");try{ui(t.questions)}catch(r){return _o(r?.message??String(r))}let n=t.seat||e.seat;Wo(),process.env[vi(n)]="active";let s=null;if(e.record!==!1)try{s=new Xt({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
|
|
306
|
+
`)}ki({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ye(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return _o(`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 _o(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function rg(){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")}bt();import{Command as dg}from"commander";import{execFile as gg,spawn as Sa}from"child_process";import{promisify as mg}from"util";import{existsSync as pg,readFileSync as ug,writeFileSync as hg,unlinkSync as fg,statSync as yg}from"fs";import{join as Is}from"path";import{tmpdir as Ea}from"os";import te from"chalk";var ag={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."}]},cg={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."}]},lg={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."}]},As=[ag,cg,lg];var Pt=mg(gg),Aa=new dg().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <id>","ElevenLabs voice id").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").action(async(e,o)=>{if(!e){console.log(te.bold(`
|
|
307
307
|
lessons
|
|
308
|
-
`));for(let l of
|
|
309
|
-
`);return}let t=
|
|
308
|
+
`));for(let l of As)console.log(` ${te.cyan(l.id.padEnd(22))} ${l.title}`),console.log(` ${" ".repeat(22)} ${te.dim(l.appHint)}
|
|
309
|
+
`);return}let t=As.find(l=>l.id===e);t||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),pg(xe)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1)),console.log(te.bold(`
|
|
310
310
|
${t.title}`)),console.log(te.dim(` ${t.appHint}
|
|
311
|
-
`));let n=null,s=null;o.record&&(s=
|
|
312
|
-
`)}catch{}},a=[],c=!1;for(let[l,d]of t.steps.entries()){console.log(` ${te.dim(String(l+1).padStart(2))} ${d.say}`),r(`Step ${l+1} of ${t.steps.length}`,d.say,"talking");let g=o.speak===!1?Promise.resolve()
|
|
313
|
-
stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${
|
|
311
|
+
`));try{t.start&&(await Pt("/usr/bin/open",wg(t.start)),await wo(2e3),await An(t.start.ready))}catch(l){console.log(te.red(` setup stopped: ${l?.message??l}`)),process.exitCode=3;return}let n=null,s=null;o.record&&(s=Is(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${s}`)),n=Sa("/usr/sbin/screencapture",["-v","-x","-C",s],{stdio:["pipe","ignore","ignore"]}),await wo(2e3));let i=o.hud===!1?null:Sa(xe,["hud"],{stdio:["pipe","ignore","ignore"]}),r=(l,d,g,p)=>{try{i?.stdin?.write(JSON.stringify({title:l,body:d,state:g,avoid:p})+`
|
|
312
|
+
`)}catch{}},a=[],c=!1;try{for(let[l,d]of t.steps.entries()){if(console.log(` ${te.dim(String(l+1).padStart(2))} ${d.say}`),r(`Step ${l+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${l+1} needs a before claim`);await An(d.before)}let g=o.speak===!1?Promise.resolve():$g(d.say,o.voice),p=d.find?await bg(d.find,a):null;if(d.find&&!p)throw a.push({tried:d.find,changed:!1,note:"not found on screen"}),await g,new Error(`Could not find "${d.find}"; stopped before acting`);if(await g,p&&(r(`Step ${l+1} of ${t.steps.length}`,d.say,"pointing",{x:p.x,y:p.y,w:p.width,h:p.height}),await Pt(xe,["point","--x",String(p.x),"--y",String(p.y),"--w",String(p.width),"--h",String(p.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:u,changed:h}=await Os(["click"]);if(u)throw new Error(u);a.push({tried:d.label??d.find??"control",changed:h!==!1,note:u??void 0}),h===!1&&console.log(te.yellow(" \xB7 clicked, but the screen did not change")),await wo(d.afterClickWaitMs??1500)}if(d.type){await An(d.before),r(`Step ${l+1} of ${t.steps.length}`,d.type,"typing");let{error:u}=await Os(["type","--text",d.type]);if(u)throw console.log(te.red(` \u2717 ${u}`)),r("Blocked",u,"waiting"),a.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(d.key){await An(d.before),r(`Step ${l+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:u}=await Os(["key","--name",d.key]);if(u)throw console.log(te.red(` \u2717 ${u}`)),r("Blocked",u,"waiting"),a.push({tried:`press ${d.key}`,changed:!1,note:u}),new Error(u)}if(!p&&!d.type&&!d.key?await wo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await wo(d.holdSeconds*1e3),d.verify){r(`Step ${l+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u;try{u=await Dt(d.verify)}catch(h){u=null,console.log(te.yellow(` ? could not check: ${h?.message??h}`))}if(!u&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(u){let h=u.outcome==="confirmed"?te.green("\u2713"):u.outcome==="refuted"?te.red("\u2717"):te.yellow("?");if(console.log(` ${h} ${te.dim(u.reason)}`),!u.ok&&!d.verifyOptional){r("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(te.red(`
|
|
313
|
+
stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${u.reason}`)),console.log(te.dim(` screenshot: ${u.sighting.shot.path}`)),await wo(2500);try{i?.stdin?.end()}catch{}c=!0;break}}}}}catch(l){c=!0,console.log(te.red(` stopping: ${l?.message??l}`)),r("Stopped",String(l?.message??l),"waiting")}finally{if(c)try{i?.stdin?.end()}catch{}}if(!c){r("Done",t.title,"done"),await wo(1200);try{i?.stdin?.end()}catch{}}if(n&&s){n.kill("SIGINT"),await wo(2500);try{let{size:l}=yg(s);console.log(te.green(` recorded ${(l/1048576).toFixed(1)} MB \u2192 ${s}`))}catch{console.log(te.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(c){console.log(te.red(` lesson stopped before the end.
|
|
314
314
|
`)),process.exitCode=3;return}console.log(te.green(`
|
|
315
315
|
done.
|
|
316
|
-
`))});async function
|
|
317
|
-
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${
|
|
316
|
+
`))});function wg(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Is(Ea(),"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 An(e){let o=await Dt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Os(e){try{let{stdout:o}=await Pt(xe,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 bg(e,o=[]){try{let t=await vn({max:45});if(t.candidates.length<2)return null;let n=await Ye(Tt,bn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),$n(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=kn(n.answers,t.candidates);return s.present<.5?null:Nt(t,s.id)}catch{return null}}async function $g(e,o){let t=kg();if(t)try{let n=o||process.env.AGENTX_VOICE_ID||"21m00Tcm4TlvDq8ikWAM",s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n}`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:"eleven_turbo_v2_5"})});if(s.ok){let i=Is(Ea(),`agentx-teach-${Date.now()}.mp3`);hg(i,Buffer.from(await s.arrayBuffer())),await Pt("/usr/bin/afplay",[i]);try{fg(i)}catch{}return}}catch{}await Pt("/usr/bin/say",[e]).catch(()=>{})}function kg(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let e of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let o=ug(e,"utf8").trim();if(o)return o}catch{}return null}var wo=e=>new Promise(o=>setTimeout(o,e));import{Command as vg}from"commander";import L from"chalk";var Do=new vg().name("attach").description("wear an agentx agent identity in this Claude Code session"),Cs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Et()}`;function js(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Rs(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 Ts(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 Oa(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function xg(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)} ${Oa(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Do.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Vn.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Cs).action(async(e,o)=>{let t=js(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)),Ai(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${Vn.join(", ")}`)),process.exit(1)),pn()||(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 Rs(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)} (${Oa(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: ${Ts(n)}`)),process.exit(1)}});Do.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",Cs).action(async e=>{let o=js(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Rs(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: ${Ts(t)}`)),process.exit(1)}});Do.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Cs).option("--json","raw JSON output").action(async e=>{let o=js();try{let n=(await Rs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:pn(),sessions:n},null,2));return}console.log(),console.log(pn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(St())}`:`${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)xg(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
|
|
317
|
+
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${Ts(t)}`)),process.exit(1)}});Do.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||Et()),t=Rr(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
|
|
318
318
|
settings \u2014 without this an attached production identity would be less
|
|
319
|
-
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)}});Do.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=Cr({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)}});Oe();import{Command as kg}from"commander";import pe from"chalk";var An=new kg().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Aa(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=W(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 Oa(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ea(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 vg(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}An.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}=Aa(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Oa(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.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(pe.dim(" (no processes)"));return}for(let r of i){let a=vg(r.state)(r.state.padEnd(9)),c=Ea(r.spawnedAt),l=r.lastTurnAt?Ea(r.lastTurnAt)+" ago":"\u2014",d=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",g=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),u=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${g} ${d} ${u}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});An.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}=Aa(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Oa(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.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(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as xg}from"commander";import je from"chalk";import{existsSync as Cs,rmSync as Sg}from"fs";import{resolve as js}from"path";var nt=new xg().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");nt.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(je.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Oi(e,o,{verbose:n}),r=Date.now()-s;console.log(je.green(` \u2713 indexed ${i.docs} doc(s) for ${je.bold(e)} in ${r}ms`)),console.log(je.dim(` \u2192 ${i.path}`))});nt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=js(e.cwd,".agentx","rag");if(!Cs(o)){console.log(je.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Cs(js(o,s,"index.json")));if(n.length===0){console.log(je.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Kn(s);console.log(` ${je.bold(s)} ${i.docs} doc(s) ${je.dim(i.path)}`)}});nt.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=Ii(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Kn(e);i.exists?console.log(je.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(je.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${je.bold(i.title)} ${je.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${je.dim(i.path)}`),console.log(` ${je.dim(i.snippet.slice(0,200))}`)});nt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=js(process.cwd(),".agentx","rag",e);if(!Cs(o)){console.log(je.dim(` no index for ${e} \u2014 nothing to clear`));return}Sg(o,{recursive:!0,force:!0}),console.log(je.green(` \u2713 cleared index for ${e}`))});Oe();import{Command as Eg}from"commander";import V from"chalk";import st from"prompts";var Po=new Eg().name("backlog").description("manage the local backlog used by business workSource=backlog");function Dt(e){let o=W(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new or(n)}}function Ag(e){return e?V.cyan(`${e.type}:${e.project}#${e.iid}`):V.dim("manual")}function Og(e){return{todo:V.gray("todo"),doing:V.yellow("doing"),blocked:V.red("blocked"),done:V.green("done")}[e]}Po.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}=Dt(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(V.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?V.magenta(`@${n.assignee}`):V.dim("unassigned");console.log(` ${Og(n.status).padEnd(7)} ${Ag(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(V.dim(` ${n.source.url}`))}console.log(),console.log(V.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Po.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=Dt(t.config);n.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(V.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=tr([o],i.source,n.config),a=await Qn(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(V.dim(" sync:"),...c));console.log(a.ok?V.dim(` synced -> ${a.url??i.source.type}`):V.yellow(` sync failed: ${a.error}`))}});Po.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=Dt(o.config);t.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(V.green(` done: ${s.title}`)),s.source){let i=await Qn(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(V.dim(" sync:"),...r));console.log(i.ok?V.dim(` synced -> ${i.url??s.source.type}`):V.yellow(` sync failed: ${i.error}`))}});Po.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}=Dt(o.config);t.remove(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1)),console.log(V.green(` removed ${e}`))});Po.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=Dt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(V.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 st({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(V.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(V.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Cg(o.config):jg(o.config);y.length?(i=(await st({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 st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await st({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(V.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Rg(o.config,i,a):await Tg(o.config,i,a);if(!c.length){console.log(V.yellow(" no open issues matched"));return}console.log(V.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,d=new Set(o.store.list().map(y=>y.id)),g=c.map(y=>{let k=Xn({type:s,project:l,iid:y.iid,url:y.url}),b=d.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${b?V.dim(" (already imported)"):""}`,value:y,disabled:b}}),p=(await st({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:g,min:1})).selected||[];if(!p.length){console.log(V.dim(" nothing selected"));return}let f=p.map(y=>{let k={type:s,host:s==="gitlab"?Ig(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Xn(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(V.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(V.dim(` ${y.id} \u2014 ${y.title}`))});function Ig(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Cg(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 jg(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 Rg(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 Tg(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(Ia)}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(Ia):[]}function Ia(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 Dg}from"commander";import z from"chalk";import{existsSync as Pg,readFileSync as Lg}from"fs";import{resolve as Mg}from"path";import Ug from"prompts";Oe();import Ng from"cronstrue";var Rs={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},On={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function eo(e){try{return Ng.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function _g(e){if(/\b(noon|midday)\b/.test(e))return On.noon;if(/\bmidnight\b/.test(e))return On.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Ts(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let g=parseInt(t[1],10);return g<1||g>59?null:{cron:`*/${g} * * * *`,human:eo(`*/${g} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:eo("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let g=parseInt(t[1],10);return g<1||g>23?null:{cron:`0 */${g} * * *`,human:eo(`0 */${g} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:eo("0 * * * *"),matched:"every hour"};let n=_g(o),s=null;for(let[g,u]of Object.entries(On))if(!(g==="noon"||g==="midnight")&&new RegExp(`\\b(every\\s+)?${g}s?\\b`).test(o)){s=u;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let g=r[1],u=1;if(g==="last"||(/^\d+(st|nd|rd|th)?$/.test(g)?u=parseInt(g,10):g==="first"||g==="1st"?u=1:g==="2nd"?u=2:g==="3rd"&&(u=3),u<1||u>31))return null;let p=i||{h:9,m:0},f=`${p.m} ${p.h} ${u} * *`;return{cron:f,human:eo(f),matched:r[0]}}let a=[],c=Object.keys(Rs).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),d=o.match(l);if(d){let g=d[1];for(let u of Object.keys(Rs))if(new RegExp(`\\b${u}s?\\b`).test(g)){let p=Rs[u];a.includes(p)||a.push(p)}}if(a.length){let g=i||{h:9,m:0};a.sort((f,w)=>f-w);let u=a.join(","),p=`${g.m} ${g.h} * * ${u}`;return{cron:p,human:eo(p),matched:`on ${u}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * 1-5`;return{cron:u,human:eo(u),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * 0,6`;return{cron:u,human:eo(u),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * *`;return{cron:u,human:eo(u),matched:s&&Object.entries(On).find(([,p])=>p===s)?.[0]||"daily"}}if(n){let g=`${n.m} ${n.h} * * *`;return{cron:g,human:eo(g),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Ca(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function ja(e){let o=e||Mg(process.cwd(),"agentx.json");return Pg(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Lg(o,"utf-8"))}function Fg(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function qg(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(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Ug([{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(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bo=new Dg().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bo.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: Africa/Tunis)","Africa/Tunis").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){bo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Ts(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=ja(o.config),s=di(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Fg(o.onError),r=await qg(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ca(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let l=await de(g=>we(g,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(z.red(` \u2717 ${l.error}`)),process.exit(1));let d=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${d} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.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=ja(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])bo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Oo(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);we(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Oo(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Ti(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ts(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as dm}from"commander";import it from"chalk";import Q from"chalk";import Lt from"prompts";import{readFileSync as Wg,writeFileSync as Bg,existsSync as Jg}from"fs";import{resolve as Ra}from"path";var Hg=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Gg(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Ns(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Ta(e=".env"){let o=Ra(e);if(!Jg(o))return[];let t=Wg(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(Hg);i?n.push({kind:"kv",key:i[1],value:Gg(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function zg(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Ns(o.value)}`:o.raw).join(`
|
|
319
|
+
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)}});Do.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=Tr({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)}});Oe();import{Command as Sg}from"commander";import pe from"chalk";var On=new Sg().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ca(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=W(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 ja(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ia(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 Eg(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}On.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}=Ca(e),n;try{n=await fetch(`${o}/api/processes`,{headers:ja(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.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(pe.dim(" (no processes)"));return}for(let r of i){let a=Eg(r.state)(r.state.padEnd(9)),c=Ia(r.spawnedAt),l=r.lastTurnAt?Ia(r.lastTurnAt)+" ago":"\u2014",d=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",g=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),p=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${g} ${d} ${p}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});On.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}=Ca(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ja(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.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(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as Ag}from"commander";import je from"chalk";import{existsSync as Ns,rmSync as Og}from"fs";import{resolve as _s}from"path";var nt=new Ag().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");nt.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(je.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await ji(e,o,{verbose:n}),r=Date.now()-s;console.log(je.green(` \u2713 indexed ${i.docs} doc(s) for ${je.bold(e)} in ${r}ms`)),console.log(je.dim(` \u2192 ${i.path}`))});nt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=_s(e.cwd,".agentx","rag");if(!Ns(o)){console.log(je.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ns(_s(o,s,"index.json")));if(n.length===0){console.log(je.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Qn(s);console.log(` ${je.bold(s)} ${i.docs} doc(s) ${je.dim(i.path)}`)}});nt.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=Ri(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Qn(e);i.exists?console.log(je.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(je.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${je.bold(i.title)} ${je.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${je.dim(i.path)}`),console.log(` ${je.dim(i.snippet.slice(0,200))}`)});nt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=_s(process.cwd(),".agentx","rag",e);if(!Ns(o)){console.log(je.dim(` no index for ${e} \u2014 nothing to clear`));return}Og(o,{recursive:!0,force:!0}),console.log(je.green(` \u2713 cleared index for ${e}`))});Oe();import{Command as Ig}from"commander";import X from"chalk";import st from"prompts";var Po=new Ig().name("backlog").description("manage the local backlog used by business workSource=backlog");function Lt(e){let o=W(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new sr(n)}}function Cg(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function jg(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}Po.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}=Lt(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(X.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${jg(n.status).padEnd(7)} ${Cg(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Po.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=Lt(t.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=ir([o],i.source,n.config),a=await os(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});Po.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=Lt(o.config);t.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await os(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});Po.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}=Lt(o.config);t.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});Po.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=Lt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(X.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 st({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Tg(o.config):Ng(o.config);y.length?(i=(await st({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 st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await st({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await _g(o.config,i,a):await Dg(o.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,d=new Set(o.store.list().map(y=>y.id)),g=c.map(y=>{let $=es({type:s,project:l,iid:y.iid,url:y.url}),b=d.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),u=(await st({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:g,min:1})).selected||[];if(!u.length){console.log(X.dim(" nothing selected"));return}let h=u.map(y=>{let $={type:s,host:s==="gitlab"?Rg(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:es($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=o.store.addMany(h);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function Rg(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Tg(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 Ng(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 _g(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 Dg(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(Ra)}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(Ra):[]}function Ra(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 Mg}from"commander";import z from"chalk";import{existsSync as Ug,readFileSync as Fg}from"fs";import{resolve as qg}from"path";import Wg from"prompts";Oe();import Pg from"cronstrue";var Ds={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},In={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function eo(e){try{return Pg.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function Lg(e){if(/\b(noon|midday)\b/.test(e))return In.noon;if(/\bmidnight\b/.test(e))return In.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Ps(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let g=parseInt(t[1],10);return g<1||g>59?null:{cron:`*/${g} * * * *`,human:eo(`*/${g} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:eo("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let g=parseInt(t[1],10);return g<1||g>23?null:{cron:`0 */${g} * * *`,human:eo(`0 */${g} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:eo("0 * * * *"),matched:"every hour"};let n=Lg(o),s=null;for(let[g,p]of Object.entries(In))if(!(g==="noon"||g==="midnight")&&new RegExp(`\\b(every\\s+)?${g}s?\\b`).test(o)){s=p;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let g=r[1],p=1;if(g==="last"||(/^\d+(st|nd|rd|th)?$/.test(g)?p=parseInt(g,10):g==="first"||g==="1st"?p=1:g==="2nd"?p=2:g==="3rd"&&(p=3),p<1||p>31))return null;let u=i||{h:9,m:0},h=`${u.m} ${u.h} ${p} * *`;return{cron:h,human:eo(h),matched:r[0]}}let a=[],c=Object.keys(Ds).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),d=o.match(l);if(d){let g=d[1];for(let p of Object.keys(Ds))if(new RegExp(`\\b${p}s?\\b`).test(g)){let u=Ds[p];a.includes(u)||a.push(u)}}if(a.length){let g=i||{h:9,m:0};a.sort((h,w)=>h-w);let p=a.join(","),u=`${g.m} ${g.h} * * ${p}`;return{cron:u,human:eo(u),matched:`on ${p}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let g=i||{h:9,m:0},p=`${g.m} ${g.h} * * 1-5`;return{cron:p,human:eo(p),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let g=i||{h:9,m:0},p=`${g.m} ${g.h} * * 0,6`;return{cron:p,human:eo(p),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let g=i||{h:9,m:0},p=`${g.m} ${g.h} * * *`;return{cron:p,human:eo(p),matched:s&&Object.entries(In).find(([,u])=>u===s)?.[0]||"daily"}}if(n){let g=`${n.m} ${n.h} * * *`;return{cron:g,human:eo(g),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Ta(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function Na(e){let o=e||qg(process.cwd(),"agentx.json");return Ug(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Fg(o,"utf-8"))}function Bg(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function Jg(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(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Wg([{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(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bo=new Mg().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bo.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: Africa/Tunis)","Africa/Tunis").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){bo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Ps(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Na(o.config),s=pi(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Bg(o.onError),r=await Jg(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ta(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let l=await de(g=>we(g,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(z.red(` \u2717 ${l.error}`)),process.exit(1));let d=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${d} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.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=Na(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])bo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Oo(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);we(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Oo(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Di(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ps(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as pm}from"commander";import it from"chalk";import Q from"chalk";import Ut from"prompts";import{readFileSync as Hg,writeFileSync as Gg,existsSync as zg}from"fs";import{resolve as _a}from"path";var Yg=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Kg(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Ls(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Da(e=".env"){let o=_a(e);if(!zg(o))return[];let t=Hg(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(Yg);i?n.push({kind:"kv",key:i[1],value:Kg(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Xg(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Ls(o.value)}`:o.raw).join(`
|
|
320
320
|
`)+`
|
|
321
|
-
`}function Pt(e,o,t=".env"){let n=Ra(t),s=Ta(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ns(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ns(o)}`})),Bg(n,zg(s))}function _s(e,o=".env"){return Ta(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Na="https://t.me/BotFather";async function Yg(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 Kg(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 _a(e={}){console.log(),console.log(Q.bold(" Connect Telegram")),console.log(),console.log(Q.dim(` 1. Open ${Na}`)),console.log(Q.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Q.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Lt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(x,[Na],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Lt({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(Q.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Yg(t.trim());n||(console.log(Q.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Q.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(Q.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(Q.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Lt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),d||(console.log(Q.red(" Aborted")),process.exit(1));let g=c.channels?.telegram?.accounts||{},u=e.account||d;g[u]&&g[u].agentBinding!==d&&(u=(await Lt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${d}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Q.red(" Aborted")),process.exit(1));let p=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Pt(p,t.trim()),process.env[p]=t.trim();let f=await de(b=>{we(b,"channels.telegram.enabled",!0),we(b,`channels.telegram.accounts.${u}`,{token:`\${${p}}`,agentBinding:d});let x=Oo(b,`agents.${d}.mentions`)||[],A=`@${n.username}`;x.includes(A)||(x.push(A),we(b,`agents.${d}.mentions`,x))},{configPath:e.configPath});if(f.success||(console.log(Q.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(Q.green(` \u2713 Bot @${n.username} bound to agent "${d}"`)),console.log(Q.dim(` Token stored in .env as ${p}`)),console.log(Q.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(Q.dim(" Daemon hot-reloaded.")):console.log(Q.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Lt({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(Q.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Q.dim(" Waiting up to 90s..."));let y=await Kg(t.trim(),9e4);if(!y){console.log(Q.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Q.dim(" agentx config set notifications.destination.channel telegram")),console.log(Q.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Q.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await de(b=>{we(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(Q.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Q.green(" \u2713 Default --notify target set")),console.log(Q.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Q.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Q.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Ds from"prompts";import{existsSync as Ls,mkdirSync as Vg,readdirSync as Xg,readFileSync as Da}from"fs";import{resolve as Ps}from"path";var Qg=".agentx/whatsapp-sessions";function Zg(){let e=Ps(process.cwd(),".agentx/daemon.pid");if(!Ls(e))return!1;try{let o=parseInt(Da(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function em(e){if(!Ls(e))return!1;try{return Xg(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function om(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Vg(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(d=>{let u=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}d(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(p.qr,{small:!0})}catch{o(` QR: ${p.qr}`)}o("")}if(p.connection==="open"){clearTimeout(u),o(ue.green(" \u2713 Paired"));try{l.end(void 0)}catch{}d(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),d(!1))})})}async function Pa(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),Zg()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ds({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Ps(process.cwd(),"agentx.json");Ls(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Da(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Qg,s=Ps(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ds({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(d=>({title:d,value:d})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(em(s)&&a){let{keep:l}=await Ds({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(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await om(s,d=>console.log(d))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{we(l,"channels.whatsapp.enabled",!0),we(l,"channels.whatsapp.sessionDir",n),we(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as tm}from"crypto";import be from"chalk";import La from"prompts";var In="agentx-mesh:",Cn="//join/";function nm(e){return Buffer.from(e,"utf-8").toString("base64url")}function sm(e){return Buffer.from(e,"base64url").toString("utf-8")}function im(e){return`${In}${Cn}${nm(JSON.stringify(e))}`}function rm(e){if(!e.startsWith(`${In}${Cn}`))throw new Error(`Not a mesh invite link \u2014 expected ${In}${Cn}\u2026`);let o=e.slice(In.length+Cn.length),t=JSON.parse(sm(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 am(){return tm(32).toString("hex")}function cm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function lm(e){return e?.node?.name||e?.node?.id||"node"}async function Ma(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(be.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=_s("MESH_TOKEN");r||(r=am(),Pt("MESH_TOKEN",r),console.log(be.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||cm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:g}=await La({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});g||(console.log(be.red(" Aborted")),process.exit(1)),a=g}let l=await de(g=>{we(g,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(be.red(` \u2717 ${l.error}`)),process.exit(1));let d=im({url:a,token:r,name:lm(i),version:1});console.log(),console.log(be.bold(" Mesh invite")),console.log(),console.log(` ${be.cyan(d)}`),console.log(),console.log(be.dim(" Run on the other node:")),console.log(be.dim(` agentx connect mesh join "${d}"`)),console.log(),console.log(be.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Ua(e,o={}){let t;try{t=rm(e)}catch(i){console.log(be.red(` \u2717 ${i.message}`)),process.exit(1)}let n=_s("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await La({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(be.red(" Aborted (keeping existing .env)")),process.exit(1))}Pt("MESH_TOKEN",t.token);let s=await de(i=>{we(i,"mesh.enabled",!0);let r=Oo(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),we(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(be.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(be.green(" \u2713 Joined mesh")),console.log(be.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(be.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(be.dim(" Daemon hot-reloaded.")):console.log(be.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(be.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(be.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(be.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rt=new dm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rt.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 _a({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rt.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 Pa({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Fa=rt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Fa.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 Ma({url:e.url,configPath:e.config})});Fa.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 Ua(e,{configPath:o.config})});rt.action(()=>{console.log(),console.log(it.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${it.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${it.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${it.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${it.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(it.dim(" GitLab connect is the next slice.")),console.log()});Oe();import{Command as gm}from"commander";import ce from"chalk";var Mt=new gm().name("usage").description("token usage analysis and reporting");Mt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=W(),[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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.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),d=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ce.dim(d)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});Mt.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});Mt.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-NS74AXSE.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-I4J63BQ7.js"),r=await i(),a=new Set(n.filter(g=>g.kind==="cli").map(g=>g.name)),c=[],l=(g,u)=>{for(let p of g.commands??[]){let f=u?`${u} ${p.name()}`:p.name();c.push(f),l(p,f)}};l(r,"");let d=c.filter(g=>!a.has(g)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:d},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${d.length}/${c.length})`)),console.log();for(let g of d)console.log(` ${ce.dim("\xB7")} ${g}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ce.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ce.dim(`${i.days}d`);console.log(` ${ce.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as mm}from"commander";import fe from"chalk";import{resolve as pm}from"path";Oe();var $o=new mm().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{$i(pm(process.cwd(),".env"))}catch{}let o=um(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-6QQCKFB3.js");t(o)}catch(o){console.log(fe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(fe.dim(o.stack)),process.exit(1)}});function um(e,o){try{let t=W();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
322
|
-
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}$o.command("list").description("list configured boards").action(()=>{try{let e=W();if(!e.boards?.length){console.log(
|
|
321
|
+
`}function Mt(e,o,t=".env"){let n=_a(t),s=Da(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ls(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ls(o)}`})),Gg(n,Xg(s))}function Ms(e,o=".env"){return Da(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Pa="https://t.me/BotFather";async function Vg(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 Qg(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 La(e={}){console.log(),console.log(Q.bold(" Connect Telegram")),console.log(),console.log(Q.dim(` 1. Open ${Pa}`)),console.log(Q.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Q.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Ut({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,[Pa],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Ut({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(Q.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Vg(t.trim());n||(console.log(Q.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Q.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(Q.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(Q.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Ut({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),d||(console.log(Q.red(" Aborted")),process.exit(1));let g=c.channels?.telegram?.accounts||{},p=e.account||d;g[p]&&g[p].agentBinding!==d&&(p=(await Ut({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${d}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Q.red(" Aborted")),process.exit(1));let u=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Mt(u,t.trim()),process.env[u]=t.trim();let h=await de(b=>{we(b,"channels.telegram.enabled",!0),we(b,`channels.telegram.accounts.${p}`,{token:`\${${u}}`,agentBinding:d});let v=Oo(b,`agents.${d}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),we(b,`agents.${d}.mentions`,v))},{configPath:e.configPath});if(h.success||(console.log(Q.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(Q.green(` \u2713 Bot @${n.username} bound to agent "${d}"`)),console.log(Q.dim(` Token stored in .env as ${u}`)),console.log(Q.dim(` Mentions updated to include @${n.username}`)),h.reloaded?console.log(Q.dim(" Daemon hot-reloaded.")):console.log(Q.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Ut({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(Q.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Q.dim(" Waiting up to 90s..."));let y=await Qg(t.trim(),9e4);if(!y){console.log(Q.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Q.dim(" agentx config set notifications.destination.channel telegram")),console.log(Q.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Q.dim(` agentx config set notifications.destination.accountId ${p}`));return}let $=await de(b=>{we(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!$.success){console.log(Q.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(Q.green(" \u2713 Default --notify target set")),console.log(Q.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Q.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(Q.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Us from"prompts";import{existsSync as qs,mkdirSync as Zg,readdirSync as em,readFileSync as Ma}from"fs";import{resolve as Fs}from"path";var om=".agentx/whatsapp-sessions";function tm(){let e=Fs(process.cwd(),".agentx/daemon.pid");if(!qs(e))return!1;try{let o=parseInt(Ma(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function nm(e){if(!qs(e))return!1;try{return em(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function sm(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Zg(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(d=>{let p=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}d(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:h}=await import("qrcode-terminal");h.generate(u.qr,{small:!0})}catch{o(` QR: ${u.qr}`)}o("")}if(u.connection==="open"){clearTimeout(p),o(ue.green(" \u2713 Paired"));try{l.end(void 0)}catch{}d(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),d(!1))})})}async function Ua(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),tm()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:l}=await Us({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Fs(process.cwd(),"agentx.json");qs(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Ma(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||om,s=Fs(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Us({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(d=>({title:d,value:d})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(nm(s)&&a){let{keep:l}=await Us({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(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await sm(s,d=>console.log(d))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{we(l,"channels.whatsapp.enabled",!0),we(l,"channels.whatsapp.sessionDir",n),we(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as im}from"crypto";import be from"chalk";import Fa from"prompts";var Cn="agentx-mesh:",jn="//join/";function rm(e){return Buffer.from(e,"utf-8").toString("base64url")}function am(e){return Buffer.from(e,"base64url").toString("utf-8")}function cm(e){return`${Cn}${jn}${rm(JSON.stringify(e))}`}function lm(e){if(!e.startsWith(`${Cn}${jn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Cn}${jn}\u2026`);let o=e.slice(Cn.length+jn.length),t=JSON.parse(am(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 dm(){return im(32).toString("hex")}function gm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function mm(e){return e?.node?.name||e?.node?.id||"node"}async function qa(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(be.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Ms("MESH_TOKEN");r||(r=dm(),Mt("MESH_TOKEN",r),console.log(be.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||gm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:g}=await Fa({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://"});g||(console.log(be.red(" Aborted")),process.exit(1)),a=g}let l=await de(g=>{we(g,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(be.red(` \u2717 ${l.error}`)),process.exit(1));let d=cm({url:a,token:r,name:mm(i),version:1});console.log(),console.log(be.bold(" Mesh invite")),console.log(),console.log(` ${be.cyan(d)}`),console.log(),console.log(be.dim(" Run on the other node:")),console.log(be.dim(` agentx connect mesh join "${d}"`)),console.log(),console.log(be.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Wa(e,o={}){let t;try{t=lm(e)}catch(i){console.log(be.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Ms("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Fa({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(be.red(" Aborted (keeping existing .env)")),process.exit(1))}Mt("MESH_TOKEN",t.token);let s=await de(i=>{we(i,"mesh.enabled",!0);let r=Oo(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),we(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(be.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(be.green(" \u2713 Joined mesh")),console.log(be.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(be.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(be.dim(" Daemon hot-reloaded.")):console.log(be.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(be.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(be.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(be.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rt=new pm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rt.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 La({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rt.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 Ua({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ba=rt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ba.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 qa({url:e.url,configPath:e.config})});Ba.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 Wa(e,{configPath:o.config})});rt.action(()=>{console.log(),console.log(it.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${it.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${it.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${it.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${it.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(it.dim(" GitLab connect is the next slice.")),console.log()});Oe();import{Command as um}from"commander";import le from"chalk";var Ft=new um().name("usage").description("token usage analysis and reporting");Ft.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=W(),[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(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.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: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.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),d=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${le.dim(d)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Ft.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(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Ft.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-NS74AXSE.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-DWZAI4GY.js"),r=await i(),a=new Set(n.filter(g=>g.kind==="cli").map(g=>g.name)),c=[],l=(g,p)=>{for(let u of g.commands??[]){let h=p?`${p} ${u.name()}`:u.name();c.push(h),l(u,h)}};l(r,"");let d=c.filter(g=>!a.has(g)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:d},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${d.length}/${c.length})`)),console.log();for(let g of d)console.log(` ${le.dim("\xB7")} ${g}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.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(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hm}from"commander";import he from"chalk";import{resolve as fm}from"path";Oe();var $o=new hm().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{xi(fm(process.cwd(),".env"))}catch{}let o=ym(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-K4DM32SO.js");t(o)}catch(o){console.log(he.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(he.dim(o.stack)),process.exit(1)}});function ym(e,o){try{let t=W();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(he.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(he.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
322
|
+
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}$o.command("list").description("list configured boards").action(()=>{try{let e=W();if(!e.boards?.length){console.log(he.dim(`
|
|
323
323
|
No boards configured.
|
|
324
|
-
`));return}console.log();for(let o of e.boards){console.log(` ${
|
|
324
|
+
`));return}console.log();for(let o of e.boards){console.log(` ${he.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(he.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(he.dim(` primary label: ${o.primaryToolLabel}`)),console.log(he.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(he.red(` ${e.message}`)),process.exit(1)}});$o.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{qt(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(he.red(` ${t.message}`)),process.exit(1)}});$o.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{qt(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(he.red(` ${t.message}`)),process.exit(1)}});var Ws=$o.command("column").description("manage a board's columns (add / remove / edit / list)");Ws.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Pc("fs").readFileSync("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(he.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(` ${he.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${he.dim(i)}`)}}catch(o){console.log(he.red(` ${o.message}`)),process.exit(1)}});Ws.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{qt(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(he.red(` ${n.message}`)),process.exit(1)}});Ws.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{qt(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(he.red(` ${t.message}`)),process.exit(1)}});$o.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{qt(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(he.red(` ${o.message}`)),process.exit(1)}});function qt(e){let{summary:o,backupPath:t}=Yo(n=>e(n));console.log(he.green(`
|
|
325
325
|
\u2713 ${o}
|
|
326
|
-
`)),t&&console.log(
|
|
327
|
-
`))}import{Command as
|
|
328
|
-
${
|
|
326
|
+
`)),t&&console.log(he.dim(` Backup: ${t}`)),console.log(he.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
327
|
+
`))}import{Command as wm}from"commander";import m from"chalk";import{resolve as F,relative as Ja,dirname as Ha}from"path";import{execSync as Lo}from"child_process";import{writeFileSync as Mo,mkdirSync as io,readFileSync as Wt,readdirSync as bm,renameSync as Rn,rmSync as $m,existsSync as qe}from"fs";function $e(e,o){return new Xn(Bt(e),void 0,o||"graph")}function Bt(e){return e||F(process.cwd(),".agentx/wiki")}function Js(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new wm().name("wiki").description("wiki knowledge base management");Z.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=$e(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Js(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())});Z.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=$e(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()});Z.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=$e(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=F(process.cwd(),".agentx/graph");return qe(p)?new co({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[u,h]of Object.entries(p.entries))r.set(u,h.path)}catch{}let a,c=p=>{let u=p.meta?.intentPath;if(Array.isArray(u)&&u.every(y=>typeof y=="string")&&u.length>0)return u;if(!i||r.size===0)return;let h=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:h});return r.get(w)},l=(p,u)=>{let h=new Map;for(let y of p){let $=u.find(x=>x.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=h.get(v);A?A.n++:h.set(v,{path:b,n:1})}if(h.size===0)return;let w;for(let y of h.values())(!w||y.n>w.n)&&(w=y);return w?.path},d=0,g=0;for(let p of n){let u=typeof e.since=="string"?e.since.trim():"",h=t.getUnabsorbedEntries(p).filter(k=>!u||(k.date??"")>=u).slice(0,s);if(h.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${h.length} entries to absorb`));for(let k of h.slice(0,3))console.log(m.dim(` [${k.date} via ${k.source}] ${k.content.slice(0,80)}...`));if(h.length>3&&console.log(m.dim(` ... and ${h.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),$=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=h.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
|
|
328
|
+
${k.content}
|
|
329
329
|
--- END ENTRY ---`).join(`
|
|
330
330
|
|
|
331
|
-
`),x="";if(e.facts!==!1){let{extractHints:$,resolveFacts:T,mergeRecords:j,renderFactsBlock:C,installPrompts:D,defaultSources:q,recordsFromEntries:P}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ke of t.listAgents())for(let he of t.getAgentWiki(ke).listArticles(ke))he.meta.type==="person"&&B.add(he.meta.title);a=[...B]}let H=$(f.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),re=P(f);if(H.length>0||re.length>0){let B=q(),{records:ke,results:he}=H.length>0?await T(H,{sources:B}):{records:[],results:[]},_=j([...re,...ke]);x=C(_);let Me=[...re.length>0?[`entries:${re.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${Me.length?` (${Me.join(" ")})`:""}`));for(let ye of D(he,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=Ui(o,u,k,y.articles,b,f.length,x);console.log(m.dim(` Mode: ${Fs(o)}`));let v=F(w.baseDir,"_tmp");ro(v,{recursive:!0});let E=F(v,"absorb-prompt.txt");Mo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Lo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Bo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if($=_.stdout||"",!$)throw _}let T=$;try{let _=JSON.parse($);T=_.result||_.content||"",T||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let j,C=[],D=T.indexOf("{"),q=T.indexOf("["),P=D>=0&&(q<0||D<q)?D:q;if(P===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(T.slice(0,500)));continue}let H=T[P],re=H==="{"?"}":"]",B=0,ke=-1;for(let _=P;_<T.length;_++)if(T[_]===H)B++;else if(T[_]===re&&(B--,B===0)){ke=_+1;break}if(ke===-1){console.log(m.red(" Unbalanced JSON"));continue}let he=T.slice(P,ke);try{let _=JSON.parse(he);Array.isArray(_)?j=_:(j=_.articles||[],C=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of j){let Me=new Date().toISOString().slice(0,10),ye=l(_.sources||[],f);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:u,access:"public",created:Me,lastUpdated:Me,sources:_.sources||[],graphPath:ye},_.content,u);let Eo=_.type?m.magenta(`[${_.type}]`)+" ":"",R=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Eo}${_.path}: ${_.title}${m.dim(R)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),g++),d++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let _ of C)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Me=new _(qt(e.dir)).add(C.map(ye=>({kind:"article",agentId:u,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));Me.added>0&&console.log(m.dim(` queued ${Me.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(d>0&&(console.log(m.green(` ${d} articles compiled across ${n.length} agent(s)`)),i)){let u=d>0?Math.round(g/d*100):0;console.log(m.dim(` ${g}/${d} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.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("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=wm(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-F3OFYTCZ.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!qe(l))console.log(m.yellow(` --reviews: no ${l}`));else{let d=new c(l,{readonly:!0});try{let g=d.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(g,{kinds:String(e.reviewKinds).split(",").map(f=>f.trim()).filter(Boolean)});let u=i.filter(f=>(f.occurrences??1)>1).length;console.log(m.dim(` ${g.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let p=i[0];p&&(p.occurrences??1)>1&&console.log(m.dim(` most recurrent (${p.occurrences} sessions): ${p.memory.description.slice(0,84)}`))}finally{d.close()}}}let r=await Fi({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,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 promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(l)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}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.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function wm(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)}Z.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-R7EI3VGX.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=$e(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),d=parseInt(e.n),g=i(e.history,c);if(!s(g)){console.log(m.yellow(` no task-history at ${g}`));return}let u=[],p=t(g).sort().reverse();for(let y of p){let k=r(g,y),b=[];try{b=t(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of b){if(u.length>=d)break;try{let A=JSON.parse(n(r(k,x),"utf-8")),v=A.message||A.task?.message;typeof v=="string"&&v.trim().length>10&&u.push({id:A.id||x.replace(".json",""),message:v.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=d)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${g}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let f=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let x=l.findRelevant(k.message,c,3).map(v=>`- **${v.meta.title}** [${v.meta.type||"?"}] (${v.path})`).join(`
|
|
332
|
-
`)||"_(none returned)_",A;try{let
|
|
331
|
+
`),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:T,mergeRecords:j,renderFactsBlock:C,installPrompts:D,defaultSources:q,recordsFromEntries:P}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ke of t.listAgents())for(let fe of t.getAgentWiki(ke).listArticles(ke))fe.meta.type==="person"&&B.add(fe.meta.title);a=[...B]}let H=k(h.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=P(h);if(H.length>0||ae.length>0){let B=q(),{records:ke,results:fe}=H.length>0?await T(H,{sources:B}):{records:[],results:[]},_=j([...ae,...ke]);v=C(_);let Ue=[...ae.length>0?[`entries:${ae.length}`]:[],...fe.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${Ue.length?` (${Ue.join(" ")})`:""}`));for(let ye of D(fe,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=Wi(o,p,$,y.articles,b,h.length,v);console.log(m.dim(` Mode: ${Js(o)}`));let x=F(w.baseDir,"_tmp");io(x,{recursive:!0});let E=F(x,"absorb-prompt.txt");Mo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=Lo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Bo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if(k=_.stdout||"",!k)throw _}let T=k;try{let _=JSON.parse(k);T=_.result||_.content||"",T||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let j,C=[],D=T.indexOf("{"),q=T.indexOf("["),P=D>=0&&(q<0||D<q)?D:q;if(P===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(T.slice(0,500)));continue}let H=T[P],ae=H==="{"?"}":"]",B=0,ke=-1;for(let _=P;_<T.length;_++)if(T[_]===H)B++;else if(T[_]===ae&&(B--,B===0)){ke=_+1;break}if(ke===-1){console.log(m.red(" Unbalanced JSON"));continue}let fe=T.slice(P,ke);try{let _=JSON.parse(fe);Array.isArray(_)?j=_:(j=_.articles||[],C=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${fe.slice(0,300)}`));continue}for(let _ of j){let Ue=new Date().toISOString().slice(0,10),ye=l(_.sources||[],h);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:p,access:"public",created:Ue,lastUpdated:Ue,sources:_.sources||[],graphPath:ye},_.content,p);let Eo=_.type?m.magenta(`[${_.type}]`)+" ":"",R=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Eo}${_.path}: ${_.title}${m.dim(R)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),g++),d++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let _ of C)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Ue=new _(Bt(e.dir)).add(C.map(ye=>({kind:"article",agentId:p,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));Ue.added>0&&console.log(m.dim(` queued ${Ue.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(d>0&&(console.log(m.green(` ${d} articles compiled across ${n.length} agent(s)`)),i)){let p=d>0?Math.round(g/d*100):0;console.log(m.dim(` ${g}/${d} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.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("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=km(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-O2PS7L3B.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!qe(l))console.log(m.yellow(` --reviews: no ${l}`));else{let d=new c(l,{readonly:!0});try{let g=d.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(g,{kinds:String(e.reviewKinds).split(",").map(h=>h.trim()).filter(Boolean)});let p=i.filter(h=>(h.occurrences??1)>1).length;console.log(m.dim(` ${g.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{d.close()}}}let r=await Bi({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,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 promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(l)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}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.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function km(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)}Z.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-3HXGBKGM.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=$e(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),d=parseInt(e.n),g=i(e.history,c);if(!s(g)){console.log(m.yellow(` no task-history at ${g}`));return}let p=[],u=t(g).sort().reverse();for(let y of u){let $=r(g,y),b=[];try{b=t($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=d)break;try{let A=JSON.parse(n(r($,v),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=d)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${g}`));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 h=[`# 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 $=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=l.findRelevant($.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
|
|
332
|
+
`)||"_(none returned)_",A;try{let x=await o($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let E=x.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
|
|
333
333
|
|
|
334
|
-
${
|
|
334
|
+
${x.answer}
|
|
335
335
|
|
|
336
|
-
**Citations:** ${E}`}}catch(
|
|
337
|
-
`);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))});Z.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-OIFU3KSQ.js"),s=e.answers?
|
|
338
|
-
`),me.trim()}return(await c.question(R)).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 d=e.topic||"";if(!d&&(d=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!d||d==="/abort")){c?.close();return}let g=(e.type||"").toLowerCase(),
|
|
336
|
+
**Citations:** ${E}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),h.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.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=h.join(`
|
|
337
|
+
`);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))});Z.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-OIFU3KSQ.js"),s=e.answers?Wt(e.answers,"utf-8").split(/\r?\n/).filter(R=>R.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=$e(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(R){console.log(m.red(` can't open wiki for agent "${e.agent}": ${R.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async R=>{if(s){let me=s[i++]??"";return process.stdout.write(R+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
|
|
338
|
+
`),me.trim()}return(await c.question(R)).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 d=e.topic||"";if(!d&&(d=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!d||d==="/abort")){c?.close();return}let g=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(g)){console.log(m.dim(` Types: ${n.join(" | ")}`));let R=await l(m.cyan(" Type? "));if(R==="/abort"){c?.close();return}p.has(R)?g=R:(console.log(m.yellow(` "${R}" isn't a valid type. Falling back to "concept".`)),g="concept")}let u={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?"]},h=u[g]||u.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(d)} \xB7 Type: ${m.magenta(g)}`)),console.log(m.dim(` ${h.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let R=0;R<h.length;R++){let me=h[R],We=await l(` ${m.dim(`[${R+1}/${h.length}]`)} ${me}
|
|
339
339
|
${m.green(">")} `);if(We==="/abort"){y=!0;break}if(We==="/done")break;We!=="/skip"&&We&&w.push({q:me,a:We})}if(!y){let R=await l(`
|
|
340
340
|
${m.dim("Anything else worth capturing?")}
|
|
341
341
|
${m.green(">")} `);R&&R!=="/abort"&&R!=="/done"&&w.push({q:"Anything else worth capturing?",a:R})}if(y||w.length===0){console.log(m.yellow(`
|
|
342
342
|
Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(R=>`- ${R.meta.title} [${R.meta.type||"?"}]`).join(`
|
|
343
|
-
`),
|
|
343
|
+
`),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${d}`,`**Type:** ${g}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(R=>`
|
|
344
344
|
Q: ${R.q}
|
|
345
345
|
A: ${R.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\`: ${g}`,' - `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(`
|
|
346
|
-
`),A=F(a.baseDir,"_tmp");
|
|
347
|
-
`)){let me=R.match(/^(\w+):\s*(.+)$/);me&&(C[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],q=C.title||d,P=q.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),
|
|
348
|
-
`)){let
|
|
349
|
-
`)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let
|
|
346
|
+
`),A=F(a.baseDir,"_tmp");io(A,{recursive:!0});let x=F(A,`interview-${t().slice(0,8)}.txt`);Mo(x,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let R=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Lo(R,{env:Bo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let We=JSON.parse(me);E=String(We.result||We.content||"")}catch{E=me}}catch(R){console.log(m.red(` synthesis failed: ${R.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let k=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(E=k[1].trim());let T=E.indexOf("---");T>0&&(E=E.slice(T));let j=E.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(E.slice(0,600)),c?.close();return}let C={};for(let R of j[1].split(`
|
|
347
|
+
`)){let me=R.match(/^(\w+):\s*(.+)$/);me&&(C[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],q=C.title||d,P=q.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[g]||g+"s"}/${P}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let B=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/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 ${x} (prompt only; no article file)`));return}let ke=D,fe={title:q,type:C.type||g,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(R=>R.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(R=>R.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let R=process.env.EDITOR||"vi",me=F(A,`draft-${t().slice(0,8)}.md`);Mo(me,E);try{Lo(`${R} '${me}'`,{stdio:"inherit"});let zn=Wt(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(zn){let ao={};for(let yt of zn[1].split(`
|
|
348
|
+
`)){let Yn=yt.match(/^(\w+):\s*(.+)$/);Yn&&(ao[Yn[1]]=Yn[2].trim().replace(/^"(.*)"$/,"$1"))}ke=zn[2],fe={...fe,title:ao.title||fe.title,type:ao.type||fe.type,access:ao.access||fe.access,related:ao.related?ao.related.replace(/^\[|\]$/g,"").split(",").map(yt=>yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.related,tags:ao.tags?ao.tags.replace(/^\[|\]$/g,"").split(",").map(yt=>yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.tags}}}catch(We){console.log(m.red(` editor failed: ${We.message}`));return}}if(!a.writeArticle(ae,fe,ke,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let Ue=a.extractWikilinks(ke),ye=new Map;for(let R of a.listArticles(e.agent))ye.set(R.meta.title.toLowerCase(),!0);let Eo=Ue.filter(R=>!ye.has(R.toLowerCase()));if(Eo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let R of Eo.slice(0,8))console.log(m.dim(` - ${R}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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-3HXGBKGM.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=$e(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(u){console.log(m.red(` can't open wiki for agent "${e.agent}": ${u.message}`));return}let r=null;if(e.script){let h=Wt(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of h){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async u=>a?(await a.question(u)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),d=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${d?"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 g=[],p=0;for(let u=0;u<l;u++){let h,w;if(r){let H=r[u];if(!H)break;h=H.q,w=H.verdict,console.log(m.cyan(` [${u+1}] Q: `)+h)}else{if(h=await c(m.cyan(` [${u+1}] Q: `)),!h||h==="/done"||h==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(h,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(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
349
|
+
`)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={q:h,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)")),g.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(g.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let E=i.readArticle(x.path);if(!E){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let k=xm(E.content,v,A,E.meta.title,E.meta.type),T=F(i.baseDir,"_tmp");io(T,{recursive:!0});let j=F(T,`quiz-patch-${t().slice(0,8)}.txt`);Mo(j,k);let C="";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"`,ae=Lo(H,{env:Bo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ke=JSON.parse(ae);C=String(ke.result||ke.content||"")}catch{C=ae}let B=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(C=B[1].trim()),C=C.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=E.content.split(`
|
|
350
350
|
`).length,q=C.split(`
|
|
351
|
-
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${q} lines (${q-D>=0?"+":""}${q-D})`)),!d){console.log(m.dim(" (--no-commit: patch not written)"))
|
|
352
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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=$e(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=
|
|
353
|
-
`).length,w=
|
|
354
|
-
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${
|
|
355
|
-
`)}function
|
|
351
|
+
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${q} lines (${q-D>=0?"+":""}${q-D})`)),!d){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,$.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),p>0&&d&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${g.length} rounds, ${p} patches applied.`)),e.out){let u=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${g.length} rounds \xB7 ${p} patches_`,""];for(let h=0;h<g.length;h++){let w=g[h];u.push(`## ${h+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}\``:""),"")}Mo(e.out,u.join(`
|
|
352
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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=$e(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=Ya(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{Lo(`${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,d=s.extractWikilinks(c.content).filter(u=>l.has(u)?!1:(l.add(u),!0)),g=c.meta.related||[];(d.some(u=>!g.includes(u))||g.some(u=>!d.includes(u)))&&(s.writeArticle(i,{...c.meta,related:d.length?d:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${d.length} wikilink${d.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)}`))}});Z.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=$e(n.dir),a;try{a=r.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=Ya(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 d=vm(l.content,l.meta.title,l.meta.type,t),g=F(a.baseDir,"_tmp");io(g,{recursive:!0});let p=F(g,`patch-${i().slice(0,8)}.txt`);Mo(p,d),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let u="";try{let x=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=Lo(x,{env:Bo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let T=JSON.parse(E);u=String(T.result||T.content||"")}catch{u=E}let k=u.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(u=k[1].trim()),u=u.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!u||u.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let h=l.content.split(`
|
|
353
|
+
`).length,w=u.split(`
|
|
354
|
+
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${h} \u2192 ${w} lines (${w-h>=0?"+":""}${w-h})`)),console.log(),console.log(u),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),E=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=E==="y"||E==="yes"}if(!y){console.log(m.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(u).filter(x=>$.has(x)?!1:($.add(x),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},u,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(x=>!b.includes(x));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 Ya(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`,d=s.find(g=>g.path===l||g.path===n);if(d)return d.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let d=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return d===a||d.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function vm(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(`
|
|
355
|
+
`)}function xm(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
356
356
|
|
|
357
357
|
${t}
|
|
358
358
|
|
|
@@ -365,8 +365,8 @@ Incorporate it into the most relevant existing section, or create a short new se
|
|
|
365
365
|
${t}
|
|
366
366
|
|
|
367
367
|
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(`
|
|
368
|
-
`)}Z.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=$e(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,d=0;for(let g of t){let
|
|
369
|
-
`)){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
|
|
368
|
+
`)}Z.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=$e(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,d=0;for(let g of t){let p=F(s,"agents",g);if(!qe(p))continue;let u=F(p,i),h=r.map(b=>({mode:b,dir:F(p,b)})).filter(b=>qe(b.dir));if(h.length===0)continue;let w=new Map;Bs(u,b=>{let v=Ja(u,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=Ga(Wt(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 h)Bs(b.dir,v=>{let A=Ja(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=Ga(Wt(v,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=h.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(g)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let E=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),k=x==="promote"?m.green("\u2192 promote "):x==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),T=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${E} ${m.dim(b.mode+"/")}${T}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?l++:d++;continue}try{if(x==="promote"){let j=F(u,b.relPath);qe(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),za(p,b),d++):(io(Ha(j),{recursive:!0}),Rn(b.absPath,j),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let j=F(u,A.relPath);if(qe(j)){let C=F(p,"_versions",A.relPath.replace(/\.md$/,""));io(C,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Rn(j,F(C,`${D}.md`))}io(Ha(j),{recursive:!0}),Rn(b.absPath,j),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else za(p,b),d++}catch(j){console.log(m.red(` ! ${x} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of h)try{$m(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(g).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: ${d}`)),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 ${d}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Bs(e,o){if(qe(e))for(let t of bm(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?Bs(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Ga(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
|
|
369
|
+
`)){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 za(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));io(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Rn(o.absPath,F(t,`${n}.md`))}Z.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=$e(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 d=o.getAgentWiki(l),g=d.listArticles(l),p=g.filter($=>!$.meta.type);if(r+=g.length,a+=p.length,p.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${g.length} articles)`);continue}let u=Math.max(0,s-c),h=Math.min(p.length,u);if(h===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${h}/${p.length} untyped articles`));let w=d.baseDir,y=F(w,"_tmp");io(y,{recursive:!0});for(let $=0;$<h;$+=n){let b=p.slice($,Math.min($+n,h)),v=Em(b),A=F(y,"migrate-prompt.txt");Mo(A,v);let x;try{let E=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,k=Lo(E,{env:Bo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),T=JSON.parse(k),C=String(T.result||T.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");x=JSON.parse(C[0])}catch(E){console.log(m.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let k=x.find(P=>P.path===E.path),T=Sm(k?.type);if(!k||!T){console.log(m.yellow(` ? ${E.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let j=d.extractWikilinks(E.content),C={...E.meta,type:T.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":""}`):"",q=T.alias?m.dim(` (from "${T.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+T.type+"]")}${q} ${E.path}${D}`),i&&(d.writeArticle(E.path,C,E.content,l),c++)}}i&&d.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 Sm(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 Em(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}"
|
|
370
370
|
title: "${t.meta.title}"
|
|
371
371
|
tags: [${i}]
|
|
372
372
|
body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
|
|
@@ -406,45 +406,45 @@ Output (JSON array, one entry per input article, same order):
|
|
|
406
406
|
[
|
|
407
407
|
{"path": "path/to/article.md", "type": "project"},
|
|
408
408
|
...
|
|
409
|
-
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(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()});Z.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-ORSGLVRW.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(),
|
|
410
|
-
${
|
|
411
|
-
${u.length} article(s) below ${g}. 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."))});Z.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-R7EI3VGX.js"),n=$e(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),d=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(d)){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(d=>d.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.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=$e(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()});Z.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=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!qe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new lo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[g,u]of Object.entries(i.entries))r.set(g,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,d=0;for(let g of t){let u=o.getAgentWiki(g),p=u.listArticles(g),f=o.getSharedStore().listEntries(),w=new Map(f.map(x=>[x.id,x])),y=0,k=0,b=0;for(let x of p){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of x.meta.sources){let $=w.get(E);if(!$)continue;let T=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:T}),C=r.get(j);if(!C?.length)continue;let D=C.join("/"),q=A.get(D);q?q.n++:A.set(D,{path:C,n:1})}if(A.size===0)continue;k++,l++;let v;for(let E of A.values())(!v||E.n>v.n)&&(v=E);v&&(e.dryRun||(u.writeArticle(x.path,{...x.meta,graphPath:v.path},x.content,g),b++,d++))}console.log(` ${m.cyan(g)}: ${m.bold(p.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)}%), ${d} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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=$e(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-ORSGLVRW.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||[],d=c.nodeId||"unknown";console.log(m.dim(` Node: ${d} \u2014 ${l.length} entries`));let g=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${d}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),g++);g>0?console.log(m.green(` ${g} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=g;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let p=await u.json();for(let f of p.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()});Z.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 zn(o,void 0,c),g=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),p=l.getUnabsorbedEntries(t),f=new Set,w=0,y=new Set;for(let b of g.articles){for(let x of b.tags||[])f.add(x);w+=b.tags?.length||0;for(let x of b.sources||[])y.add(x)}let k=new Set(g.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Fs(c),articles:g.articles.length,entries:u.length,unabsorbed:p.length,uniqueTags:f.size,avgTags:g.articles.length>0?(w/g.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:g.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 d=s.map(g=>l(g).padEnd(i));console.log(` ${c.padEnd(20)} ${d.join(" ")}`)}console.log();let a=(c,l)=>{let d=Math.max(...s.map(u=>u[c])),g=s.filter(u=>u[c]===d).map(u=>u.label);d>0&&console.log(m.dim(` Best ${l}: ${g.join(", ")} (${d})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.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");qe(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:d}=await import("fs"),g=qe(s)?d(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${xm(g)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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-L4D2BOGY.js"),{askSeat:a}=await import("./seat-ZVHXNAEN.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=$e(e.dir,e.mode),d=[],g=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),p=0,f=[];e:for(let E of g){let $=l.getAgentWiki(E);for(let T of $.listArticles(E)){if(p>=u)break e;let j=$.readArticle(T.path);if(!j||e.type&&j.meta.type!==e.type)continue;p++;let C=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:T.path}],features:{agent:E,type:j.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,C.answers);for(let q of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&q.needsHuman||(e.ask&&q.needsHuman&&d.push({kind:"field",agentId:E,path:T.path,subject:j.meta.title,field:q.field,tier:q.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${q.label}?`}),f.push({tier:q.tier,need:q.field,how:q.needsHuman?m.yellow("ask"):q.sources.join("/"),uncertain:q.uncertain?"?":"",agent:E,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&d.length>0&&(w=new c(qt(e.dir)).add(d)),e.json){console.log(JSON.stringify(f,null,2));return}if(f.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...f.map($=>k($[E]).length))),x=(E,$)=>String(E)+" ".repeat(Math.max(0,b[$]-k(E).length));console.log(),console.log(m.bold(y.map((E,$)=>x(E,$)).join(" ")));for(let E of f)console.log(y.map(($,T)=>x(E[$],T)).join(" "));let A=f.filter(E=>E.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${f.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${f.length-A} need a person.`));let v=f[0]?.tier;if(v&&console.log(m.dim(` Start at ${v} \u2014 ${i[v]}.`)),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:E}=await import("./article-fields-L4D2BOGY.js"),$=E[e.notifyTier]??E.pillar,T=d.filter(j=>(E[j.tier??"furniture"]??9)<=$);if(T.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-ORSGLVRW.js"),C=j(),D=C?.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 q=T.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
|
|
409
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(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()});Z.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-ORSGLVRW.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(),ur(o,t,e.agent,n,e.mode)});Z.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-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-FZRNRAHQ.js"),c=$e(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),d=parseInt(e.limit),g=parseFloat(e.min),p=[];e:for(let y of l){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(p.length>=d)break e;let v=$.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):{}},x=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(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(x.answers),k=e.fields?r(v.meta.type,x.answers):null;E.completeness>=g&&!(k&&!k.fit)||p.push({agent:y,type:v.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.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,$)=>parseFloat(y.score)-parseFloat($.score));let u=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],h=u.map(y=>Math.max(y.length,...p.map($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(h[b])).join(" ");console.log(),console.log(m.bold(w(u)));for(let y of p)console.log(w(u.map($=>y[$])));if(e.fields){let y=p.filter($=>$.missing!=="-").length;console.log(m.dim(`
|
|
410
|
+
${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(`
|
|
411
|
+
${p.length} article(s) below ${g}. 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."))});Z.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-3HXGBKGM.js"),n=$e(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),d=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(d)){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(d=>d.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.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=$e(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()});Z.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=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!qe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new co({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[g,p]of Object.entries(i.entries))r.set(g,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,d=0;for(let g of t){let p=o.getAgentWiki(g),u=p.listArticles(g),h=o.getSharedStore().listEntries(),w=new Map(h.map(v=>[v.id,v])),y=0,$=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 E of v.meta.sources){let k=w.get(E);if(!k)continue;let T=String(k.meta?.sender??""),j=s.fingerprint({text:k.content,channel:k.source,sender:T}),C=r.get(j);if(!C?.length)continue;let D=C.join("/"),q=A.get(D);q?q.n++:A.set(D,{path:C,n:1})}if(A.size===0)continue;$++,l++;let x;for(let E of A.values())(!x||E.n>x.n)&&(x=E);x&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,g),b++,d++))}console.log(` ${m.cyan(g)}: ${m.bold(u.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${d} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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=$e(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-ORSGLVRW.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||[],d=c.nodeId||"unknown";console.log(m.dim(` Node: ${d} \u2014 ${l.length} entries`));let g=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}@${d}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),g++);g>0?console.log(m.green(` ${g} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=g;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let u=await p.json();for(let h of u.agents||[])h.totalEntries>0&&console.log(m.dim(` ${h.agentId}: ${h.totalEntries} entries, ${h.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()});Z.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 Xn(o,void 0,c),g=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),u=l.getUnabsorbedEntries(t),h=new Set,w=0,y=new Set;for(let b of g.articles){for(let v of b.tags||[])h.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(g.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Js(c),articles:g.articles.length,entries:p.length,unabsorbed:u.length,uniqueTags:h.size,avgTags:g.articles.length>0?(w/g.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:g.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 d=s.map(g=>l(g).padEnd(i));console.log(` ${c.padEnd(20)} ${d.join(" ")}`)}console.log();let a=(c,l)=>{let d=Math.max(...s.map(p=>p[c])),g=s.filter(p=>p[c]===d).map(p=>p.label);d>0&&console.log(m.dim(` Best ${l}: ${g.join(", ")} (${d})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.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");qe(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:d}=await import("fs"),g=qe(s)?d(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Am(g)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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-L4D2BOGY.js"),{askSeat:a}=await import("./seat-FZRNRAHQ.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=$e(e.dir,e.mode),d=[],g=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),u=0,h=[];e:for(let E of g){let k=l.getAgentWiki(E);for(let T of k.listArticles(E)){if(u>=p)break e;let j=k.readArticle(T.path);if(!j||e.type&&j.meta.type!==e.type)continue;u++;let C=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:T.path}],features:{agent:E,type:j.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,C.answers);for(let q of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&q.needsHuman||(e.ask&&q.needsHuman&&d.push({kind:"field",agentId:E,path:T.path,subject:j.meta.title,field:q.field,tier:q.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${q.label}?`}),h.push({tier:q.tier,need:q.field,how:q.needsHuman?m.yellow("ask"):q.sources.join("/"),uncertain:q.uncertain?"?":"",agent:E,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&d.length>0&&(w=new c(Bt(e.dir)).add(d)),e.json){console.log(JSON.stringify(h,null,2));return}if(h.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"],$=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...h.map(k=>$(k[E]).length))),v=(E,k)=>String(E)+" ".repeat(Math.max(0,b[k]-$(E).length));console.log(),console.log(m.bold(y.map((E,k)=>v(E,k)).join(" ")));for(let E of h)console.log(y.map((k,T)=>v(E[k],T)).join(" "));let A=h.filter(E=>E.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${h.length} gap(s) across ${u} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${h.length-A} need a person.`));let x=h[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${i[x]}.`)),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:E}=await import("./article-fields-L4D2BOGY.js"),k=E[e.notifyTier]??E.pillar,T=d.filter(j=>(E[j.tier??"furniture"]??9)<=k);if(T.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-ORSGLVRW.js"),C=j(),D=C?.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 q=T.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
|
|
412
412
|
`),P=T.length>10?`
|
|
413
413
|
\u2026and ${T.length-10} more`:"",H=`${T.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
414
414
|
${q}${P}
|
|
415
415
|
|
|
416
|
-
agentx wiki questions`,re=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${re}/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(B.ok?m.cyan(` Pushed ${T.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.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-L4D2BOGY.js"),{askSeat:r}=await import("./seat-ZVHXNAEN.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:d,recordsFromEntries:g}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),p=$e(e.dir,e.mode),f=e.agent?[e.agent]:p.listAgents(),w=parseInt(e.limit),y=d(),k=c(g(p.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),x=0,A=0,v=[],E=!1;e:for(let C of f){let D=p.getAgentWiki(C);for(let q of D.listArticles(C)){if(x>=w)break e;if(q.meta.type!=="person")continue;let P=D.readArticle(q.path);if(!P)continue;x++;let H=await r(s,n({title:P.meta.title,type:P.meta.type,body:P.content}),o(P.meta.type),{links:[{kind:"article",id:q.path}],features:{agent:C,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(P.meta.type,H.answers).missing.filter(R=>i.includes(R));if(B.length===0)continue;let{records:ke,results:he}=await a([{name:P.meta.title,type:"person"}],{sources:y}),_=b.get(P.meta.title.toLowerCase().trim());if(!E){for(let R of l(he,y))console.log(m.yellow(` ! ${R.source} ${R.kind} \u2014 would supply ${R.provides.join(", ")}`)),console.log(m.dim(` ${R.hint}`));E=!0}let Me=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([R,me])=>[R,me.value]))}]:[],...ke]);if(Me.length===0)continue;let{content:ye,edits:Eo}=u(P.content,Me[0],B);if(Eo.length!==0){for(let R of Eo)v.push({agent:C,article:P.meta.title.slice(0,32),field:R.field,action:R.replaced?"replace":"add",got:`${R.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(q.path,P.meta,ye,C)?A++:console.log(m.red(` could not write ${q.path}`)))}}}if(e.json){console.log(JSON.stringify(v,null,2));return}if(v.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],T=$.map(C=>Math.max(C.length,...v.map(D=>String(D[C]).length))),j=C=>C.map((D,q)=>String(D).padEnd(T[q])).join(" ");console.log(),console.log(m.bold(j($)));for(let C of v)console.log(j($.map(D=>C[D])));console.log(),e.apply?(console.log(m.green(` ${v.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(` ${v.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.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-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(qt(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`))});Z.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-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(qt(t.dir));if(t.dismiss){let p=r.resolve(e,"dismissed");console.log(p?m.dim(` dismissed: ${p.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=$e(t.dir,t.mode).getAgentWiki(a.agentId),d=l.readArticle(a.path);if(!d){console.log(m.yellow(` article gone: ${a.path}`));return}let g=s(d.content,a.field,`${o} (answered by operator)`);if(!g){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,d.meta,g.content,a.agentId);console.log(u?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Z.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-LK34TSQD.js"),{askSeat:i}=await import("./seat-ZVHXNAEN.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:d}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:g}=await import("./calibration-ILS5OI44.js"),p=$e(e.dir,"graph").getSharedStore(),f=p.listEntries(),w=new Set(p.getUnabsorbedEntries().map(P=>P.id)),{labeled:y,backlog:k}=r(f,w),b=a(y,P=>P.absorbed,parseInt(e.n)),x={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=[],v=0,E=Date.now();if(e.load){let{readFileSync:P}=await import("fs");A.push(...JSON.parse(P(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 P of e.load?[]:b){let H=await i(o,n(P),t,{features:{source:P.source??"",absorbed:P.absorbed}});if(!H){v++;continue}let re=H.answers;A.push({entry:P,verdict:s(H.answers,x),citeWorthy:re.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:P}=await import("fs");P(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),T=l(A,"seat","seat"),j=g(T,{minN:50}),C=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:v,elapsed:C},null,2));return}let D=P=>`${(P*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 P=$.droppedBy;console.log(m.dim(` dropped by: type ${P.type} \xB7 worth ${P.worth} \xB7 durability ${P.durability} (a positive can fail several)`))}let q=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${q.worth.toFixed(2)} \xB7 durability ${q.durability.toFixed(2)} \xB7 typeConf ${q.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${v} 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 P=parseFloat(e.minRecall),{best:H,points:re}=d(A,{minRecall:P});if(console.log(),console.log(m.bold(` threshold sweep (${re.length} policies, recall floor ${D(P)})`)),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(P)} recall \u2014 not even keeping everything typed.`));let B=re.slice().sort((ke,he)=>he.recall-ke.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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);qe(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");qe(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 xm(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"}Fc();import{Command as Sm}from"commander";import N from"chalk";import{resolve as Rn}from"path";import{existsSync as Em}from"fs";Oe();var at=new Sm().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");at.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=W();if(!o.graph?.enabled){console.log(N.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(N.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(N.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 lo({baseDir:Rn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(N.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(N.bold(` Graph review \u2014 ${r.length} pending`)),console.log(N.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,d=0,g=0,u=0;for(let f=0;f<r.length;f++){let w=r[f],y=Vt(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${N.cyan(w.msgHash.slice(0,8))} ${N.dim(y)} ... `);let k=Am(w,a,c),b=null;try{b=await Om(n,t,k,o.dashboard?.token)}catch(v){u++,console.log(N.red(`ERR ${v.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(N.red("ERR no decision"));continue}let x=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(N.green("APPROVE")+" "+N.dim(A)),e.dryRun)l++;else try{Im(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(v){console.log(N.yellow(` (commit failed, staying pending: ${v.message?.slice(0,100)})`)),u++}else x==="reject"?(console.log(N.red("REJECT")+" "+N.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),d++):(console.log(N.yellow("SKIP")+" "+N.dim(A||x)),g++)}console.log();let p=e.dryRun?"would":"did";console.log(N.dim(` Summary: ${p} approve ${l}, ${p} reject ${d}, ${g} skipped, ${u} errors.`)),e.dryRun&&(l>0||d>0)&&console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});at.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=W();if(!o.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Rn(process.cwd(),o.graph.baseDir);if(!Em(t)){console.log(N.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new lo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(N.dim(" "),...a)});console.log(),console.log(N.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(N.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});at.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=W();if(!o.graph?.enabled){console.log(N.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 lo({baseDir:Rn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(N.bold(` graph pull \u2190 ${t}`));let l,d,g;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}`);d=(await j.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);g=(await C.json()).classifications||[]}catch($){console.log(N.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),p=l?.levels?.map($=>$.id).join(","),f=u===p;f?console.log(N.dim(` schema matches (${r.levels.length} levels)`)):(console.log(N.yellow(" \u26A0 schema levels differ:")),console.log(N.dim(` local: ${u}`)),console.log(N.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(N.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(N.yellow(" keeping local schema; node import may fail if levels disagree")));let w=f?r:l,y=new Map;w.levels.forEach(($,T)=>y.set($.id,T));let k=[...d].sort(($,T)=>(y.get($.level)??99)-(y.get(T.level)??99)),b=0,x=0,A=0;for(let $ of k){if(c.has($.id)){x++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(T){A++,console.log(N.yellow(` skip node ${$.id}: ${T.message?.slice(0,100)}`))}}console.log(N.dim(` nodes: +${b} added \xB7 ${x} already-present \xB7 ${A} failed`));let v=0,E=0;for(let $ of g)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){E++;continue}if(e.dryRun){v++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),v++}console.log(N.dim(` fingerprints: +${v} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` \u2713 pulled from ${t}`)),console.log()});function Am(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(`
|
|
416
|
+
agentx wiki questions`,ae=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/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(B.ok?m.cyan(` Pushed ${T.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.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-L4D2BOGY.js"),{askSeat:r}=await import("./seat-FZRNRAHQ.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:d,recordsFromEntries:g}=await import("./facts-YVEJOM7O.js"),{backfillArticle:p}=await import("./backfill-MTD2B62I.js"),u=$e(e.dir,e.mode),h=e.agent?[e.agent]:u.listAgents(),w=parseInt(e.limit),y=d(),$=c(g(u.getSharedStore().listEntries())),b=new Map($.map(C=>[C.name.toLowerCase().trim(),C])),v=0,A=0,x=[],E=!1;e:for(let C of h){let D=u.getAgentWiki(C);for(let q of D.listArticles(C)){if(v>=w)break e;if(q.meta.type!=="person")continue;let P=D.readArticle(q.path);if(!P)continue;v++;let H=await r(s,n({title:P.meta.title,type:P.meta.type,body:P.content}),o(P.meta.type),{links:[{kind:"article",id:q.path}],features:{agent:C,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(P.meta.type,H.answers).missing.filter(R=>i.includes(R));if(B.length===0)continue;let{records:ke,results:fe}=await a([{name:P.meta.title,type:"person"}],{sources:y}),_=b.get(P.meta.title.toLowerCase().trim());if(!E){for(let R of l(fe,y))console.log(m.yellow(` ! ${R.source} ${R.kind} \u2014 would supply ${R.provides.join(", ")}`)),console.log(m.dim(` ${R.hint}`));E=!0}let Ue=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([R,me])=>[R,me.value]))}]:[],...ke]);if(Ue.length===0)continue;let{content:ye,edits:Eo}=p(P.content,Ue[0],B);if(Eo.length!==0){for(let R of Eo)x.push({agent:C,article:P.meta.title.slice(0,32),field:R.field,action:R.replaced?"replace":"add",got:`${R.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(q.path,P.meta,ye,C)?A++:console.log(m.red(` could not write ${q.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],T=k.map(C=>Math.max(C.length,...x.map(D=>String(D[C]).length))),j=C=>C.map((D,q)=>String(D).padEnd(T[q])).join(" ");console.log(),console.log(m.bold(j(k)));for(let C of x)console.log(j(k.map(D=>C[D])));console.log(),e.apply?(console.log(m.green(` ${x.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(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.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-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(Bt(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`))});Z.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-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(Bt(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=$e(t.dir,t.mode).getAgentWiki(a.agentId),d=l.readArticle(a.path);if(!d){console.log(m.yellow(` article gone: ${a.path}`));return}let g=s(d.content,a.field,`${o} (answered by operator)`);if(!g){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,d.meta,g.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Z.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-LK34TSQD.js"),{askSeat:i}=await import("./seat-FZRNRAHQ.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:d}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:g}=await import("./calibration-ILS5OI44.js"),u=$e(e.dir,"graph").getSharedStore(),h=u.listEntries(),w=new Set(u.getUnabsorbedEntries().map(P=>P.id)),{labeled:y,backlog:$}=r(h,w),b=a(y,P=>P.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=[],x=0,E=Date.now();if(e.load){let{readFileSync:P}=await import("fs");A.push(...JSON.parse(P(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 (${$} in backlog) \u2014 grading ${b.length}`));for(let P of e.load?[]:b){let H=await i(o,n(P),t,{features:{source:P.source??"",absorbed:P.absorbed}});if(!H){x++;continue}let ae=H.answers;A.push({entry:P,verdict:s(H.answers,v),citeWorthy:ae.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:P}=await import("fs");P(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),T=l(A,"seat","seat"),j=g(T,{minN:50}),C=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:j,failures:x,elapsed:C},null,2));return}let D=P=>`${(P*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${D(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.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)")}`),k.lostPositives>0){let P=k.droppedBy;console.log(m.dim(` dropped by: type ${P.type} \xB7 worth ${P.worth} \xB7 durability ${P.durability} (a positive can fail several)`))}let q=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${q.worth.toFixed(2)} \xB7 durability ${q.durability.toFixed(2)} \xB7 typeConf ${q.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${x} 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 P=parseFloat(e.minRecall),{best:H,points:ae}=d(A,{minRecall:P});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${D(P)})`)),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(P)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((ke,fe)=>fe.recall-ke.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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);qe(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");qe(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 Am(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"}Wc();import{Command as Om}from"commander";import N from"chalk";import{resolve as Tn}from"path";import{existsSync as Im}from"fs";Oe();var at=new Om().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");at.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=W();if(!o.graph?.enabled){console.log(N.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(N.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(N.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 co({baseDir:Tn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(N.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(N.bold(` Graph review \u2014 ${r.length} pending`)),console.log(N.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,d=0,g=0,p=0;for(let h=0;h<r.length;h++){let w=r[h],y=Qt(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${h+1}/${r.length}] ${N.cyan(w.msgHash.slice(0,8))} ${N.dim(y)} ... `);let $=Cm(w,a,c),b=null;try{b=await jm(n,t,$,o.dashboard?.token)}catch(x){p++,console.log(N.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(N.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(N.green("APPROVE")+" "+N.dim(A)),e.dryRun)l++;else try{Rm(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(x){console.log(N.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(N.red("REJECT")+" "+N.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),d++):(console.log(N.yellow("SKIP")+" "+N.dim(A||v)),g++)}console.log();let u=e.dryRun?"would":"did";console.log(N.dim(` Summary: ${u} approve ${l}, ${u} reject ${d}, ${g} skipped, ${p} errors.`)),e.dryRun&&(l>0||d>0)&&console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});at.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=W();if(!o.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Tn(process.cwd(),o.graph.baseDir);if(!Im(t)){console.log(N.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new co({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(N.dim(" "),...a)});console.log(),console.log(N.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(N.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});at.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=W();if(!o.graph?.enabled){console.log(N.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 co({baseDir:Tn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(N.bold(` graph pull \u2190 ${t}`));let l,d,g;try{let k=await fetch(`${t}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);d=(await j.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);g=(await C.json()).classifications||[]}catch(k){console.log(N.red(` fetch failed: ${k.message}`));return}let p=r.levels.map(k=>k.id).join(","),u=l?.levels?.map(k=>k.id).join(","),h=p===u;h?console.log(N.dim(` schema matches (${r.levels.length} levels)`)):(console.log(N.yellow(" \u26A0 schema levels differ:")),console.log(N.dim(` local: ${p}`)),console.log(N.dim(` peer: ${u}`)),a.length===0&&!e.dryRun?(console.log(N.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(N.yellow(" keeping local schema; node import may fail if levels disagree")));let w=h?r:l,y=new Map;w.levels.forEach((k,T)=>y.set(k.id,T));let $=[...d].sort((k,T)=>(y.get(k.level)??99)-(y.get(T.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${t}`}),c.add(k.id),b++}catch(T){A++,console.log(N.yellow(` skip node ${k.id}: ${T.message?.slice(0,100)}`))}}console.log(N.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let x=0,E=0;for(let k of g)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){E++;continue}if(e.dryRun){x++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),x++}console.log(N.dim(` fingerprints: +${x} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` \u2713 pulled from ${t}`)),console.log()});function Cm(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(`
|
|
417
417
|
`),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(`
|
|
418
|
-
`)}async function
|
|
418
|
+
`)}async function jm(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 bi((c?.content||"").toString())}finally{clearTimeout(r)}}function Rm(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Hs(){let e=W();if(!e.graph?.baseDir)return console.log(N.red(" graph.baseDir is not configured")),null;let o=Tn(process.cwd(),e.graph.baseDir);return{store:new co({baseDir:o}),baseDir:o}}var Gs=at.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Gs.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=Hs();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.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(N.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):N.dim("cache");console.log(` ${N.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${N.bold(Qt(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(N.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(N.dim(` ${r.length} to check (${e.strategy}).`)),console.log(N.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Gs.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(N.red(" verdict must be correct | wrong | unsure"));return}let n=Hs();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(N.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(N.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(N.green(` ${o}: ${Qt(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(N.dim(` should have been: ${t.path}`))});Gs.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Hs();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.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} ${N.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(N.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),d=c.n>=5&&l>.15?N.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${d}`)}}console.log(),r.calibratable<100?console.log(N.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(N.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as Lm}from"commander";import Y from"chalk";import{Command as Xa}from"commander";import se from"chalk";import{existsSync as Tm}from"fs";import{resolve as Nm}from"path";import _m from"better-sqlite3";function Dm(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(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Pm(e){let o=Nm(process.cwd(),e);return Tm(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new _m(o,{readonly:!0})}var Va=new Xa().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(kt)).option("--max <n>","max clusters distilled per run",String(on)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Pm(e.path),t=await Ji(o,{since:Dm(e.since),agentId:e.agent,sessions:new Si(process.cwd()),minOccurrences:Number(e.minOccurrences)||kt,max:Number(e.max)||on,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
|
|
419
419
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(se.green(` \u2713 draft written: ${n.id}`)+se.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(se.yellow(` \u26A0 ${n}`));t.dryRun?console.log(se.dim(`
|
|
420
420
|
dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
|
|
421
|
-
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),
|
|
422
|
-
`),i=await de(a=>{we(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&we(a,"crons.procedure-extract.enabled",!1):o&&we(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(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ze=new
|
|
421
|
+
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Ka={hourly:"0 * * * *",daily:"0 3 * * *"},Qa=new Xa().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(kt)).option("--timezone <tz>","IANA timezone","Africa/Tunis").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?Ka.hourly:e.daily?Ka.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||kt,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 ${on} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
|
|
422
|
+
`),i=await de(a=>{we(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&we(a,"crons.procedure-extract.enabled",!1):o&&we(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(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ze=new Lm().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ze.addCommand(Va);ze.addCommand(Qa);ze.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 lo,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"}.`))});ze.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 lo,t=e.steps?String(e.steps):`## Steps
|
|
423
423
|
|
|
424
424
|
1. (fill in)
|
|
425
425
|
|
|
426
426
|
## Notes
|
|
427
427
|
|
|
428
|
-
`;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)}});ze.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new
|
|
428
|
+
`;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)}});ze.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new lo,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()});ze.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new lo;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)}});ze.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new lo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});ze.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new lo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});ze.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 lo,n=Pi(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 Fm}from"commander";import S from"chalk";import{resolve as lt,basename as qm}from"path";import{existsSync as zs,readFileSync as Ys,writeFileSync as Nn}from"fs";import Mb from"better-sqlite3";import{readFileSync as Mm}from"fs";import{resolve as ct,dirname as Za}from"path";import{fileURLToPath as Um}from"url";var Jt=[{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 ec(e){let o=Za(Um(import.meta.url)),t=process.argv[1]?Za(process.argv[1]):"",n=[ct(o,`${e}.yaml`),ct(o,"workflows/templates",`${e}.yaml`),ct(o,"..","workflows/templates",`${e}.yaml`),ct(o,"../..","workflows/templates",`${e}.yaml`),t?ct(t,"workflows/templates",`${e}.yaml`):"",t?ct(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Mm(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
|
|
429
429
|
${n.join(`
|
|
430
|
-
`)}`)}var
|
|
431
|
-
`)}else
|
|
432
|
-
`),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${d}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let g=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let
|
|
433
|
-
`;
|
|
430
|
+
`)}`)}var Le=new Fm().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Le.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ao().list();if(!o.length){console.log(S.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"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Le.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 Ao().get(e);n||(console.log(S.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Oi(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Le.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=lt(process.cwd(),e);zs(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=Ys(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Go(r,{filePath:e}):JSON.parse(r),l=Ho.safeParse(c);if(!l.success){console.log(S.red(` \u2717 ${i}`));for(let g of l.error.issues)console.log(` ${g.path.join(".")||"<root>"}: ${g.message}`);process.exit(1)}let d=Zt(l.data);if(d.length){console.log(S.yellow(` ! ${i} (lint)`));for(let g of d)console.log(` ${g}`);process.exit(1)}console.log(S.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof en?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Ao().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Le.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Jt.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");Jt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${Jt.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(S.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Ao;!o.force&&n.get(e)&&(console.log(S.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=ec(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=Go(s,{filePath:`${e}.yaml`}),c=Ho.safeParse(a);if(!c.success){console.log(S.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(S.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=lt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Go(s,{filePath:`${e}.yaml`}),c=Ho.parse(a);Nn(r,JSON.stringify(c,null,2)+`
|
|
431
|
+
`)}else Nn(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Le.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Jt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Le.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=lt(process.cwd(),e);zs(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=Ys(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Go(n,{filePath:e}):JSON.parse(n)}catch(p){let u=p instanceof en?p.message:`parse error: ${p?.message??p}`;console.log(S.red(` ${u}`)),process.exit(1)}let r=Ho.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=Zt(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new Ao,l=s?qm(e).match(/\.yml$/i)?"yml":"yaml":"json",d=lt(c.baseDir,`${r.data.id}.${l}`);if(Nn(d,s?n:JSON.stringify(r.data,null,2)+`
|
|
432
|
+
`),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${d}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let g=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(g,{method:"POST"});p.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Le.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 $t({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.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"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Le.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(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=lt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&zs(s)){let c=Ys(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),d;try{d=l?Go(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof en?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${v}`)),process.exit(1)}let g=Ho.safeParse(d);if(!g.success){console.log(S.red(" \u2717 schema:"));for(let b of g.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=Zt(g.data);if(p.length){console.log(S.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let u=new Ao,h=g.data.id.startsWith("_adhoc-")?g.data.id:`_adhoc-${g.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=lt(u.baseDir,`${h}.${w}`),$=l?c.replace(new RegExp(`^id:\\s*${g.data.id}\\b`,"m"),`id: ${h}`):JSON.stringify({...g.data,id:h},null,2)+`
|
|
433
|
+
`;Nn(y,$),n=h,console.log(S.dim(` ad-hoc registered as "${h}" \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 d=await c.text();console.log(S.red(` run failed (${c.status}): ${d.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?S.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Wm({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Wm(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"?S.green:a==="error"?S.red:S.cyan,l=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",d=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${l} ${d}`),r.error&&console.log(` ${S.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(` ${S.dim("run finished:")} ${c.status}`),console.log(S.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(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Le.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}oc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(S.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(S.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(S.yellow(` no traces for "${e}"`)),console.log(S.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(S.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)oc(i)});function oc(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.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))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}Le.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 $t({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Le.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 $t({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Le.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 $t({nodeId:t}).setStatus(e,"canceled")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 canceled ${e}`))});import{Command as tc}from"commander";import ee from"chalk";import Uo from"prompts";import{readFileSync as Bm,existsSync as Jm}from"fs";import{resolve as Hm}from"path";var Ht=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Ks=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),nc={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 sc(){let e=Hm(process.cwd(),"agentx.json");if(!Jm(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Bm(e,"utf-8"))}function Gm(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ee.yellow("\u26A0 no signing secret"):ee.green("\u2713 active"):ee.dim("disabled")}function zm(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Ks.has(e.source)?ee.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ee.cyan(e.id)} ${Gm(e)}`),console.log(` ${ee.dim(e.source)} \u2192 ${ee.bold(e.agentId)}${n}`),console.log(` POST ${ee.dim(t)}`),e.secretEnv&&console.log(` secret: ${ee.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ee.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ee.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ee.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var ro=new tc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");ro.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=sc(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ee.dim(`
|
|
434
434
|
No webhooks registered. Add one with: agentx webhook add
|
|
435
|
-
`));return}console.log();for(let n of t)
|
|
435
|
+
`));return}console.log();for(let n of t)zm(n)});ro.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Ht.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=sc(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(u=>u.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(),d=String(o.description||"").trim(),g=o.prompt!==!1;if(!r&&g&&(r=((await Uo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:h=>/^[a-z0-9][a-z0-9_-]*$/.test(h)||"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&&g&&(a=(await Uo({type:"select",name:"source",message:"Source",choices:Ht.map(h=>({title:`${h}${Ks.has(h)?" \u2713 wired":""}`,value:h,description:nc[h]}))})).source),!Ht.includes(a))throw new Error(`Source must be one of: ${Ht.join(", ")}`);if(!c&&g&&(i?c=((await Uo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Uo({type:"select",name:"agentId",message:"Agent",choices:n.map(h=>({title:h,value:h}))})).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&&g&&a!=="custom"&&(l=((await Uo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!d&&g&&(d=((await Uo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await de(u=>{if(u.webhooks=Array.isArray(u.webhooks)?u.webhooks:[],u.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let h={id:r,source:a,agentId:c,enabled:!0};l&&(h.secretEnv=l),d&&(h.description=d),i&&(h.node=i),u.webhooks.push(h)});if(!p.success)throw new Error(p.error);console.log(ee.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(ee.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ee.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});ro.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Uo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(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(ee.green(`\u2713 removed webhook "${e}"`))});function ic(e){return async o=>{let t=await de(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(ee.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}ro.command("enable <id>").description("enable a webhook entry").action(ic(!0));ro.command("disable <id>").description("disable a webhook entry").action(ic(!1));var _n=new tc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");_n.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(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(ee.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});_n.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(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(ee.green(`\u2713 removed trigger ${o} from "${e}"`))});_n.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 de(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(ee.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});ro.addCommand(_n);ro.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Ht.map(t=>({source:t,wired:Ks.has(t),hint:nc[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ee.green("\u2713 wired"):ee.dim("inbound-only");console.log(` ${ee.cyan(t.source.padEnd(8))} ${n} ${ee.dim(t.hint)}`)}console.log(),console.log(ee.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ee.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Ym}from"commander";import oe from"chalk";Oe();function dt(e){let{summary:o,backupPath:t}=Yo(n=>e(n));console.log(oe.green(`
|
|
436
436
|
\u2713 ${o}`)),t&&console.log(oe.dim(` Backup: ${t}`)),console.log(oe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
437
|
-
`))}function
|
|
438
|
-
`):(console.error(Re.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Re.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=
|
|
439
|
-
`))console.log(` ${s}`);console.log();let n=
|
|
440
|
-
\u2713 ${o}`)),t&&console.log(
|
|
441
|
-
`))}var pt=new
|
|
437
|
+
`))}function Dn(){try{return W().business||{}}catch{return{}}}var gt=new Ym().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");gt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Dn();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(oe.yellow(" business block not enabled (or missing).")),console.log(oe.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(oe.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(oe.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?oe.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?oe.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${oe.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(oe.bold(` Projects (${n.length})`)),n.length===0)console.log(oe.dim(" (empty)"));else for(let r of n){let a=r.pm?oe.dim(` \xB7 pm=${r.pm}`):"",c=r.client?oe.dim(` \xB7 client=${r.client}`):"";console.log(` ${oe.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(oe.bold(` Contact map (${s.length})`)),s.length===0)console.log(oe.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(` ${oe.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?oe.dim(` (${r.displayName})`):""}`)}console.log()});var Xs=gt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Xs.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Dn(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(oe.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${oe.cyan(n)} ${s.role}${s.reportsTo?oe.dim(` \u2192 ${s.reportsTo}`):""}`)});Xs.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);dt(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}`:""})`))});Xs.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{dt(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 Vs=gt.command("project").description("manage business.projects \u2014 id, pm, client");Vs.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Dn().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(oe.dim(" no projects"));return}for(let n of t)console.log(` ${oe.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Vs.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)=>{dt(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`})});Vs.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{dt(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 Qs=gt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Qs.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Dn().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(oe.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+"/":""}${oe.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Qs.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(oe.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),dt(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`})});Qs.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=>{dt(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 Km}from"commander";import Re from"chalk";Oe();var Xm={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Zs(e){let o=Xm[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Pn(){let o=W().business?.standup?.plansDir||".agentx/plans";return new rr(o)}var mt=new Km().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");mt.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=Zs(e),n=Pn(),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(`
|
|
438
|
+
`):(console.error(Re.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Re.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=ts(s);if(r.length){console.log(Re.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Re.dim(` \u2022 ${a}`))}});mt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Pn();if(e){let n=Zs(e),s=o.read(n);if(!s){console.log(Re.dim(` No ${n} plan set.`));return}rc(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Re.yellow(" No plan set at any tier.")),console.log(Re.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Re.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}rc(t.tier,t.date,t.content)});mt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Pn().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Re.dim(" No plans yet."));return}for(let n of t)console.log(` ${Re.cyan(n.tier.padEnd(5))} ${Re.bold(n.date.padEnd(11))} ${Re.dim(n.path)}`)});mt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Zs(e),n=Pn().read(o);if(!n){console.log(Re.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Re.green(` \u2713 ${o} plan cleared (${n.path})`))});function rc(e,o,t){console.log(Re.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
|
|
439
|
+
`))console.log(` ${s}`);console.log();let n=ts(t);n.length&&console.log(Re.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Vm}from"commander";import Fe from"chalk";Oe();function Qm(){try{return W().notifications||{}}catch{return{}}}function Ln(e){let{summary:o,backupPath:t}=Yo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Fe.green(`
|
|
440
|
+
\u2713 ${o}`)),t&&console.log(Fe.dim(` Backup: ${t}`)),console.log(Fe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
441
|
+
`))}var pt=new Vm().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");pt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Qm();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Fe.cyan(o.destination.channel+":"+o.destination.chatId)}${Fe.dim(n)}`)}else console.log(` destination ${Fe.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Fe.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Fe.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Fe.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Fe.dim("off")}`),console.log()});pt.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){Ln(o=>(delete o.destination,"notifications destination cleared"));return}Ln(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})`:""}`))});pt.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(Fe.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(Fe.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";Ln(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});pt.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(Fe.red(" threshold must be a non-negative integer")),process.exit(1)),Ln(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as Zm}from"commander";import ko from"chalk";import{readdirSync as ei,statSync as ac,unlinkSync as ep,rmSync as op,existsSync as cc}from"fs";import{resolve as lc,join as dc}from"path";var gc=[{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 oi(e,o){if(!cc(e))return[];let t=[];for(let n of ei(e,{withFileTypes:!0})){let s=dc(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...oi(s,!0))}return t}var Un=new Zm().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Un.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of gc){let t=lc(process.cwd(),o.dir),n=oi(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=ac(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(` ${ko.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Mn(s).padStart(10)} oldest=${r}`)}console.log(ko.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Mn(e).padStart(10)} total`)),console.log(),console.log(ko.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Un.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(ko.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(ko.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?ko.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of gc){if(n&&r.dir!==n)continue;let a=lc(process.cwd(),r.dir),c=oi(a,!!r.recursive),l=0,d=0;for(let p of c)try{let u=ac(p);if(u.mtimeMs<t&&(d+=u.size,l++,!e.dryRun))try{ep(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{mc(a)}catch{}let g=e.dryRun?"would remove":"removed";console.log(` ${ko.cyan(r.dir.padEnd(22))} ${g} ${String(l).padStart(5)} files (${Mn(d)})`),s+=l,i+=d}console.log(),console.log(ko.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Mn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function mc(e){if(cc(e))for(let o of ei(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=dc(e,o.name);mc(t);try{ei(t).length===0&&op(t,{recursive:!1})}catch{}}}function Mn(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 tp}from"commander";import M from"chalk";var vo=new tp().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");vo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new zo().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(M.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?M.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(` ${M.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${M.dim(i)}`)}console.log()});vo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new zo().get(e);if(n||(console.log(M.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(M.bold(` ${n.title}`)),n.description&&console.log(M.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(M.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?M.red("*"):" ",r=s.defaultValue!==void 0?M.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?M.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${M.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});vo.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=np(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(M.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(M.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(M.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(M.red(" --kind must be shell|http")),process.exit(1);let s=Ii.safeParse(n);if(!s.success){console.log(M.red(" validation failed:"));for(let a of s.error.issues)console.log(M.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new zo().save(s.data);console.log(M.green(`
|
|
442
442
|
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(M.dim(` Test: agentx actions run ${r.id}
|
|
443
|
-
`))});vo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new zo().delete(e)||(console.log(M.red(` no action "${e}"`)),process.exit(1)),console.log(M.green(` \u2713 action "${e}" removed`))});vo.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 zo().get(e);n||(console.log(M.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(M.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await
|
|
443
|
+
`))});vo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new zo().delete(e)||(console.log(M.red(` no action "${e}"`)),process.exit(1)),console.log(M.green(` \u2713 action "${e}" removed`))});vo.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 zo().get(e);n||(console.log(M.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(M.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ci(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?M.green("\u2713 ok"):M.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(M.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(M.dim(" --- errors ---")),console.log(M.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(M.red(` ${i.message}`)),process.exit(1)}});vo.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(M.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(M.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(M.bold(" Built-in typed actions")),console.log(M.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?M.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${M.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(M.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(M.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(M.bold(` ${r.name}`)),r.description&&console.log(M.dim(` ${r.description}`)),console.log(),console.log(M.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(M.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(M.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(M.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(M.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(M.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function np(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}Oe();import{Command as sp}from"commander";import V from"chalk";var pc=new sp().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=W(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(V.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(V.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(V.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:d,value:g}=await a.read();if(d)break;l+=c.decode(g,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
444
444
|
|
|
445
|
-
`))>=0;){let
|
|
446
|
-
`))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?
|
|
447
|
-
bye`)),process.exit(0)});;){let d;try{d=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!d)continue;if(d==="/exit"||d==="/quit"){a.close();return}if(d==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(d==="/clear"){i=`chat-cli:${
|
|
445
|
+
`))>=0;){let u=l.slice(0,p);l=l.slice(p+2),ip(u)}}}catch(r){console.error(V.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function ip(e){let o="message",t="";for(let i of e.split(`
|
|
446
|
+
`))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?V.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=V.cyan(n.phase?.padEnd(9)??"run"),r=V.bold(n.workflowId??""),a=V.dim((n.runId??"").slice(0,8)),c=n.nodeId?V.yellow(n.nodeId):"",l=n.note?V.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=V.magenta(`task.${n.phase}`.padEnd(14)),r=V.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?V.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${V.cyan(a)} ${c}`);break}case"signal":{let i=V.green("signal".padEnd(9)),r=V.bold(n.name),a=V.dim(`(${n.scope})`),c=n.workflowId?V.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=V.blue("mesh".padEnd(9)),r=V.bold(n.peer),a=n.healthy?V.green("\u2713 healthy"):V.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${V.dim(n.delta??"")}`);break}case"channel":{let i=V.yellow("channel".padEnd(9)),r=n.direction==="in"?V.cyan("\u2190"):V.magenta("\u2192"),a=V.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?V.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(V.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 ap}from"commander";import Fn from"chalk";import{spawn as cp}from"node:child_process";import{execFileSync as rp}from"node:child_process";function uc(e=()=>rp("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 hc=new ap().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(Fn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-5Z3URGPY.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:uc();if(n?.ok){let{fetchAgents:l}=await import("./client-5Z3URGPY.js"),d=await l(t);if(!d.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let g=e.agent||d[0].id;if(!d.some(y=>y.id===g))throw new Error(`Unknown AgentX agent: ${g}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let u=Object.fromEntries(d.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),h={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${g}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:u}}})};console.error(Fn.dim(`Opening ${n.version} with AgentX model ${g}.`));let w=cp("opencode",["--standalone"],{stdio:"inherit",env:h});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Fn.yellow(n.reason)),console.error(Fn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-IEQXWJ7B.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 lp}from"commander";import K from"chalk";import{randomUUID as wc}from"crypto";import{createInterface as dp}from"node:readline/promises";import gp from"ora";import qn from"chalk";function fc(e){console.error(),console.error(qn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(qn.dim(` ${e.why}`)),console.error(),console.error(` Use ${qn.cyan(e.instead)} instead.`),e.note&&console.error(qn.dim(` ${e.note}`)),console.error()}var yc={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 bc=new lp().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)=>{fc({what:"agentx chat",...yc});let t=hr({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${wc().slice(0,12)}`,r=[];try{r=await nn(t)}catch(d){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${d?.message||d}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(d=>d.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(d=>`@${d.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:d}=await import("ink"),{ChatApp:g}=await import("./ChatApp-NWOSAP5U.js"),p=(await import("react")).default;await d(p.createElement(g,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}pp(t.baseUrl,n,i,s);let a=dp({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
|
|
447
|
+
bye`)),process.exit(0)});;){let d;try{d=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!d)continue;if(d==="/exit"||d==="/quit"){a.close();return}if(d==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(d==="/clear"){i=`chat-cli:${wc().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(d==="/agents"){try{let h=await nn(t);for(let w of h){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(h){console.error(K.red(` failed to list agents: ${h?.message||h}`))}continue}if(d.startsWith("/agent ")){let h=d.slice(7).replace(/^@/,"").trim();if(!h){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await nn(t)).find(y=>y.id===h)){console.log(K.red(` unknown agent: @${h}`));continue}n=h,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(d.startsWith("/")){console.log(K.red(` unknown command: ${d.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let g=gp({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),u=mp(n);try{let h=await fr(t,n,d,{channel:s,chatId:i,onText:y=>{g.stop(),u.text(y)},onThinking:()=>{},onTool:y=>{g.stop(),u.tool(y)}});g.stop();let w=Math.round((Date.now()-p)/100)/10;h.error?u.finishError(h.error):u.finish(w,h.usage)}catch(h){g.stop(),u.finishError(h?.message||String(h))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function mp(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
|
|
448
448
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
449
449
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
450
450
|
`&&(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(`
|
|
@@ -459,14 +459,15 @@ agentx wiki questions`,re=C?.daemon?.port??C?.port??18800;try{let B=await fetch(
|
|
|
459
459
|
`))},finishError(r){o&&!t&&process.stdout.write(`
|
|
460
460
|
`),process.stdout.write(K.red(` \u2717 ${r}
|
|
461
461
|
|
|
462
|
-
`))}}}function
|
|
462
|
+
`))}}}function pp(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as up}from"commander";import Te from"chalk";import{readFileSync as hp}from"fs";var Wn=["user","feedback","project","reference"],Fo=new up().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Fo.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(!Wn.includes(e.type)){console.error(Te.red(` --type must be one of: ${Wn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await fp();else try{o=hp(e.file,"utf-8")}catch(s){console.error(Te.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Te.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Jo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Te.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Fo.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 Jo().list(e.agent);if(e.type){if(!Wn.includes(e.type)){console.error(Te.red(` --type must be one of: ${Wn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Te.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(Te.bold(` ${s.type}`)),n=s.type),console.log(` ${Te.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Te.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Fo.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 Jo().get(o.agent,e);if(!n){console.error(Te.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Te.bold(`${n.type}/${n.name}`)+Te.dim(` (${n.description})`)),console.log(Te.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Fo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Jo().remove(o.agent,e)){console.error(Te.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Te.green(` \u2713 memory "${e}" removed`))});Fo.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 Jo().indexMarkdown(e.agent);if(!t){console.log(Te.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function fp(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Lc();import ti from"chalk";import{Command as yp}from"commander";import{resolve as wp}from"path";var $c=new yp().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(wp(e.cwd)),e.stdio!==!1?await Li():(oo.error("Only stdio transport is currently supported."),oo.info(`Usage: ${ti.green("agentx serve --stdio")} or configure in your MCP client.`),oo.break(),oo.info("Add to Claude Code:"),oo.info(ti.dim(" claude mcp add agentx -- npx agentx serve --stdio")),oo.break(),oo.info("Add to Cursor/MCP config:"),oo.info(ti.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){ar(o)}});import{Command as bp}from"commander";import ie from"chalk";import{spawn as ni}from"child_process";import{mkdirSync as $p,writeFileSync as Hn,readFileSync as kp,readdirSync as vp,rmSync as vc,openSync as xc,existsSync as Bn}from"fs";import{resolve as xp,join as Ne}from"path";import{randomBytes as Sp}from"crypto";var kc={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 Sc="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Ep="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Ap(e,o){return[{dir:Ne(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(kc,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:Ne(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:Ne(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 Op(e,o,t){let n=Ne(e.dir,"workspaces",e.agentId);$p(n,{recursive:!0}),Hn(Ne(n,"CLAUDE.md"),`# ${e.agentName}
|
|
463
463
|
|
|
464
464
|
${e.persona}
|
|
465
|
-
`),
|
|
465
|
+
`),Hn(Ne(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}};Hn(Ne(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function si(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 ii(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 Jn(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
466
466
|
`).join(`
|
|
467
|
-
`)}`)}var xc=new hp().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").action(async e=>{let o=parseInt(e.basePort,10),t=wp(process.cwd(),".agentx-demo"),n=kp(t,o),s=bp(24).toString("hex"),i=[],r=process.argv[1];(!r||!kc(r))&&(console.error(le.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),kc(t)&&bc(t,{recursive:!0,force:!0});for(let d of n)vp(d,n,s);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 a=!1,c=d=>{if(!a){a=!0;for(let g of i)try{g.kill("SIGTERM")}catch{}setTimeout(()=>{if(!e.keep)try{bc(t,{recursive:!0,force:!0})}catch{}process.exit(d)},800)}};process.on("SIGINT",()=>c(0)),process.on("SIGTERM",()=>c(0));let l={...process.env};delete l.ANTHROPIC_API_KEY,delete l.ANTHROPIC_API_KEY_OLD,delete l.OPENAI_API_KEY,delete l.DEEPSEEK_API_KEY;try{for(let p of n){let f=$c(Fe(p.dir,"daemon.log"),"a"),w=Zs(process.execPath,[r,"daemon","start","-c",Fe(p.dir,"agentx.json")],{cwd:p.dir,env:{...l,MESH_TOKEN:s,AGENTX_DEMO_SCRIPT:Fe(p.dir,"demo-script.json")},stdio:["ignore",f,f]});i.push(w),console.log(le.dim(` \u25B8 ${p.name} starting on 127.0.0.1:${p.port} (log: ${Fe(p.dir,"daemon.log")})`))}for(let p of n)await oi(`${p.name} /health`,async()=>(await fetch(`http://127.0.0.1:${p.port}/health`)).ok,3e4);console.log(le.green(" \u2713 three daemons up"));let d=n[0].port+10;{let p=$c(Fe(n[0].dir,"board.log"),"a"),f=Zs(process.execPath,[r,"board","serve"],{cwd:n[0].dir,env:{...l,MESH_TOKEN:s},stdio:["ignore",p,p]});i.push(f)}await oi("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${d}/live`)).ok,3e4),console.log(le.green(" \u2713 dashboard up")),await oi("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(y=>y.healthy&&y.skills?.length).length>=2,3e4),console.log(le.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let g=`http://127.0.0.1:${d}/live`;if(console.log(),console.log(` Dashboard: ${le.cyan(g)} (all three nodes via the mesh)`),console.log(le.dim(` Daemon APIs: ${n.map(p=>`127.0.0.1:${p.port}`).join(" \xB7 ")}`)),e.open!==!1){let p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Zs(p,[g],{stdio:"ignore",detached:!0}).unref()}catch{}}let u=async()=>{console.log(),console.log(le.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Wn("You \u2192 @cx (laptop-paris)",vc,le.cyan);let p=await ti(n[0].port,"/task",{agent:"cx",message:vc});Wn("@cx (laptop-paris)",p.content||"(no content)",le.green),console.log(),console.log(le.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let f=await ti(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:$p}),w=typeof f.messageId=="string"?f.messageId:f.content||"(no reply)";Wn("@builder (vps-nyc)",w,le.yellow);let y=await ti(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${w}`});Wn("@cx (laptop-paris)",y.content||"(no content)",le.green),console.log(),console.log(le.dim(` Inspect the run: ${g} \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(await u(),e.once){console.log(),console.log(le.dim(" --once: shutting down.")),c(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",()=>{u().catch(p=>console.error(le.red(` Replay failed: ${p.message}`)))}),process.stdin.resume()}catch(d){console.error(),console.error(le.red(` Demo failed: ${d.message}`)),console.error(le.dim(` Node logs: ${n.map(g=>Fe(g.dir,"daemon.log")).join(", ")}`)),c(1)}});Oe();import{Command as xp}from"commander";import Se from"chalk";var xo=new xp().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");xo.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 Jt("/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(Se.dim(" no chats cached yet"));return}console.log(),console.log(Se.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Se.cyan("group"):Se.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Se.dim(n.jid.padEnd(40))} ${Se.dim(i)}`)}console.log()}catch(o){ut(o)}});xo.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 Jt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Se.dim(" no contacts cached yet"));return}console.log(),console.log(Se.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} ${Se.dim(i)} ${Se.dim(n.jid)}`)}console.log()}catch(o){ut(o)}});xo.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 si("/whatsapp/ingest",o);ni(t,!!e.dryRun)}catch(o){ut(o)}});xo.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 si("/whatsapp/ingest",t);ni(n,!!o.dryRun)}catch(t){ut(t)}});xo.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 si("/whatsapp/ingest",t);ni(n,!!o.dryRun)}catch(t){ut(t)}});xo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Jt("/whatsapp/state"),o=await Jt("/whatsapp/chats"),t=await Jt("/whatsapp/contacts");console.log(),console.log(Se.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){ut(e)}});function ni(e,o){if(console.log(),console.log(Se.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(Se.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Se.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Se.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Se.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Se.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Sc(){try{let e=W(),[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 Jt(e){let o=await fetch(`${Sc()}${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 si(e,o){let t=await fetch(`${Sc()}${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 ut(e){console.error(Se.red(` ${e.message||e}`)),process.exit(1)}Oe();import{Command as Sp}from"commander";import ie from"chalk";import{existsSync as Ep,mkdirSync as Ec,writeFileSync as Ht}from"fs";import{join as ft,resolve as Ap}from"path";var Gt=new Sp().name("plugin").description("manage agentx plugins (Move B)");Gt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(ie.dim(" No plugins configured.")),console.log(ie.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ie.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ie.cyan(t)}`);console.log(),console.log(ie.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ie.red(` ${e.message}`)),process.exitCode=1}});Gt.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(ie.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=Ap(o.cwd,t);Ep(n)&&!o.force&&(console.log(ie.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Ec(n,{recursive:!0}),Ec(ft(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Ht(ft(n,"package.json"),jp(e,s)),Ht(ft(n,"tsconfig.json"),Rp()),Ht(ft(n,"src/index.ts"),Tp(e)),Ht(ft(n,"README.md"),Np(e,s)),Ht(ft(n,".gitignore"),_p()),console.log(),console.log(ie.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ie.bold(" Next steps:")),console.log(ie.dim(` cd ${t}`)),console.log(ie.dim(" pnpm install")),console.log(ie.dim(" pnpm build")),console.log(ie.dim(" pnpm link --global # for local testing")),console.log(ie.dim(" # then in your agentx project:")),console.log(ie.dim(` pnpm link --global ${e}`)),console.log(ie.dim(` agentx config set plugins[0] "${e}"`)),console.log(ie.dim(" agentx plugin doctor")),console.log()});Gt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(ie.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Op(n);s.kind==="ok"?console.log(` ${ie.green("\u2713")} ${ie.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ie.red("\u2717")} ${ie.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ie.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ie.red(` ${e.message}`)),process.exitCode=1}});async function Op(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Ip(o);if(!Cp(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Yi.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 Ip(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 Cp(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function jp(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)+`
|
|
468
|
-
`}function Rp(){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)+`
|
|
469
|
-
`}function
|
|
467
|
+
`)}`)}var Ec=new bp().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=xp(process.cwd(),".agentx-demo"),n=Ap(t,o),s=Ne(t,"mesh-token"),i=!!e.reuse&&Bn(s)&&Bn(Ne(n[0].dir,"agentx.json")),r=i?kp(s,"utf8").trim():Sp(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Bn(l))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Bn(t))for(let u of vp(t))vc(Ne(t,u),{recursive:!0,force:!0});for(let u of n)Op(u,n,r);Hn(s,r+`
|
|
468
|
+
`,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let d=!1,g=u=>{if(!d){d=!0;for(let h of c)try{h.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{vc(t,{recursive:!0,force:!0})}catch{}process.exit(u)},800)}};process.on("SIGINT",()=>g(0)),process.on("SIGTERM",()=>g(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;try{for(let y of n){let $=xc(Ne(y.dir,"daemon.log"),"a"),b=ni(process.execPath,[l,"daemon","start","-c",Ne(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Ne(y.dir,"demo-script.json")},stdio:["ignore",$,$]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Ne(y.dir,"daemon.log")})`))}for(let y of n)await si(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ie.green(" \u2713 three daemons up"));let u=n[0].port+10;{let y=xc(Ne(n[0].dir,"board.log"),"a"),$=ni(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await si("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${u}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await si("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(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let h=`http://127.0.0.1:${u}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(h)} (all three nodes via the mesh)`),console.log(ie.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{ni(y,[h],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Jn("You \u2192 @cx (laptop-paris)",Sc,ie.cyan);let y=await ii(n[0].port,"/task",{agent:"cx",message:Sc});Jn("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await ii(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Ep}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";Jn("@builder (vps-nyc)",b,ie.yellow);let v=await ii(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Jn("@cx (laptop-paris)",v.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${h} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),g(0);return}console.log(),console.log(ie.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(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(u){console.error(),console.error(ie.red(` Demo failed: ${u.message}`)),console.error(ie.dim(` Node logs: ${n.map(h=>Ne(h.dir,"daemon.log")).join(", ")}`)),g(1)}});Oe();import{Command as Ip}from"commander";import Se from"chalk";var xo=new Ip().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");xo.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 Gt("/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(Se.dim(" no chats cached yet"));return}console.log(),console.log(Se.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Se.cyan("group"):Se.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Se.dim(n.jid.padEnd(40))} ${Se.dim(i)}`)}console.log()}catch(o){ut(o)}});xo.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 Gt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Se.dim(" no contacts cached yet"));return}console.log(),console.log(Se.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} ${Se.dim(i)} ${Se.dim(n.jid)}`)}console.log()}catch(o){ut(o)}});xo.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 ai("/whatsapp/ingest",o);ri(t,!!e.dryRun)}catch(o){ut(o)}});xo.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 ai("/whatsapp/ingest",t);ri(n,!!o.dryRun)}catch(t){ut(t)}});xo.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 ai("/whatsapp/ingest",t);ri(n,!!o.dryRun)}catch(t){ut(t)}});xo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Gt("/whatsapp/state"),o=await Gt("/whatsapp/chats"),t=await Gt("/whatsapp/contacts");console.log(),console.log(Se.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){ut(e)}});function ri(e,o){if(console.log(),console.log(Se.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(Se.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Se.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Se.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Se.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Se.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Ac(){try{let e=W(),[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 Gt(e){let o=await fetch(`${Ac()}${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 ai(e,o){let t=await fetch(`${Ac()}${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 ut(e){console.error(Se.red(` ${e.message||e}`)),process.exit(1)}Oe();import{Command as Cp}from"commander";import re from"chalk";import{existsSync as jp,mkdirSync as Oc,writeFileSync as zt}from"fs";import{join as ht,resolve as Rp}from"path";var Yt=new Cp().name("plugin").description("manage agentx plugins (Move B)");Yt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});Yt.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(re.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=Rp(o.cwd,t);jp(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Oc(n,{recursive:!0}),Oc(ht(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;zt(ht(n,"package.json"),Dp(e,s)),zt(ht(n,"tsconfig.json"),Pp()),zt(ht(n,"src/index.ts"),Lp(e)),zt(ht(n,"README.md"),Mp(e,s)),zt(ht(n,".gitignore"),Up()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});Yt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Tp(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function Tp(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Np(o);if(!_p(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Vi.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 Np(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 _p(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Dp(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)+`
|
|
469
|
+
`}function Pp(){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)+`
|
|
470
|
+
`}function Lp(e){return`// ${e} \u2014 AgentX plugin
|
|
470
471
|
//
|
|
471
472
|
// A plugin's default export is { manifest, setup }. The daemon calls
|
|
472
473
|
// setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
|
|
@@ -502,7 +503,7 @@ const plugin = {
|
|
|
502
503
|
}
|
|
503
504
|
|
|
504
505
|
export default plugin
|
|
505
|
-
`}function
|
|
506
|
+
`}function Mp(e,o){return`# ${e}
|
|
506
507
|
|
|
507
508
|
${o}
|
|
508
509
|
|
|
@@ -529,19 +530,19 @@ agentx plugin doctor
|
|
|
529
530
|
\`\`\`
|
|
530
531
|
|
|
531
532
|
Restart the daemon to activate.
|
|
532
|
-
`}function
|
|
533
|
+
`}function Up(){return`node_modules/
|
|
533
534
|
dist/
|
|
534
535
|
*.log
|
|
535
536
|
.env
|
|
536
|
-
`}import{Command as
|
|
537
|
+
`}import{Command as Fp}from"commander";import Ee from"chalk";import{writeFileSync as qp,mkdirSync as Wp,existsSync as Gn,readFileSync as Ic,appendFileSync as Cc}from"fs";import{resolve as ft,dirname as Tc}from"path";import{homedir as li}from"os";var Nc=new Fp().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-DWZAI4GY.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Hp(t);break;case"bash":s=Xp(t);break;case"fish":s=Vp(t);break;default:console.error(Ee.red(`unsupported shell: ${n}`)),console.error(Ee.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?ft(String(e.output)):Bp(n);Wp(Tc(i),{recursive:!0}),qp(i,s),console.log(Ee.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Jp(n,i,!!e.yes)});function Bp(e){let o=li();switch(e){case"zsh":return ft(o,".zsh","completions","_agentx");case"bash":return ft(o,".bash_completion.d","agentx.bash");case"fish":return ft(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Jp(e,o,t){if(e==="zsh"){let n=ft(li(),".zshrc"),s=Tc(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Gn(n)?Ic(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ee.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Gn(n)){let d=["","# agentx completion"];c&&d.push(i),l&&d.push(r),Cc(n,d.join(`
|
|
537
538
|
`)+`
|
|
538
|
-
`),console.log(Ee.green("\u2713 Patched ~/.zshrc")),console.log(Ee.dim("Reload your shell: exec zsh"));return}console.log(Ee.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ee.cyan(` ${i}`)),l&&console.log(Ee.cyan(` ${r}`)),console.log(),console.log(Ee.dim("Then reload: exec zsh")),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=
|
|
539
|
+
`),console.log(Ee.green("\u2713 Patched ~/.zshrc")),console.log(Ee.dim("Reload your shell: exec zsh"));return}console.log(Ee.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ee.cyan(` ${i}`)),l&&console.log(Ee.cyan(` ${r}`)),console.log(),console.log(Ee.dim("Then reload: exec zsh")),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=ft(li(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Gn(n)?Ic(n,"utf-8"):"").includes(o)){console.log(Ee.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Gn(n)){Cc(n,`
|
|
539
540
|
# agentx completion
|
|
540
541
|
${s}
|
|
541
|
-
`),console.log(Ee.green("\u2713 Patched ~/.bashrc")),console.log(Ee.dim("Reload your shell: exec bash"));return}console.log(Ee.dim("Add this to ~/.bashrc:")),console.log(Ee.cyan(` ${s}`)),console.log(),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ee.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function
|
|
542
|
-
`)}function
|
|
543
|
-
`)}function
|
|
544
|
-
`)}function
|
|
545
|
-
`)}),o}var
|
|
546
|
-
`)}export{
|
|
547
|
-
//# sourceMappingURL=chunk-
|
|
542
|
+
`),console.log(Ee.green("\u2713 Patched ~/.bashrc")),console.log(Ee.dim("Reload your shell: exec bash"));return}console.log(Ee.dim("Add this to ~/.bashrc:")),console.log(Ee.cyan(` ${s}`)),console.log(),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ee.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Me(e){return e._name||e.name()||""}function So(e){return e.commands.filter(o=>{let t=Me(o);return!(!t||t==="help")})}function Kt(e){return e.options.filter(o=>!o.hidden)}function Hp(e){let o=[];return o.push("#compdef agentx"),o.push(""),_c(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
|
|
543
|
+
`)}function jc(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function _c(e,o,t){let n=So(e),i=Kt(e).map(Yp).filter(c=>!!c),r=jc(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(Kp).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=jc([...o,Me(c)]);t.push(` (${Me(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)_c(c,[...o,Me(c)],t)}function Gp(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function zp(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Yp(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Gp(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Kp(e){let o=zp(e.description()||"");return`'${Me(e)}[${o}]'`}function Xp(e){let o=So(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(Me).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=So(n).map(Me),i=Rc(n);if(t.push(` ${Me(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 So(n)){let a=Rc(r);t.push(` ${Me(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(`
|
|
544
|
+
`)}function Rc(e){let o=[];for(let t of Kt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Vp(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 So(e)){let n=di(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Me(t)}" -d "${n}"`)}o.push("");for(let t of Kt(e)){let n=ci(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of So(e)){let n=Me(t);o.push(`# ${n}`);for(let s of Kt(t)){let i=ci(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of So(t)){let i=di(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${So(t).map(Me).join(" ")}" -a "${Me(s)}" -d "${i}"`);for(let r of Kt(s)){let a=ci(r,[`__fish_seen_subcommand_from ${Me(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
|
|
545
|
+
`)}function di(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ci(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=di(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 xv(){let e=await cr(),o=new Qp().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=mr(n);pr(s)&&gr("cli",s)});for(let t of[qr,Mr,rt,Xo,Ke,dr,Co,hn,bo,Do,un,hc,yo,ea,la,ba,va,xa,Aa,Ft,$c,Ot,po,Nc])o.addCommand(t);for(let t of Dc)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Dc.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Zp(t,74," "),""].join(`
|
|
546
|
+
`)}),o}var Dc=[Z,at,Fo,ze,Ct,nt,Le,ro,$o,Po,gt,mt,fo,De,jt,On,pc,so,et,yr,jo,Yt,us,vo,Zo,hs,Un,pt,xo,Ec,bc];function Zp(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(`
|
|
547
|
+
`)}export{xv as a};
|
|
548
|
+
//# sourceMappingURL=chunk-42DCRKUD.js.map
|