agentix-cli 0.55.0 → 0.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +46 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +7 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +8 -2
- package/apps/mac-voice/Sources/AgentXVoice/HotkeySpec.swift +80 -0
- package/apps/mac-voice/Sources/AgentXVoice/Orb.swift +311 -0
- package/apps/mac-voice/Sources/AgentXVoice/OrbMath.swift +57 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +14 -1
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +33 -1
- package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +518 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +8 -2
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +23 -1
- package/apps/mac-voice/Sources/AgentXVoice/VoiceSettings.swift +101 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +161 -39
- package/apps/mac-voice/build.sh +1 -1
- package/dist/{App-4EM7IPB3.js → App-Z5VOAUXB.js} +2 -2
- package/dist/{ChatApp-FYTEEGSU.js → ChatApp-BE7ONQKS.js} +2 -2
- package/dist/{agent-RZ46ZB4W.js → agent-Q74EISKP.js} +2 -2
- package/dist/{board-dashboard-NRRYCDZW.js → board-dashboard-A7PQOI6C.js} +4 -4
- package/dist/{chunk-W4YMMWJL.js → chunk-2MIOMYT2.js} +2 -2
- package/dist/{chunk-EZN2YXRY.js → chunk-547G3HYQ.js} +2 -2
- package/dist/{chunk-LKJSPO3S.js → chunk-5LLGIX5M.js} +2 -2
- package/dist/{chunk-WOMQ2VGA.js → chunk-5W7NJHCS.js} +2 -2
- package/dist/{chunk-4HEVSWO3.js → chunk-6OABTCRA.js} +2 -2
- package/dist/{chunk-UIVHSYCN.js → chunk-6QNPCVRN.js} +3 -3
- package/dist/chunk-6QNPCVRN.js.map +1 -0
- package/dist/{chunk-CELYD5QW.js → chunk-CQUVUVXR.js} +2 -2
- package/dist/chunk-ERL6AS3O.js +15 -0
- package/dist/chunk-ERL6AS3O.js.map +1 -0
- package/dist/{chunk-EJ5ISSWW.js → chunk-I2LYULR4.js} +5 -5
- package/dist/{chunk-76AHNHWC.js → chunk-KKGFZEXS.js} +2 -2
- package/dist/{chunk-6AK6WKE5.js → chunk-KW7TIOS3.js} +2 -2
- package/dist/{chunk-SA23V7WX.js → chunk-NKMFHEGV.js} +2 -2
- package/dist/{chunk-K4RDE6YU.js → chunk-OZZPJ2YG.js} +197 -188
- package/dist/chunk-OZZPJ2YG.js.map +1 -0
- package/dist/{chunk-JC5Q5MPI.js → chunk-POL7RAJQ.js} +17 -17
- package/dist/{chunk-D3LSPFHK.js → chunk-Q6SMLSRO.js} +2 -2
- package/dist/{chunk-723K4SAW.js → chunk-RXEAACVH.js} +2 -2
- package/dist/{chunk-O3XG2NVR.js → chunk-U5YBQJ5Q.js} +2 -2
- package/dist/{chunk-XEOAKD5C.js → chunk-V7ZK6ZIO.js} +2 -2
- package/dist/{chunk-M4AG2YNX.js → chunk-VI7GBDKV.js} +2 -2
- package/dist/{chunk-GSOL2LW6.js → chunk-VVBGPT6W.js} +2 -2
- package/dist/{chunk-C3VRBEJ7.js → chunk-XTD3SZIP.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-EFP2PKA3.js +2 -0
- package/dist/config-P6YXC6XZ.js +2 -0
- package/dist/config-mutator-3GKXLTHH.js +2 -0
- package/dist/doctor-JEWMHXYH.js +2 -0
- package/dist/index.d.ts +109 -3
- package/dist/index.js +1 -1
- package/dist/program-7DUQJDSQ.js +2 -0
- package/dist/{promote-T4UJROEH.js → promote-KVPLDSKT.js} +2 -2
- package/dist/query-AGOMCYTT.js +2 -0
- package/dist/{registry-DX2RI7I7.js → registry-AUOI4TW2.js} +2 -2
- package/dist/{request-planner-B7DE7VJR.js → request-planner-LMZ5ZAXC.js} +2 -2
- package/dist/{review-candidates-4YJHIBAF.js → review-candidates-WCBXLLDS.js} +2 -2
- package/dist/{routing-MZG3UODH.js → routing-FBASYKUL.js} +2 -2
- package/dist/schedule-tool-RJRJ63SS.js +2 -0
- package/dist/scheduler-ATA7Z44S.js +2 -0
- package/dist/{seat-2PEI7JRX.js → seat-DBFW3Z5P.js} +2 -2
- package/dist/{select-4KIUR27O.js → select-6CNVVFA5.js} +2 -2
- package/dist/{set-enabled-SE7HQKPF.js → set-enabled-AYZH3KSB.js} +2 -2
- package/dist/{tool-5VMD7IE4.js → tool-PKS4NBZ6.js} +2 -2
- package/dist/wiki-QW6BDNEQ.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-K4RDE6YU.js.map +0 -1
- package/dist/chunk-U4H35SJS.js +0 -15
- package/dist/chunk-U4H35SJS.js.map +0 -1
- package/dist/chunk-UIVHSYCN.js.map +0 -1
- package/dist/client-IA7ZPE56.js +0 -2
- package/dist/config-HPN2F7LH.js +0 -2
- package/dist/config-mutator-7GPTMTVB.js +0 -2
- package/dist/doctor-IBWQVQV4.js +0 -2
- package/dist/program-D5TAPSIH.js +0 -2
- package/dist/query-VUJC4Y5O.js +0 -2
- package/dist/schedule-tool-A4OFQ4YZ.js +0 -2
- package/dist/scheduler-RHJW2V4M.js +0 -2
- package/dist/wiki-2QFLAH4U.js +0 -2
- /package/dist/{App-4EM7IPB3.js.map → App-Z5VOAUXB.js.map} +0 -0
- /package/dist/{ChatApp-FYTEEGSU.js.map → ChatApp-BE7ONQKS.js.map} +0 -0
- /package/dist/{agent-RZ46ZB4W.js.map → agent-Q74EISKP.js.map} +0 -0
- /package/dist/{board-dashboard-NRRYCDZW.js.map → board-dashboard-A7PQOI6C.js.map} +0 -0
- /package/dist/{chunk-W4YMMWJL.js.map → chunk-2MIOMYT2.js.map} +0 -0
- /package/dist/{chunk-EZN2YXRY.js.map → chunk-547G3HYQ.js.map} +0 -0
- /package/dist/{chunk-LKJSPO3S.js.map → chunk-5LLGIX5M.js.map} +0 -0
- /package/dist/{chunk-WOMQ2VGA.js.map → chunk-5W7NJHCS.js.map} +0 -0
- /package/dist/{chunk-4HEVSWO3.js.map → chunk-6OABTCRA.js.map} +0 -0
- /package/dist/{chunk-CELYD5QW.js.map → chunk-CQUVUVXR.js.map} +0 -0
- /package/dist/{chunk-EJ5ISSWW.js.map → chunk-I2LYULR4.js.map} +0 -0
- /package/dist/{chunk-76AHNHWC.js.map → chunk-KKGFZEXS.js.map} +0 -0
- /package/dist/{chunk-6AK6WKE5.js.map → chunk-KW7TIOS3.js.map} +0 -0
- /package/dist/{chunk-SA23V7WX.js.map → chunk-NKMFHEGV.js.map} +0 -0
- /package/dist/{chunk-JC5Q5MPI.js.map → chunk-POL7RAJQ.js.map} +0 -0
- /package/dist/{chunk-D3LSPFHK.js.map → chunk-Q6SMLSRO.js.map} +0 -0
- /package/dist/{chunk-723K4SAW.js.map → chunk-RXEAACVH.js.map} +0 -0
- /package/dist/{chunk-O3XG2NVR.js.map → chunk-U5YBQJ5Q.js.map} +0 -0
- /package/dist/{chunk-XEOAKD5C.js.map → chunk-V7ZK6ZIO.js.map} +0 -0
- /package/dist/{chunk-M4AG2YNX.js.map → chunk-VI7GBDKV.js.map} +0 -0
- /package/dist/{chunk-GSOL2LW6.js.map → chunk-VVBGPT6W.js.map} +0 -0
- /package/dist/{chunk-C3VRBEJ7.js.map → chunk-XTD3SZIP.js.map} +0 -0
- /package/dist/{client-IA7ZPE56.js.map → client-EFP2PKA3.js.map} +0 -0
- /package/dist/{config-HPN2F7LH.js.map → config-P6YXC6XZ.js.map} +0 -0
- /package/dist/{config-mutator-7GPTMTVB.js.map → config-mutator-3GKXLTHH.js.map} +0 -0
- /package/dist/{doctor-IBWQVQV4.js.map → doctor-JEWMHXYH.js.map} +0 -0
- /package/dist/{program-D5TAPSIH.js.map → program-7DUQJDSQ.js.map} +0 -0
- /package/dist/{promote-T4UJROEH.js.map → promote-KVPLDSKT.js.map} +0 -0
- /package/dist/{query-VUJC4Y5O.js.map → query-AGOMCYTT.js.map} +0 -0
- /package/dist/{registry-DX2RI7I7.js.map → registry-AUOI4TW2.js.map} +0 -0
- /package/dist/{request-planner-B7DE7VJR.js.map → request-planner-LMZ5ZAXC.js.map} +0 -0
- /package/dist/{review-candidates-4YJHIBAF.js.map → review-candidates-WCBXLLDS.js.map} +0 -0
- /package/dist/{routing-MZG3UODH.js.map → routing-FBASYKUL.js.map} +0 -0
- /package/dist/{schedule-tool-A4OFQ4YZ.js.map → schedule-tool-RJRJ63SS.js.map} +0 -0
- /package/dist/{scheduler-RHJW2V4M.js.map → scheduler-ATA7Z44S.js.map} +0 -0
- /package/dist/{seat-2PEI7JRX.js.map → seat-DBFW3Z5P.js.map} +0 -0
- /package/dist/{select-4KIUR27O.js.map → select-6CNVVFA5.js.map} +0 -0
- /package/dist/{set-enabled-SE7HQKPF.js.map → set-enabled-AYZH3KSB.js.map} +0 -0
- /package/dist/{tool-5VMD7IE4.js.map → tool-PKS4NBZ6.js.map} +0 -0
- /package/dist/{wiki-2QFLAH4U.js.map → wiki-QW6BDNEQ.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $c,b as Hn,g as kc}from"./chunk-
|
|
1
|
+
import{a as $c,b as Hn,g as kc}from"./chunk-5W7NJHCS.js";import{a as gc,c as mc}from"./chunk-Q6SMLSRO.js";import{a as ro,b as dc,f as Jn,g as pc,h as uc,i as ii,j as wc,l as bc}from"./chunk-KKGFZEXS.js";import{a as fc,c as hc,d as yc}from"./chunk-Z3IP66SL.js";import{a as Gs,b as Gr}from"./chunk-RKPAVWXF.js";import{a as pt}from"./chunk-GV7S5BAX.js";import{e as Pr}from"./chunk-GSX4NK2N.js";import{c as Mr}from"./chunk-SZDACK6O.js";import{$ as oc,A as Ua,B as qa,C as Wa,D as Ba,E as Ja,F as Ha,G as Xt,H as Xs,I as Mn,J as Ga,K as Eo,L as za,M as Qs,N as Zs,O as Ya,P as Va,Q as Qt,R as Ln,S as Ka,T as Xa,U as Fn,V as Un,W as Qa,X as Za,Y as ft,Z as ht,_ as ec,a as ea,aa as Ce,b as oa,ba as qn,ca as Zt,da as ei,ea as tc,fa as ic,ga as ni,h as ia,ha as ac,i as Kt,ia as Wn,j as Nn,ja as yt,k as ca,ka as Bn,l as la,la as si,m as da,ma as cc,n as ga,na as lc,o as ka,p as va,q as Pn,r as Vs,s as Ta,t as Na,u as Da,v as Pa,w as Ma,x as La,y as Fa,z as Ks}from"./chunk-OZZPJ2YG.js";import{A as Ca,J as nc,K as oi,L as sc,M as ti,_ as io,aa as rc,m as So,p as Oa,s as Ia,z as ja}from"./chunk-6QNPCVRN.js";import{a as ta,d as na,e as sa}from"./chunk-RXEAACVH.js";import{a as Ys,b as Rn,c as _n,d as ma,e as pa,f as ua,i as fa,j as ha,k as ya,l as wa,o as Dn,q as ba,r as $a}from"./chunk-S7CVSKOX.js";import{a as zs,e as zr,f as Yr,h as Vr,i as Kr,k as Xr,l as Qr,m as Zr}from"./chunk-NKMFHEGV.js";import{a as ra,p as aa}from"./chunk-2MIOMYT2.js";import{a as xa,b as Sa,c as Ea,d as Aa}from"./chunk-2D3RYIDU.js";import{a as Ra,b as _a}from"./chunk-L53FTKEP.js";import{B as xo,H as Jr,S as Hr,h as jr,q as Cr,v as Bs,w as _r}from"./chunk-I2LYULR4.js";import{b as Yt,c as gt,d as jn,e as Cn,f as mt,g as Dr,h as Ho,i as Vt}from"./chunk-CQUVUVXR.js";import{e as qr,f as Hs,k as Wr}from"./chunk-WP6KLXTP.js";import{a as Ir}from"./chunk-N6EWZGIX.js";import{b as dt}from"./chunk-DP7RTNDM.js";import{a as Nr,k as Ur}from"./chunk-U5YBQJ5Q.js";import{b as he,c as Ae,d as ut,e as Br}from"./chunk-547G3HYQ.js";import{j as Rr}from"./chunk-X5C5W3E4.js";import{f as Lr,g as Fr,h as Js}from"./chunk-76Z4VHDX.js";import{h as Or}from"./chunk-DWADWDMU.js";import{a as Ws}from"./chunk-5LLGIX5M.js";import{b as vo,d as In}from"./chunk-XTD3SZIP.js";import{b as lt,d as Tr}from"./chunk-2GIDVZ4H.js";import{a as qs,b as fr,c as bg,d as Tn,e as hr,f as kr,g as kg,h as vr,i as vg,m as ct,n as Sr,o as Er,s as Ar,v as so,w as zt}from"./chunk-VI7GBDKV.js";import{a as fo,b as at,e as wr,f as Gt}from"./chunk-72SZI2UW.js";import{a as xr,b as xg}from"./chunk-FX3D7YON.js";import{a as uo,b as wg}from"./chunk-7I7IEX4S.js";import{q as yr,r as j,s as On,u as re}from"./chunk-ERL6AS3O.js";import{g as br,k as $r,l as $g}from"./chunk-RGDKHYY2.js";import{Command as Sg}from"commander";var vc=new Sg().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 oa({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});re();import{Command as Eg}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as xc,existsSync as ai,mkdirSync as ri,mkdtempSync as Ag,rmSync as Tg,writeFileSync as Sc}from"node:fs";import{dirname as Ec,join as Le}from"node:path";import{homedir as Gn,release as Og,tmpdir as Ig}from"node:os";import{setTimeout as jg}from"node:timers/promises";function zn(){let e=ma(process.platform,process.arch,Og());if(e)throw new Error(e)}function en(){return`gui/${process.getuid()}/${Ys}`}function wt(){return Le(Gn(),"Library/LaunchAgents",`${Ys}.plist`)}async function Ac(){try{ao("launchctl",["bootout",en()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",en()],{stdio:"pipe"})}catch{return}await jg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Tc(){if(!ai(wt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",en()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,wt()],{stdio:"pipe"}),ao("launchctl",["kickstart",en()],{stdio:"pipe"})}function Cg(){let e=wa();if(e&&ai(Le(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var bt=new Eg("desktop").description("install and control the macOS desktop assistant");bt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{zn();let o=j(),t=pa(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Cg(),r=Le(Gn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Le(r,Rn)}
|
|
2
2
|
Computer-use helper \u2192 ${Le(r,_n)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -26,7 +26,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
26
26
|
`))});function gm(){let e;try{e=JSON.parse(Gc("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var mm=new Set(["/app","/api/app"]);function pm(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!mm.has(g)&&n.push(`${i}${a}`)}return n}function um(){try{return JSON.parse(Gc("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function pi(){try{return j().dashboard.port||4202}catch{return 4202}}re();import{Command as lo}from"commander";import h from"chalk";import Re from"prompts";import{readFileSync as To,writeFileSync as xt,existsSync as ue,mkdirSync as co,cpSync as ui,readdirSync as hi}from"fs";import{resolve as H,join as Ao,dirname as fm}from"path";import{fileURLToPath as hm}from"url";function ae(){let e=H(process.cwd(),"agentx.json");if(!ue(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(To(e,"utf-8"))}function Fe(e){return he(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Yo=new lo().name("agent").description("manage agents \u2014 add, list, remove");Yo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Yo.command("add").description("add a new agent interactively").action(async()=>{let e=ae(),o=await Re([{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:H(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:Ao(o.workspace,o.id);co(H(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(fm(hm(import.meta.url)),"../wiki/SKILL.md"),c=ue(r)?r:a;ue(c)&&(co(H(t,".claude/skills/wiki"),{recursive:!0}),ui(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Fe(e),console.log(h.green(`
|
|
27
27
|
Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Yo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ae();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Fe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Yo.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Fe(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var rn=new lo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");rn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
28
28
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
29
|
-
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});rn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ae();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-HPN2F7LH.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Re({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Re({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Re({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 Re({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 Re({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Re({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Fe(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});rn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Fe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});rn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Yo.addCommand(rn);var Zn=new lo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Zn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ae();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Zn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ae(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Re({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 Re([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Fe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Re([{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 Re([{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 Fe(e),co(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Re([{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 Re([{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 Fe(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var St=new lo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");St.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});St.command("add").description("add a cron job").action(async()=>{let e=ae(),o=Object.keys(e.agents||{}),t=await Re([{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 Fe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});St.command("enable <id>").description("enable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Fe(o),console.log(h.green(` Cron "${e}" enabled`))});St.command("disable <id>").description("disable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Fe(o),console.log(h.green(` Cron "${e}" disabled`))});var Vo=new lo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vo.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ae();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});Vo.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ae(),o=await Re([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Fe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});Vo.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ae();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Fe(o),console.log(h.green(` Peer "${e}" removed`)))});Vo.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ae();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Fe(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});Vo.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=j().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Ko=new lo().name("skill").description("manage skills \u2014 add to agent(s), list");Ko.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ae(),n=H(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(Ao(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 Re({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);co(c,{recursive:!0}),ue(Ao(n,"SKILL.md"))?ui(n,c,{recursive:!0}):n.endsWith(".md")&&ui(n,Ao(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ko.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=ue(n)?hi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ko.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]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=To(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=j()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(co(A,{recursive:!0}),xt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=To(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||xt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ko.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ae().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let p=ae();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Ko.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ae(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-4KIUR27O.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
29
|
+
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});rn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ae();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-P6YXC6XZ.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Re({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Re({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Re({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 Re({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 Re({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Re({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Fe(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});rn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Fe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});rn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Yo.addCommand(rn);var Zn=new lo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Zn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ae();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Zn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ae(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Re({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 Re([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Fe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Re([{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 Re([{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 Fe(e),co(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Re([{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 Re([{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 Fe(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var St=new lo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");St.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});St.command("add").description("add a cron job").action(async()=>{let e=ae(),o=Object.keys(e.agents||{}),t=await Re([{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 Fe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});St.command("enable <id>").description("enable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Fe(o),console.log(h.green(` Cron "${e}" enabled`))});St.command("disable <id>").description("disable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Fe(o),console.log(h.green(` Cron "${e}" disabled`))});var Vo=new lo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vo.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ae();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});Vo.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ae(),o=await Re([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Fe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});Vo.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ae();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Fe(o),console.log(h.green(` Peer "${e}" removed`)))});Vo.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ae();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Fe(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});Vo.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=j().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Ko=new lo().name("skill").description("manage skills \u2014 add to agent(s), list");Ko.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ae(),n=H(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(Ao(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 Re({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);co(c,{recursive:!0}),ue(Ao(n,"SKILL.md"))?ui(n,c,{recursive:!0}):n.endsWith(".md")&&ui(n,Ao(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ko.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=ue(n)?hi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ko.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]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=To(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=j()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(co(A,{recursive:!0}),xt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=To(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||xt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ko.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ae().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let p=ae();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Ko.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ae(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-6CNVVFA5.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
30
30
|
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
|
|
31
31
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var an=new lo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");an.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");ue(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");co(i,{recursive:!0}),co(r,{recursive:!0});let a=hi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=Ao(i,d);if(ue(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let u=To(Ao(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);xt(p,u),console.log(h.green(` + ${p}`)),c++}let g=Ao(r,`${e}.yaml`);if(ue(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(ue(s)){let d=To(s,"utf-8").replaceAll("example.",`${e}.`);xt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});an.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),p=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
|
|
32
32
|
--- ${w} ---`)),console.log(y.split(`
|
|
@@ -35,7 +35,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
35
35
|
`).length>30&&console.log(h.dim(` \u2026 (${y.split(`
|
|
36
36
|
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}co(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=Ao(p,w);if(ue(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}xt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});an.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(H(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var yi=new lo().name("hook").description("manage hooks \u2014 add to agent workspace");yi.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ae().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=ue(n)?JSON.parse(To(n,"utf-8")):{},i=await Re([{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),co(H(t.workspace,".claude"),{recursive:!0}),xt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var wi=new lo().name("migrate").description("import configuration from OpenClaw or other tools");wi.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,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ue(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(To(n,"utf-8")),i=ue(H(process.cwd(),"agentx.json"))?ae():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){co(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.js");y(u,i.agents[u])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let p=H(n,"../cron/jobs.json");if(ue(p)){let f=JSON.parse(To(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
|
|
37
37
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Fe(i),console.log(h.green(`
|
|
38
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Oo=new lo().name("config").description("validate and inspect configuration");Oo.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=j(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=On(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(H(r,".claude")),c=ue(H(r,"CLAUDE.md")),l=ue(H(r,".claude/settings.json")),g=ue(H(r,".claude/skills"))?hi(H(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Oo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=j(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function ym(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 fi(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Oo.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-
|
|
38
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Oo=new lo().name("config").description("validate and inspect configuration");Oo.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=j(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=On(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(H(r,".claude")),c=ue(H(r,"CLAUDE.md")),l=ue(H(r,".claude/settings.json")),g=ue(H(r,".claude/skills"))?hi(H(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Oo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=j(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function ym(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 fi(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Oo.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-3GKXLTHH.js"),{expandEnvVars:r}=await import("./config-P6YXC6XZ.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(fi(g))});Oo.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-3GKXLTHH.js"),r=ym(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${fi(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${fi(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Oo.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-3GKXLTHH.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Oo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=j(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as wm}from"commander";import Io from"chalk";import{resolve as jo}from"path";import{existsSync as bm}from"fs";var ho=new wm().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Xo(e){let o=jo(e,".agentx/db.sqlite");bm(o)||(console.log(Io.red(` No SQLite at ${o}`)),console.log(Io.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Ir({path:o});return t||(console.log(Io.red(` Could not open ${o}`)),console.log(Io.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Qo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Io.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])))}ho.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=Xo(jo(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=`
|
|
39
39
|
SELECT agent_id, channel, status, duration_ms,
|
|
40
40
|
input_tokens, output_tokens,
|
|
41
41
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -276,7 +276,7 @@ rules:
|
|
|
276
276
|
action: deny
|
|
277
277
|
severity: critical
|
|
278
278
|
message: "coder-agent is not permitted to run commands against production."
|
|
279
|
-
`,il=[{relPath:"policy.yaml",content:qm},{relPath:"environments/production.yaml",content:Wm},{relPath:"agents/coder-agent.yaml",content:Bm}];var Ro=new Jm().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ai(e){return e==="deny"?me.red:e==="escalate"||e==="ask"?me.yellow:e==="warn"?me.magenta:me.green}function ns(e){return e.root?al(e.root):Ha()}Ro.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Ja({root:ns(e),agentId:e.agent,env:e.env}),process.exit(0)});Ro.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=ns(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Ba({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Vm(s,i,r)});function Vm(e,o,t){let n=Ai(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":me.dim(" (no rule matched)")}`),console.log(` enforced as ${Ai(e.effectiveAction)(e.effectiveAction)} ${me.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${me.cyan(e.ruleId)}${e.severity?me.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${me.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${me.dim(`evaluated in ${t}ms`)}`),console.log()}Ro.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=jr({root:ns(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(me.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Ai(t.verdict),i=t.effective_action!==t.verdict?me.dim(`->${t.effective_action}`):"";console.log(` ${me.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${me.cyan((t.agent_id??"?").padEnd(16))} ${me.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(me.dim(` target: ${t.resolved_target}`))}});Ro.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=rl(al(e.root),qa),t=0;for(let n of il){let s=rl(o,n.relPath);if(Hm(s)&&!e.force){console.log(me.dim(` skip (exists) ${n.relPath}`));continue}Gm(Ym(s),{recursive:!0}),zm(s,n.content),console.log(me.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${me.cyan(o)}`),console.log(me.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(me.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Ro.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(me.green(` daemon reloaded (${e.url})`)):console.log(me.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(me.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Ro.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Wa(ns(e),e.agent);console.log(JSON.stringify(o,null,2))});zt();import{Command as Km}from"commander";import{execFile as Xm}from"child_process";import{promisify as Qm}from"util";import{existsSync as Zm}from"fs";import Ze from"chalk";Gt();var ln="ui-element";function ss(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:cn(t.tried,80),screenChanged:t.changed,note:t.note?cn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:cl(t.role),label:cn(t.label,120),value:t.value?cn(t.value,80):null,enabled:t.enabled}))}}function is(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${cl(t.role)}: ${cn(n,80)}`}return{target:at(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:fo("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function rs(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function cl(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function cn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var ll=Qm(Xm),dl=new Km().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{Zm(Ce)||(console.log(Ze.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await
|
|
279
|
+
`,il=[{relPath:"policy.yaml",content:qm},{relPath:"environments/production.yaml",content:Wm},{relPath:"agents/coder-agent.yaml",content:Bm}];var Ro=new Jm().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ai(e){return e==="deny"?me.red:e==="escalate"||e==="ask"?me.yellow:e==="warn"?me.magenta:me.green}function ns(e){return e.root?al(e.root):Ha()}Ro.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Ja({root:ns(e),agentId:e.agent,env:e.env}),process.exit(0)});Ro.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=ns(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Ba({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Vm(s,i,r)});function Vm(e,o,t){let n=Ai(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":me.dim(" (no rule matched)")}`),console.log(` enforced as ${Ai(e.effectiveAction)(e.effectiveAction)} ${me.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${me.cyan(e.ruleId)}${e.severity?me.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${me.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${me.dim(`evaluated in ${t}ms`)}`),console.log()}Ro.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=jr({root:ns(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(me.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Ai(t.verdict),i=t.effective_action!==t.verdict?me.dim(`->${t.effective_action}`):"";console.log(` ${me.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${me.cyan((t.agent_id??"?").padEnd(16))} ${me.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(me.dim(` target: ${t.resolved_target}`))}});Ro.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=rl(al(e.root),qa),t=0;for(let n of il){let s=rl(o,n.relPath);if(Hm(s)&&!e.force){console.log(me.dim(` skip (exists) ${n.relPath}`));continue}Gm(Ym(s),{recursive:!0}),zm(s,n.content),console.log(me.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${me.cyan(o)}`),console.log(me.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(me.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Ro.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(me.green(` daemon reloaded (${e.url})`)):console.log(me.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(me.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Ro.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Wa(ns(e),e.agent);console.log(JSON.stringify(o,null,2))});zt();import{Command as Km}from"commander";import{execFile as Xm}from"child_process";import{promisify as Qm}from"util";import{existsSync as Zm}from"fs";import Ze from"chalk";Gt();var ln="ui-element";function ss(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:cn(t.tried,80),screenChanged:t.changed,note:t.note?cn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:cl(t.role),label:cn(t.label,120),value:t.value?cn(t.value,80):null,enabled:t.enabled}))}}function is(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${cl(t.role)}: ${cn(n,80)}`}return{target:at(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:fo("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function rs(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function cl(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function cn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var ll=Qm(Xm),dl=new Km().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{Zm(Ce)||(console.log(Ze.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await qn({max:Number(o.max)||40})}catch(d){console.log(Ze.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ze.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=Zt(t,n[0].id);d&&(console.log(Ze.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ze.bold(n[0].label)),await ll(Ce,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await so(ln,ss({request:e,app:t.app,window:t.window,candidates:n}),is(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ze.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${ln}.mode`)),process.exit(1));let i=rs(s.answers,n),r=Zt(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Ze.yellow(` nothing on screen matches "${e}"`)+Ze.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(p=>p.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${Ze.green("\u2192")} ${Ze.bold(g)} `+Ze.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await ll(Ce,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as kp}from"commander";import Be from"chalk";import{readFileSync as gl}from"fs";import{homedir as ep}from"os";import{join as op}from"path";var ml=12e5,tp="https://openrouter.ai/api/v1/chat/completions",np=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function sp(e={kind:"window"},o=ml,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return yt(e,{},n);try{return await yt(e,{untilStable:!0},n)}catch(s){if(s instanceof ac)return yt(e,{},n);throw s}}var ip=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
280
280
|
|
|
281
281
|
Report only what is visible in this image.
|
|
282
282
|
|
|
@@ -309,7 +309,7 @@ ${e.slice(-n)}`}function Al(e){let o=e.trim();return o.includes(`
|
|
|
309
309
|
`).map(t=>` ${t}`).join(`
|
|
310
310
|
`),ls=_p(Rp(),".agentx","paste-undo.txt");function Pp(e){try{Np(Dp(ls),{recursive:!0}),Il(ls,e,{mode:384})}catch{}}function Mp(){try{let e=Cp(ls,"utf-8");return Il(ls,"",{mode:384}),e.length?e:null}catch{return null}}async function Lp(){let{stdout:e}=await Ii("pbpaste",[],{maxBuffer:16777216});return e}async function Nl(e){await new Promise((o,t)=>{Ol("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Fp(){if(!jp(Ce))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Ii(Ce,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Up(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Up(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as qp}from"commander";import Ue from"chalk";re();function Rl(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await Bn(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var Wp=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Bp(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
|
|
311
311
|
${n}`:n,a=await fetch(`${Wp}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function Jp(e){let o;try{o=j(e.config)}catch{o=void 0}let t=Dn(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??Pn(o);return{alert:ba(t),banner:t.banner,channel:n}}var _l=new qp().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel (default: notifications.channel, else push when it is on, else ntfy)").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new ga,n=la(),{alert:s,banner:i,channel:r}=Jp(o),a=s,c;if(o.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let g=io(o.config),d=Rl(s,Wn("notifications",g),{settings:g});a=d.alert,c=d.proof}if(o.status){let g=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?Ue.yellow("\u25D0"):Ue.green("\u25CB")} ${da(n)} ${Ue.dim(`\xB7 ${n.reason}`)}`),console.log(` ${g.length} held`);for(let d of g.slice(0,8)){let p=new Date(d.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ue.dim(` ${p} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=Bp(r,o.chatId);if(o.flush){let g=await va(l,{queue:t,alert:s});console.log(g?Ue.green(` delivered ${g} held notification(s)`):Ue.dim(" nothing was held"));return}e?.trim()||(console.log(Ue.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await ka({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:r,chatId:o.chatId},l,{queue:t,alert:a,focus:n}),d=c?.();if(o.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let p=g.delivered?Ue.green("\u2192"):Ue.yellow("\u23F8");console.log(` ${p} ${g.reason}`),g.held&&console.log(Ue.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Ue.yellow("?"):Ue.green("\u2713")} banner: ${d.shot.path}${Ue.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Ue.yellow(` ${d.error}`))}catch(g){console.log(Ue.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});zt();Sr();hr();Gt();import{Command as Hp}from"commander";import{readFileSync as Gp}from"fs";var Dl=new Hp().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Gp(e.file,"utf8"):await zp()}catch(r){et(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return et("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return et(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return et("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return et("spec needs at least one entry in `questions`");try{wr(t.questions)}catch(r){return et(r?.message??String(r))}let n=t.seat||e.seat;ct(),process.env[Ar(n)]="active";let s=null;if(e.record!==!1)try{s=new Tn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
|
|
312
|
-
`)}Er({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await so(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return et(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function et(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function zp(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}zt();import{Command as Su}from"commander";import{execFile as Eu,spawn as Kl}from"child_process";import{promisify as Au}from"util";import{existsSync as Tu,statSync as Ou}from"fs";import{join as Xl}from"path";import{tmpdir as Iu}from"os";import Q from"chalk";var Yp={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},Vp={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},Kp={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},ji=[Yp,Vp,Kp];re();re();import oo from"chalk";import{execFile as Xp}from"child_process";import{promisify as Qp}from"util";import{createInterface as Zp}from"readline";var Pl=Qp(Xp);function eu(e){e.type==="step"?console.log(`${oo.cyan(` ${e.n}. ${e.action}`)}${e.target?oo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(oo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?oo.red(` failed: ${e.error}`):oo.dim(" done it")):e.type==="replanned"?console.log(oo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(oo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(oo.red(` error: ${e.error}`)):e.type==="end"&&console.log(oo.dim(` \xB7 ended (${e.reason})`))}async function ou(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Pl("open",["-a",e]).catch(()=>{});try{let s=(await ei()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Ml(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Pl("open",["-a",o.app]),i=await ou(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Ln(n,t.agents,!1),a=t.voice.listener??Qa,c=
|
|
312
|
+
`)}Er({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await so(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return et(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function et(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function zp(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}zt();import{Command as Su}from"commander";import{execFile as Eu,spawn as Kl}from"child_process";import{promisify as Au}from"util";import{existsSync as Tu,statSync as Ou}from"fs";import{join as Xl}from"path";import{tmpdir as Iu}from"os";import Q from"chalk";var Yp={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},Vp={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},Kp={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},ji=[Yp,Vp,Kp];re();re();import oo from"chalk";import{execFile as Xp}from"child_process";import{promisify as Qp}from"util";import{createInterface as Zp}from"readline";var Pl=Qp(Xp);function eu(e){e.type==="step"?console.log(`${oo.cyan(` ${e.n}. ${e.action}`)}${e.target?oo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(oo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?oo.red(` failed: ${e.error}`):oo.dim(" done it")):e.type==="replanned"?console.log(oo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(oo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(oo.red(` error: ${e.error}`)):e.type==="end"&&console.log(oo.dim(` \xB7 ended (${e.reason})`))}async function ou(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Pl("open",["-a",e]).catch(()=>{});try{let s=(await ei()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Ml(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Pl("open",["-a",o.app]),i=await ou(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Ln(n,t.agents,!1),a=t.voice.listener??Qa,c=Fn(n,t.agents[n]),l=new oc({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:ei,presence:new Un(c,Ce,n),speech:new ft,model:ht({system:ec(r.persona,a)}),act:tc});l.on(eu),console.log(oo.bold(`
|
|
313
313
|
${c.name} teaches: ${e}`)+oo.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
|
|
314
314
|
`));let g=Zp({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}re();import to from"chalk";import{execFile as fu}from"child_process";import{existsSync as Ri,writeFileSync as hu}from"fs";import{homedir as yu}from"os";import{join as Yl,resolve as wu}from"path";import{promisify as bu}from"util";var qe={w:1e3,h:640},Ci=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Ul=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Ll=["none","semi","solid","fill","pattern"],Ni=180,ql=48,tu=["s","m","l","xl"],nu=["draw","sans","serif","mono"];function Wl(){return[`You are an illustrator drawing on a tldraw canvas ${qe.w} wide and ${qe.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${Ni}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${ql} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${Ul.join(", ")}.`,`color is one of: ${Ci.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
|
|
315
315
|
`)}function Ot(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function ot(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var tt=(e,o,t)=>Math.min(t,Math.max(o,e)),Fl=e=>tt(ot(e)??1,.1,1),su=/^#[0-9a-f]{6}$/i;function iu(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Ci.includes(t)&&typeof n=="string"&&su.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function ru(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,ql)){if(!Array.isArray(t))return null;let n=ot(t[0]),s=ot(t[1]);if(n===null||s===null)return null;o.push([tt(n,0,qe.w),tt(s,0,qe.h)])}return o.length>=2?o:null}function Bl(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=iu(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Ot(n.color,Ci,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=ru(n.path),g=Ot(n.fill,Ll,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Fl(n.opacity)}}let a=ot(n.x),c=ot(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:tt(a,0,qe.w-20),y:tt(c,0,qe.h-20),size:Ot(n.size,tu,"l"),color:r,font:Ot(n.font,nu,"draw")};if(typeof n.geo=="string"){let l=ot(n.w),g=ot(n.h);if(l===null||g===null||l<4||g<4)return null;let d=tt(a,0,qe.w-4),p=tt(c,0,qe.h-4);return{kind:"geo",id:s,say:i,geo:Ot(n.geo,Ul,"rectangle"),x:d,y:p,w:Math.min(l,qe.w-d),h:Math.min(g,qe.h-p),color:r,fill:Ot(n.fill,Ll,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Fl(n.opacity)}}return null}var ds=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
|
|
@@ -367,7 +367,7 @@ return id`:`${n}
|
|
|
367
367
|
const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
|
|
368
368
|
const aid = typeof arrow === 'string' ? arrow : arrow?.id
|
|
369
369
|
if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
|
|
370
|
-
return aid ?? null`}function gu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yo(s[0][0],s[0][1]),yo(i[0],i[1])]}if(e.kind==="geo")return[yo(e.x,e.y),yo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Hl(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[yo(t.x+t.w/2,t.y+t.h/2),yo(n.x+n.w/2,n.y+n.h/2)]}var yo=(e,o)=>({x:e,y:o,w:0,h:0});async function zl(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,cu(60)),g=new Set,d=new Map,p=[],f=!1,u=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},v=x=>{if(g.size>=Ni)return;let $=Bl(x,g);if(!$){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add($.id),w??=i()-c,p.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let x=new ds;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))x.push($).forEach(v);x.flush().forEach(v)}catch($){y=$?.message??String($)}finally{u=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=p.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let $=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,Gl(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-$});continue}let[R,C]=gu(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(Jl(l,R.x,R.y)),await s(250),o.presence.moveTo(Jl(l,C.x,C.y));try{await o.api.exec(t.docId,du(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?Hl(x):x.kind==="path"?lu(x.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let I=(x.say?r:0)-(i()-$);I>0&&await s(I)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:u}}import{readFileSync as mu}from"fs";import{homedir as pu}from"os";import{join as uu}from"path";var pn=uu(pu(),"Library","Application Support","tldraw","server.json"),gs=class{constructor(o=pn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=mu(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var $u=bu(fu),ku="claude-sonnet-5";function vu(e){e.type==="planned"?console.log(to.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${to.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${to.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(to.yellow(` skipped: ${e.line}`)):console.log(to.red(` error: ${e.error}`))}async function xu(){if(!Ri(pn)){await $u("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Ri(pn);e++)await new Promise(o=>setTimeout(o,500));if(!Ri(pn))throw new Error("tldraw offline did not start")}}async function Vl(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||ku,i=wu(o.out||Yl(yu(),"Documents")),r=
|
|
370
|
+
return aid ?? null`}function gu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yo(s[0][0],s[0][1]),yo(i[0],i[1])]}if(e.kind==="geo")return[yo(e.x,e.y),yo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Hl(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[yo(t.x+t.w/2,t.y+t.h/2),yo(n.x+n.w/2,n.y+n.h/2)]}var yo=(e,o)=>({x:e,y:o,w:0,h:0});async function zl(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,cu(60)),g=new Set,d=new Map,p=[],f=!1,u=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},v=x=>{if(g.size>=Ni)return;let $=Bl(x,g);if(!$){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add($.id),w??=i()-c,p.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let x=new ds;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))x.push($).forEach(v);x.flush().forEach(v)}catch($){y=$?.message??String($)}finally{u=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=p.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let $=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,Gl(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-$});continue}let[R,C]=gu(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(Jl(l,R.x,R.y)),await s(250),o.presence.moveTo(Jl(l,C.x,C.y));try{await o.api.exec(t.docId,du(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?Hl(x):x.kind==="path"?lu(x.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let I=(x.say?r:0)-(i()-$);I>0&&await s(I)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:u}}import{readFileSync as mu}from"fs";import{homedir as pu}from"os";import{join as uu}from"path";var pn=uu(pu(),"Library","Application Support","tldraw","server.json"),gs=class{constructor(o=pn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=mu(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var $u=bu(fu),ku="claude-sonnet-5";function vu(e){e.type==="planned"?console.log(to.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${to.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${to.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(to.yellow(` skipped: ${e.line}`)):console.log(to.red(` error: ${e.error}`))}async function xu(){if(!Ri(pn)){await $u("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Ri(pn);e++)await new Promise(o=>setTimeout(o,500));if(!Ri(pn))throw new Error("tldraw offline did not start")}}async function Vl(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||ku,i=wu(o.out||Yl(yu(),"Documents")),r=Fn(n,t.agents[n]),a=ht({system:Wl(),model:s}),c=new Un(r,Ce,n),l=new gs;try{await xu();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(to.bold(`
|
|
371
371
|
${r.name} draws: ${e}`)+to.dim(` (${s}, ${d.filePath})
|
|
372
372
|
`));let p=new AbortController;process.once("SIGINT",()=>p.abort());let f=await zl(e,{api:l,presence:c,model:a},{docId:d.id,signal:p.signal},vu);await l.exec(d.id,"await helpers.saveDoc(); return true");let u=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Yl(i,`agentx-draw-${g}.png`);hu(w,Buffer.from(u.slice(u.indexOf(",")+1),"base64")),console.log(to.bold(`
|
|
373
373
|
${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+to.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let y=a.lastUsage;y&&console.log(to.dim(` tokens: ${y.inputTokens} in, ${y.outputTokens} out, ${y.cacheReadTokens} cache read, ${y.cacheWriteTokens} cache write; cost ${y.costUsd===null?"not reported":`$${y.costUsd.toFixed(4)}`}`)),console.log(to.dim(` ${d.filePath}
|
|
@@ -382,7 +382,7 @@ return aid ?? null`}function gu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
382
382
|
stopping: could not confirm \u2014 ${d.verify}`)),console.log(Q.dim(` ${w.reason}`)),console.log(Q.dim(` screenshot: ${w.sighting.shot.path}`)),await Do(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(Q.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Do(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Do(2500);try{let{size:g}=Ou(i);console.log(Q.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(Q.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(Q.red(` lesson stopped before the end.
|
|
383
383
|
`)),process.exitCode=3;return}console.log(Q.green(`
|
|
384
384
|
done.
|
|
385
|
-
`))});function ju(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Xl(Iu(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function ms(e){let o=await gn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function _i(e){try{let{stdout:o}=await Di(Ce,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Cu(e,o=[]){try{let t=await
|
|
385
|
+
`))});function ju(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Xl(Iu(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function ms(e){let o=await gn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function _i(e){try{let{stdout:o}=await Di(Ce,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Cu(e,o=[]){try{let t=await qn({max:45});if(t.candidates.length<2)return null;let n=await so(ln,ss({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),is(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=rs(n.answers,t.candidates);return s.present<.5?null:Zt(t,s.id)}catch{return null}}function Nu(e,o){if(e?.trim().toLowerCase()===Eo)return{provider:"system",elevenlabs:Qt(),system:null,fallback:!0};let t=e?Mn(e,Xt()):null;if(t)return{provider:"system",elevenlabs:Qt(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=j(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(Q.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Va(za(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Qt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(Q.dim(` no agent voice (${String(n?.message??n).split(`
|
|
386
386
|
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Qt(),system:null,fallback:!0}}}var Ru=new ft;async function _u(e,o){o&&await Ru.say({voice:o,text:e})}var Do=e=>new Promise(o=>setTimeout(o,e));re();import{Command as Zl}from"commander";import Je from"chalk";import{createInterface as ed}from"readline";var Du=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function It(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Du()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Pu(e){e.type==="line"?console.log(`${Je.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Je.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Je.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Je.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Je.dim(" \xB7 hushed")):e.type==="error"?console.log(Je.red(` error: ${e.error}`)):e.type==="end"&&console.log(Je.dim(` \xB7 ended (${e.reason})`))}function od(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function Mu(e,o,t){let n=j(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await It("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Xa(()=>n,()=>d),i.usePool(await Ka(Ga()))}let r=e.map(d=>s[d]?Ln(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new Za({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ft,listener:n.voice.listener,model:(d,p)=>ht({system:p})});l.on(Pu),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Je.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=ed({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Je.dim(` ${od(l.gaps)}`))}async function Lu(e,o,t){let n=await It("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=ed({input:process.stdin});s.on("line",a=>{a.trim()&&It("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void It("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await It("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Je.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Je.dim(` ${od(r)}`))}var td=new Zl().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Mu:Lu)([e,o],s,n),process.exit(0)}catch(i){console.error(Je.red(` ${i?.message??i}`)),process.exit(1)}}),nd=new Zl().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Je.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await It("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Je.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});re();import{Command as Fu}from"commander";import Oe from"chalk";import{existsSync as Uu,readFileSync as qu,writeFileSync as Wu}from"fs";import{resolve as sd}from"path";var ps=new Fu().name("voice").description("list installed system voices and pick each agent's voice");function Bu(e){let o=e?[e]:[sd(process.cwd(),"agentx.json"),sd(process.cwd(),".agentx/config.json")],t=o.find(n=>Uu(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Ju(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===Eo,y=w?null:Mn(t,s,a??e?.voice?.locale),k=y?`system voice ${Qs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?Eo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)p(w?Eo:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let u=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:u}}ps.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Xt(),t;try{t=j(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Ya(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Zs(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Oe.yellow(`
|
|
387
387
|
No system voices found (system voices need macOS).
|
|
388
388
|
`));else{let r=e.all?Xs(o,""):Xs(o,n);console.log(Oe.bold(`
|
|
@@ -396,7 +396,7 @@ return aid ?? null`}function gu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
396
396
|
settings \u2014 without this an attached production identity would be less
|
|
397
397
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Po.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=Nc({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});re();import{Command as Ku}from"commander";import ye from"chalk";var ws=new Ku().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function cd(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=j(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 ld(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function ad(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 Xu(e){return e==="busy"?ye.magenta:e==="warm-hot"?ye.green:e==="warm-cold"?ye.cyan:e==="idle"?ye.yellow:e==="dead"?ye.red:ye.dim}ws.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}=cd(e),n;try{n=await fetch(`${o}/api/processes`,{headers:ld(t)})}catch(r){console.log(ye.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ye.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ye.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ye.dim(" (no processes)"));return}for(let r of i){let a=Xu(r.state)(r.state.padEnd(9)),c=ad(r.spawnedAt),l=r.lastTurnAt?ad(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ye.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?ye.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ye.dim("sess=\u2014"),p=r.pendingTaskId?ye.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ye.bold(r.key.agentId)}${ye.dim(":"+r.key.channel+":"+r.key.chatId)} ${ye.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${p}`),r.deadReason&&console.log(` ${ye.red("dead:")} ${r.deadReason}`)}});ws.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}=cd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ld(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ye.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ye.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ye.red(` ${a}`)),process.exit(1)}console.log(ye.green(` killed ${e}:${o}:${t}`))});import{Command as Qu}from"commander";import De from"chalk";import{existsSync as Pi,rmSync as Zu}from"fs";import{resolve as Mi}from"path";var jt=new Qu().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");jt.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(De.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Lr(e,o,{verbose:n}),r=Date.now()-s;console.log(De.green(` \u2713 indexed ${i.docs} doc(s) for ${De.bold(e)} in ${r}ms`)),console.log(De.dim(` \u2192 ${i.path}`))});jt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Mi(e.cwd,".agentx","rag");if(!Pi(o)){console.log(De.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Pi(Mi(o,s,"index.json")));if(n.length===0){console.log(De.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Js(s);console.log(` ${De.bold(s)} ${i.docs} doc(s) ${De.dim(i.path)}`)}});jt.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=Fr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Js(e);i.exists?console.log(De.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(De.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${De.bold(i.title)} ${De.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${De.dim(i.path)}`),console.log(` ${De.dim(i.snippet.slice(0,200))}`)});jt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Mi(process.cwd(),".agentx","rag",e);if(!Pi(o)){console.log(De.dim(` no index for ${e} \u2014 nothing to clear`));return}Zu(o,{recursive:!0,force:!0}),console.log(De.green(` \u2713 cleared index for ${e}`))});re();import{Command as ef}from"commander";import X from"chalk";import Ct from"prompts";var nt=new ef().name("backlog").description("manage the local backlog used by business workSource=backlog");function un(e){let o=j(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new nc(n)}}function of(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function tf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}nt.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}=un(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(` ${tf(n.status).padEnd(7)} ${of(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()}`))});nt.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=un(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=sc([o],i.source,n.config),a=await ti(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}`))}});nt.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=un(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 ti(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}`))}});nt.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}=un(o.config);t.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});nt.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=un(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 Ct({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"?sf(o.config):rf(o.config);y.length?(i=(await Ct({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 Ct({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Ct({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Ct({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 af(o.config,i,a):await cf(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,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=oi({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Ct({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(X.dim(" nothing selected"));return}let u=f.map(y=>{let k={type:s,host:s==="gitlab"?nf(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:oi(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(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 nf(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function sf(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 rf(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 af(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 cf(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(dd)}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(dd):[]}function dd(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 lf}from"commander";import W from"chalk";import{existsSync as df,readFileSync as gf}from"fs";import{resolve as mf}from"path";import pf from"prompts";re();function gd(e){let o=e||mf(process.cwd(),"agentx.json");return df(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(gf(o,"utf-8"))}async function uf(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await pf([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wo=new lf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wo.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: ${zs})`,zs).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){wo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Gs(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=gd(o.config),s=yr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await uf(o.notify,s),r=o.id||Gr(t.matched,o.agent),a=Yr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:zr(o.onError),enabled:!o.disabled}),c=a.onError,l=await he(d=>Ae(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.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=gd(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Kr(Vr(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])wo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Zr(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!ut(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Br(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",Xr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Qr,"reject an agent's pending create/delete request (drops the request)"]])wo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Gs(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as ff}from"commander";import ve from"chalk";var Mo=new ff("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),hf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function md(){return{root:process.cwd()}}function Li(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function yf(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${hf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Li(e.snoozed_until)})`):""}`),console.log(` ${ve.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ve.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(ve.yellow(` Expires ${Li(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ve.dim(` ${e.detail}`)),e.source&&console.log(ve.dim(` ${e.source}`)),console.log(ve.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mo.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=ja(md(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ve.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ve.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)yf(t),console.log();console.log(ve.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Fi(e,o,t){let n=Jn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ve.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Ca(md(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(ve.red(` ${i.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 ${i.message}`))}Mo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,o)=>Fi(e,"yes",o));Mo.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>Fi(e,"no",o));Mo.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>Fi(e,"later",o));Mo.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Oa.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let o=Jn(),t=Ia(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(ve.red(` ${t.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 card:${t.card.id} raised; expires ${Li(t.card.expires)}, then: ${t.card.if_silent}`))});Mo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=pc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(ve.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await uc(o);if(!a.success){console.error(ve.red(` ${a.error}`)),process.exitCode=1;return}console.log(ve.green(" \u2713 saved")+(a.reloaded?ve.dim(" (daemon reloaded)"):""))}let i=Jn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as Uf}from"commander";import Nt from"chalk";import te from"chalk";import hn from"prompts";import{readFileSync as wf,writeFileSync as bf,existsSync as $f}from"fs";import{resolve as pd}from"path";var kf=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function vf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Ui(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ud(e=".env"){let o=pd(e);if(!$f(o))return[];let t=wf(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(kf);i?n.push({kind:"kv",key:i[1],value:vf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function xf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Ui(o.value)}`:o.raw).join(`
|
|
398
398
|
`)+`
|
|
399
|
-
`}function fn(e,o,t=".env"){let n=pd(t),s=ud(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ui(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ui(o)}`})),bf(n,xf(s))}function qi(e,o=".env"){return ud(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var fd="https://t.me/BotFather";async function Sf(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 Ef(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 hd(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${fd}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await hn({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,[fd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await hn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Sf(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await hn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await hn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;fn(f,t.trim()),process.env[f]=t.trim();let u=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(te.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${f}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await hn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await Ef(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Wi from"prompts";import{existsSync as Ji,mkdirSync as Af,readdirSync as Tf,readFileSync as yd}from"fs";import{resolve as Bi}from"path";var Of=".agentx/whatsapp-sessions";function If(){let e=Bi(process.cwd(),".agentx/daemon.pid");if(!Ji(e))return!1;try{let o=parseInt(yd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function jf(e){if(!Ji(e))return!1;try{return Tf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Cf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Af(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function wd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),If()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Wi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Bi(process.cwd(),"agentx.json");Ji(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(yd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Of,s=Bi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Wi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(jf(s)&&a){let{keep:l}=await Wi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Cf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Nf}from"crypto";import xe from"chalk";import bd from"prompts";var bs="agentx-mesh:",$s="//join/";function Rf(e){return Buffer.from(e,"utf-8").toString("base64url")}function _f(e){return Buffer.from(e,"base64url").toString("utf-8")}function Df(e){return`${bs}${$s}${Rf(JSON.stringify(e))}`}function Pf(e){if(!e.startsWith(`${bs}${$s}`))throw new Error(`Not a mesh invite link \u2014 expected ${bs}${$s}\u2026`);let o=e.slice(bs.length+$s.length),t=JSON.parse(_f(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Mf(){return Nf(32).toString("hex")}function Lf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ff(e){return e?.node?.name||e?.node?.id||"node"}async function $d(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=qi("MESH_TOKEN");r||(r=Mf(),fn("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Lf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await bd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=Df({url:a,token:r,name:Ff(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function kd(e,o={}){let t;try{t=Pf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=qi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await bd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}fn("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=ut(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Rt=new Uf().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 hd({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 wd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var vd=Rt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");vd.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 $d({url:e.url,configPath:e.config})});vd.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 kd(e,{configPath:o.config})});Rt.action(()=>{console.log(),console.log(Nt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Nt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Nt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Nt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Nt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Nt.dim(" GitLab connect is the next slice.")),console.log()});re();import{Command as qf}from"commander";import pe from"chalk";var yn=new qf().name("usage").description("token usage analysis and reporting");yn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});yn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});yn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-D5TAPSIH.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Wf}from"commander";import be from"chalk";import{readFileSync as Bf}from"fs";import{resolve as Jf}from"path";re();var Lo=new Wf().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Tr(Jf(process.cwd(),".env"))}catch{}let o=Hf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-NRRYCDZW.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function Hf(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
399
|
+
`}function fn(e,o,t=".env"){let n=pd(t),s=ud(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ui(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ui(o)}`})),bf(n,xf(s))}function qi(e,o=".env"){return ud(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var fd="https://t.me/BotFather";async function Sf(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 Ef(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 hd(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${fd}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await hn({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,[fd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await hn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Sf(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await hn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await hn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;fn(f,t.trim()),process.env[f]=t.trim();let u=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(te.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${f}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await hn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await Ef(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Wi from"prompts";import{existsSync as Ji,mkdirSync as Af,readdirSync as Tf,readFileSync as yd}from"fs";import{resolve as Bi}from"path";var Of=".agentx/whatsapp-sessions";function If(){let e=Bi(process.cwd(),".agentx/daemon.pid");if(!Ji(e))return!1;try{let o=parseInt(yd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function jf(e){if(!Ji(e))return!1;try{return Tf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Cf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Af(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function wd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),If()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Wi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Bi(process.cwd(),"agentx.json");Ji(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(yd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Of,s=Bi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Wi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(jf(s)&&a){let{keep:l}=await Wi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Cf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Nf}from"crypto";import xe from"chalk";import bd from"prompts";var bs="agentx-mesh:",$s="//join/";function Rf(e){return Buffer.from(e,"utf-8").toString("base64url")}function _f(e){return Buffer.from(e,"base64url").toString("utf-8")}function Df(e){return`${bs}${$s}${Rf(JSON.stringify(e))}`}function Pf(e){if(!e.startsWith(`${bs}${$s}`))throw new Error(`Not a mesh invite link \u2014 expected ${bs}${$s}\u2026`);let o=e.slice(bs.length+$s.length),t=JSON.parse(_f(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Mf(){return Nf(32).toString("hex")}function Lf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ff(e){return e?.node?.name||e?.node?.id||"node"}async function $d(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=qi("MESH_TOKEN");r||(r=Mf(),fn("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Lf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await bd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=Df({url:a,token:r,name:Ff(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function kd(e,o={}){let t;try{t=Pf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=qi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await bd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}fn("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=ut(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Rt=new Uf().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 hd({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 wd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var vd=Rt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");vd.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 $d({url:e.url,configPath:e.config})});vd.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 kd(e,{configPath:o.config})});Rt.action(()=>{console.log(),console.log(Nt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Nt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Nt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Nt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Nt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Nt.dim(" GitLab connect is the next slice.")),console.log()});re();import{Command as qf}from"commander";import pe from"chalk";var yn=new qf().name("usage").description("token usage analysis and reporting");yn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});yn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});yn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-7DUQJDSQ.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Wf}from"commander";import be from"chalk";import{readFileSync as Bf}from"fs";import{resolve as Jf}from"path";re();var Lo=new Wf().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Tr(Jf(process.cwd(),".env"))}catch{}let o=Hf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-A7PQOI6C.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function Hf(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
400
400
|
`)),{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}}}}Lo.command("list").description("list configured boards").action(()=>{try{let e=j();if(!e.boards?.length){console.log(be.dim(`
|
|
401
401
|
No boards configured.
|
|
402
402
|
`));return}console.log();for(let o of e.boards){console.log(` ${be.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(be.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(be.dim(` primary label: ${o.primaryToolLabel}`)),console.log(be.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});Lo.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{wn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});Lo.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{wn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});var Hi=Lo.command("column").description("manage a board's columns (add / remove / edit / list)");Hi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Bf("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(be.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Hi.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{wn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(be.red(` ${n.message}`)),process.exit(1)}});Hi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{wn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});Lo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{wn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});function wn(e){let{summary:o,backupPath:t}=ro(n=>e(n));console.log(be.green(`
|
|
@@ -406,9 +406,9 @@ return aid ?? null`}function gu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
406
406
|
${$.content}
|
|
407
407
|
--- END ENTRY ---`).join(`
|
|
408
408
|
|
|
409
|
-
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:R,mergeRecords:C,renderFactsBlock:I,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let G=$(u.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ge=L(u);if(G.length>0||ge.length>0){let J=B(),{records:Ee,results:$e}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...ge,...Ee]);v=I(M);let ze=[...ge.length>0?[`entries:${ge.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${ze.length?` (${ze.join(" ")})`:""}`));for(let ke of P($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=ra(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${zi(o)}`));let S=F(w.baseDir,"_tmp");bo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");it(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=st(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:lt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if($=M.stdout||"",!$)throw M}let R=$;try{let M=JSON.parse($);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,I=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],ge=G==="{"?"}":"]",J=0,Ee=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===ge&&(J--,J===0)){Ee=M+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=R.slice(L,Ee);try{let M=JSON.parse($e);Array.isArray(M)?C=M:(C=M.articles||[],I=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let M of C){let ze=new Date().toISOString().slice(0,10),ke=l(M.sources||[],u);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:p,access:"public",created:ze,lastUpdated:ze,sources:M.sources||[],graphPath:ke},M.content,p);let Jo=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jo}${M.path}: ${M.title}${m.dim(_)}`);let fe=(M.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let M of I)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-2V2VGIT4.js"),ze=new M($n(e.dir)).add(I.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});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("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Vf(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-4YJHIBAF.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ye(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ye(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(o??6048e5)}),u=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let w=u[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...u]}finally{p.close()}}}let r=await aa({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var vs=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function xs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}vs.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(xs(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});vs.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(xs(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
409
|
+
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:R,mergeRecords:C,renderFactsBlock:I,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let G=$(u.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ge=L(u);if(G.length>0||ge.length>0){let J=B(),{records:Ee,results:$e}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...ge,...Ee]);v=I(M);let ze=[...ge.length>0?[`entries:${ge.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${ze.length?` (${ze.join(" ")})`:""}`));for(let ke of P($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=ra(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${zi(o)}`));let S=F(w.baseDir,"_tmp");bo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");it(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=st(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:lt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if($=M.stdout||"",!$)throw M}let R=$;try{let M=JSON.parse($);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,I=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],ge=G==="{"?"}":"]",J=0,Ee=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===ge&&(J--,J===0)){Ee=M+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=R.slice(L,Ee);try{let M=JSON.parse($e);Array.isArray(M)?C=M:(C=M.articles||[],I=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let M of C){let ze=new Date().toISOString().slice(0,10),ke=l(M.sources||[],u);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:p,access:"public",created:ze,lastUpdated:ze,sources:M.sources||[],graphPath:ke},M.content,p);let Jo=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jo}${M.path}: ${M.title}${m.dim(_)}`);let fe=(M.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let M of I)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-2V2VGIT4.js"),ze=new M($n(e.dir)).add(I.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});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("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Vf(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-WCBXLLDS.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ye(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ye(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(o??6048e5)}),u=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let w=u[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...u]}finally{p.close()}}}let r=await aa({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var vs=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function xs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}vs.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(xs(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});vs.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(xs(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
410
410
|
`).map(s=>` ${s}`).join(`
|
|
411
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});vs.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-
|
|
411
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});vs.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-KVPLDSKT.js"),n=t(xs(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});vs.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-KVPLDSKT.js"),n=t(xs(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Vf(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-AGOMCYTT.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Se(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
412
412
|
`)||"_(none returned)_",A;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
|
|
413
413
|
|
|
414
414
|
${S.answer}
|
|
@@ -425,7 +425,7 @@ Q: ${_.q}
|
|
|
425
425
|
A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
|
|
426
426
|
`),A=F(a.baseDir,"_tmp");bo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);it(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=st(_,{env:lt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ve=JSON.parse(fe);x=String(Ve.result||Ve.content||"")}catch{x=fe}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let $=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(x=$[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let C=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let I={};for(let _ of C[1].split(`
|
|
427
427
|
`)){let fe=_.match(/^(\w+):\s*(.+)$/);fe&&(I[fe[1]]=fe[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=I.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ge=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ge}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Ee=P,$e={title:B,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",fe=F(A,`draft-${t().slice(0,8)}.md`);it(fe,x);try{st(`${_} '${fe}'`,{stdio:"inherit"});let Fs=bn(fe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Fs){let ko={};for(let Ht of Fs[1].split(`
|
|
428
|
-
`)){let Us=Ht.match(/^(\w+):\s*(.+)$/);Us&&(ko[Us[1]]=Us[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Fs[2],$e={...$e,title:ko.title||$e.title,type:ko.type||$e.type,access:ko.access||$e.access,related:ko.related?ko.related.replace(/^\[|\]$/g,"").split(",").map(Ht=>Ht.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:ko.tags?ko.tags.replace(/^\[|\]$/g,"").split(",").map(Ht=>Ht.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ve){console.log(m.red(` editor failed: ${Ve.message}`));return}}if(!a.writeArticle(ge,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ge} saved.`));let ze=a.extractWikilinks(Ee),ke=new Map;for(let _ of a.listArticles(e.agent))ke.set(_.meta.title.toLowerCase(),!0);let Jo=ze.filter(_=>!ke.has(_.toLowerCase()));if(Jo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jo.slice(0,8))console.log(m.dim(` - ${_}`));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-
|
|
428
|
+
`)){let Us=Ht.match(/^(\w+):\s*(.+)$/);Us&&(ko[Us[1]]=Us[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Fs[2],$e={...$e,title:ko.title||$e.title,type:ko.type||$e.type,access:ko.access||$e.access,related:ko.related?ko.related.replace(/^\[|\]$/g,"").split(",").map(Ht=>Ht.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:ko.tags?ko.tags.replace(/^\[|\]$/g,"").split(",").map(Ht=>Ht.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ve){console.log(m.red(` editor failed: ${Ve.message}`));return}}if(!a.writeArticle(ge,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ge} saved.`));let ze=a.extractWikilinks(Ee),ke=new Map;for(let _ of a.listArticles(e.agent))ke.set(_.meta.title.toLowerCase(),!0);let Jo=ze.filter(_=>!ke.has(_.toLowerCase()));if(Jo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jo.slice(0,8))console.log(m.dim(` - ${_}`));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-AGOMCYTT.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Se(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=bn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],p=0;for(let f=0;f<l;f++){let u,w;if(r){let G=r[f];if(!G)break;u=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.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 G=y.citations.map(ge=>`${ge.title} [${ge.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
429
429
|
`)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=Xf(x.content,v,A,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");bo(R,{recursive:!0});let C=F(R,`quiz-patch-${t().slice(0,8)}.txt`);it(C,$);let I="";try{let G=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ge=st(G,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ee=JSON.parse(ge);I=String(Ee.result||Ee.content||"")}catch{I=ge}let J=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(I=J[1].trim()),I=I.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
|
|
430
430
|
`).length,B=I.split(`
|
|
431
431
|
`).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<d.length;u++){let w=d[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}it(e.out,f.join(`
|
|
@@ -486,14 +486,14 @@ Output (JSON array, one entry per input article, same order):
|
|
|
486
486
|
[
|
|
487
487
|
{"path": "path/to/article.md", "type": "project"},
|
|
488
488
|
...
|
|
489
|
-
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});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-
|
|
489
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});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-P6YXC6XZ.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(),bc(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-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-DBFW3Z5P.js"),c=Se(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||p.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
|
|
490
490
|
${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(`
|
|
491
|
-
${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});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-VUJC4Y5O.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});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=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});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=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ye(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),f=p.listArticles(d),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let R=String($.meta?.sender??""),C=s.fingerprint({text:$.content,channel:$.source,sender:R}),I=r.get(C);if(!I?.length)continue;let P=I.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:I,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});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=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-HPN2F7LH.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});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 Ws(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:zi(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});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");Ye(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ye(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${eh(d)})`)),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-PITN4NHA.js"),{askSeat:a}=await import("./seat-2PEI7JRX.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let R of $.listArticles(x)){if(f>=p)break e;let C=$.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let I=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,I.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),u.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c($n(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...u.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of u)console.log(y.map(($,R)=>v(x[$],R)).join(" "));let A=u.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=$);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-HPN2F7LH.js"),I=C(),P=I?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
491
|
+
${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});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-AGOMCYTT.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});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=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});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=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ye(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),f=p.listArticles(d),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let R=String($.meta?.sender??""),C=s.fingerprint({text:$.content,channel:$.source,sender:R}),I=r.get(C);if(!I?.length)continue;let P=I.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:I,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});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=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-P6YXC6XZ.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});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 Ws(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:zi(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});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");Ye(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ye(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${eh(d)})`)),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-PITN4NHA.js"),{askSeat:a}=await import("./seat-DBFW3Z5P.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let R of $.listArticles(x)){if(f>=p)break e;let C=$.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let I=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,I.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),u.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c($n(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...u.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of u)console.log(y.map(($,R)=>v(x[$],R)).join(" "));let A=u.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=$);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-P6YXC6XZ.js"),I=C(),P=I?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
492
492
|
`),L=R.length>10?`
|
|
493
493
|
\u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
494
494
|
${B}${L}
|
|
495
495
|
|
|
496
|
-
agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ge}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});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-PITN4NHA.js"),{askSeat:r}=await import("./seat-2PEI7JRX.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Se(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of u){let P=f.getAgentWiki(I);for(let B of P.listArticles(I)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:I,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l($e,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let ze=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,fe])=>[_,fe.value]))}]:[],...Ee]);if(ze.length===0)continue;let{content:ke,edits:Jo}=p(L.content,ze[0],J);if(Jo.length!==0){for(let _ of Jo)S.push({agent:I,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ke,I)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],R=$.map(I=>Math.max(I.length,...S.map(P=>String(P[I]).length))),C=I=>I.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C($)));for(let I of S)console.log(C($.map(P=>I[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});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-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o($n(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-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n($n(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});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-LZWMMLLN.js"),{askSeat:i}=await import("./seat-2PEI7JRX.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Se(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let ge=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:ge.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:C,failures:S,elapsed:I},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${P($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:ge}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ge.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=ge.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.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);Ye(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");Ye(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 eh(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"}xg();import{Command as oh}from"commander";import D from"chalk";import{resolve as Ss}from"path";import{existsSync as th}from"fs";re();var _t=new oh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");_t.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=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.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 vo({baseDir:Ss(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=In(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let k=nh(w,a,c),b=null;try{b=await sh(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(D.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(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{ih(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});_t.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=j();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Ss(process.cwd(),o.graph.baseDir);if(!th(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});_t.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=j();if(!o.graph?.enabled){console.log(D.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 vo({baseDir:Ss(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch($){console.log(D.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${p}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:l,y=new Map;w.levels.forEach(($,R)=>y.set($.id,R));let k=[...g].sort(($,R)=>(y.get($.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${$.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function nh(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(`
|
|
496
|
+
agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ge}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});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-PITN4NHA.js"),{askSeat:r}=await import("./seat-DBFW3Z5P.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Se(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of u){let P=f.getAgentWiki(I);for(let B of P.listArticles(I)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:I,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l($e,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let ze=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,fe])=>[_,fe.value]))}]:[],...Ee]);if(ze.length===0)continue;let{content:ke,edits:Jo}=p(L.content,ze[0],J);if(Jo.length!==0){for(let _ of Jo)S.push({agent:I,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ke,I)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],R=$.map(I=>Math.max(I.length,...S.map(P=>String(P[I]).length))),C=I=>I.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C($)));for(let I of S)console.log(C($.map(P=>I[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});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-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o($n(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-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n($n(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});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-LZWMMLLN.js"),{askSeat:i}=await import("./seat-DBFW3Z5P.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Se(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let ge=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:ge.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:C,failures:S,elapsed:I},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${P($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:ge}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ge.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=ge.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.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);Ye(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");Ye(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 eh(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"}xg();import{Command as oh}from"commander";import D from"chalk";import{resolve as Ss}from"path";import{existsSync as th}from"fs";re();var _t=new oh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");_t.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=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.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 vo({baseDir:Ss(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=In(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let k=nh(w,a,c),b=null;try{b=await sh(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(D.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(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{ih(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});_t.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=j();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Ss(process.cwd(),o.graph.baseDir);if(!th(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});_t.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=j();if(!o.graph?.enabled){console.log(D.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 vo({baseDir:Ss(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch($){console.log(D.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${p}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:l,y=new Map;w.levels.forEach(($,R)=>y.set($.id,R));let k=[...g].sort(($,R)=>(y.get($.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${$.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function nh(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(`
|
|
497
497
|
`),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(`
|
|
498
498
|
`)}async function sh(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 xr((c?.content||"").toString())}finally{clearTimeout(r)}}function ih(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Yi(){let e=j();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=Ss(process.cwd(),e.graph.baseDir);return{store:new vo({baseDir:o}),baseDir:o}}var Vi=_t.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Vi.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=Yi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.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):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(In(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Vi.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(D.red(" verdict must be correct | wrong | unsure"));return}let n=Yi();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.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(D.green(` ${o}: ${In(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Vi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Yi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as gh}from"commander";import V from"chalk";import{Command as Id}from"commander";import ce from"chalk";import{existsSync as rh}from"fs";import{resolve as ah}from"path";import ch from"better-sqlite3";function lh(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(ce.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function dh(e){let o=ah(process.cwd(),e);return rh(o)||(console.log(ce.red(` No db at ${o}`)),process.exit(1)),new ch(o,{readonly:!0})}var jd=new Id().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(Nn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(ce.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=dh(e.path),t=await ca(o,{since:lh(e.since),agentId:e.agent,sessions:new Cr(process.cwd()),minOccurrences:Number(e.minOccurrences)||Kt,max:Number(e.max)||Nn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ce.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${ce.cyan(n.key)} ${ce.bold(`\xD7${n.count}`)} ${ce.dim(n.status)}`),n.sampleMessage&&console.log(ce.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ce.dim(`
|
|
499
499
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ce.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ce.green(` \u2713 draft written: ${n.id}`)+ce.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ce.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ce.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ce.dim(`
|
|
@@ -529,7 +529,7 @@ agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(
|
|
|
529
529
|
|
|
530
530
|
`))>=0;){let f=l.slice(0,p);l=l.slice(p+2),Dh(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Dh(e){let o="message",t="";for(let i of e.split(`
|
|
531
531
|
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}re();import{Command as Ph}from"commander";import qt from"chalk";function Mh(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var zd=new Ph().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=j(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(Mh(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(qt.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(qt.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(qt.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(qt.dim(" no events"));return}for(let a of i)console.log(` ${Rr(a)} ${qt.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(qt.dim(`
|
|
532
|
-
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as Fh}from"commander";import Cs from"chalk";import{spawn as Uh}from"node:child_process";import{execFileSync as Lh}from"node:child_process";function Yd(e=()=>Lh("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 Vd=new Fh().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(Cs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-
|
|
532
|
+
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as Fh}from"commander";import Cs from"chalk";import{spawn as Uh}from"node:child_process";import{execFileSync as Lh}from"node:child_process";function Yd(e=()=>Lh("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 Vd=new Fh().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(Cs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-EFP2PKA3.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Yd();if(n?.ok){let{fetchAgents:l}=await import("./client-EFP2PKA3.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${d}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Cs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=Uh("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Cs.yellow(n.reason)),console.error(Cs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-Z5VOAUXB.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 qh}from"commander";import K from"chalk";import{randomUUID as Qd}from"crypto";import{createInterface as Wh}from"node:readline/promises";import Bh from"ora";import Ns from"chalk";function Kd(e){console.error(),console.error(Ns.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ns.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ns.cyan(e.instead)} instead.`),e.note&&console.error(Ns.dim(` ${e.note}`)),console.error()}var Xd={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 Zd=new qh().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)=>{Kd({what:"agentx chat",...Xd});let t=$c({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Qd().slice(0,12)}`,r=[];try{r=await Hn(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),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(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.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:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-BE7ONQKS.js"),p=(await import("react")).default;await g(p.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Hh(t.baseUrl,n,i,s);let a=Wh({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
|
|
533
533
|
bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Qd().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await Hn(t);for(let w of u){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(K.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await Hn(t)).find(y=>y.id===u)){console.log(K.red(` unknown agent: @${u}`));continue}n=u,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Bh({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Jh(n);try{let u=await kc(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){d.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function Jh(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
|
|
534
534
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
535
535
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
@@ -622,7 +622,7 @@ Restart the daemon to activate.
|
|
|
622
622
|
dist/
|
|
623
623
|
*.log
|
|
624
624
|
.env
|
|
625
|
-
`}import{Command as Ey}from"commander";import je from"chalk";import{writeFileSync as Ay,mkdirSync as Ty,existsSync as Ls,readFileSync as dg,appendFileSync as gg}from"fs";import{resolve as Jt,dirname as ug}from"path";import{homedir as pr}from"os";var fg=new Ey().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-
|
|
625
|
+
`}import{Command as Ey}from"commander";import je from"chalk";import{writeFileSync as Ay,mkdirSync as Ty,existsSync as Ls,readFileSync as dg,appendFileSync as gg}from"fs";import{resolve as Jt,dirname as ug}from"path";import{homedir as pr}from"os";var fg=new Ey().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-7DUQJDSQ.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=jy(t);break;case"bash":s=Dy(t);break;case"fish":s=Py(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Jt(String(e.output)):Oy(n);Ty(ug(i),{recursive:!0}),Ay(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Iy(n,i,!!e.yes)});function Oy(e){let o=pr();switch(e){case"zsh":return Jt(o,".zsh","completions","_agentx");case"bash":return Jt(o,".bash_completion.d","agentx.bash");case"fish":return Jt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Iy(e,o,t){if(e==="zsh"){let n=Jt(pr(),".zshrc"),s=ug(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ls(n)?dg(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ls(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),gg(n,g.join(`
|
|
626
626
|
`)+`
|
|
627
627
|
`),console.log(je.green("\u2713 Patched ~/.zshrc")),console.log(je.dim("Reload your shell: exec zsh"));return}console.log(je.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(je.cyan(` ${i}`)),l&&console.log(je.cyan(` ${r}`)),console.log(),console.log(je.dim("Then reload: exec zsh")),console.log(je.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Jt(pr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ls(n)?dg(n,"utf-8"):"").includes(o)){console.log(je.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ls(n)){gg(n,`
|
|
628
628
|
# agentx completion
|
|
@@ -633,4 +633,4 @@ ${s}
|
|
|
633
633
|
`)}function ur(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=ur(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 $1(){let e=await lc(),o=new My().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=hc(n);yc(s)&&fc("cli",s)});for(let t of[Hc,Wc,Rt,bt,vt,Ke,mc,Yo,Zn,wo,Mo,Po,Qn,Vd,Ro,dl,bl,mn,jl,_l,Dl,Ql,td,nd,ps,yn,eg,sn,Oo,fg])o.addCommand(t);for(let t of yg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=yg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Ly(t,74," "),""].join(`
|
|
634
634
|
`)}),o}var yg=[Z,_t,qo,no,an,jt,He,$o,Lo,nt,Lt,Ft,Co,We,At,ws,Gd,zd,ho,Vo,vc,Ko,En,yi,Uo,St,wi,js,po,Wo,ig,ag,Zd];function Ly(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(`
|
|
635
635
|
`)}export{$1 as a};
|
|
636
|
-
//# sourceMappingURL=chunk-
|
|
636
|
+
//# sourceMappingURL=chunk-POL7RAJQ.js.map
|