agentix-cli 0.30.0 → 0.31.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/{App-IEQXWJ7B.js → App-6TP7YMQ3.js} +2 -2
- package/dist/{ChatApp-NWOSAP5U.js → ChatApp-G2MQUBR3.js} +2 -2
- package/dist/{agent-SPE7Q7MD.js → agent-A5G4DGVU.js} +2 -2
- package/dist/{board-dashboard-K4DM32SO.js → board-dashboard-BU6QJK6X.js} +192 -171
- package/dist/board-dashboard-BU6QJK6X.js.map +1 -0
- package/dist/{chunk-DI7FMCDK.js → chunk-2J3NV6RZ.js} +2 -2
- package/dist/{chunk-UCQ2N3KO.js → chunk-2TJ5L7CB.js} +2 -2
- package/dist/{chunk-FKBGJYWQ.js → chunk-3RHPZXCR.js} +2 -2
- package/dist/{chunk-AUNDQPDR.js → chunk-6DD4DA2L.js} +2 -2
- package/dist/{chunk-52ZPELD2.js → chunk-7CVJ4JOE.js} +2 -2
- package/dist/{chunk-IVQO43U2.js → chunk-7JWYLSFF.js} +2 -2
- package/dist/{chunk-GUBMLV34.js → chunk-7MNXKITO.js} +8 -8
- package/dist/chunk-7MNXKITO.js.map +1 -0
- package/dist/{chunk-45BLFNDG.js → chunk-COOJI5SR.js} +37 -37
- package/dist/chunk-COOJI5SR.js.map +1 -0
- package/dist/{chunk-JKYMXLYL.js → chunk-DLOYTMYZ.js} +2 -2
- package/dist/{chunk-SC5DIKBB.js → chunk-FFDXDUVQ.js} +2 -2
- package/dist/{chunk-MGNJWBVP.js → chunk-JC6ZHSTY.js} +2 -2
- package/dist/{chunk-MGNJWBVP.js.map → chunk-JC6ZHSTY.js.map} +1 -1
- package/dist/{chunk-UU4WOZNR.js → chunk-JJIYFBDH.js} +2 -2
- package/dist/{chunk-EL3J74N2.js → chunk-JV52UMCI.js} +2 -2
- package/dist/{chunk-Q7CZIRBB.js → chunk-NZ346QCV.js} +2 -2
- package/dist/{chunk-M4AMWP3H.js → chunk-QLTM3F7M.js} +17 -8
- package/dist/{chunk-M4AMWP3H.js.map → chunk-QLTM3F7M.js.map} +1 -1
- package/dist/{chunk-4KXBUORV.js → chunk-R7WLFEW3.js} +2 -2
- package/dist/{chunk-GK7XAM3D.js → chunk-UOGDSRG3.js} +2 -2
- package/dist/{chunk-IWMW5432.js → chunk-V7FYSZSV.js} +1 -1
- package/dist/{chunk-IWMW5432.js.map → chunk-V7FYSZSV.js.map} +1 -1
- package/dist/chunk-VMDA2SX2.js +43 -0
- package/dist/chunk-VMDA2SX2.js.map +1 -0
- package/dist/{chunk-V4HURNMX.js → chunk-W6HKWISZ.js} +2 -2
- package/dist/{chunk-GMNKJXTR.js → chunk-Z3RKXKE2.js} +2 -2
- package/dist/{chunk-GMNKJXTR.js.map → chunk-Z3RKXKE2.js.map} +1 -1
- package/dist/{chunk-42DCRKUD.js → chunk-ZZQMR526.js} +12 -12
- package/dist/cli.js +1 -1
- package/dist/client-QALLJG62.js +2 -0
- package/dist/config-TNNODULV.js +2 -0
- package/dist/config-mutator-RI77M5YT.js +2 -0
- package/dist/doctor-DW27MR2T.js +2 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +1 -1
- package/dist/processes-I3XAPHG7.js +2 -0
- package/dist/program-WZ3GEOXO.js +2 -0
- package/dist/query-7X6VO5VU.js +2 -0
- package/dist/{registry-EJRWAJYG.js → registry-LUMYXZ6F.js} +2 -2
- package/dist/request-planner-RNQB4L6F.js +2 -0
- package/dist/request-planner-RNQB4L6F.js.map +1 -0
- package/dist/{review-candidates-O2PS7L3B.js → review-candidates-ZX4JBWQL.js} +2 -2
- package/dist/{routing-5K7PGHPL.js → routing-5VGXQ4VG.js} +2 -2
- package/dist/scheduler-W5C43ZTE.js +2 -0
- package/dist/{seat-FZRNRAHQ.js → seat-SXPFROXT.js} +2 -2
- package/dist/{select-SOJYFAMI.js → select-GJ47QACY.js} +2 -2
- package/dist/{surface-usage-NS74AXSE.js → surface-usage-UREILT2E.js} +2 -2
- package/dist/web/activity-graph.global.js +901 -368
- package/dist/web/activity-graph.global.js.map +1 -1
- package/dist/wiki-SRH3JKI4.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-K4DM32SO.js.map +0 -1
- package/dist/chunk-45BLFNDG.js.map +0 -1
- package/dist/chunk-4BR7D2OU.js +0 -36
- package/dist/chunk-4BR7D2OU.js.map +0 -1
- package/dist/chunk-GUBMLV34.js.map +0 -1
- package/dist/client-5Z3URGPY.js +0 -2
- package/dist/config-ORSGLVRW.js +0 -2
- package/dist/config-mutator-JB3S2E7H.js +0 -2
- package/dist/doctor-FS2BX6H4.js +0 -2
- package/dist/processes-WU23U2OJ.js +0 -2
- package/dist/program-DWZAI4GY.js +0 -2
- package/dist/query-3HXGBKGM.js +0 -2
- package/dist/request-planner-BCOXUAPA.js +0 -2
- package/dist/request-planner-BCOXUAPA.js.map +0 -1
- package/dist/scheduler-DSAOMV4O.js +0 -2
- package/dist/wiki-34XVI32N.js +0 -2
- /package/dist/{App-IEQXWJ7B.js.map → App-6TP7YMQ3.js.map} +0 -0
- /package/dist/{ChatApp-NWOSAP5U.js.map → ChatApp-G2MQUBR3.js.map} +0 -0
- /package/dist/{agent-SPE7Q7MD.js.map → agent-A5G4DGVU.js.map} +0 -0
- /package/dist/{chunk-DI7FMCDK.js.map → chunk-2J3NV6RZ.js.map} +0 -0
- /package/dist/{chunk-UCQ2N3KO.js.map → chunk-2TJ5L7CB.js.map} +0 -0
- /package/dist/{chunk-FKBGJYWQ.js.map → chunk-3RHPZXCR.js.map} +0 -0
- /package/dist/{chunk-AUNDQPDR.js.map → chunk-6DD4DA2L.js.map} +0 -0
- /package/dist/{chunk-52ZPELD2.js.map → chunk-7CVJ4JOE.js.map} +0 -0
- /package/dist/{chunk-IVQO43U2.js.map → chunk-7JWYLSFF.js.map} +0 -0
- /package/dist/{chunk-JKYMXLYL.js.map → chunk-DLOYTMYZ.js.map} +0 -0
- /package/dist/{chunk-SC5DIKBB.js.map → chunk-FFDXDUVQ.js.map} +0 -0
- /package/dist/{chunk-UU4WOZNR.js.map → chunk-JJIYFBDH.js.map} +0 -0
- /package/dist/{chunk-EL3J74N2.js.map → chunk-JV52UMCI.js.map} +0 -0
- /package/dist/{chunk-Q7CZIRBB.js.map → chunk-NZ346QCV.js.map} +0 -0
- /package/dist/{chunk-4KXBUORV.js.map → chunk-R7WLFEW3.js.map} +0 -0
- /package/dist/{chunk-GK7XAM3D.js.map → chunk-UOGDSRG3.js.map} +0 -0
- /package/dist/{chunk-V4HURNMX.js.map → chunk-W6HKWISZ.js.map} +0 -0
- /package/dist/{chunk-42DCRKUD.js.map → chunk-ZZQMR526.js.map} +0 -0
- /package/dist/{client-5Z3URGPY.js.map → client-QALLJG62.js.map} +0 -0
- /package/dist/{config-ORSGLVRW.js.map → config-TNNODULV.js.map} +0 -0
- /package/dist/{config-mutator-JB3S2E7H.js.map → config-mutator-RI77M5YT.js.map} +0 -0
- /package/dist/{doctor-FS2BX6H4.js.map → doctor-DW27MR2T.js.map} +0 -0
- /package/dist/{processes-WU23U2OJ.js.map → processes-I3XAPHG7.js.map} +0 -0
- /package/dist/{program-DWZAI4GY.js.map → program-WZ3GEOXO.js.map} +0 -0
- /package/dist/{query-3HXGBKGM.js.map → query-7X6VO5VU.js.map} +0 -0
- /package/dist/{registry-EJRWAJYG.js.map → registry-LUMYXZ6F.js.map} +0 -0
- /package/dist/{review-candidates-O2PS7L3B.js.map → review-candidates-ZX4JBWQL.js.map} +0 -0
- /package/dist/{routing-5K7PGHPL.js.map → routing-5VGXQ4VG.js.map} +0 -0
- /package/dist/{scheduler-DSAOMV4O.js.map → scheduler-W5C43ZTE.js.map} +0 -0
- /package/dist/{seat-FZRNRAHQ.js.map → seat-SXPFROXT.js.map} +0 -0
- /package/dist/{select-SOJYFAMI.js.map → select-GJ47QACY.js.map} +0 -0
- /package/dist/{surface-usage-NS74AXSE.js.map → surface-usage-UREILT2E.js.map} +0 -0
- /package/dist/{wiki-34XVI32N.js.map → wiki-SRH3JKI4.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as hr,b as nn,g as fr}from"./chunk-
|
|
1
|
+
import{a as hr,b as nn,g as fr}from"./chunk-2J3NV6RZ.js";import{b as dr}from"./chunk-DLOYTMYZ.js";import{a as Yo,b as lr,f as tn,j as ur}from"./chunk-NZ346QCV.js";import{a as gr,c as mr,d as pr}from"./chunk-2TJ5L7CB.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-7MNXKITO.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-JV52UMCI.js";import{m as Si,o as Jo,q as Vn,r as Ai,t as lo,z as Pi}from"./chunk-COOJI5SR.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-7JWYLSFF.js";import{d as Zn,f as _i}from"./chunk-VMDA2SX2.js";import{a as Ni}from"./chunk-QLTM3F7M.js";import{a as Ei,e as Ti}from"./chunk-R7WLFEW3.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-FFDXDUVQ.js";import{b as co,d as Qt,f as Xn}from"./chunk-6DD4DA2L.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-JC6ZHSTY.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-Z3RKXKE2.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
4
|
<key>Label</key><string>${sn}</string>
|
|
@@ -30,7 +30,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
30
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
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(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(`
|
|
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-TNNODULV.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-GJ47QACY.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
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
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(`
|
|
@@ -39,7 +39,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
39
39
|
`).length>30&&console.log(f.dim(` \u2026 (${y.split(`
|
|
40
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
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-
|
|
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-RI77M5YT.js"),{expandEnvVars:r}=await import("./config-TNNODULV.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-RI77M5YT.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-RI77M5YT.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,
|
|
@@ -318,7 +318,7 @@ ${n}`:n,a=await fetch(`${tg}/send`,{method:"POST",headers:{"Content-Type":"appli
|
|
|
318
318
|
settings \u2014 without this an attached production identity would be less
|
|
319
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 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.
|
|
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-UREILT2E.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-WZ3GEOXO.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-BU6QJK6X.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
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
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(`
|
|
@@ -328,7 +328,7 @@ ${n}`:n,a=await fetch(`${tg}/send`,{method:"POST",headers:{"Content-Type":"appli
|
|
|
328
328
|
${k.content}
|
|
329
329
|
--- END ENTRY ---`).join(`
|
|
330
330
|
|
|
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(`
|
|
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-ZX4JBWQL.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-7X6VO5VU.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
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}
|
|
@@ -345,7 +345,7 @@ 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
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
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-
|
|
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-7X6VO5VU.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
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
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(`
|
|
@@ -406,14 +406,14 @@ 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-
|
|
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-TNNODULV.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-SXPFROXT.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
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(`
|
|
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-7X6VO5VU.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-TNNODULV.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-SXPFROXT.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-TNNODULV.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`,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(`
|
|
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-SXPFROXT.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-SXPFROXT.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
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(`
|
|
@@ -443,7 +443,7 @@ agentx wiki questions`,ae=C?.daemon?.port??C?.port??18800;try{let B=await fetch(
|
|
|
443
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
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-
|
|
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-QALLJG62.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-QALLJG62.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-6TP7YMQ3.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-G2MQUBR3.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
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===`
|
|
@@ -534,7 +534,7 @@ Restart the daemon to activate.
|
|
|
534
534
|
dist/
|
|
535
535
|
*.log
|
|
536
536
|
.env
|
|
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-
|
|
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-WZ3GEOXO.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(`
|
|
538
538
|
`)+`
|
|
539
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,`
|
|
540
540
|
# agentx completion
|
|
@@ -545,4 +545,4 @@ ${s}
|
|
|
545
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
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
547
|
`)}export{xv as a};
|
|
548
|
-
//# sourceMappingURL=chunk-
|
|
548
|
+
//# sourceMappingURL=chunk-ZZQMR526.js.map
|