agentix-cli 0.23.0 → 0.25.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/LICENSE +21 -0
- package/README.md +102 -103
- package/agentx.example.json +9 -3
- package/dist/App-6Y7B3YQH.js +8 -0
- package/dist/App-6Y7B3YQH.js.map +1 -0
- package/dist/ChatApp-KIEUJ2DS.js +7 -0
- package/dist/ChatApp-KIEUJ2DS.js.map +1 -0
- package/dist/{agent-FSE4KRLX.js → agent-QGZIAZMY.js} +2 -2
- package/dist/architect-SEPWMWS4.js +2 -0
- package/dist/{board-dashboard-PUACKWAN.js → board-dashboard-CQ5F4GPD.js} +3756 -1010
- package/dist/board-dashboard-CQ5F4GPD.js.map +1 -0
- package/dist/builtin-FRKAQMFS.js +2 -0
- package/dist/chunk-2WVX3LEC.js +2 -0
- package/dist/chunk-2WVX3LEC.js.map +1 -0
- package/dist/chunk-3WQFCIB6.js +24 -0
- package/dist/chunk-3WQFCIB6.js.map +1 -0
- package/dist/chunk-53GCFZPR.js +116 -0
- package/dist/chunk-53GCFZPR.js.map +1 -0
- package/dist/{chunk-IKBHHTIT.js → chunk-5U35WAZF.js} +2 -2
- package/dist/chunk-67Q4DCPS.js +54 -0
- package/dist/chunk-67Q4DCPS.js.map +1 -0
- package/dist/chunk-76Z4VHDX.js +8 -0
- package/dist/chunk-76Z4VHDX.js.map +1 -0
- package/dist/{chunk-7P5QRX5W.js → chunk-BFXONUUN.js} +2 -2
- package/dist/{chunk-DXTIG5YV.js → chunk-FDMWOPEL.js} +2 -2
- package/dist/chunk-FDWOECJY.js +54 -0
- package/dist/chunk-FDWOECJY.js.map +1 -0
- package/dist/chunk-G57RZCXM.js +5 -0
- package/dist/chunk-G57RZCXM.js.map +1 -0
- package/dist/{chunk-NOF4HSGK.js → chunk-H5D7ATXS.js} +2 -2
- package/dist/chunk-HA3XI7Z2.js +155 -0
- package/dist/chunk-HA3XI7Z2.js.map +1 -0
- package/dist/chunk-HR4JSRZS.js +3 -0
- package/dist/{chunk-A6BKSZQA.js.map → chunk-HR4JSRZS.js.map} +1 -1
- package/dist/chunk-I3SIXTJO.js +44 -0
- package/dist/chunk-I3SIXTJO.js.map +1 -0
- package/dist/chunk-ISEBLHWX.js +118 -0
- package/dist/chunk-ISEBLHWX.js.map +1 -0
- package/dist/{chunk-4ITQP3XL.js → chunk-JP5IEXR7.js} +2 -2
- package/dist/chunk-JXWAGMI2.js +13 -0
- package/dist/chunk-JXWAGMI2.js.map +1 -0
- package/dist/chunk-KUCCW2VG.js +431 -0
- package/dist/chunk-KUCCW2VG.js.map +1 -0
- package/dist/chunk-LDHPMJ7M.js +257 -0
- package/dist/chunk-LDHPMJ7M.js.map +1 -0
- package/dist/{chunk-KWUWZQGV.js → chunk-LNXCJWOU.js} +29 -30
- package/dist/chunk-LNXCJWOU.js.map +1 -0
- package/dist/chunk-M4AMWP3H.js +178 -0
- package/dist/chunk-M4AMWP3H.js.map +1 -0
- package/dist/chunk-NGSIRE4X.js +126 -0
- package/dist/chunk-NGSIRE4X.js.map +1 -0
- package/dist/{chunk-CNNLREHD.js → chunk-P4VWIVKN.js} +268 -410
- package/dist/chunk-P4VWIVKN.js.map +1 -0
- package/dist/chunk-Q6YO7LYE.js +47 -0
- package/dist/chunk-Q6YO7LYE.js.map +1 -0
- package/dist/chunk-TMKLHTCG.js +971 -0
- package/dist/chunk-TMKLHTCG.js.map +1 -0
- package/dist/chunk-TRJTTBE2.js +7 -0
- package/dist/chunk-TRJTTBE2.js.map +1 -0
- package/dist/chunk-U2CKL755.js +4 -0
- package/dist/chunk-U2CKL755.js.map +1 -0
- package/dist/chunk-UCQ2N3KO.js +9 -0
- package/dist/chunk-UCQ2N3KO.js.map +1 -0
- package/dist/chunk-W4YR2RO2.js +2 -0
- package/dist/chunk-W4YR2RO2.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-GGVVLOOF.js +2 -0
- package/dist/{compaction-BTUJJ3LJ.js → compaction-NWEMOSHA.js} +3 -3
- package/dist/config-7FSZFRTQ.js +2 -0
- package/dist/config-mutator-POCOYYJ4.js +2 -0
- package/dist/{context-planner-I7ID7XF3.js → context-planner-45GEWKGL.js} +2 -2
- package/dist/doctor-DHLBEKA4.js +2 -0
- package/dist/heal-HZ3EQD52.js +2 -0
- package/dist/index.d.ts +1193 -225
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-AENFVVO5.js +2 -0
- package/dist/processes-UIC4XXA6.js +2 -0
- package/dist/program-WVAVJFND.js +2 -0
- package/dist/projects-api-KRME2YKZ.js +2 -0
- package/dist/projects-api-KRME2YKZ.js.map +1 -0
- package/dist/projects-mutate-3NHVG437.js +7 -0
- package/dist/projects-mutate-3NHVG437.js.map +1 -0
- package/dist/providers-L27BJ5A6.js +2 -0
- package/dist/registry-T36ZIAWV.js +2 -0
- package/dist/rotation-memo-B3EXXSEH.js +13 -0
- package/dist/rotation-memo-B3EXXSEH.js.map +1 -0
- package/dist/scheduler-GH7TIKYS.js +2 -0
- package/dist/surface-usage-PRL6Z4U3.js +2 -0
- package/dist/wiki-M6YNRFC4.js +2 -0
- package/dist/workflows/templates/branching.yaml +75 -0
- package/dist/workflows/templates/extract.yaml +59 -0
- package/dist/workflows/templates/linear.yaml +37 -0
- package/dist/workflows/templates/retry.yaml +61 -0
- package/dist/workspace-setup-TBQAHYHJ.js +2 -0
- package/package.json +10 -3
- package/dist/board-dashboard-PUACKWAN.js.map +0 -1
- package/dist/builtin-TQKMR42Z.js +0 -2
- package/dist/chunk-3SHMHYPD.js +0 -450
- package/dist/chunk-3SHMHYPD.js.map +0 -1
- package/dist/chunk-4INOOHND.js +0 -6
- package/dist/chunk-4INOOHND.js.map +0 -1
- package/dist/chunk-5F3J55LG.js +0 -2
- package/dist/chunk-5F3J55LG.js.map +0 -1
- package/dist/chunk-72PAN7UI.js +0 -103
- package/dist/chunk-72PAN7UI.js.map +0 -1
- package/dist/chunk-A6BKSZQA.js +0 -3
- package/dist/chunk-BHSPAP4U.js +0 -44
- package/dist/chunk-BHSPAP4U.js.map +0 -1
- package/dist/chunk-BOUKM2PS.js +0 -163
- package/dist/chunk-BOUKM2PS.js.map +0 -1
- package/dist/chunk-CDNWCYF7.js +0 -2
- package/dist/chunk-CDNWCYF7.js.map +0 -1
- package/dist/chunk-CNNLREHD.js.map +0 -1
- package/dist/chunk-EK37JHJI.js +0 -13
- package/dist/chunk-EK37JHJI.js.map +0 -1
- package/dist/chunk-EQPUB7CZ.js +0 -685
- package/dist/chunk-EQPUB7CZ.js.map +0 -1
- package/dist/chunk-EW27SCCC.js +0 -2
- package/dist/chunk-EW27SCCC.js.map +0 -1
- package/dist/chunk-GOLZ6NEL.js +0 -111
- package/dist/chunk-GOLZ6NEL.js.map +0 -1
- package/dist/chunk-JGXE2YNV.js +0 -46
- package/dist/chunk-JGXE2YNV.js.map +0 -1
- package/dist/chunk-KWUWZQGV.js.map +0 -1
- package/dist/chunk-MTRWXRFF.js +0 -380
- package/dist/chunk-MTRWXRFF.js.map +0 -1
- package/dist/chunk-N67JZAXU.js +0 -2
- package/dist/chunk-N67JZAXU.js.map +0 -1
- package/dist/chunk-PD5Q7D6Z.js +0 -7
- package/dist/chunk-PD5Q7D6Z.js.map +0 -1
- package/dist/chunk-Q6CAFGXT.js +0 -118
- package/dist/chunk-Q6CAFGXT.js.map +0 -1
- package/dist/chunk-WJXU5F4Z.js +0 -53
- package/dist/chunk-WJXU5F4Z.js.map +0 -1
- package/dist/chunk-ZZFXI3CS.js +0 -8
- package/dist/chunk-ZZFXI3CS.js.map +0 -1
- package/dist/config-ADS54KLC.js +0 -2
- package/dist/config-mutator-WTRMBZTO.js +0 -2
- package/dist/doctor-T6RB4Q5X.js +0 -2
- package/dist/editor-chat-RVLCKKB7.js +0 -137
- package/dist/editor-chat-RVLCKKB7.js.map +0 -1
- package/dist/heal-YEQYWX2L.js +0 -2
- package/dist/inbox-BIN2S5XN.js +0 -2
- package/dist/memory-extract-KRCHD3OP.js +0 -2
- package/dist/processes-RJ6RDP32.js +0 -2
- package/dist/program-V7NGFB2R.js +0 -2
- package/dist/providers-WVCMIW67.js +0 -2
- package/dist/registry-42HEWCLA.js +0 -2
- package/dist/rotation-memo-GMTZPMNE.js +0 -13
- package/dist/rotation-memo-GMTZPMNE.js.map +0 -1
- package/dist/scheduler-C56ABAVP.js +0 -2
- package/dist/slack-6P7ZJ32Y.js +0 -3
- package/dist/slack-6P7ZJ32Y.js.map +0 -1
- package/dist/store-BAPDZHXE.js +0 -2
- package/dist/task-store-RHISEU6V.js +0 -2
- package/dist/telegram-PIYDRM46.js +0 -3
- package/dist/telegram-PIYDRM46.js.map +0 -1
- package/dist/types-ZRLHHCGB.js +0 -2
- package/dist/web/workflow-editor.global.js +0 -1452
- package/dist/web/workflow-editor.global.js.map +0 -1
- package/dist/whatsapp-PFRDMUMT.js +0 -3
- package/dist/whatsapp-PFRDMUMT.js.map +0 -1
- package/dist/wiki-53W5NLZV.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js.map +0 -1
- /package/dist/{agent-FSE4KRLX.js.map → agent-QGZIAZMY.js.map} +0 -0
- /package/dist/{builtin-TQKMR42Z.js.map → architect-SEPWMWS4.js.map} +0 -0
- /package/dist/{config-ADS54KLC.js.map → builtin-FRKAQMFS.js.map} +0 -0
- /package/dist/{chunk-IKBHHTIT.js.map → chunk-5U35WAZF.js.map} +0 -0
- /package/dist/{chunk-7P5QRX5W.js.map → chunk-BFXONUUN.js.map} +0 -0
- /package/dist/{chunk-DXTIG5YV.js.map → chunk-FDMWOPEL.js.map} +0 -0
- /package/dist/{chunk-NOF4HSGK.js.map → chunk-H5D7ATXS.js.map} +0 -0
- /package/dist/{chunk-4ITQP3XL.js.map → chunk-JP5IEXR7.js.map} +0 -0
- /package/dist/{config-mutator-WTRMBZTO.js.map → client-GGVVLOOF.js.map} +0 -0
- /package/dist/{compaction-BTUJJ3LJ.js.map → compaction-NWEMOSHA.js.map} +0 -0
- /package/dist/{doctor-T6RB4Q5X.js.map → config-7FSZFRTQ.js.map} +0 -0
- /package/dist/{heal-YEQYWX2L.js.map → config-mutator-POCOYYJ4.js.map} +0 -0
- /package/dist/{context-planner-I7ID7XF3.js.map → context-planner-45GEWKGL.js.map} +0 -0
- /package/dist/{inbox-BIN2S5XN.js.map → doctor-DHLBEKA4.js.map} +0 -0
- /package/dist/{memory-extract-KRCHD3OP.js.map → heal-HZ3EQD52.js.map} +0 -0
- /package/dist/{processes-RJ6RDP32.js.map → memory-extract-AENFVVO5.js.map} +0 -0
- /package/dist/{program-V7NGFB2R.js.map → processes-UIC4XXA6.js.map} +0 -0
- /package/dist/{providers-WVCMIW67.js.map → program-WVAVJFND.js.map} +0 -0
- /package/dist/{registry-42HEWCLA.js.map → providers-L27BJ5A6.js.map} +0 -0
- /package/dist/{scheduler-C56ABAVP.js.map → registry-T36ZIAWV.js.map} +0 -0
- /package/dist/{store-BAPDZHXE.js.map → scheduler-GH7TIKYS.js.map} +0 -0
- /package/dist/{task-store-RHISEU6V.js.map → surface-usage-PRL6Z4U3.js.map} +0 -0
- /package/dist/{types-ZRLHHCGB.js.map → wiki-M6YNRFC4.js.map} +0 -0
- /package/dist/{wiki-53W5NLZV.js.map → workspace-setup-TBQAHYHJ.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{f as C}from"./chunk-JXWAGMI2.js";import{Command as S}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{existsSync as y,readFileSync as k,readdirSync as j,statSync as R}from"fs";import{resolve as m}from"path";import{createRequire as N}from"module";async function W(n={}){let i=[];await E(i);let e=P(i);return e&&T(i,e),e&&L(i,e),e&&_(i,e),e&&D(i,e),e&&z(i,e),n.running!==!1&&e&&await q(i,e),{checks:i,summary:A(i)}}var U=new S().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async n=>{let{checks:i,summary:e}=await W({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:i,summary:e},null,2)+`
|
|
2
|
+
`):B(i),process.exit(e.errors>0?1:0)});async function E(n){let i=Number(process.versions.node.split(".")[0]);n.push({severity:i>=20?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:i>=20?void 0:"AgentX needs Node 20 or newer.",fix:i>=20?void 0:"Install a newer Node (nvm install 20 && nvm use 20)"});let e=a=>{try{return h(process.platform==="win32"?"where":"which",[a],{encoding:"utf-8"}).trim().split(`
|
|
3
|
+
`)[0]}catch{return null}},o=e("npm");n.push({severity:o?"ok":"fail",group:"Environment",title:o?"npm on PATH":"npm not found",detail:o||void 0});let s=e("claude");if(s){let a;try{a=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${a||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let a;try{a=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${a||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let l=e("opencode");if(l){let a;try{a=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${a||"installed"}`,detail:l})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{N(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(a){n.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:a?.message??String(a),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function P(n){let i=m(process.cwd(),"agentx.json");if(!y(i))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${i}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(k(i,"utf-8"))}catch(l){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:l.message}),null}try{C(i),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(l){n.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:l.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let o=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="claude-code");o.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use claude-code tier but claude CLI is missing`,detail:o.map(([a])=>a).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([a])=>a).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([a])=>a).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function T(n,i){let e=new Set;if($(i,e),e.size===0){n.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let o=m(process.cwd(),".env"),s={};if(y(o))for(let a of k(o,"utf-8").split(/\r?\n/)){let g=a.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);g&&(s[g[1]]=g[2])}let r=[],l=[];for(let a of e){let g=process.env[a]??s[a];g===void 0?r.push(a):(!g.trim()||/^["']?\s*["']?$/.test(g))&&l.push(a)}r.length===0&&l.length===0?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),l.length>0&&n.push({severity:"warn",group:"Secrets",title:`${l.length} env var(s) set but empty`,detail:l.join(", ")}))}function $(n,i){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))i.add(e[1]);else if(Array.isArray(n))for(let e of n)$(e,i);else if(n&&typeof n=="object")for(let e of Object.values(n))$(e,i)}function L(n,i){let e=[];for(let[o,s]of Object.entries(i.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{R(r).isDirectory()||e.push(`${o}: ${r} (exists but not a directory)`)}catch{e.push(`${o}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
|
+
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function _(n,i){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,o=[];for(let[s,r]of Object.entries(i.agents||{})){if(!r.workspace)continue;let l=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let a of["settings.json","settings.local.json"]){let g=m(l,".claude",a);if(!y(g))continue;let w;try{w=JSON.parse(k(g,"utf-8"))}catch(d){o.push({severity:"fail",agent:s,msg:`${a}: JSON parse error \u2014 ${d.message}`});continue}let b=w.env||{};for(let[d,p]of Object.entries(b)){if(typeof p!="string")continue;let u=p.match(e);u&&o.push({severity:"fail",agent:s,msg:`${a} env.${d} contains unexpanded ${[...new Set(u)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let t=b.PATH;if(typeof t=="string"){let d=t.split(":").filter(Boolean);d.includes("/usr/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&o.push({severity:"warn",agent:s,msg:`${a} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(o.length===0){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(i.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of o)n.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function D(n,i){let e=i.webhooks??[],o=[],s=m(process.cwd(),i.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let t of j(s))t.endsWith(".json")&&!t.startsWith("_")&&!t.endsWith(".disabled.json")&&r.add(t.replace(/\.json$/,""))}catch{}let l=new Set(["github","gitlab"]);for(let t of e){if(!t.enabled||!l.has(t.source))continue;!(t.triggers&&Object.keys(t.triggers).length>0)&&!t.defaultWorkflow&&o.push({severity:"warn",title:`webhook "${t.id}" (${t.source} -> ${t.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let t of e)if(!(!t.enabled||!t.triggers)){for(let[c,d]of Object.entries(t.triggers))r.size>0&&!r.has(d)&&o.push({severity:"fail",title:`webhook "${t.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${i.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});t.defaultWorkflow&&r.size>0&&!r.has(t.defaultWorkflow)&&o.push({severity:"fail",title:`webhook "${t.id}".defaultWorkflow -> "${t.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let t of j(s))if(!(!t.endsWith(".json")||t.startsWith("_")||t.endsWith(".disabled.json")))try{let c=JSON.parse(k(m(s,t),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&o.push({severity:"warn",title:`workflow "${c.id??t}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let a=new Set((i.mesh?.peers??[]).map(t=>t.name));for(let t of e)!t.enabled||!t.node||a.has(t.node)||o.push({severity:"fail",title:`webhook "${t.id}" routes to mesh peer "${t.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let g=new Map;for(let t of e){if(!t.enabled)continue;let c=`${t.source}:${t.agentId}`,d=g.get(c);d?o.push({severity:"warn",title:`webhook entries "${d}" and "${t.id}" both enabled for ${t.source} -> ${t.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):g.set(c,t.id)}let w=new Set(Object.keys(i.agents??{}));for(let t of i.channels?.gitlab?.agentMappings??[])if(t?.agentId){if(t.node){a.has(t.node)||o.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${t.agentId}" routes to mesh peer "${t.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(t.agentId)||o.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${t.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[t,c]of Object.entries(i.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||o.push({severity:"fail",title:`telegram account "${t}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):o.push({severity:"fail",title:`telegram account "${t}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let b=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[t,c]of Object.entries(i.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let u of d){let x=`${u.kind}::${u.label}`;p.has(x)&&o.push({severity:"warn",title:`agents.${t}.integrations: duplicate (${u.kind}, ${u.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(x),b.has(u.kind)||o.push({severity:"warn",title:`agents.${t}.integrations: unknown kind "${u.kind}" on integration "${u.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let I=u.credentials||{};for(let[O,v]of Object.entries(I))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&o.push({severity:"warn",title:`agents.${t}.integrations[${u.kind}/${u.label}].${O} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(o.length===0){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(i.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let t of o)n.push({severity:t.severity,group:"Routing",title:t.title,fix:t.fix})}async function q(n,i){let e=i.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",o={};i.dashboard?.token&&(o.Authorization=`Bearer ${i.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),l=await fetch(e+"/health",{headers:o,signal:s.signal});if(clearTimeout(r),!l.ok){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${l.status}`,detail:e});return}let a=await l.json();n.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${a.agents?.length??0} agents live, uptime ${Math.round((a.uptime??0)/60)}m`,detail:e})}catch{n.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function z(n,i){let e=Object.entries(i.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let o=null;try{o=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
|
+
`)[0]||null}catch{o=null}if(o){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:o})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let l=m(r.workspace,".codegraph","codegraph.db");y(l)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:l}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function A(n){return{errors:n.filter(i=>i.severity==="fail").length,warnings:n.filter(i=>i.severity==="warn").length,ok:n.filter(i=>i.severity==="ok").length}}function B(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let i=new Map;for(let o of n)i.has(o.group)||i.set(o.group,[]),i.get(o.group).push(o);for(let[o,s]of i){console.log(f.bold(" "+o));for(let r of s){let l=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${l} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
|
+
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=A(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{W as a,U as b};
|
|
7
|
+
//# sourceMappingURL=chunk-TRJTTBE2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const nodeMajor = Number(process.versions.node.split(\".\")[0])\n checks.push({\n severity: nodeMajor >= 20 ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: nodeMajor >= 20 ? undefined : \"AgentX needs Node 20 or newer.\",\n fix: nodeMajor >= 20 ? undefined : \"Install a newer Node (nvm install 20 && nvm use 20)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n"],"mappings":"wCAAA,OAAS,WAAAA,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KAChE,OAAS,WAAAC,MAAe,OACxB,OAAS,iBAAAC,MAAqB,SA8B9B,eAAsBC,EACpBC,EAA8B,CAAC,EAC0D,CACzF,IAAMC,EAAkB,CAAC,EACzB,MAAMC,EAAaD,CAAM,EACzB,IAAME,EAAMC,EAAgBH,CAAM,EAClC,OAAIE,GAAKE,EAAmBJ,EAAQE,CAAG,EACnCA,GAAKG,EAAmBL,EAAQE,CAAG,EACnCA,GAAKI,EAA2BN,EAAQE,CAAG,EAC3CA,GAAKK,EAAiBP,EAAQE,CAAG,EACjCA,GAAKM,EAAmBR,EAAQE,CAAG,EACnCH,EAAK,UAAY,IAASG,GAAK,MAAMO,EAAiBT,EAAQE,CAAG,EAC9D,CAAE,OAAAF,EAAQ,QAASU,EAAUV,CAAM,CAAE,CAC9C,CAEO,IAAMW,EAAS,IAAIC,EAAQ,EAC/B,KAAK,QAAQ,EACb,YAAY,4DAA4D,EACxE,OAAO,eAAgB,4BAA4B,EAC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AM,QAAG,EAChDD,EAAE,WAAa,OAASC,EAAM,OAAO,GAAG,EACxCA,EAAM,IAAI,QAAG,EACjB,QAAQ,IAAI,OAAOI,KAAUL,EAAE,OAAO,EAClCA,EAAE,QAAQ,QAAQ,IAAIC,EAAM,IAAI,SAAWD,EAAE,OAAO,QAAQ,MAAO;AAAA,OAAU,CAAC,CAAC,EAC/EA,EAAE,KAAK,QAAQ,IAAIC,EAAM,IAAI,gBAAaD,EAAE,GAAG,CAAC,EAEtD,QAAQ,IAAI,EAGd,IAAMM,EAAI9F,EAAUV,CAAM,EACtBwG,EAAE,OAAS,EACb,QAAQ,IAAIL,EAAM,IAAI,KAAK,KAAKK,EAAE,eAAeA,EAAE,SAAW,EAAI,GAAK,KAAK,GACzEA,EAAE,SAAWL,EAAM,OAAO,KAAKK,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,KAAK,EAAI,IACtF,kBAAkBA,EAAE,SAAW,EAAI,GAAK,gBAAgB,EACjDA,EAAE,SAAW,EACtB,QAAQ,IAAIL,EAAM,OAAO,KAAK,KAAKK,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,MAAM,EAAIL,EAAM,IAAI,2BAA2B,CAAC,EAEhI,QAAQ,IAAIA,EAAM,MAAM,KAAK,wBAAwBK,EAAE,MAAM,CAAC,EAEhE,QAAQ,IAAI,CACd","names":["Command","chalk","execFileSync","existsSync","readFileSync","readdirSync","statSync","resolve","createRequire","runDoctorChecks","opts","checks","runEnvChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runRuntimeChecks","summarize","doctor","Command","summary","printHumanReport","nodeMajor","which","bin","execFileSync","npmPath","claudePath","ver","codexPath","openCodePath","createRequire","e","cfgPath","resolve","existsSync","readFileSync","loadDaemonConfig","claudeCodeAgents","a","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","name","raw","node","into","item","v","abs","statSync","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","readdirSync","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","url","headers","ac","timer","r","body","optedIn","cgPath","def","dbPath","c","chalk","groups","group","items","marker","s"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{marked as l}from"marked";import{markedTerminal as y}from"marked-terminal";import s from"chalk";var g=-1;function k(e){e!==g&&(g=e,l.setOptions({gfm:!0,breaks:!1}),l.use(y({width:e,reflowText:!0,showSectionPrefix:!1,tab:2,heading:s.bold.cyan,firstHeading:s.bold.cyan,code:s.gray,codespan:s.yellow,blockquote:s.gray.italic,link:s.blue.underline,href:s.blue.underline})))}function w(e){let n=e;(n.match(/```/g)||[]).length%2===1&&(n+="\n```");let t=n.replace(/```[\s\S]*?```/g,"");return(t.match(/`/g)||[]).length%2===1&&(n+="`"),(t.match(/\*\*/g)||[]).length%2===1&&(n+="**"),n}function R(e,n=80,t){let o=Math.max(20,Math.min(n,120));try{k(o);let r=t?.balance?w(e):e;return l.parse(r,{async:!1}).replace(/\n+$/,"").replace(/^(\s*)\* /gm,"$1\u2022 ")}catch{return e.trimEnd()}}import{readdirSync as M}from"fs";import{resolve as C,dirname as S,basename as v,join as T}from"path";function $(e){let n=/(^|\s)@([\w./@-]*)$/.exec(e);return n?{token:n[2],start:n.index+n[1].length}:null}function P(e,n){let t=e.toLowerCase();return n.filter(o=>o.toLowerCase().includes(t)).map(o=>`@${o}`)}function L(e,n){try{let t=e.includes("/")?S(e):".",o=e.includes("/")?v(e):e,r=C(n,t);return M(r,{withFileTypes:!0}).filter(i=>!i.name.startsWith(".")&&i.name.toLowerCase().startsWith(o.toLowerCase())).map(i=>{let a=t==="."?i.name:T(t,i.name);return i.isDirectory()?`${a}/`:a})}catch{return[]}}function W(e,n,t,o=6){let r=$(e);if(!r)return null;let i=[...P(r.token,n),...L(r.token,t)].slice(0,o);return i.length?{mention:r,items:i}:null}function u(e,n,t){let o=e.slice(0,n.start),r=t.endsWith("/")?"":" ";return o+t+r}function z(e,n,t,o){if(n.current){let i=n.current;return i.idx=(i.idx+1)%i.items.length,u(e,{token:"",start:i.start},i.items[i.idx])}let r=W(e,t,o);return r?(n.current={start:r.mention.start,items:r.items,idx:0},u(e,r.mention,r.items[0])):null}function H(e,n,t){let o=(e??"").replace(/[\r\n]+$/,"");if(/[\r\n]/.test(o))return{kind:"paste",text:o.replace(/\r\n?/g,`
|
|
2
|
+
`)};if(n||/[\r\n]$/.test(e??"")){let r=t+o;return r.endsWith("\\")?{kind:"continue",buffer:r.slice(0,-1)+`
|
|
3
|
+
`}:{kind:"submit",text:r}}return e?{kind:"type",text:e}:{kind:"none"}}import{useEffect as I,useState as A}from"react";import{Text as c}from"ink";import{jsx as D,jsxs as d}from"react/jsx-runtime";var m=["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"],p=["Thinking","Pondering","Cerebrating","Noodling","Percolating","Ruminating","Conjuring","Synthesizing","Deliberating","Marinating"];function Q({startedAt:e,phase:n,hint:t,indent:o=" "}){let[r,i]=A(0);I(()=>{let b=setInterval(()=>i(x=>x+1),120);return()=>clearInterval(b)},[]);let a=m[r%m.length],f=Math.floor((Date.now()-e)/1e3),h=n==="responding"?"Responding":p[Math.floor(r/16)%p.length];return d(c,{children:[o,D(c,{color:"magenta",children:a})," ",d(c,{color:"magenta",bold:!0,children:[h,"\u2026"]})," ",d(c,{dimColor:!0,children:["(",f,"s",t?` \xB7 ${t}`:"",")"]})]})}function Y(e,n){let t=(n||"").toLowerCase();switch(e){case"claude-code":return{id:"claude",label:"claude",command:"claude",color:"yellow",glyph:"\u2726"};case"codex-cli":return{id:"codex",label:"codex",command:"codex",color:"green",glyph:"\u2733"};case"opencode":return{id:"opencode",label:"opencode",command:"opencode",color:"cyan",glyph:"\u25C6"};case"sdk":return{id:"anthropic",label:"anthropic",command:"@anthropic-ai/sdk",color:"yellow",glyph:"\u2726"};case"orchestrator":return t.includes("deepseek")?{id:"deepseek",label:"deepseek",command:"deepseek",color:"blue",glyph:"\u25C6"}:t.includes("gpt")||t.includes("o1")||t.includes("o3")||t.includes("openai")?{id:"openai",label:"openai",command:"openai",color:"cyan",glyph:"\u25C6"}:t.includes("gemini")?{id:"gemini",label:"gemini",command:"gemini",color:"magenta",glyph:"\u25C6"}:t.includes("claude")?{id:"claude",label:"claude",command:"anthropic",color:"yellow",glyph:"\u2726"}:{id:"orchestrator",label:"orchestrator",command:e,color:"gray",glyph:"\u25C6"};default:return{id:"unknown",label:e||"agent",command:e||"",color:"gray",glyph:"\u25C6"}}}function Z(e){return e?e.replace(/^(claude|gpt|gemini|deepseek|anthropic)-/i,""):""}export{R as a,W as b,z as c,H as d,Q as e,Y as f,Z as g};
|
|
4
|
+
//# sourceMappingURL=chunk-U2CKL755.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tui/markdown.ts","../src/tui/mention-complete.ts","../src/tui/composer-input.ts","../src/tui/working-status.tsx","../src/tui/provider.ts"],"sourcesContent":["import { marked } from \"marked\"\nimport { markedTerminal } from \"marked-terminal\"\nimport chalk from \"chalk\"\n\n// Render an agent's markdown reply to ANSI for the terminal — bold/italic,\n// headings, lists, blockquotes, and syntax-highlighted fenced code blocks\n// (marked-terminal delegates code highlighting to cli-highlight). Kept as a\n// pure string→string function so it works in both the plain REPL and inside\n// an Ink <Text>. Falls back to the raw markdown on any parser error so a\n// malformed reply is never swallowed.\n\nlet configuredWidth = -1\n\n/** (Re)configure the marked instance for a given wrap width. marked is a\n * singleton, so we only re-apply the extension when the width changes. */\nfunction ensureConfigured(width: number): void {\n if (width === configuredWidth) return\n configuredWidth = width\n marked.setOptions({ gfm: true, breaks: false })\n marked.use(\n markedTerminal({\n width,\n reflowText: true,\n // Don't prepend literal \"## \" to headings — render the text styled only.\n showSectionPrefix: false,\n // Shallower indent for lists/code so replies read as chat, not a man page.\n tab: 2,\n heading: chalk.bold.cyan,\n firstHeading: chalk.bold.cyan,\n code: chalk.gray,\n codespan: chalk.yellow,\n blockquote: chalk.gray.italic,\n link: chalk.blue.underline,\n href: chalk.blue.underline,\n }) as any,\n )\n}\n\n/**\n * Auto-close markdown markers left open by a mid-stream partial reply, so a\n * half-written `**bold` or ```` ```code ```` renders styled immediately\n * instead of flashing raw syntax while the closing marker is still arriving.\n * Conservative: only balances unterminated code fences, inline code, and\n * bold — the markers that actually cause visible flashes.\n */\nexport function balanceMarkdown(md: string): string {\n let out = md\n // Unterminated fenced code block → close it.\n if (((out.match(/```/g) || []).length) % 2 === 1) out += \"\\n```\"\n // After fences are balanced, count inline markers outside code blocks.\n const bare = out.replace(/```[\\s\\S]*?```/g, \"\")\n if (((bare.match(/`/g) || []).length) % 2 === 1) out += \"`\"\n if (((bare.match(/\\*\\*/g) || []).length) % 2 === 1) out += \"**\"\n return out\n}\n\n/** Render markdown → ANSI string, wrapped to `width` columns. When `balance`\n * is set (live streaming), open markers are auto-closed first (see above). */\nexport function renderMarkdown(md: string, width = 80, opts?: { balance?: boolean }): string {\n const w = Math.max(20, Math.min(width, 120))\n try {\n ensureConfigured(w)\n const src = opts?.balance ? balanceMarkdown(md) : md\n const out = marked.parse(src, { async: false }) as string\n // marked-terminal hardcodes \"* \" list bullets — swap for a cleaner \"•\".\n return out.replace(/\\n+$/, \"\").replace(/^(\\s*)\\* /gm, \"$1• \")\n } catch {\n return md.trimEnd()\n }\n}\n","import { readdirSync } from \"fs\"\nimport { resolve, dirname, basename, join } from \"path\"\n\n// `@`-mention autocomplete for the chat composer: `@agent` completes to a\n// registered agent id, `@path/frag` completes to files/dirs under cwd. The\n// parse + agent match are pure (unit-tested); file match touches the fs.\n\nexport interface Mention {\n /** The text after `@` being typed (may be empty). */\n token: string\n /** Index of the `@` in the input buffer. */\n start: number\n}\n\n/** The trailing `@mention` being typed at the end of the buffer, or null.\n * Only fires at a word boundary so mid-word emails/handles don't trigger. */\nexport function parseMention(input: string): Mention | null {\n const m = /(^|\\s)@([\\w./@-]*)$/.exec(input)\n if (!m) return null\n return { token: m[2], start: m.index + m[1].length }\n}\n\n/** Agent ids containing `token`, as `@id`. */\nexport function matchAgents(token: string, agentIds: string[]): string[] {\n const t = token.toLowerCase()\n return agentIds.filter((id) => id.toLowerCase().includes(t)).map((id) => `@${id}`)\n}\n\n/** Files/dirs under cwd whose name starts with the token's basename.\n * Directories get a trailing slash so completion can continue into them. */\nexport function matchFiles(token: string, cwd: string): string[] {\n try {\n const dir = token.includes(\"/\") ? dirname(token) : \".\"\n const base = token.includes(\"/\") ? basename(token) : token\n const abs = resolve(cwd, dir)\n return readdirSync(abs, { withFileTypes: true })\n .filter((e) => !e.name.startsWith(\".\") && e.name.toLowerCase().startsWith(base.toLowerCase()))\n .map((e) => {\n const rel = dir === \".\" ? e.name : join(dir, e.name)\n return e.isDirectory() ? `${rel}/` : rel\n })\n } catch {\n return []\n }\n}\n\nexport interface MentionSuggestions {\n mention: Mention\n items: string[]\n}\n\n/** Combined agent + file suggestions for the trailing mention, capped. */\nexport function mentionSuggestions(input: string, agentIds: string[], cwd: string, limit = 6): MentionSuggestions | null {\n const mention = parseMention(input)\n if (!mention) return null\n const items = [...matchAgents(mention.token, agentIds), ...matchFiles(mention.token, cwd)].slice(0, limit)\n return items.length ? { mention, items } : null\n}\n\n/** Replace the mention token with a completion. Agents and files get a\n * trailing space; a directory (ends with `/`) stays open to keep typing. */\nexport function applyMention(input: string, mention: Mention, item: string): string {\n const head = input.slice(0, mention.start)\n const trailing = item.endsWith(\"/\") ? \"\" : \" \"\n return head + item + trailing\n}\n\n/** Frozen suggestion list for Tab-cycling: the `@` position + the items as\n * captured on the first Tab, so subsequent Tabs cycle without the (now\n * completed) buffer re-deriving a different list. */\nexport interface MentionCycle {\n start: number\n items: string[]\n idx: number\n}\n\n/**\n * Tab handler: on the first Tab, freeze the current suggestions and apply the\n * top one; on subsequent Tabs, cycle to the next and re-apply at the frozen\n * `@` position. Returns the new buffer, or null when there's nothing to\n * complete. Callers reset `cycleRef.current` to null on any non-Tab edit.\n */\nexport function advanceMention(\n input: string,\n cycleRef: { current: MentionCycle | null },\n agentIds: string[],\n cwd: string,\n): string | null {\n if (cycleRef.current) {\n const c = cycleRef.current\n c.idx = (c.idx + 1) % c.items.length\n return applyMention(input, { token: \"\", start: c.start }, c.items[c.idx])\n }\n const s = mentionSuggestions(input, agentIds, cwd)\n if (!s) return null\n cycleRef.current = { start: s.mention.start, items: s.items, idx: 0 }\n return applyMention(input, s.mention, s.items[0])\n}\n","// Classify a composer keystroke/paste chunk into an action. Ink calls the\n// input handler once per stdin data event with the whole chunk, so a\n// multi-line paste arrives intact (internal newlines, not a discrete Enter)\n// while a real Enter arrives as an empty chunk with key.return set. Kept pure\n// so both composers (standalone ChatApp + tui pane) share it and it's\n// unit-testable without a pty.\n\nexport type ComposerAction =\n | { kind: \"paste\"; text: string } // append (multi-line paste; newlines preserved)\n | { kind: \"type\"; text: string } // append typed characters\n | { kind: \"continue\"; buffer: string } // trailing \"\\\" → newline, don't submit\n | { kind: \"submit\"; text: string } // Enter (or single-line text+newline)\n | { kind: \"none\" }\n\nexport function classifyComposerInput(chunk: string, isReturn: boolean, buffer: string): ComposerAction {\n const body = (chunk ?? \"\").replace(/[\\r\\n]+$/, \"\")\n // Internal newline in a single chunk ⇒ multi-line paste: keep it whole.\n if (/[\\r\\n]/.test(body)) {\n return { kind: \"paste\", text: body.replace(/\\r\\n?/g, \"\\n\") }\n }\n // A real Enter (empty chunk + key.return) or a single-line \"text\\n\" chunk.\n if (isReturn || /[\\r\\n]$/.test(chunk ?? \"\")) {\n const combined = buffer + body\n if (combined.endsWith(\"\\\\\")) return { kind: \"continue\", buffer: combined.slice(0, -1) + \"\\n\" }\n return { kind: \"submit\", text: combined }\n }\n if (chunk) return { kind: \"type\", text: chunk }\n return { kind: \"none\" }\n}\n","import React, { useEffect, useState } from \"react\"\nimport { Text } from \"ink\"\n\n// Claude-Code-style animated working indicator: a pulsing glyph, a rotating\n// gerund while the model is thinking, a live elapsed counter, and (in the\n// standalone REPL) a real \"esc to interrupt\" hint. Self-contained: its own\n// interval drives the frame, so mounting it is all a caller needs.\n\nconst PULSE = [\"✶\", \"✸\", \"✹\", \"✺\", \"✹\", \"✷\"]\nconst GERUNDS = [\n \"Thinking\", \"Pondering\", \"Cerebrating\", \"Noodling\", \"Percolating\",\n \"Ruminating\", \"Conjuring\", \"Synthesizing\", \"Deliberating\", \"Marinating\",\n]\n\nexport function WorkingStatus({\n startedAt,\n phase,\n hint,\n indent = \" \",\n}: {\n startedAt: number\n phase: \"thinking\" | \"responding\"\n /** Trailing hint, e.g. \"esc to interrupt\". Omit in constrained panes. */\n hint?: string\n indent?: string\n}) {\n const [frame, setFrame] = useState(0)\n useEffect(() => {\n const t = setInterval(() => setFrame((f) => f + 1), 120)\n return () => clearInterval(t)\n }, [])\n const glyph = PULSE[frame % PULSE.length]\n const secs = Math.floor((Date.now() - startedAt) / 1000)\n const word = phase === \"responding\" ? \"Responding\" : GERUNDS[Math.floor(frame / 16) % GERUNDS.length]\n return (\n <Text>\n {indent}<Text color=\"magenta\">{glyph}</Text> <Text color=\"magenta\" bold>{word}…</Text>{\" \"}\n <Text dimColor>({secs}s{hint ? ` · ${hint}` : \"\"})</Text>\n </Text>\n )\n}\n","// Map an agent's tier (+ model) to the underlying provider/command that\n// actually runs it, so the UI reflects reality — agentx is provider-agnostic,\n// not Claude-only. The `tier` decides the spawn path; `model` disambiguates\n// the orchestrator tier's backend.\n\nexport interface ProviderInfo {\n id: \"claude\" | \"codex\" | \"opencode\" | \"anthropic\" | \"deepseek\" | \"openai\" | \"gemini\" | \"orchestrator\" | \"unknown\"\n /** Short label shown in the UI, e.g. \"claude\". */\n label: string\n /** The underlying command/SDK, e.g. \"claude\", \"codex\", \"@anthropic-ai/sdk\". */\n command: string\n /** Badge accent color (per provider — distinct from the agentx accent). */\n color: string\n /** A small mark for the badge. */\n glyph: string\n}\n\nexport function resolveProvider(tier: string, model?: string): ProviderInfo {\n const m = (model || \"\").toLowerCase()\n switch (tier) {\n case \"claude-code\":\n return { id: \"claude\", label: \"claude\", command: \"claude\", color: \"yellow\", glyph: \"✦\" }\n case \"codex-cli\":\n return { id: \"codex\", label: \"codex\", command: \"codex\", color: \"green\", glyph: \"✳\" }\n case \"opencode\":\n return { id: \"opencode\", label: \"opencode\", command: \"opencode\", color: \"cyan\", glyph: \"◆\" }\n case \"sdk\":\n return { id: \"anthropic\", label: \"anthropic\", command: \"@anthropic-ai/sdk\", color: \"yellow\", glyph: \"✦\" }\n case \"orchestrator\": {\n if (m.includes(\"deepseek\")) return { id: \"deepseek\", label: \"deepseek\", command: \"deepseek\", color: \"blue\", glyph: \"◆\" }\n if (m.includes(\"gpt\") || m.includes(\"o1\") || m.includes(\"o3\") || m.includes(\"openai\")) return { id: \"openai\", label: \"openai\", command: \"openai\", color: \"cyan\", glyph: \"◆\" }\n if (m.includes(\"gemini\")) return { id: \"gemini\", label: \"gemini\", command: \"gemini\", color: \"magenta\", glyph: \"◆\" }\n if (m.includes(\"claude\")) return { id: \"claude\", label: \"claude\", command: \"anthropic\", color: \"yellow\", glyph: \"✦\" }\n return { id: \"orchestrator\", label: \"orchestrator\", command: tier, color: \"gray\", glyph: \"◆\" }\n }\n default:\n return { id: \"unknown\", label: tier || \"agent\", command: tier || \"\", color: \"gray\", glyph: \"◆\" }\n }\n}\n\n/** Strip a provider prefix from a model id for compact display\n * (claude-opus-4-8 → opus-4-8, gpt-5-codex → 5-codex). */\nexport function shortModel(model?: string): string {\n if (!model) return \"\"\n return model.replace(/^(claude|gpt|gemini|deepseek|anthropic)-/i, \"\")\n}\n"],"mappings":"AAAA,OAAS,UAAAA,MAAc,SACvB,OAAS,kBAAAC,MAAsB,kBAC/B,OAAOC,MAAW,QASlB,IAAIC,EAAkB,GAItB,SAASC,EAAiBC,EAAqB,CACzCA,IAAUF,IACdA,EAAkBE,EAClBL,EAA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AO,QAAI,EAC1G,IAAK,eACH,OAAIE,EAAE,SAAS,UAAU,EAAU,CAAE,GAAI,WAAY,MAAO,WAAY,QAAS,WAAY,MAAO,OAAQ,MAAO,QAAI,EACnHA,EAAE,SAAS,KAAK,GAAKA,EAAE,SAAS,IAAI,GAAKA,EAAE,SAAS,IAAI,GAAKA,EAAE,SAAS,QAAQ,EAAU,CAAE,GAAI,SAAU,MAAO,SAAU,QAAS,SAAU,MAAO,OAAQ,MAAO,QAAI,EACxKA,EAAE,SAAS,QAAQ,EAAU,CAAE,GAAI,SAAU,MAAO,SAAU,QAAS,SAAU,MAAO,UAAW,MAAO,QAAI,EAC9GA,EAAE,SAAS,QAAQ,EAAU,CAAE,GAAI,SAAU,MAAO,SAAU,QAAS,YAAa,MAAO,SAAU,MAAO,QAAI,EAC7G,CAAE,GAAI,eAAgB,MAAO,eAAgB,QAASF,EAAM,MAAO,OAAQ,MAAO,QAAI,EAE/F,QACE,MAAO,CAAE,GAAI,UAAW,MAAOA,GAAQ,QAAS,QAASA,GAAQ,GAAI,MAAO,OAAQ,MAAO,QAAI,CACnG,CACF,CAIO,SAASG,EAAWF,EAAwB,CACjD,OAAKA,EACEA,EAAM,QAAQ,4CAA6C,EAAE,EADjD,EAErB","names":["marked","markedTerminal","chalk","configuredWidth","ensureConfigured","width","balanceMarkdown","md","out","bare","renderMarkdown","opts","w","src","readdirSync","resolve","dirname","basename","join","parseMention","input","m","matchAgents","token","agentIds","id","matchFiles","cwd","dir","base","abs","e","rel","mentionSuggestions","limit","mention","items","applyMention","item","head","trailing","advanceMention","cycleRef","c","s","classifyComposerInput","chunk","isReturn","buffer","body","combined","useEffect","useState","Text","jsx","jsxs","PULSE","GERUNDS","WorkingStatus","startedAt","phase","hint","indent","frame","setFrame","t","f","glyph","secs","word","resolveProvider","tier","model","m","shortModel"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as o}from"./chunk-M4AMWP3H.js";import{existsSync as s}from"fs";import{resolve as a}from"path";function u(){return!!(process.env.VITEST||process.env.NODE_ENV==="test"||process.env.AGENTX_NO_TELEMETRY)}function c(){let n=process.cwd();for(let t=0;t<5;t++){if(s(a(n,".agentx"))||s(a(n,"agentx.json")))return n;let e=a(n,"..");if(e===n)break;n=e}return null}function d(n=new Date){return n.toISOString().slice(0,10)}function m(n,t,e=new Date){try{if(!t||u()||!c())return;let r=o({quiet:!0});if(!r)return;r.prepare(`INSERT INTO surface_usage (kind, name, day, count, last_at)
|
|
2
|
+
VALUES (?, ?, ?, 1, ?)
|
|
3
|
+
ON CONFLICT(kind, name, day)
|
|
4
|
+
DO UPDATE SET count = count + 1, last_at = excluded.last_at`).run(n,t,d(e),e.toISOString())}catch{}}function g(n={}){try{let t=o({quiet:!0});if(!t)return[];let e=new Date(Date.now()-(n.sinceDays??30)*864e5).toISOString().slice(0,10),r=["day >= ?"],i=[e];return n.kind&&(r.push("kind = ?"),i.push(n.kind)),t.prepare(`SELECT kind, name, SUM(count) AS count, COUNT(DISTINCT day) AS days, MAX(last_at) AS last_at
|
|
5
|
+
FROM surface_usage
|
|
6
|
+
WHERE ${r.join(" AND ")}
|
|
7
|
+
GROUP BY kind, name
|
|
8
|
+
ORDER BY count DESC`).all(...i)}catch{return[]}}function E(n){let t=[],e=n;for(;e&&typeof e.name=="function";){let r=e.name();e.parent&&t.unshift(r),e=e.parent}return t.join(" ")}var f=new Set(["guard check","completion","serve"]);function T(n){return!!n&&!f.has(n)}export{m as a,g as b,E as c,T as d};
|
|
9
|
+
//# sourceMappingURL=chunk-UCQ2N3KO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/observability/surface-usage.ts"],"sourcesContent":["import { existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { openDb } from \"@/storage/sqlite\"\n\n// --- Which operator surfaces actually get used ---\n//\n// `task_history` answers \"which agents ran\". It says nothing about which of\n// the ~46 CLI commands or 16 dashboard pages anyone ever opens — and those are\n// the two biggest surfaces by count, so they are exactly what the\n// surface-reduction work needs evidence for.\n//\n// See docs/architecture/surface-reduction.md for the bar a surface has to\n// clear to survive. This module is the missing measurement.\n//\n// Three rules, all of them about being unobtrusive:\n//\n// 1. Names only. `agentx guard log --limit 5` records \"guard log\". A page\n// view records \"/live\". Never arguments, never query strings, never\n// payloads. This counts which door was opened, not what went through it.\n// 2. Never create state. If there is no `.agentx` here, we are being run\n// from someone's home directory or a random repo — recording would\n// litter a stray database. Do nothing instead.\n// 3. Never throw, never block. A telemetry bug must not break the CLI or a\n// dashboard request. Every failure is swallowed.\n\n/**\n * True while a test runner is driving us.\n *\n * Three suites (trace-cli, process-cli, intent-ledger-cli) shell out to the\n * real CLI, so a full `pnpm test` recorded dozens of invocations of exactly\n * the commands that happen to have CLI tests — `trace list` showed 72 uses\n * against a human total of zero. That is worse than no data: it inverts the\n * ranking, making well-tested commands look popular and untested ones look\n * dead, which is precisely backwards for deciding what to remove.\n */\nfunction underTest(): boolean {\n return Boolean(process.env.VITEST || process.env.NODE_ENV === \"test\" || process.env.AGENTX_NO_TELEMETRY)\n}\n\n/** Where the install lives, or null when we're not inside one. Never creates\n * anything — the check IS the guard against writing stray databases. */\nfunction installRoot(): string | null {\n let dir = process.cwd()\n for (let i = 0; i < 5; i++) {\n if (existsSync(resolve(dir, \".agentx\")) || existsSync(resolve(dir, \"agentx.json\"))) return dir\n const parent = resolve(dir, \"..\")\n if (parent === dir) break\n dir = parent\n }\n return null\n}\n\nfunction today(now = new Date()): string {\n return now.toISOString().slice(0, 10)\n}\n\nexport type SurfaceKind = \"cli\" | \"page\"\n\n/**\n * Record one use of a surface. Silent no-op when we're outside an install,\n * when SQLite is unavailable, or on any error.\n */\nexport function recordSurfaceUse(kind: SurfaceKind, name: string, now = new Date()): void {\n try {\n if (!name) return\n if (underTest()) return\n if (!installRoot()) return\n const db = openDb({ quiet: true })\n if (!db) return\n db.prepare(\n `INSERT INTO surface_usage (kind, name, day, count, last_at)\n VALUES (?, ?, ?, 1, ?)\n ON CONFLICT(kind, name, day)\n DO UPDATE SET count = count + 1, last_at = excluded.last_at`,\n ).run(kind, name, today(now), now.toISOString())\n } catch {\n /* telemetry must never break the thing it measures */\n }\n}\n\nexport interface SurfaceRow {\n kind: string\n name: string\n count: number\n days: number\n last_at: string | null\n}\n\n/** Usage totals over a window, busiest first. Powers `agentx usage surfaces`. */\nexport function listSurfaceUse(opts: { kind?: SurfaceKind; sinceDays?: number } = {}): SurfaceRow[] {\n try {\n const db = openDb({ quiet: true })\n if (!db) return []\n const since = new Date(Date.now() - (opts.sinceDays ?? 30) * 86_400_000)\n .toISOString()\n .slice(0, 10)\n const where = [\"day >= ?\"]\n const params: unknown[] = [since]\n if (opts.kind) {\n where.push(\"kind = ?\")\n params.push(opts.kind)\n }\n return db\n .prepare(\n `SELECT kind, name, SUM(count) AS count, COUNT(DISTINCT day) AS days, MAX(last_at) AS last_at\n FROM surface_usage\n WHERE ${where.join(\" AND \")}\n GROUP BY kind, name\n ORDER BY count DESC`,\n )\n .all(...params) as SurfaceRow[]\n } catch {\n return []\n }\n}\n\n/**\n * The command path a commander invocation resolved to — \"guard log\", not\n * \"guard log --limit 5\". Walks up from the deepest matched subcommand so\n * nesting is preserved without ever touching argv.\n */\nexport function commandPath(cmd: { name(): string; parent?: unknown } | null | undefined): string {\n const parts: string[] = []\n let node: any = cmd\n while (node && typeof node.name === \"function\") {\n const n = node.name()\n // The root program is \"agentx\" itself — not a surface worth counting.\n if (node.parent) parts.unshift(n)\n node = node.parent\n }\n return parts.join(\" \")\n}\n\n/** Hook entrypoints fire per tool call, not per human decision. Counting them\n * would swamp the table and tell us nothing about operator behaviour. */\nconst NOT_A_SURFACE = new Set([\"guard check\", \"completion\", \"serve\"])\n\nexport function shouldRecordCommand(path: string): boolean {\n return Boolean(path) && !NOT_A_SURFACE.has(path)\n}\n"],"mappings":"wCAAA,OAAS,cAAAA,MAAkB,KAC3B,OAAS,WAAAC,MAAe,OAkCxB,SAASC,GAAqB,CAC5B,MAAO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AG7B,EACC,IAAI,GAAGC,CAAM,CAClB,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAOO,SAASC,EAAYC,EAAsE,CAChG,IAAMC,EAAkB,CAAC,EACrBC,EAAYF,EAChB,KAAOE,GAAQ,OAAOA,EAAK,MAAS,YAAY,CAC9C,IAAMC,EAAID,EAAK,KAAK,EAEhBA,EAAK,QAAQD,EAAM,QAAQE,CAAC,EAChCD,EAAOA,EAAK,OAEd,OAAOD,EAAM,KAAK,GAAG,CACvB,CAIA,IAAMG,EAAgB,IAAI,IAAI,CAAC,cAAe,aAAc,OAAO,CAAC,EAE7D,SAASC,EAAoBC,EAAuB,CACzD,MAAO,EAAQA,GAAS,CAACF,EAAc,IAAIE,CAAI,CACjD","names":["existsSync","resolve","underTest","installRoot","dir","i","existsSync","resolve","parent","today","now","recordSurfaceUse","kind","name","db","openDb","listSurfaceUse","opts","since","where","params","commandPath","cmd","parts","node","n","NOT_A_SURFACE","shouldRecordCommand","path"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/channels/router-instance.ts"],"sourcesContent":["import type { MessageRouter } from \"./router\"\n\n// --- Singleton accessor for the live MessageRouter ---\n//\n// Mirrors src/agents/registry-instance.ts. The daemon registers its\n// router at boot; tier-3 procedure code (channel.reply built-in\n// action, MCP-exposed channel tools) reads it via getMessageRouter()\n// to send outbound messages without going through HTTP or knowing\n// which adapter implements the channel.\n//\n// Documented seam under the three-tier discipline rule — listed in\n// test/tier-discipline.test.ts:DOCUMENTED_SEAMS. Reusing the router's\n// dedupe + marker + identity-resolution + ledger-recording is exactly\n// why this exists: agents that post via channel.reply get those for\n// free; agents that bypass to raw curl don't, which is the bug the\n// reimplementation is meant to retire.\n\nlet _router: MessageRouter | null = null\n\nexport function getMessageRouter(): MessageRouter | null {\n return _router\n}\n\nexport function setMessageRouter(r: MessageRouter | null): void {\n _router = r\n}\n\n/** Test-only — clean slate between cases. */\nexport function resetMessageRouterForTesting(): void {\n _router = null\n}\n"],"mappings":"AAiBA,IAAIA,EAAgC,KAE7B,SAASC,GAAyC,CACvD,OAAOD,CACT,CAEO,SAASE,EAAiBC,EAA+B,CAC9DH,EAAUG,CACZ","names":["_router","getMessageRouter","setMessageRouter","r"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as s}from"./chunk-
|
|
2
|
+
import{a as s}from"./chunk-KUCCW2VG.js";import"./chunk-G57RZCXM.js";import"./chunk-TRJTTBE2.js";import"./chunk-LNXCJWOU.js";import"./chunk-UCQ2N3KO.js";import"./chunk-P4VWIVKN.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-TMKLHTCG.js";import"./chunk-3WQFCIB6.js";import"./chunk-HA3XI7Z2.js";import"./chunk-Q6YO7LYE.js";import"./chunk-M4AMWP3H.js";import"./chunk-NGSIRE4X.js";import"./chunk-SFQUP3BP.js";import"./chunk-I3SIXTJO.js";import"./chunk-67Q4DCPS.js";import"./chunk-LDHPMJ7M.js";import"./chunk-2WVX3LEC.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-53GCFZPR.js";import"./chunk-FDMWOPEL.js";import"./chunk-JXWAGMI2.js";import"./chunk-ISEBLHWX.js";import"./chunk-HR4JSRZS.js";import"./chunk-VWTBHLMX.js";import"./chunk-BFXONUUN.js";import"./chunk-JTJIPNXY.js";import"./chunk-64P4QHSZ.js";import"./chunk-BFZUG66X.js";import"./chunk-SR3X25TN.js";import"./chunk-53NRX2NA.js";import"./chunk-FDWOECJY.js";import"./chunk-VJUTQAPJ.js";import"./chunk-DJEZ2HVU.js";import"./chunk-DSYKYZMT.js";import"./chunk-5U35WAZF.js";import"./chunk-QOYAX2FT.js";import"./chunk-4YCH6IZV.js";process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function o(){let r=await s();if(process.argv.slice(2).length===0){r.outputHelp();return}r.parse()}o();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";oqCAGA,QAAQ,GAAG,SAAU,IAAM,QAAQ,KAAK,CAAC,CAAC,EAC1C,QAAQ,GAAG,UAAW,IAAM,QAAQ,KAAK,CAAC,CAAC,EAE3C,eAAeA,GAAO,CACpB,IAAMC,EAAU,MAAMC,EAAa,EAGnC,GADa,QAAQ,KAAK,MAAM,CAAC,EACxB,SAAW,EAAG,CACrBD,EAAQ,WAAW,EACnB,OAGFA,EAAQ,MAAM,CAChB,CAEAD,EAAK","names":["main","program","buildProgram"]}
|
|
@@ -17,12 +17,12 @@ Format as a structured summary:
|
|
|
17
17
|
Keep it under 500 words. Prioritize actionable information over conversational flow.
|
|
18
18
|
Do NOT include greetings, acknowledgments, or meta-commentary about the conversation.`;function U(t){return t.length<v?!1:t.reduce((n,e)=>n+e.content.length,0)>R}async function G(t,o,n){if(t.length<v)return{summary:"",compactedCount:0,keptCount:t.length,memoryFlushed:!1};let e=Math.max(0,t.length-A),r=t.slice(0,e),s=t.slice(e);if(r.length===0)return{summary:"",compactedCount:0,keptCount:s.length,memoryFlushed:!1};let a=f(r);C(o,a);let c=!1;if(n)try{await _(o,r,n),c=!0}catch{}let m=$(r),l=await j(m),{qualityScore:u,lostEntities:i}=P(m,l),p,F=[{role:"agent",content:l,timestamp:new Date().toISOString()}],x=f(F),d=M(o);return d&&(p=y(d,x)),{summary:l,compactedCount:r.length,keptCount:s.length,memoryFlushed:c,qualityScore:u,lostEntities:i.length>0?i:void 0,drift:p&&p.overallScore>.1?p:void 0}}function P(t,o){let n=B(t);if(n.length===0)return{qualityScore:100,lostEntities:[]};let e=o.toLowerCase(),r=[],s=[];for(let c of n)e.includes(c.toLowerCase())?r.push(c):s.push(c);return{qualityScore:Math.round(r.length/n.length*100),lostEntities:s}}function B(t){let o=[],n=new Set,e=i=>{let p=i.toLowerCase().trim();p.length<3||n.has(p)||(n.add(p),o.push(i.trim()))},r=t.match(/https?:\/\/[^\s<>)"]+/g)||[];for(let i of r)e(i.slice(0,80));let s=t.match(/(?:\/[\w.-]+){2,}/g)||[];for(let i of s)e(i);let a=t.match(/[#!]\d{2,}/g)||[];for(let i of a)e(i);let c=t.match(/[\w.-]+@[\w.-]+\.\w+/g)||[];for(let i of c)e(i);let m=t.match(/"([^"]{3,40})"/g)||[];for(let i of m)e(i.slice(1,-1));let l=t.match(/[A-Z][a-z]+(?:\s+[A-Z][a-z]+)+/g)||[];for(let i of l)e(i);let u=t.match(/[a-f0-9]{8,}/gi)||[];for(let i of u.slice(0,5))e(i);return o.slice(0,30)}function J(t,o){if(o.compactedCount===0)return t;let n=t.slice(-o.keptCount);return[{role:"agent",name:"system",content:`[Compacted conversation summary \u2014 ${o.compactedCount} earlier messages]
|
|
19
19
|
|
|
20
|
-
${o.summary}`,timestamp:new Date().toISOString()},...n]}async function _(t,o,n){let e=[],r=[];for(let a of o)a.role==="user"?e.push(`${a.name||"User"}: ${a.content}`):r.push(a.content);if(e.length===0||r.length===0)return;let{extractMemories:s}=await import("./memory-extract-
|
|
20
|
+
${o.summary}`,timestamp:new Date().toISOString()},...n]}async function _(t,o,n){let e=[],r=[];for(let a of o)a.role==="user"?e.push(`${a.name||"User"}: ${a.content}`):r.push(a.content);if(e.length===0||r.length===0)return;let{extractMemories:s}=await import("./memory-extract-AENFVVO5.js");await s(t,e.join(`
|
|
21
21
|
`),r.join(`
|
|
22
22
|
`),{channel:"compaction",chatId:"flush",sender:"compaction"},n)}function $(t){return t.map(o=>{let n=o.timestamp.slice(11,16),e=o.role==="user"?o.name||"User":o.name||"Agent";return`[${n}] ${e}: ${o.content}`}).join(`
|
|
23
23
|
|
|
24
|
-
`)}async function j(t){let n=t.length>2e4?t.slice(-2e4):t;try{let{createProvider:e}=await import("./providers-
|
|
24
|
+
`)}async function j(t){let n=t.length>2e4?t.slice(-2e4):t;try{let{createProvider:e}=await import("./providers-L27BJ5A6.js");return(await e("claude").generate([{role:"system",content:K},{role:"user",content:n}],{model:I,maxTokens:1024})).content.trim()}catch{let s=t.split(`
|
|
25
25
|
`).slice(-20);return`[Summary unavailable \u2014 keeping last ${s.length} lines]
|
|
26
26
|
${s.join(`
|
|
27
27
|
`)}`}}export{J as applyCompaction,G as compactSession,U as needsCompaction};
|
|
28
|
-
//# sourceMappingURL=compaction-
|
|
28
|
+
//# sourceMappingURL=compaction-NWEMOSHA.js.map
|
|
@@ -11,7 +11,7 @@ Rules:
|
|
|
11
11
|
|
|
12
12
|
Be conservative \u2014 unneeded context costs tokens. When in doubt, exclude.`;async function N(e){let s=Date.now(),o=e.timeoutMs??8e3,r=I(e.sessions,e.agentId,e.channel,e.chatId,4),t=[`Agent: ${e.agentId}`,`Channel: ${e.channel}`,r?`Recent conversation:
|
|
13
13
|
${r}`:"Recent conversation: (none \u2014 first message)","",`Current message: ${e.message.slice(0,1500)}`].join(`
|
|
14
|
-
`),n;try{let{createProvider:l}=await import("./providers-
|
|
14
|
+
`),n;try{let{createProvider:l}=await import("./providers-L27BJ5A6.js"),y=l("claude"),f=new AbortController,p=setTimeout(()=>f.abort(),o);try{let b=await y.generate([{role:"system",content:x},{role:"user",content:t}],{model:S,maxTokens:256});n=w(b.content)}finally{clearTimeout(p)}}catch(l){return process.env.AGENTX_PLANNER_DEBUG&&console.error(`[planner] error: ${l?.message??l}`),null}if(!n||typeof n!="object")return null;let m=M(n.recentTurns,0,6,3),a=!!n.memory?.include,c=typeof n.memory?.query=="string"?n.memory.query:"",i=!!n.crossChat,u=typeof n.reasoning=="string"?n.reasoning:void 0,d=C(e.sessions,e.agentId,e.channel,e.chatId,m),g="";if(a&&c)try{let l=e.memoryStore.findRelevant(c,e.agentId,5);g=e.memoryStore.buildContext(l)}catch{}let h="";return i&&(h=e.sessions.getCrossSessionSummary(e.agentId,e.channel,e.chatId,"")),{sessionHistory:d,memoryContext:g,crossChatContext:h,debug:{recentTurns:m,memoryIncluded:a,memoryQuery:c||void 0,crossChatIncluded:i,reasoning:u,planLatencyMs:Date.now()-s}}}function C(e,s,o,r,t){if(t<=0)return"";let n=e.getSession(s,o,r);if(n.messages.length===0)return"";let m=Math.min(n.messages.length,t*2),a=n.messages.slice(-m),c=[`[Recent exchange \u2014 last ${a.length} messages]`];for(let i of a){let u=i.name||(i.role==="user"?"User":"Agent");c.push(`${u}: ${i.content}`)}return c.push("[End recent exchange \u2014 respond to the latest message above]"),c.push(""),c.join(`
|
|
15
15
|
`)}function I(e,s,o,r,t){let n=e.getSession(s,o,r);return n.messages.length===0?"":n.messages.slice(-t).map(a=>{let c=a.name||(a.role==="user"?"User":"Agent"),i=a.content.length>200?a.content.slice(0,200)+"\u2026":a.content;return` ${c}: ${i}`}).join(`
|
|
16
16
|
`)}function w(e){if(!e)return null;let s=e.trim();try{return JSON.parse(s)}catch{}let o=s.indexOf("{");if(o<0)return null;let r=0;for(let t=o;t<s.length;t++)if(s[t]==="{")r++;else if(s[t]==="}"&&(r--,r===0))try{return JSON.parse(s.slice(o,t+1))}catch{return null}return null}function M(e,s,o,r){let t=typeof e=="number"?Math.floor(e):Number.parseInt(String(e??""),10);return Number.isFinite(t)?Math.min(o,Math.max(s,t)):r}export{N as planContext};
|
|
17
|
-
//# sourceMappingURL=context-planner-
|
|
17
|
+
//# sourceMappingURL=context-planner-45GEWKGL.js.map
|