agentix-cli 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +43 -2
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +6 -1
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +5 -3
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +5 -4
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +27 -5
- package/dist/{App-2LAWZNMG.js → App-QHPZXA42.js} +2 -2
- package/dist/{ChatApp-2KRDHMTV.js → ChatApp-EAHHH365.js} +2 -2
- package/dist/{agent-ZRRIMLTX.js → agent-KBBO7OZS.js} +2 -2
- package/dist/{board-dashboard-XYB7M5BH.js → board-dashboard-74OLMLAD.js} +4 -4
- package/dist/{chunk-UEP7IRBD.js → chunk-33G4TIZT.js} +184 -177
- package/dist/chunk-33G4TIZT.js.map +1 -0
- package/dist/{chunk-5FEQI22L.js → chunk-5H5L75RN.js} +2 -2
- package/dist/chunk-6WGTLDME.js +551 -0
- package/dist/chunk-6WGTLDME.js.map +1 -0
- package/dist/{chunk-G5MFPNGJ.js → chunk-CY24RXE4.js} +2 -2
- package/dist/{chunk-JGJE5Y2J.js → chunk-IUNCX6BG.js} +2 -2
- package/dist/{chunk-4CR463C6.js → chunk-IVAGDL5M.js} +2 -2
- package/dist/{chunk-K6E7WJ7O.js → chunk-JDC35PWM.js} +2 -2
- package/dist/{chunk-JWKIFAXA.js → chunk-MJYE5ADH.js} +2 -2
- package/dist/{chunk-MFVI5FOM.js → chunk-PG7BAZIZ.js} +2 -2
- package/dist/{chunk-W3YGESNK.js → chunk-QKNAGTJK.js} +2 -2
- package/dist/{chunk-2DBGOCCW.js → chunk-QXAUKNMW.js} +2 -2
- package/dist/chunk-SPJWXIAV.js +13 -0
- package/dist/chunk-SPJWXIAV.js.map +1 -0
- package/dist/{chunk-B2XTYYXV.js → chunk-U5P7XGCB.js} +2 -2
- package/dist/{chunk-A4YR3PQY.js → chunk-UJF5JUFJ.js} +2 -2
- package/dist/{chunk-GWQIMAJ7.js → chunk-X6HLI6XB.js} +2 -2
- package/dist/{chunk-6VQKHMEQ.js → chunk-ZMFUBIEQ.js} +5 -5
- package/dist/cli.js +1 -1
- package/dist/client-CAGQYJML.js +2 -0
- package/dist/config-NPLE42XY.js +2 -0
- package/dist/config-mutator-FFTODESU.js +2 -0
- package/dist/doctor-X4KHQFRF.js +2 -0
- package/dist/index.d.ts +110 -0
- package/dist/index.js +1 -1
- package/dist/program-ISXECD4J.js +2 -0
- package/dist/query-XLJ6I34S.js +2 -0
- package/dist/{registry-OB6S66XX.js → registry-3RN7I6YW.js} +2 -2
- package/dist/{request-planner-F5NVL2G7.js → request-planner-JX7M3PTD.js} +2 -2
- package/dist/{review-candidates-IRPKFWL2.js → review-candidates-UTS4RX4U.js} +2 -2
- package/dist/{routing-OSPRKRAY.js → routing-D7APOAP6.js} +2 -2
- package/dist/scheduler-EGR5AJAQ.js +2 -0
- package/dist/{seat-2MHKVMW2.js → seat-UA2ROH3V.js} +2 -2
- package/dist/{select-7LCHJVPK.js → select-WQXHYEPD.js} +2 -2
- package/dist/wiki-RNANPNUX.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-2DMVKLLE.js +0 -13
- package/dist/chunk-2DMVKLLE.js.map +0 -1
- package/dist/chunk-UEP7IRBD.js.map +0 -1
- package/dist/chunk-WZD3OS7T.js +0 -550
- package/dist/chunk-WZD3OS7T.js.map +0 -1
- package/dist/client-IP643GRO.js +0 -2
- package/dist/config-IVDP46ZG.js +0 -2
- package/dist/config-mutator-UCGAV3SP.js +0 -2
- package/dist/doctor-MMT4SREV.js +0 -2
- package/dist/program-PK5R7GIC.js +0 -2
- package/dist/query-RHVR6QUZ.js +0 -2
- package/dist/scheduler-JL6K5HHI.js +0 -2
- package/dist/wiki-MY32MON3.js +0 -2
- /package/dist/{App-2LAWZNMG.js.map → App-QHPZXA42.js.map} +0 -0
- /package/dist/{ChatApp-2KRDHMTV.js.map → ChatApp-EAHHH365.js.map} +0 -0
- /package/dist/{agent-ZRRIMLTX.js.map → agent-KBBO7OZS.js.map} +0 -0
- /package/dist/{board-dashboard-XYB7M5BH.js.map → board-dashboard-74OLMLAD.js.map} +0 -0
- /package/dist/{chunk-5FEQI22L.js.map → chunk-5H5L75RN.js.map} +0 -0
- /package/dist/{chunk-G5MFPNGJ.js.map → chunk-CY24RXE4.js.map} +0 -0
- /package/dist/{chunk-JGJE5Y2J.js.map → chunk-IUNCX6BG.js.map} +0 -0
- /package/dist/{chunk-4CR463C6.js.map → chunk-IVAGDL5M.js.map} +0 -0
- /package/dist/{chunk-K6E7WJ7O.js.map → chunk-JDC35PWM.js.map} +0 -0
- /package/dist/{chunk-JWKIFAXA.js.map → chunk-MJYE5ADH.js.map} +0 -0
- /package/dist/{chunk-MFVI5FOM.js.map → chunk-PG7BAZIZ.js.map} +0 -0
- /package/dist/{chunk-W3YGESNK.js.map → chunk-QKNAGTJK.js.map} +0 -0
- /package/dist/{chunk-2DBGOCCW.js.map → chunk-QXAUKNMW.js.map} +0 -0
- /package/dist/{chunk-B2XTYYXV.js.map → chunk-U5P7XGCB.js.map} +0 -0
- /package/dist/{chunk-A4YR3PQY.js.map → chunk-UJF5JUFJ.js.map} +0 -0
- /package/dist/{chunk-GWQIMAJ7.js.map → chunk-X6HLI6XB.js.map} +0 -0
- /package/dist/{chunk-6VQKHMEQ.js.map → chunk-ZMFUBIEQ.js.map} +0 -0
- /package/dist/{client-IP643GRO.js.map → client-CAGQYJML.js.map} +0 -0
- /package/dist/{config-IVDP46ZG.js.map → config-NPLE42XY.js.map} +0 -0
- /package/dist/{config-mutator-UCGAV3SP.js.map → config-mutator-FFTODESU.js.map} +0 -0
- /package/dist/{doctor-MMT4SREV.js.map → doctor-X4KHQFRF.js.map} +0 -0
- /package/dist/{program-PK5R7GIC.js.map → program-ISXECD4J.js.map} +0 -0
- /package/dist/{query-RHVR6QUZ.js.map → query-XLJ6I34S.js.map} +0 -0
- /package/dist/{registry-OB6S66XX.js.map → registry-3RN7I6YW.js.map} +0 -0
- /package/dist/{request-planner-F5NVL2G7.js.map → request-planner-JX7M3PTD.js.map} +0 -0
- /package/dist/{review-candidates-IRPKFWL2.js.map → review-candidates-UTS4RX4U.js.map} +0 -0
- /package/dist/{routing-OSPRKRAY.js.map → routing-D7APOAP6.js.map} +0 -0
- /package/dist/{scheduler-JL6K5HHI.js.map → scheduler-EGR5AJAQ.js.map} +0 -0
- /package/dist/{seat-2MHKVMW2.js.map → seat-UA2ROH3V.js.map} +0 -0
- /package/dist/{select-7LCHJVPK.js.map → select-WQXHYEPD.js.map} +0 -0
- /package/dist/{wiki-MY32MON3.js.map → wiki-RNANPNUX.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{g as C,j as S}from"./chunk-
|
|
1
|
+
import{g as C,j as S}from"./chunk-SPJWXIAV.js";S();import{Command as R}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 N}from"fs";import{resolve as m}from"path";import{createRequire as W}from"module";async function E(n={}){let i=[];await P(i);let e=T(i);return e&&L(i,e),e&&_(i,e),e&&D(i,e),e&&q(i,e),e&&B(i,e),n.running!==!1&&e&&await z(i,e),{checks:i,summary:A(i)}}var K=new R().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 E({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:i,summary:e},null,2)+`
|
|
2
2
|
`):H(i),process.exit(e.errors>0?1:0)});async function P(n){let i=Number(process.versions.node.split(".")[0]);n.push({severity:i==22?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:i==22?void 0:"AgentX requires Node 22.x.",fix:i==22?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=a=>{try{return h(process.platform==="win32"?"where":"which",[a],{encoding:"utf-8"}).trim().split(`
|
|
3
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{W(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 T(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 L(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 _(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{N(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
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function D(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 q(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 z(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 B(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
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 H(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
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{E as a,K as b};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-CY24RXE4.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as R,b as j,c as O,d as W,e as D}from"./chunk-AJ5RMU7X.js";import{b as C}from"./chunk-2GIDVZ4H.js";import{v,w as Q}from"./chunk-
|
|
1
|
+
import{a as R,b as j,c as O,d as W,e as D}from"./chunk-AJ5RMU7X.js";import{b as C}from"./chunk-2GIDVZ4H.js";import{v,w as Q}from"./chunk-QXAUKNMW.js";import{b as $,c as M}from"./chunk-QOYAX2FT.js";import{readFileSync as T,existsSync as _}from"fs";Q();import{resolve as b}from"path";import{execSync as Y}from"child_process";async function V(n,i,s,e={}){let d=e.selectorModel??"haiku",a=e.synthModel??"sonnet",c=e.maxCandidates??3,l=e.maxHops??2,r=e.maxArticles??8,p=e.timeoutMs??6e4,u=e.log??console.error.bind(console,"[wiki-query]"),h=b(i.baseDir,"_index.md");if(!_(h))return w("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let k=T(h,"utf-8"),t=Date.now(),g=[],m="";try{let o=await B(n,i,s,c);o?(g=o,m=`[wiki-rerank seat] ${o.map(y=>y.title).join(" | ")}`):(m=await N(I(n,k,c),d,p),g=F(m))}catch(o){return u("selector failed:",o?.message),{...w("error",n,`Selector: ${o?.message||"unknown"}`),trace:{selectorMs:Date.now()-t,synthesisMs:0,selectorOutput:m}}}let A=Date.now()-t;if(g.length===0)return{...w("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:A,synthesisMs:0,selectorOutput:m}};let f=E(g,i,s,l,r);if(f.length===0)return{...w("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:g,trace:{selectorMs:A,synthesisMs:0,selectorOutput:m}};let S=Date.now(),x="";try{x=await N(L(n,f),a,p*2)}catch(o){return u("synthesis failed:",o?.message),{...w("error",n,`Synthesis: ${o?.message||"unknown"}`),candidates:g,walked:f.map(y=>({title:y.meta.title,path:y.path,type:y.meta.type,hop:y.hop??0})),trace:{selectorMs:A,synthesisMs:Date.now()-S,selectorOutput:m}}}let P=Date.now()-S;return{answer:x.trim(),citations:f.map(o=>({title:o.meta.title,path:o.path,type:o.meta.type})),candidates:g,walked:f.map(o=>({title:o.meta.title,path:o.path,type:o.meta.type,hop:o.hop??0})),status:"ok",trace:{selectorMs:A,synthesisMs:P,selectorOutput:m}}}function w(n,i,s){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:s}}function E(n,i,s,e,d){let a=new Map;for(let r of i.listArticles(s||""))a.set(r.meta.title.toLowerCase(),r.path);let c=new Map,l=[];for(let r of n)c.has(r.path)||l.push({path:r.path,hop:0});for(;l.length&&c.size<d;){let r=l.shift();if(c.has(r.path)||r.hop>e)continue;let p=s?i.readArticleAs(r.path,s):i.readArticle(r.path);if(p&&(c.set(r.path,{...p,hop:r.hop}),!(r.hop>=e)))for(let u of p.meta.related||[]){let h=a.get(u.toLowerCase());h&&!c.has(h)&&l.push({path:h,hop:r.hop+1})}}return Array.from(c.values())}async function B(n,i,s,e){try{let a=(i.rebuildIndex().articles??[]).filter(t=>t.path&&!t.path.includes("/_versions/"));if(a.length<2)return null;let c=a.map(t=>[t.title,(t.tags??[]).join(" "),(t.related??[]).join(" ")].join(" ")),l=M(n,$(c)).map(t=>t.docIndex);for(let t=0;t<a.length;t++)l.includes(t)||l.push(t);let p=l.slice(0,j).map(t=>({id:`k${t}`,title:a[t].title||a[t].path,tags:a[t].tags,excerpt:[a[t].type?`type: ${a[t].type}`:"",(a[t].related??[]).length?`related: ${(a[t].related??[]).join(", ")}`:""].filter(Boolean).join(" \xB7 ")})),u=await v(R,O({query:n,candidates:p,excerptChars:300}),W(p),{features:{agent:s??"unknown",stage:"catalog-selector"}});if(!u||u.mode!=="active")return null;let k=D(u.answers,p).ranked.slice(0,e).map(t=>a[Number(t.slice(1))]).filter(Boolean).map(t=>({title:t.title,path:t.path}));return k.length>0?k:null}catch{return null}}function I(n,i,s){return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
|
|
2
2
|
|
|
3
3
|
## Question
|
|
4
4
|
|
|
@@ -42,4 +42,4 @@ ${s}
|
|
|
42
42
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
43
43
|
|
|
44
44
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function F(n){let i=n.match(/\[[\s\S]*?\]/);if(!i)return[];try{let s=JSON.parse(i[0]);return Array.isArray(s)?s.filter(e=>e&&typeof e.title=="string"&&typeof e.path=="string").map(e=>({title:e.title,path:e.path})):[]}catch{return[]}}async function N(n,i,s){let{writeFileSync:e,mkdirSync:d,rmSync:a}=await import("fs"),{tmpdir:c}=await import("os"),l=b(c(),`agentx-wiki-query-${process.pid}`);d(l,{recursive:!0});let r=b(l,`prompt-${Date.now()}.txt`);e(r,n);try{let p=`cat '${r}' | claude -p - --output-format json --max-turns 1 --model ${i} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,u=Y(p,{env:C({...process.env}),encoding:"utf-8",timeout:s,maxBuffer:4*1024*1024});try{let h=JSON.parse(u);return String(h.result||h.content||"")}catch{return u}}finally{try{a(r,{force:!0})}catch{}}}export{V as a};
|
|
45
|
-
//# sourceMappingURL=chunk-
|
|
45
|
+
//# sourceMappingURL=chunk-IUNCX6BG.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{g as m,j as b}from"./chunk-
|
|
1
|
+
import{g as m,j as b}from"./chunk-SPJWXIAV.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-IVAGDL5M.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-2SJHSSJS.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-2SJHSSJS.js"),{getGlobalRegistry:i}=await import("./registry-3RN7I6YW.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-JDC35PWM.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{e as m,f as $,j as S}from"./chunk-
|
|
1
|
+
import{e as m,f as $,j as S}from"./chunk-SPJWXIAV.js";S();import{readFileSync as x,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=x(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
|
|
4
4
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{J as a,N as b,j as c,A as d};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-MJYE5ADH.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as P,c as _,d as G}from"./chunk-PNWNVOEZ.js";import{b as ee}from"./chunk-64P4QHSZ.js";import{a as te,b as se,c as re,d as ie,e as ne}from"./chunk-AJ5RMU7X.js";import{v as Z,w as he}from"./chunk-
|
|
1
|
+
import{a as T,b as P,c as _,d as G}from"./chunk-PNWNVOEZ.js";import{b as ee}from"./chunk-64P4QHSZ.js";import{a as te,b as se,c as re,d as ie,e as ne}from"./chunk-AJ5RMU7X.js";import{v as Z,w as he}from"./chunk-QXAUKNMW.js";import{a as Q,b as pe}from"./chunk-AJONZWLT.js";import{c as M,d as L}from"./chunk-QOYAX2FT.js";import{o as X,p as de}from"./chunk-LCIREYTD.js";var A={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},F=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as D,writeFileSync as J,appendFileSync as ge,existsSync as I,mkdirSync as U,renameSync as ue}from"fs";import{resolve as R,dirname as ae}from"path";import{createHash as fe}from"crypto";var H=class{baseDir;log;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),U(this.baseDir,{recursive:!0})}schemaPath(){return R(this.baseDir,"schema.json")}nodesPath(){return R(this.baseDir,"nodes.json")}indexPath(){return R(this.baseDir,"index.json")}classificationsPath(){return R(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!I(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;let t=D(e,"utf-8"),s=T.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{J(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(n){this.log(`could not back up old schema: ${n?.message??n}`)}this.saveSchema(A);let o=this.nodesPath();if(I(o)){let n=o.replace(/\.json$/,".v1.bak.json");try{J(n,D(o,"utf-8")),this.log(`archived v1 nodes.json -> ${n}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=oe();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!I(e)){let r=oe();return this.saveNodes(r),r}let t=D(e,"utf-8"),s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveNodes(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.nodesPath(),t.data)}validateNode(e,t,s){let r=t.levels.find(i=>i.id===e.level);if(!r)throw new Error(`Unknown level: "${e.level}"`);let o=r.axes.filter(i=>!i.optional).filter(i=>!(i.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(i=>i.name).join(", ")}`);for(let i of r.axes){let a=e.axes[i.name];if(a!=null){if(i.type==="enum"&&i.values&&!i.values.includes(a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===a);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let n=t.levels.findIndex(i=>i.id===e.level);if(n===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let i=s.find(c=>c.id===e.parentId);if(!i)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let a=t.levels.findIndex(c=>c.id===i.level);if(a<0||a>=n)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${i.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,s,r){let o=[],n=[],i=new Date().toISOString();for(let a=0;a<e.length;a++){let c=e[a],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){n.push(c);continue}let p=0;for(let m=a-1;m>=0;m--){let w=e[m],N=l.find(k=>k.id===w)||o.find(k=>k.id===w);if(N){p=s.levels.findIndex(k=>k.id===N.level)+1;break}}let g=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let w=s.levels[m];if(w.axes.filter(k=>!k.optional).filter(k=>!(k.name in g)).length===0){d=w.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=a-1;m>=0;m--){let w=e[m],N=l.find(C=>C.id===w)||o.find(C=>C.id===w);if(!N)continue;let k=s.levels.findIndex(C=>C.id===N.level);if(k>=0&&k<f){h=w;break}}let u={id:c,level:d,parentId:h,axes:g,createdAt:i,createdBy:r};this.addNode(u),o.push(u)}return{added:o,skipped:n}}addNode(e){let t=this.loadSchema(),s=this.loadNodes();if(s.nodes.some(r=>r.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...s.nodes,e]),s.nodes.push(e),this.saveNodes(s),e}appendClassification(e){let t=P.safeParse(e);if(!t.success){let o=t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let s=JSON.stringify(t.data)+`
|
|
2
2
|
`,r=this.classificationsPath();return I(r)||U(ae(r),{recursive:!0}),ge(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!I(e))return[];let s=D(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),r=new Map;for(let o of s)try{let n=P.safeParse(JSON.parse(o));if(!n.success)continue;r.set(n.data.msgHash,n.data)}catch{}return Array.from(r.values()).sort((o,n)=>o.ts<n.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(n=>n.msgHash===e);if(!r)return null;let o={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let n=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((r.preview||"")+n).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!I(t))return[];let r=D(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let n=r.length-1;n>=0&&o.length<e;n--)try{let i=P.safeParse(JSON.parse(r[n]));i.success&&o.push(i.data)}catch{}return o}fingerprint(e){let s=[e.text.toLowerCase().replace(/\s+/g," ").trim(),e.channel??"",e.sender??""].join("");return fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){let e=this.indexPath();if(!I(e))return{version:1,entries:{}};let t=D(e,"utf-8"),s=G.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.indexPath(),t.data)}getFingerprint(e){return this.loadIndex().entries[e]}setFingerprint(e,t){let s=this.loadIndex();s.entries[e]={...t,fingerprint:e,updatedAt:new Date().toISOString()},this.saveIndex(s)}updateNodeAxes(e,t){let s=this.loadSchema(),r=this.loadNodes(),o=r.nodes.find(i=>i.id===e);if(!o)throw new Error(`Node not found: ${e}`);let n={...o,axes:t};return this.validateNode(n,s,r.nodes.map(i=>i.id===e?n:i)),r.nodes=r.nodes.map(i=>i.id===e?n:i),this.saveNodes(r),n}deleteNode(e){let t=this.loadNodes(),s=t.nodes.find(o=>o.parentId===e);if(s)throw new Error(`Cannot delete "${e}" \u2014 child node "${s.id}" still points to it`);let r=t.nodes.find(o=>Object.values(o.axes).some(n=>n===e));if(r)throw new Error(`Cannot delete "${e}" \u2014 node "${r.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),s=new Set(this.loadNodes().nodes.map(r=>r.id));for(let r=0;r<e.path.length;r++){let o=e.path[r];if(s.has(o))continue;let n=t.levels[r]?.id;if(!n)break;let i=e.proposedAxes?.[o]??{},a=r===0?null:e.path[r-1];this.addNode({id:o,level:n,parentId:a,axes:i,createdAt:new Date().toISOString(),createdBy:e.agentId}),s.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function B(b,e){U(ae(b),{recursive:!0});let t=`${b}.tmp-${process.pid}`;J(t,JSON.stringify(e,null,2)),ue(t,b)}function oe(){let b=new Date().toISOString(),e=[],t=new Set;for(let s of F)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:b,createdBy:"starter"}),t.add(s.category));for(let s of F)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:b,createdBy:"starter"});return{version:1,nodes:e}}pe();de();import{createHash as me}from"crypto";var q=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=X(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),s=this.store.getFingerprint(t);if(s)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:s.path,proposedAxes:{},leaf:s.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:s.path,pathId:z(s.path),pathLabel:K(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),o=this.store.loadNodes().nodes,n=await this.proposePath(e,r,o).catch(u=>(this.log("LLM proposal failed:",u?.message||u),null));if(!n)return null;let{path:i,proposedAxes:a,confidence:c,leaf:l}=n;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:a,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(o.map(u=>u.id)),g=i.map((u,m)=>p.has(u)?-1:m).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=g.length===0,m=g.length===1&&g[0]===i.length-1;d=u||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,a,r,o,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:z(i),pathLabel:K(i,this.store.loadNodes().nodes),axes:a,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(r,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
@@ -106,4 +106,4 @@ We use GitLab for version control.
|
|
|
106
106
|
There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
107
107
|
|
|
108
108
|
${s}`}walkDir(e,t){if(x(e))for(let s of O(e)){let r=be(e,s);ye(r).isDirectory()?this.walkDir(r,t):t(r)}}};import{resolve as Y}from"path";import{existsSync as ke,readdirSync as Se,mkdirSync as xe}from"fs";var le=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=Y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki-hub]"),s="graph"){this.baseDir=e,this.agentsDir=Y(e,"agents"),this.mode=s,this.log=t,xe(this.agentsDir,{recursive:!0}),this.sharedStore=new E(e,t)}getMode(){return this.mode}getAgentWiki(e){let t=`${e}:${this.mode}`;if(this.agentStores.has(t))return this.agentStores.get(t);let s=Y(this.agentsDir,e,this.mode),r=new E(s,this.log);return this.agentStores.set(t,r),r}getSharedStore(){return this.sharedStore}listAgents(){let e=new Set,t=this.sharedStore.listEntries();for(let s of t)e.add(s.agentId);if(ke(this.agentsDir))for(let s of Se(this.agentsDir))!s.startsWith("_")&&!s.startsWith(".")&&e.add(s);return[...e].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){let t=this.getAgentWiki(e),s=this.getAgentEntries(e),r=new Set,o=t.rebuildIndex();for(let n of o.articles)if(n.sources)for(let i of n.sources)r.add(i);return s.filter(n=>!r.has(n.id))}summary(){return this.listAgents().map(t=>{let s=this.getAgentEntries(t),o=this.getAgentWiki(t).rebuildIndex(),n=this.getUnabsorbedEntries(t);return{agentId:t,totalEntries:s.length,totalArticles:o.articles.length,unabsorbed:n.length,articles:o.articles}})}};export{A as a,H as b,q as c,K as d,E as e,le as f};
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-PG7BAZIZ.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{v as l,w}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{v as l,w}from"./chunk-QXAUKNMW.js";import{a as i,f as p}from"./chunk-F4HZTZHW.js";w();p();var d="task-tier";function u(e){return{task:f(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:i("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function f(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2,m=60*60*1e3;function F(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function M(e){let n=(o,r=null)=>({downgraded:!1,needsFlagship:r,reason:o});if(e.channel==="voice"||e.channel==="desktop"||e.channel==="opencode")return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let o=e.sessionIdleMs??0,r=e.cacheTtlMs??m;if(o<r)return n(`follow-up on a warm cache (idle ${Math.round(o/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"}})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let s=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${s<(e.threshold??h)?"downgrade":"keep"} (${s.toFixed(2)})`,s);let a=e.threshold??h;return s>=a?n(`needs the flagship (${s.toFixed(2)})`,s):{model:e.cheapModel,downgraded:!0,needsFlagship:s,reason:`mechanical task (${s.toFixed(2)} below ${a}) \u2192 ${e.cheapModel}`}}export{F as a,M as b};
|
|
2
|
+
//# sourceMappingURL=chunk-QKNAGTJK.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ne,b as He}from"./chunk-ZTEU5JVQ.js";import{a as Te,b as ft}from"./chunk-AJONZWLT.js";import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-F4HZTZHW.js";import{o as we,p as Ke}from"./chunk-LCIREYTD.js";import{i as We,j as Ze}from"./chunk-
|
|
1
|
+
import{a as ne,b as He}from"./chunk-ZTEU5JVQ.js";import{a as Te,b as ft}from"./chunk-AJONZWLT.js";import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-F4HZTZHW.js";import{o as we,p as Ke}from"./chunk-LCIREYTD.js";import{i as We,j as Ze}from"./chunk-SPJWXIAV.js";import{a as rt,b as ot,c as st,d as it,e as at,f as ct,g as ut,h as lt,i as dt,j as pt,k as mt,l as bt}from"./chunk-BH3GTCZ6.js";import{b as E,c as Ye,d as he}from"./chunk-FIOB3MEX.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function gt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import yt from"better-sqlite3";import{createHash as ht}from"crypto";import{mkdirSync as wt}from"fs";import{dirname as Tt,resolve as Et}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function kt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function xt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&Rt(e),t<2&&At(e),t<3&&St(e)}function St(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function At(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as ne,b as He}from"./chunk-ZTEU5JVQ.js";import{a as Te,b as ft}from"./c
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:g,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function $t(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:B,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:B}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===B),u=a&&a.type==="tool_use"?a.input:null;return{answers:Pe(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Vt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Pe(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Pe(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function zt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Jt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,Pt,qt,Be,Xt,be=E(()=>{"use strict";Ke();Ue();ft();j();Y();N();z();Bt="claude-code",Pt="claude-haiku-4-5-20251001",qt=24e3,Be=2e3,Xt=3e4});import{readFileSync as Gt}from"fs";import{homedir as Yt}from"os";import{join as Kt}from"path";function v(e={}){let t=(e.baseUrl??Ht).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??Zt,s=e.maxChoiceOptions??en,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),on(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:y,dispose:d}=sn(a.abortSignal,a.timeoutMs??e.timeoutMs??Wt);try{let b={"Content-Type":"application/json"},g=rn(e.apiKeyEnv,e.apiKeyFile);g&&(b.Authorization=`Bearer ${g}`);let w=await p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:nn(a.questions)}),signal:y});if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await w.json(),m=F(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function nn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:tn[n.type]};return t}function rn(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Kt(Yt(),t.slice(2)):t;if(!Z.has(n))try{let o=Gt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function on(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function sn(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Ht,Wt,Zt,en,tn,Z,fe=E(()=>{"use strict";j();N();z();Y();Ht="http://127.0.0.1:8000/v1",Wt=3e4,Zt=6e3,en=50;tn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var qe={};Ye(qe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>B,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>gt,agreement:()=>rt,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>lt,askSeat:()=>pn,band:()=>Ie,bootstrapInterval:()=>pt,brier:()=>at,buildDesign:()=>Ne,calibrationReport:()=>mt,choice:()=>tt,compareCalibrators:()=>Lt,confidenceFor:()=>re,configureDecisions:()=>cn,coverageCurve:()=>ut,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>v,decisionsRuntime:()=>ln,describeIssues:()=>U,ece:()=>st,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>ve,fitRecalibrator:()=>P,fitTemperature:()=>dt,getDecisionBackend:()=>D,getSeatMode:()=>Ve,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ct,logit:()=>le,mce:()=>it,measureConsistency:()=>Qt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>et,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>F,recordSeatOutcome:()=>dn,registerBuiltinDecisionBackends:()=>an,registerDecisionBackend:()=>R,reliabilityBins:()=>ot,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>un,score:()=>nt,seatEnvVar:()=>$e,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function an(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>v(t)),R("jev",()=>v({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>v({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var Xe=E(()=>{"use strict";ke();N();j();z();C();Y();V();bt();Me();je();ze();pe();be();fe();C();pe();be();fe()});function cn(e){T={...ye,...T,...e},ee=!0}function un(){T={...ye,seats:{}},ee=!1}function mn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(Ze(),he(We)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=(Xe(),he(qe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function ln(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return bn.includes(t)?t:null}function $e(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Ve(e,t=process.env){mn();let r=ge(t[$e(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function dn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function pn(e,t,r,n={}){let o=Ve(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=fn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return gn(e,o,t,r,i,n,s,a,u),yn(e,i,u),null}}function fn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ge(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function gn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ge(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ge(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function yn(e,t,r){let n=Date.now();n-Je<6e4||(Je=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,bn,Je,ze=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;bn=["off","shadow","active"];Je=0});export{D as a,Ee as b,C as c,I as d,V as e,Lt as f,Me as g,Qt as h,je as i,me as j,Un as k,Ue as l,an as m,Xe as n,cn as o,un as p,ln as q,ge as r,$e as s,Ve as t,dn as u,pn as v,ze as w};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-QXAUKNMW.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{b as m,c as C}from"./chunk-FIOB3MEX.js";import{z as t}from"zod";var T,A,I,$,P,D,L,_,z,h,y=m(()=>{"use strict";T=t.enum(["mon","tue","wed","thu","fri","sat","sun"]),A=t.object({days:t.array(T).default(["mon","tue","wed","thu","fri"]),start:t.string().regex(/^\d{2}:\d{2}$/),end:t.string().regex(/^\d{2}:\d{2}$/),lunch:t.object({start:t.string().regex(/^\d{2}:\d{2}$/),end:t.string().regex(/^\d{2}:\d{2}$/)}).optional()}),I=t.object({title:t.string(),responsibilities:t.array(t.string()).default([]),sopPath:t.string().optional(),kpis:t.array(t.string()).default([])}),$=t.object({role:t.string(),reportsTo:t.string().optional(),schedule:A,utilizationTarget:t.number().min(0).max(1).default(.8)}),P=t.object({channel:t.string(),chatId:t.string(),accountId:t.string().optional()}),D=t.discriminatedUnion("type",[t.object({type:t.literal("backlog"),path:t.string().default(".agentx/backlog.md")}),t.object({type:t.literal("gitlab"),projects:t.array(t.string()).default([])}),t.object({type:t.literal("wiki"),path:t.string(),glob:t.string().default("**/*.md")})]),L=t.object({id:t.string(),pm:t.string().optional(),client:t.string().optional()}),_=t.object({channel:t.string().optional(),chatId:t.string().optional(),username:t.string().optional(),senderId:t.string().optional(),client:t.string(),project:t.string().optional(),displayName:t.string().optional()}),z=t.object({name:t.string().optional(),kind:t.enum(["client","internal","own"]).optional(),respondWithin:t.string().optional(),standing:t.array(t.string()).default([])}),h=t.object({enabled:t.boolean().default(!1),timezone:t.string().default("UTC"),mainChannel:P,workSource:D,roles:t.record(t.string(),I).default({}),orgChart:t.record(t.string(),$).default({}),projects:t.array(L).default([]),contactMap:t.array(_).default([]),clients:t.record(t.string(),z).default({}),workTickMinutes:t.number().int().min(1).max(60).default(15),idleQueueThreshold:t.number().int().min(0).default(0),standup:t.object({enabled:t.boolean().default(!0),plansDir:t.string().default(".agentx/plans"),maxAgentsPerDay:t.number().int().min(1).max(100).default(20),dryRun:t.boolean().default(!1)}).default({})})});import{z as n}from"zod";function be(a,i){let s=new Set(a.labels||[]);if(a.state==="closed"){let r=i.find(l=>l.kind==="closed");if(r)return r.id}for(let r of i)if(r.kind==="scoped-label"&&r.scopedLabel&&s.has(r.scopedLabel))return r.id;for(let r of i)if(r.kind==="label"&&r.mapsToLabel&&s.has(r.mapsToLabel))return r.id;let o=i.find(r=>r.kind==="open-backlog");if(o){let r=o.scopedPrefix+"::";return[...s].some(u=>u.startsWith(r))?null:o.id}return i[0]?.id??null}function he(a,i){let s=[],o=[],r=!1,l=!1;return i.kind==="scoped-label"&&i.scopedLabel?s.push(i.scopedLabel):i.kind==="label"&&i.mapsToLabel?s.push(i.mapsToLabel):i.kind==="closed"&&(r=!0),a&&(a.kind==="scoped-label"&&a.scopedLabel?o.push(a.scopedLabel):a.kind==="label"&&a.mapsToLabel?o.push(a.mapsToLabel):a.kind==="closed"&&i.kind!=="closed"&&(l=!0)),{addLabels:s.length?s:void 0,removeLabels:o.length?o:void 0,closeIssue:r||void 0,reopen:l||void 0}}var E,B,M,R,O,U,x,K,S,k=m(()=>{"use strict";E=n.object({name:n.string(),color:n.string().regex(/^#[0-9a-f]{6}$/i).default("#6366f1"),description:n.string().optional()}),B=n.object({id:n.string().regex(/^[a-z0-9_-]+$/,"column id must be lowercase slug"),title:n.string(),kind:n.enum(["open-backlog","scoped-label","closed","label"]).default("label"),mapsToLabel:n.string().optional(),scopedLabel:n.string().optional(),scopedPrefix:n.string().default("Status"),accent:n.string().optional()}),M=n.object({enabled:n.boolean().default(!0),staleDoingMinutes:n.number().int().min(1).default(45),respectLunchBreak:n.boolean().default(!0),respectSchedule:n.boolean().default(!0),action:n.enum(["badge","notify"]).default("badge")}),R=n.discriminatedUnion("type",[n.object({type:n.literal("gitlab"),projects:n.array(n.string()).min(1)})]),O=[{id:"open",title:"Open",kind:"open-backlog",scopedPrefix:"Status",accent:"#6b7280"},{id:"todo",title:"To Do",kind:"scoped-label",scopedLabel:"Status::To Do",scopedPrefix:"Status",accent:"#fb7a35"},{id:"doing",title:"Doing",kind:"scoped-label",scopedLabel:"Status::Doing",scopedPrefix:"Status",accent:"#22c55e"},{id:"onhold",title:"On Hold",kind:"scoped-label",scopedLabel:"Status::On Hold",scopedPrefix:"Status",accent:"#f59e0b"},{id:"review",title:"Review",kind:"scoped-label",scopedLabel:"Status::Review",scopedPrefix:"Status",accent:"#3b82f6"},{id:"closed",title:"Closed",kind:"closed",scopedPrefix:"Status",accent:"#6b7280"}],U=n.object({id:n.string().regex(/^[a-z0-9_-]+$/,"board id must be lowercase slug"),name:n.string(),source:R,primaryToolLabel:n.string().optional(),labels:n.array(E).default([]),columns:n.array(B).min(1).default(O),timeRangeDays:n.number().int().min(1).max(365).default(30),closedWindowDays:n.number().int().min(1).max(365).default(30),reconciliation:M.default({})}),x=n.array(U).default([]),K=n.object({name:n.string(),url:n.string(),dashboardUrl:n.string().optional(),token:n.string().optional(),dashboardToken:n.string().optional()}),S=n.object({enabled:n.boolean().default(!1),port:n.number().int().default(4202),bind:n.string().default("127.0.0.1"),token:n.string().optional(),daemonUrl:n.string().default("http://localhost:18800"),daemons:n.array(K).default([]),draftAgent:n.string().optional()}).default({})});var ce={};C(ce,{INTEGRATION_KINDS:()=>G,daemonConfigSchema:()=>w,expandEnvVars:()=>g,loadDaemonConfig:()=>de,validateWorkspaces:()=>ue});import{z as e}from"zod";import{readFileSync as j,existsSync as f}from"fs";import{resolve as p}from"path";function N(a){let i=p(a,".env");if(!f(i))return;let s=j(i,"utf-8");for(let o of s.split(`
|
|
2
|
+
`)){let r=o.trim();if(!r||r.startsWith("#"))continue;let l=r.indexOf("=");if(l===-1)continue;let u=r.slice(0,l).trim(),d=r.slice(l+1).trim();process.env[u]||(process.env[u]=d)}}function g(a){if(typeof a=="string")return a.replace(/\$\{(\w+)\}/g,(i,s)=>process.env[s]||"");if(Array.isArray(a))return a.map(g);if(a!==null&&typeof a=="object"){let i={};for(let[s,o]of Object.entries(a))i[s]=g(o);return i}return a}function le(a,i){let s=[],o=new Set;for(let r of a){let l=r.path.join("."),u=/^channels\.telegram\.accounts\.([^.]+)\.token$/.exec(l);if(u&&r.message.toLowerCase().includes("required")){let d=u[1],c=`tg:${d}`;if(o.has(c))continue;o.add(c),s.push(`Hint: Telegram account "${d}" is enabled but has no bot token.
|
|
3
|
+
Either:
|
|
4
|
+
A) Open ${i} and set channels.telegram.accounts.${d}.token to your bot token (or "\${TG_${d.toUpperCase()}_BOT_TOKEN}" + the matching .env entry).
|
|
5
|
+
B) If you don't need Telegram on this instance, remove the entire "telegram" block under "channels" (or set channels.telegram.enabled to false AND drop accounts.${d}).`)}}return s}function de(a){let i=a?[a]:[p(process.cwd(),"agentx.json"),p(process.cwd(),".agentx/config.json")];N(process.cwd());let s,o;for(let d of i)if(f(d)){s=j(d,"utf-8"),o=d;break}if(!s||!o)throw new Error(`No config found. Create agentx.json or .agentx/config.json
|
|
6
|
+
Searched: ${i.join(", ")}`);let r;try{r=JSON.parse(s)}catch(d){throw new Error(`Invalid JSON in ${o}: ${d.message}`)}let l=g(r),u=w.safeParse(l);if(!u.success){let d=u.error.issues.map(b=>` ${b.path.join(".")}: ${b.message}`).join(`
|
|
7
|
+
`),c=le(u.error.issues,o),v=c.length?`
|
|
8
|
+
|
|
9
|
+
${c.join(`
|
|
10
|
+
|
|
11
|
+
`)}`:"";throw new Error(`Config validation failed (${o}):
|
|
12
|
+
${d}${v}`)}return u.data}function ue(a){let i=[];for(let[s,o]of Object.entries(a.agents)){if(!f(o.workspace)){i.push(`Agent "${s}": workspace not found at ${o.workspace}`);continue}if(o.tier==="claude-code"){let u=p(o.workspace,".claude");f(u)||i.push(`Agent "${s}": no .claude/ directory in workspace ${o.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let r=o.provider||"claude",l=a.providers[r];!["claude-code","codex-cli","opencode"].includes(o.tier)&&(!l||!l.apiKey)&&i.push(`Agent "${s}": provider "${r}" has no API key configured. Set providers.${r}.apiKey in config or use a CLI-backed tier ("claude-code", "codex-cli", or "opencode").`)}for(let[s,o]of Object.entries(a.crons))a.agents[o.agent]||i.push(`Cron "${s}": references unknown agent "${o.agent}"`);if(a.channels.telegram.enabled)for(let[s,o]of Object.entries(a.channels.telegram.accounts))a.agents[o.agentBinding]||i.push(`Telegram account "${s}": references unknown agent "${o.agentBinding}"`);return i}var Z,F,W,q,H,J,G,Y,Q,V,X,ee,te,ne,ae,oe,re,ie,se,w,fe=m(()=>{y();k();Z=e.object({apiKey:e.string().optional(),defaultModel:e.string().optional(),baseUrl:e.string().optional(),thinking:e.boolean().optional()}),F=e.object({type:e.literal("stdio").optional(),command:e.string(),args:e.array(e.string()).default([]),env:e.record(e.string(),e.string()).optional()}),W=e.object({type:e.literal("http"),url:e.string().url(),headers:e.record(e.string(),e.string()).optional()}),q=e.union([W,F]),H=e.object({tokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),privateAppTokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),apiKeyEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),refreshTokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),clientIdEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),clientSecretEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),auth:e.literal("keyring").optional(),sessionDir:e.string().optional()}).strict(),J=e.object({kind:e.string().min(1),label:e.string().min(1),credentials:H.default({}),metadata:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()])).default({}),enabled:e.boolean().default(!0)}),G=["telegram-bot","whatsapp","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"],Y=e.object({name:e.string(),workspace:e.string(),tier:e.enum(["claude-code","codex-cli","opencode","sdk","orchestrator"]).default("claude-code"),provider:e.string().optional(),model:e.string().optional(),systemPrompt:e.string().optional(),mentions:e.array(e.string()).default([]),intents:e.array(e.string()).default([]),maxDelegationDepth:e.number().int().min(0).max(50).default(5),mcp:e.record(e.string(),q).optional(),codegraph:e.boolean().default(!1),contextStrategy:e.enum(["layered","planner"]).optional(),contextReferences:e.boolean().default(!1),richMessages:e.boolean().default(!0),maxConcurrent:e.number().default(1),maxExecutionMinutes:e.number().int().min(1).max(240).default(20),permissionMode:e.string().default("default"),billing:e.enum(["subscription","api"]).default("subscription"),toolUseRequired:e.array(e.string()).default([]),gitlabAutoReply:e.boolean().optional(),persistentProcess:e.boolean().default(!1),queueMode:e.enum(["collect","followup","drop"]).default("collect"),heartbeat:e.object({enabled:e.boolean().default(!1),intervalMinutes:e.number().default(30),prompt:e.string().default("Check inbox, pending tasks, and system health. Report anything that needs attention."),channel:e.string().default("heartbeat")}).default({}),access:e.enum(["private","public"]).default("private"),integrations:e.array(J).default([]),voice:e.object({elevenlabsVoiceId:e.string().optional(),gender:e.enum(["female","male","neutral"]).optional(),style:e.string().optional(),intro:e.string().optional(),narrate:e.enum(["off","on","all"]).optional()}).optional()}),Q=e.object({token:e.string(),agentBinding:e.string(),allowFrom:e.array(e.string()).optional(),pollInbound:e.boolean().default(!0)}),V=e.object({telegram:e.object({enabled:e.boolean().default(!1),accounts:e.record(e.string(),Q).default({}),policy:e.object({dm:e.enum(["pair","block"]).default("pair"),group:e.enum(["mention-required","all"]).default("mention-required"),allowFrom:e.array(e.string()).optional()}).default({})}).default({}),whatsapp:e.object({enabled:e.boolean().default(!1),sessionDir:e.string().default(".agentx/whatsapp-sessions"),defaultAgent:e.string().optional(),allowFrom:e.array(e.string()).optional(),routes:e.array(e.object({contact:e.string().optional(),group:e.string().optional(),agent:e.string()})).default([]),ingest:e.object({enabled:e.boolean().default(!1),mode:e.enum(["metadata-only","messages"]).default("metadata-only"),allowContacts:e.array(e.string()).default([]),allowGroups:e.array(e.string()).default([]),denyContacts:e.array(e.string()).default([]),denyGroups:e.array(e.string()).default([]),messageCap:e.number().int().min(1).max(500).default(50),historyDays:e.number().int().min(1).max(365).default(30),contactRefreshDays:e.number().int().min(1).max(90).default(7),throttle:e.object({minMsBetweenCalls:e.number().int().min(100).default(1500),maxCallsPerMinute:e.number().int().min(1).default(20),maxChatsPerSweep:e.number().int().min(1).default(25)}).default({}),retentionDays:e.number().int().min(0).default(0)}).default({})}).default({}),gitlab:e.object({enabled:e.boolean().default(!1),webhookPort:e.number().default(18810),webhookSecret:e.string().optional(),host:e.string().default("https://gitlab.com"),token:e.string().optional(),autoReplyLegacy:e.boolean().default(!0),routes:e.array(e.object({project:e.string(),agent:e.string()})).default([]),agentMappings:e.array(e.object({agentId:e.string(),gitlabUsernames:e.array(e.string()).default([]),keywords:e.array(e.string()).default([]),token:e.string().optional(),node:e.string().optional()})).default([])}).default({}),github:e.object({enabled:e.boolean().default(!1),autoReplyLegacy:e.boolean().default(!0),token:e.string().optional(),tokenFile:e.string().optional(),appId:e.number().optional(),clientId:e.string().optional(),privateKeyFile:e.string().optional(),webhookSecret:e.string().optional(),routes:e.array(e.object({repo:e.string(),agent:e.string()})).default([]),agentMappings:e.array(e.object({agentId:e.string(),githubUsernames:e.array(e.string()).default([]),token:e.string().optional(),tokenFile:e.string().optional(),node:e.string().optional()})).default([])}).default({}),ntfy:e.object({enabled:e.boolean().default(!1),server:e.string().default("https://ntfy.sh"),topic:e.string().optional(),token:e.string().optional(),defaultPriority:e.number().int().min(1).max(5).default(3),defaultTitle:e.string().optional()}).default({}),webrtc:e.object({enabled:e.boolean().default(!1),stunServers:e.array(e.string()).default(["stun:stun.l.google.com:19302"]),turnServers:e.array(e.object({urls:e.string(),username:e.string().optional(),credential:e.string().optional()})).default([]),allowedCallers:e.array(e.string()).default([]),ringNotify:e.array(e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()})).default([]),callUrlBase:e.string().optional(),bot:e.object({enabled:e.boolean().default(!1),defaultAgentId:e.string().optional(),whisperBackend:e.enum(["auto","mlx","openai"]).default("auto"),whisperModel:e.string().optional(),whisperLanguage:e.string().default("auto"),mlxBinary:e.string().optional(),transcriptChannel:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional(),maxCallMinutes:e.number().int().min(1).max(240).default(30)}).default({})}).default({})}),X=e.object({enabled:e.boolean().default(!0),schedule:e.string(),timezone:e.string().default("UTC"),agent:e.string(),prompt:e.string().default(""),command:e.string().optional(),timeout:e.number().default(600),model:e.string().optional(),maxOutputTokens:e.number().int().min(50).max(8e3).optional(),onError:e.union([e.enum(["log","notify","disable"]),e.array(e.enum(["log","notify","disable"]))]).default("log").transform(a=>Array.isArray(a)?a:[a]),notify:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional()}).refine(a=>!!(a.command?.trim()||a.prompt?.trim()),{message:"a cron needs either a prompt (dispatch an agent) or a command (run it directly)"}),ee=e.object({name:e.string(),triggers:e.array(e.object({pattern:e.string(),channel:e.string().optional()})),allowedContacts:e.array(e.string()).optional(),agent:e.string(),prompt:e.string(),schedule:e.string().optional(),timezone:e.string().default("UTC"),notify:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional()}),te=e.object({url:e.string(),name:e.string(),token:e.string().optional()}),ne=e.object({name:e.string(),agent:e.string(),enabled:e.boolean().default(!0)}),ae=e.object({enabled:e.boolean().default(!1),peers:e.array(te).default([]),inboxes:e.array(ne).default([]),discovery:e.enum(["static","mdns"]).default("static"),healthCheck:e.object({interval:e.number().default(60),timeout:e.number().default(10)}).default({})}),oe=e.object({enabled:e.boolean().default(!1),baseDir:e.string().default(".agentx/graph"),draftAgent:e.string().optional(),reviewAgent:e.string().optional(),autoApproveStructure:e.enum(["strict","extend-leaves","any"]).default("extend-leaves"),autoApproveConfidence:e.number().min(0).max(1).default(1),classifierModel:e.string().default("claude-haiku-4-5-20251001"),retrievalWeights:e.object({graph:e.number().min(0).default(.6),bm25:e.number().min(0).default(.4)}).default({})}).default({}),re=e.object({mode:e.enum(["off","shadow","active"]).default("off"),backend:e.string().optional(),model:e.string().optional(),timeoutMs:e.number().int().min(100).default(1e4),temperature:e.number().min(.01).default(1),explore:e.number().min(0).max(1).default(.15),holdout:e.number().min(0).max(1).optional()}).default({}),ie=e.object({enabled:e.boolean().default(!1),dbPath:e.string().default(".agentx/decisions/decisions.sqlite"),redactState:e.boolean().default(!1),keepStateRows:e.number().int().min(0).default(2e3),defaultBackend:e.string().default("local"),backends:e.object({local:e.object({provider:e.string().default("claude-code"),model:e.string().default("claude-haiku-4-5-20251001"),structureMode:e.enum(["auto","tool","text"]).default("auto"),normalizeProbabilities:e.boolean().default(!0),nRetryMalformedStructure:e.number().int().min(0).max(3).default(1),maxStateChars:e.number().int().min(500).default(24e3)}).default({}),simpleJev:e.object({baseUrl:e.string().default("http://127.0.0.1:8000/v1"),model:e.string().optional(),apiKeyEnv:e.string().optional(),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(6e3),maxChoiceOptions:e.number().int().min(2).max(255).default(50)}).default({}),jev:e.object({baseUrl:e.string().default("https://openrouter.ai/api/alpha"),path:e.string().default("/decisions"),model:e.string().default("jev-latest"),apiKeyEnv:e.string().default("OPENROUTER_API_KEY"),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(9e4),maxChoiceOptions:e.number().int().min(2).max(255).default(255)}).default({}),typesafe:e.object({baseUrl:e.string().default("https://api.typesafe.ai/v1"),path:e.string().default("/systemone"),model:e.string().default("jev-latest"),apiKeyEnv:e.string().default("TYPESAFE_API_KEY"),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(9e4),maxChoiceOptions:e.number().int().min(2).max(255).default(255)}).default({})}).default({}),seats:e.record(e.string(),re).default({}),routing:e.object({cheapModel:e.string().optional(),cheapModels:e.object({"claude-code":e.string().optional(),"codex-cli":e.string().optional()}).optional()}).default({})}).default({}),se=e.object({longTaskThreshold:e.number().default(30),destination:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional(),on:e.object({taskComplete:e.boolean().default(!0),taskError:e.boolean().default(!0),taskQueued:e.boolean().default(!1)}).default({})}).default({}),w=e.object({node:e.object({id:e.string(),name:e.string(),bind:e.string().default("127.0.0.1:18800"),defaultAgent:e.string().optional()}),providers:e.record(e.string(),Z).default({}),agents:e.record(e.string(),Y).default({}),channels:V.default({}),crons:e.record(e.string(),X).default({}),services:e.record(e.string(),ee).default({}),notifications:se,mesh:ae.default({}),business:h.optional(),boards:x,dashboard:S,graph:oe,decisions:ie,workflows:e.object({enabled:e.boolean().default(!1),dir:e.string().default(".agentx/workflows"),n8n:e.object({baseUrl:e.string().default(""),apiKey:e.string().default("")}).default({baseUrl:"",apiKey:""}),matching:e.object({enabled:e.boolean().default(!1),mode:e.enum(["suggest","auto"]).default("suggest"),autoRunThreshold:e.number().min(0).max(1).default(.85),suggestThreshold:e.number().min(0).max(1).default(.65)}).default({}),editor:e.enum(["disabled","readonly","edit"]).default("edit")}).default({}),procedures:e.object({enabled:e.boolean().default(!0),dir:e.string().default(".agentx/procedures"),extraction:e.object({enabled:e.boolean().default(!1),onTaskCompletion:e.boolean().default(!1),minOccurrences:e.number().int().min(2).default(3),sinceDays:e.number().int().min(1).default(7),maxClusters:e.number().int().min(1).default(5),via:e.string().optional()}).default({}),injection:e.object({enabled:e.boolean().default(!0),maxProcedures:e.number().int().min(1).default(2),minScore:e.number().min(0).max(1).default(.5)}).default({})}).default({}),webhooks:e.array(e.object({id:e.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"webhook id must be lowercase slug"),source:e.string().min(1),agentId:e.string(),secretEnv:e.string().optional(),description:e.string().optional(),enabled:e.boolean().default(!0),node:e.string().optional(),triggers:e.record(e.string(),e.string()).optional(),defaultWorkflow:e.string().optional()})).default([]),session:e.object({staleMinutes:e.number().int().min(1).max(1440).default(720),maxTurnsPerSession:e.number().int().min(2).max(200).default(40),tierTwoThresholdTokens:e.number().int().min(5e4).max(2e5).default(18e4),contextStrategy:e.enum(["layered","planner"]).default("layered"),maxClaudeCodeDispatchesPerHour:e.number().int().min(1).max(1e4).default(80),maxClaudeCodeDispatchesPer5h:e.number().int().min(1).max(5e4).default(180),continuityStateTurns:e.number().int().min(0).max(5).default(0)}).default({}),plugins:e.array(e.string()).default([]),processPool:e.object({maxIdleSeconds:e.number().int().min(5).max(86400).default(30),maxAgeSeconds:e.number().int().min(60).max(86400).default(2700),sweepIntervalSeconds:e.number().int().min(1).max(300).default(5)}).default({})})});export{be as a,he as b,k as c,G as d,w as e,g as f,de as g,ue as h,ce as i,fe as j};
|
|
13
|
+
//# sourceMappingURL=chunk-SPJWXIAV.js.map
|