agentix-cli 0.126.2 → 0.128.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-BUYK4EGC.js → App-BOLQUKCN.js} +2 -2
- package/dist/{ChatApp-ZS6EPDDK.js → ChatApp-72HXQV24.js} +2 -2
- package/dist/absorb-eval-O3HA6XA5.js +2 -0
- package/dist/{agent-WJTYM5HR.js → agent-S2DXXALS.js} +2 -2
- package/dist/{board-dashboard-DQR2OSV7.js → board-dashboard-ZKXXK5CG.js} +303 -228
- package/dist/board-dashboard-ZKXXK5CG.js.map +1 -0
- package/dist/chunk-2SV4RKRW.js +128 -0
- package/dist/chunk-2SV4RKRW.js.map +1 -0
- package/dist/{chunk-WUDVBPQV.js → chunk-4V7SWL2S.js} +2 -2
- package/dist/chunk-52SIHG45.js +4 -0
- package/dist/chunk-52SIHG45.js.map +1 -0
- package/dist/chunk-5DAEJF5S.js +36 -0
- package/dist/chunk-5DAEJF5S.js.map +1 -0
- package/dist/{chunk-GUQDPA6R.js → chunk-6GGGXCOY.js} +2 -2
- package/dist/{chunk-JIXNSA67.js → chunk-6KIUVVKX.js} +2 -2
- package/dist/{chunk-O4XEQTEN.js → chunk-C5MTLW7O.js} +3 -3
- package/dist/chunk-C5MTLW7O.js.map +1 -0
- package/dist/{chunk-FHBPKMCF.js → chunk-D2WX3BET.js} +2 -2
- package/dist/chunk-DN3RLR5Z.js +17 -0
- package/dist/chunk-DN3RLR5Z.js.map +1 -0
- package/dist/{chunk-Z7XXUYBB.js → chunk-DQ2LNQ2D.js} +33 -35
- package/dist/chunk-DQ2LNQ2D.js.map +1 -0
- package/dist/{chunk-UUVFH7BO.js → chunk-EJT4MA3J.js} +102 -102
- package/dist/chunk-EJT4MA3J.js.map +1 -0
- package/dist/chunk-FSW4FUMW.js +55 -0
- package/dist/chunk-FSW4FUMW.js.map +1 -0
- package/dist/chunk-FXBMFGOV.js +6 -0
- package/dist/chunk-FXBMFGOV.js.map +1 -0
- package/dist/{chunk-WMTGAVPW.js → chunk-HKW56YZK.js} +2 -2
- package/dist/{chunk-VXKNB4AW.js → chunk-LDS4SZBU.js} +2 -2
- package/dist/chunk-MRYA4J5F.js +54 -0
- package/dist/chunk-MRYA4J5F.js.map +1 -0
- package/dist/{chunk-LVV7JBHM.js → chunk-O2BS6N3T.js} +2 -2
- package/dist/{chunk-ZQWWMAMJ.js → chunk-P4XGM7ZM.js} +2 -2
- package/dist/{chunk-D6SWAB5J.js → chunk-QACEFESP.js} +32 -32
- package/dist/chunk-QACEFESP.js.map +1 -0
- package/dist/{chunk-6GLJIA25.js → chunk-QFZU5CEO.js} +2 -2
- package/dist/{chunk-FVG2BADS.js → chunk-QQFURUMS.js} +2 -2
- package/dist/chunk-QUXMLLX5.js +2 -0
- package/dist/chunk-QUXMLLX5.js.map +1 -0
- package/dist/{chunk-CY6ABHF2.js → chunk-TG6CT54D.js} +2 -2
- package/dist/chunk-TPNTFCSQ.js +4 -0
- package/dist/chunk-TPNTFCSQ.js.map +1 -0
- package/dist/{chunk-56KNKUFF.js → chunk-VD7IO653.js} +3 -3
- package/dist/{chunk-56KNKUFF.js.map → chunk-VD7IO653.js.map} +1 -1
- package/dist/{chunk-JUIL2EW3.js → chunk-YWKLUQDC.js} +2 -2
- package/dist/chunk-Z3W7D5RR.js +4 -0
- package/dist/chunk-Z3W7D5RR.js.map +1 -0
- package/dist/{chunk-QQYXYJOG.js → chunk-ZLC4TSXF.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-PO5LDFS4.js → client-VBV7Q43P.js} +2 -2
- package/dist/config-52C3DJD2.js +2 -0
- package/dist/config-mutate-DKQESY6F.js +2 -0
- package/dist/config-mutator-BF4D4QGN.js +2 -0
- package/dist/contributions-5OEZWYXI.js +57 -0
- package/dist/contributions-5OEZWYXI.js.map +1 -0
- package/dist/doctor-VLRC4HW2.js +2 -0
- package/dist/{follow-up-tool-AIOLNUF7.js → follow-up-tool-235LDEMP.js} +2 -2
- package/dist/{follow-up-tool-AIOLNUF7.js.map → follow-up-tool-235LDEMP.js.map} +1 -1
- package/dist/hub-5QK7KYTZ.js +2 -0
- package/dist/index.d.ts +339 -50
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/notes-YLTNRMB5.js +2 -0
- package/dist/notes-settings-X63D5HPM.js +2 -0
- package/dist/{program-LGCT7FFJ.js → program-MVD57PKP.js} +236 -232
- package/dist/program-MVD57PKP.js.map +1 -0
- package/dist/{promote-MQYJMGGZ.js → promote-UPPQ4BQE.js} +2 -2
- package/dist/query-XQS5JN6E.js +2 -0
- package/dist/registry-MOMTLJ6R.js +2 -0
- package/dist/{request-planner-XYHM26CO.js → request-planner-QGZJEAKY.js} +2 -2
- package/dist/{review-candidates-XRBAMRBH.js → review-candidates-PAKF2JQF.js} +2 -2
- package/dist/{rotation-memo-6UW6DTBQ.js → rotation-memo-7VLREGS6.js} +2 -2
- package/dist/routing-JG3EV4O4.js +2 -0
- package/dist/schedule-tool-O7ZZ2A7X.js +2 -0
- package/dist/scheduler-LMPBAA34.js +2 -0
- package/dist/scheduler-LMPBAA34.js.map +1 -0
- package/dist/score-KDNIUTNV.js +3 -0
- package/dist/score-KDNIUTNV.js.map +1 -0
- package/dist/{seat-LKBZ6SDS.js → seat-JN3IVZ3G.js} +2 -2
- package/dist/seat-JN3IVZ3G.js.map +1 -0
- package/dist/{select-BSC3TFMZ.js → select-ZMMRFMNO.js} +2 -2
- package/dist/{set-enabled-YWXWSKME.js → set-enabled-7Y3TW6Z4.js} +2 -2
- package/dist/{tool-FZEC5FQX.js → tool-OCYXCDOK.js} +2 -2
- package/dist/{tool-FZEC5FQX.js.map → tool-OCYXCDOK.js.map} +1 -1
- package/dist/{tool-5JTCSRTW.js → tool-S7QI6HRA.js} +2 -2
- package/dist/{tool-5JTCSRTW.js.map → tool-S7QI6HRA.js.map} +1 -1
- package/dist/wiki-OCLFFZG6.js +2 -0
- package/dist/wiki-OCLFFZG6.js.map +1 -0
- package/package.json +1 -1
- package/dist/absorb-eval-5Y5IZWW2.js +0 -2
- package/dist/board-dashboard-DQR2OSV7.js.map +0 -1
- package/dist/chunk-2C3X6DVD.js +0 -49
- package/dist/chunk-2C3X6DVD.js.map +0 -1
- package/dist/chunk-2W3X6H7Z.js +0 -51
- package/dist/chunk-2W3X6H7Z.js.map +0 -1
- package/dist/chunk-46JKX6CT.js +0 -54
- package/dist/chunk-46JKX6CT.js.map +0 -1
- package/dist/chunk-5DFUUYEA.js +0 -126
- package/dist/chunk-5DFUUYEA.js.map +0 -1
- package/dist/chunk-D6SWAB5J.js.map +0 -1
- package/dist/chunk-O4XEQTEN.js.map +0 -1
- package/dist/chunk-UUVFH7BO.js.map +0 -1
- package/dist/chunk-YNA5T43U.js +0 -4
- package/dist/chunk-YNA5T43U.js.map +0 -1
- package/dist/chunk-Z7XXUYBB.js.map +0 -1
- package/dist/config-L2RQ6EJX.js +0 -2
- package/dist/config-mutator-44OAOZXM.js +0 -2
- package/dist/doctor-AU5TCOSG.js +0 -2
- package/dist/hub-53YQQCVA.js +0 -2
- package/dist/program-LGCT7FFJ.js.map +0 -1
- package/dist/query-DNJONEKC.js +0 -2
- package/dist/registry-5A3SLBVJ.js +0 -2
- package/dist/routing-OMIWZKNC.js +0 -2
- package/dist/schedule-tool-YRANRFHO.js +0 -2
- package/dist/scheduler-L4P4Z55R.js +0 -2
- package/dist/wiki-BT3H2WCD.js +0 -2
- /package/dist/{App-BUYK4EGC.js.map → App-BOLQUKCN.js.map} +0 -0
- /package/dist/{ChatApp-ZS6EPDDK.js.map → ChatApp-72HXQV24.js.map} +0 -0
- /package/dist/{absorb-eval-5Y5IZWW2.js.map → absorb-eval-O3HA6XA5.js.map} +0 -0
- /package/dist/{agent-WJTYM5HR.js.map → agent-S2DXXALS.js.map} +0 -0
- /package/dist/{chunk-WUDVBPQV.js.map → chunk-4V7SWL2S.js.map} +0 -0
- /package/dist/{chunk-GUQDPA6R.js.map → chunk-6GGGXCOY.js.map} +0 -0
- /package/dist/{chunk-JIXNSA67.js.map → chunk-6KIUVVKX.js.map} +0 -0
- /package/dist/{chunk-FHBPKMCF.js.map → chunk-D2WX3BET.js.map} +0 -0
- /package/dist/{chunk-WMTGAVPW.js.map → chunk-HKW56YZK.js.map} +0 -0
- /package/dist/{chunk-VXKNB4AW.js.map → chunk-LDS4SZBU.js.map} +0 -0
- /package/dist/{chunk-LVV7JBHM.js.map → chunk-O2BS6N3T.js.map} +0 -0
- /package/dist/{chunk-ZQWWMAMJ.js.map → chunk-P4XGM7ZM.js.map} +0 -0
- /package/dist/{chunk-6GLJIA25.js.map → chunk-QFZU5CEO.js.map} +0 -0
- /package/dist/{chunk-FVG2BADS.js.map → chunk-QQFURUMS.js.map} +0 -0
- /package/dist/{chunk-CY6ABHF2.js.map → chunk-TG6CT54D.js.map} +0 -0
- /package/dist/{chunk-JUIL2EW3.js.map → chunk-YWKLUQDC.js.map} +0 -0
- /package/dist/{chunk-QQYXYJOG.js.map → chunk-ZLC4TSXF.js.map} +0 -0
- /package/dist/{client-PO5LDFS4.js.map → client-VBV7Q43P.js.map} +0 -0
- /package/dist/{config-L2RQ6EJX.js.map → config-52C3DJD2.js.map} +0 -0
- /package/dist/{config-mutator-44OAOZXM.js.map → config-mutate-DKQESY6F.js.map} +0 -0
- /package/dist/{doctor-AU5TCOSG.js.map → config-mutator-BF4D4QGN.js.map} +0 -0
- /package/dist/{hub-53YQQCVA.js.map → doctor-VLRC4HW2.js.map} +0 -0
- /package/dist/{promote-MQYJMGGZ.js.map → hub-5QK7KYTZ.js.map} +0 -0
- /package/dist/{query-DNJONEKC.js.map → notes-YLTNRMB5.js.map} +0 -0
- /package/dist/{registry-5A3SLBVJ.js.map → notes-settings-X63D5HPM.js.map} +0 -0
- /package/dist/{routing-OMIWZKNC.js.map → promote-UPPQ4BQE.js.map} +0 -0
- /package/dist/{schedule-tool-YRANRFHO.js.map → query-XQS5JN6E.js.map} +0 -0
- /package/dist/{scheduler-L4P4Z55R.js.map → registry-MOMTLJ6R.js.map} +0 -0
- /package/dist/{request-planner-XYHM26CO.js.map → request-planner-QGZJEAKY.js.map} +0 -0
- /package/dist/{review-candidates-XRBAMRBH.js.map → review-candidates-PAKF2JQF.js.map} +0 -0
- /package/dist/{rotation-memo-6UW6DTBQ.js.map → rotation-memo-7VLREGS6.js.map} +0 -0
- /package/dist/{seat-LKBZ6SDS.js.map → routing-JG3EV4O4.js.map} +0 -0
- /package/dist/{wiki-BT3H2WCD.js.map → schedule-tool-O7ZZ2A7X.js.map} +0 -0
- /package/dist/{select-BSC3TFMZ.js.map → select-ZMMRFMNO.js.map} +0 -0
- /package/dist/{set-enabled-YWXWSKME.js.map → set-enabled-7Y3TW6Z4.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{oa as S,
|
|
1
|
+
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{oa as S,ua as L}from"./chunk-MRYA4J5F.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().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 t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.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 l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.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 a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.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{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).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(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).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(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.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>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.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 ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} 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&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.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 te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.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 o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" 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 l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.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(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.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[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=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[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${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(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.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 oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.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)){t.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 a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.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 W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${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=W(t);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{P as a,J as b,ke as c,G as d,V as e,ne as f};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-QFZU5CEO.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-YWKLUQDC.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("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 b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(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 v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/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"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-QQFURUMS.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var s=/^[A-Za-z0-9][A-Za-z0-9._:@-]*$/;function a(o){let n=o&&typeof o=="object"?o:{};return{enabled:n.enabled===!0,inbox:typeof n.inbox=="string"?n.inbox:"",crons:Array.isArray(n.crons)?n.crons.filter(r=>typeof r=="string"):[],maxNotesPerRun:Number.isInteger(n.maxNotesPerRun)?n.maxNotesPerRun:20,maxDeferrals:Number.isInteger(n.maxDeferrals)?n.maxDeferrals:3}}function b(o,n){let r={...o.wikiNotes&&typeof o.wikiNotes=="object"?o.wikiNotes:{}},t=[];if(n.inbox!==void 0){let e=String(n.inbox).trim();if(e&&!s.test(e))throw new Error(`"${e}" is not an agent id`);e?r.inbox=e:delete r.inbox,t.push(e?`inbox=${e}`:"inbox cleared")}if(n.crons!==void 0){let e=[...new Set(n.crons.map(i=>String(i).trim()).filter(Boolean))];r.crons=e,t.push(`crons=${e.length?e.join(","):"none"}`)}if(n.maxNotesPerRun!==void 0){let e=Number(n.maxNotesPerRun);if(!Number.isInteger(e)||e<1||e>100)throw new Error("max notes per run must be a whole number from 1 to 100");r.maxNotesPerRun=e,t.push(`maxNotesPerRun=${e}`)}if(n.maxDeferrals!==void 0){let e=Number(n.maxDeferrals);if(!Number.isInteger(e)||e<1||e>20)throw new Error("deferrals before a note expires must be a whole number from 1 to 20");r.maxDeferrals=e,t.push(`maxDeferrals=${e}`)}if(n.enabled!==void 0&&(r.enabled=!!n.enabled,t.push(r.enabled?"on":"off")),t.length===0)throw new Error("nothing to update");if(r.enabled&&!r.inbox)throw new Error("set the inbox agent first: the agent that runs the wiki observe/sweep schedule");for(let e of r.crons??[]){let i=o.crons?.[e];if(!i)throw new Error(`no schedule "${e}" on this node`);if(r.inbox&&i.agent!==r.inbox)throw new Error(`schedule "${e}" runs as "${i.agent}", not the inbox agent "${r.inbox}"`)}return o.wikiNotes=r,`wiki notes updated (${t.join(", ")})`}export{a,b};
|
|
2
|
+
//# sourceMappingURL=chunk-QUXMLLX5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/notes-settings.ts"],"sourcesContent":["// Settings for the wiki notes inbox (#825), shared by\n// `agentx wiki notes config` and the dashboard's Schedules tab so both\n// apply the same checks to agentx.json.\n\nexport interface WikiNotesPatch {\n enabled?: boolean\n /** Agent that runs the wiki observe/sweep schedule. \"\" clears it. */\n inbox?: string\n /** Replace the list of schedules that read the inbox. */\n crons?: string[]\n maxNotesPerRun?: number\n maxDeferrals?: number\n}\n\nexport interface WikiNotesView {\n enabled: boolean\n inbox: string\n crons: string[]\n maxNotesPerRun: number\n maxDeferrals: number\n}\n\nconst ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:@-]*$/\n\n/** The current settings, with defaults filled in. */\nexport function wikiNotesSettings(raw: any): WikiNotesView {\n const n = raw && typeof raw === \"object\" ? raw : {}\n return {\n enabled: n.enabled === true,\n inbox: typeof n.inbox === \"string\" ? n.inbox : \"\",\n crons: Array.isArray(n.crons) ? n.crons.filter((c: unknown) => typeof c === \"string\") : [],\n maxNotesPerRun: Number.isInteger(n.maxNotesPerRun) ? n.maxNotesPerRun : 20,\n maxDeferrals: Number.isInteger(n.maxDeferrals) ? n.maxDeferrals : 3,\n }\n}\n\n/**\n * Apply `patch` to `cfg.wikiNotes` in place and say what changed. Throws a\n * message meant for a person when the result would not work.\n *\n * The inbox agent may live on another node (a node that only posts notes),\n * so it is not required to be in `cfg.agents`. A schedule listed in\n * `crons` must exist here and run as the inbox agent: that is the run\n * that reads the notes.\n */\nexport function patchWikiNotes(cfg: any, patch: WikiNotesPatch): string {\n const cur = { ...(cfg.wikiNotes && typeof cfg.wikiNotes === \"object\" ? cfg.wikiNotes : {}) }\n const changes: string[] = []\n\n if (patch.inbox !== undefined) {\n const inbox = String(patch.inbox).trim()\n if (inbox && !ID_RE.test(inbox)) throw new Error(`\"${inbox}\" is not an agent id`)\n if (inbox) cur.inbox = inbox\n else delete cur.inbox\n changes.push(inbox ? `inbox=${inbox}` : \"inbox cleared\")\n }\n if (patch.crons !== undefined) {\n const ids = [...new Set(patch.crons.map((c) => String(c).trim()).filter(Boolean))]\n cur.crons = ids\n changes.push(`crons=${ids.length ? ids.join(\",\") : \"none\"}`)\n }\n if (patch.maxNotesPerRun !== undefined) {\n const n = Number(patch.maxNotesPerRun)\n if (!Number.isInteger(n) || n < 1 || n > 100) throw new Error(\"max notes per run must be a whole number from 1 to 100\")\n cur.maxNotesPerRun = n\n changes.push(`maxNotesPerRun=${n}`)\n }\n if (patch.maxDeferrals !== undefined) {\n const n = Number(patch.maxDeferrals)\n if (!Number.isInteger(n) || n < 1 || n > 20) throw new Error(\"deferrals before a note expires must be a whole number from 1 to 20\")\n cur.maxDeferrals = n\n changes.push(`maxDeferrals=${n}`)\n }\n if (patch.enabled !== undefined) {\n cur.enabled = Boolean(patch.enabled)\n changes.push(cur.enabled ? \"on\" : \"off\")\n }\n if (changes.length === 0) throw new Error(\"nothing to update\")\n\n if (cur.enabled && !cur.inbox) {\n throw new Error(\"set the inbox agent first: the agent that runs the wiki observe/sweep schedule\")\n }\n for (const id of cur.crons ?? []) {\n const job = cfg.crons?.[id]\n if (!job) throw new Error(`no schedule \"${id}\" on this node`)\n if (cur.inbox && job.agent !== cur.inbox) {\n throw new Error(`schedule \"${id}\" runs as \"${job.agent}\", not the inbox agent \"${cur.inbox}\"`)\n }\n }\n\n cfg.wikiNotes = cur\n return `wiki notes updated (${changes.join(\", \")})`\n}\n"],"mappings":"AAsBA,IAAMA,EAAQ,iCAGP,SAASC,EAAkBC,EAAyB,CACzD,IAAM,EAAIA,GAAO,OAAOA,GAAQ,SAAWA,EAAM,CAAC,EAClD,MAAO,CACL,QAAS,EAAE,UAAY,GACvB,MAAO,OAAO,EAAE,OAAU,SAAW,EAAE,MAAQ,GAC/C,MAAO,MAAM,QAAQ,EAAE,KAAK,EAAI,EAAE,MAAM,OAAQC,GAAe,OAAOA,GAAM,QAAQ,EAAI,CAAC,EACzF,eAAgB,OAAO,UAAU,EAAE,cAAc,EAAI,EAAE,eAAiB,GACxE,aAAc,OAAO,UAAU,EAAE,YAAY,EAAI,EAAE,aAAe,CACpE,CACF,CAWO,SAASC,EAAeC,EAAU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,MAAM,IAAI,MAAM,mBAAmB,EAE7D,GAAID,EAAI,SAAW,CAACA,EAAI,MACtB,MAAM,IAAI,MAAM,gFAAgF,EAElG,QAAWK,KAAML,EAAI,OAAS,CAAC,EAAG,CAChC,IAAMM,EAAMR,EAAI,QAAQO,CAAE,EAC1B,GAAI,CAACC,EAAK,MAAM,IAAI,MAAM,gBAAgBD,iBAAkB,EAC5D,GAAIL,EAAI,OAASM,EAAI,QAAUN,EAAI,MACjC,MAAM,IAAI,MAAM,aAAaK,eAAgBC,EAAI,gCAAgCN,EAAI,QAAQ,EAIjG,OAAAF,EAAI,UAAYE,EACT,uBAAuBC,EAAQ,KAAK,IAAI,IACjD","names":["ID_RE","wikiNotesSettings","raw","c","patchWikiNotes","cfg","patch","cur","changes","inbox","ids","n","id","job"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-ZLC4TSXF.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-HKW56YZK.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
2
|
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-TG6CT54D.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{oa as l,ua as m}from"./chunk-MRYA4J5F.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
|
|
2
|
+
`,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
|
|
4
|
+
//# sourceMappingURL=chunk-TPNTFCSQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/daemon/config-mutate.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, copyFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { loadDaemonConfig } from \"./config\"\n\n// --- Shared helpers for safe agentx.json mutation ---\n//\n// Multiple CLI commands and the dashboard admin UI all need to read → tweak →\n// write agentx.json without corrupting it on failure. This module owns the\n// atomic-write + backup + best-effort-reload pattern so every caller gets the\n// same guarantees.\n\nexport interface MutateOptions {\n /** Absolute path to the target agentx.json. Defaults to ./agentx.json. */\n configPath?: string\n /** When true, don't write a timestamped backup. Use for operations that are\n * intrinsically reversible (or when the caller already took a snapshot). */\n skipBackup?: boolean\n /** When true, don't POST /reload after writing. Handy in tests. */\n skipReload?: boolean\n}\n\nexport interface MutateResult<T = void> {\n summary: string\n payload?: T\n}\n\n/**\n * Read agentx.json, let the mutator tweak it in-place, then atomically write\n * the result back to disk. The mutator returns a short human-readable summary\n * of what changed and may optionally return a payload for the caller to relay.\n *\n * If the mutator throws, nothing is written. If writing succeeds but the file\n * doesn't round-trip as JSON, we restore from backup and rethrow.\n */\nexport function mutateAgentxConfig<T = void>(\n mutator: (cfg: any) => MutateResult<T> | string,\n opts: MutateOptions = {},\n): { summary: string; payload?: T; backupPath?: string } {\n const file = opts.configPath || resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(file)) throw new Error(`agentx.json not found at ${file}`)\n\n const cfg = JSON.parse(readFileSync(file, \"utf-8\"))\n const raw = mutator(cfg)\n const result: MutateResult<T> = typeof raw === \"string\" ? { summary: raw } : raw\n\n const json = JSON.stringify(cfg, null, 2) + \"\\n\"\n const tmp = file + \".tmp\"\n writeFileSync(tmp, json, \"utf-8\")\n try {\n JSON.parse(readFileSync(tmp, \"utf-8\"))\n } catch (e: any) {\n throw new Error(`config did not round-trip cleanly: ${e.message}`)\n }\n\n let backupPath: string | undefined\n if (!opts.skipBackup) {\n backupPath = `${file}.bak.${Date.now()}`\n copyFileSync(file, backupPath)\n }\n writeFileSync(file, json, \"utf-8\")\n\n if (!opts.skipReload) triggerLocalReload().catch(() => { /* daemon may be off */ })\n\n return { summary: result.summary, payload: result.payload, backupPath }\n}\n\n/**\n * Write a fresh agentx.json from scratch. Used by the setup wizard on a truly\n * empty working directory. Fails if a file already exists (callers must pass\n * the overwrite flag explicitly — we don't want to silently clobber an\n * operator's hand-written config).\n */\nexport function writeAgentxConfig(\n cfg: unknown,\n opts: { configPath?: string; overwrite?: boolean } = {},\n): { file: string } {\n const file = opts.configPath || resolve(process.cwd(), \"agentx.json\")\n if (existsSync(file) && !opts.overwrite) {\n throw new Error(`agentx.json already exists at ${file}. Pass overwrite=true to replace it.`)\n }\n writeFileSync(file, JSON.stringify(cfg, null, 2) + \"\\n\", \"utf-8\")\n return { file }\n}\n\n/**\n * POST to the primary daemon's /reload endpoint so it picks up config changes\n * without a full restart. Silently no-ops if the daemon isn't running.\n */\nasync function triggerLocalReload(): Promise<void> {\n try {\n const cfg = loadDaemonConfig()\n const url = cfg.dashboard.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n await fetch(`${url}/reload`, { method: \"POST\" }).catch(() => null)\n } catch { /* config didn't load — leave it */ }\n}\n"],"mappings":"iDAEAA,IAFA,OAAS,cAAAC,EAAY,gBAAAC,EAAc,iBAAAC,EAAe,gBAAAC,MAAoB,KACtE,OAAS,WAAAC,MAAe,OAiCjB,SAASC,EACdC,EACAC,EAAsB,CAAC,EACgC,CACvD,IAAMC,EAAOD,EAAK,YAAcH,EAAQ,QAAQ,IAAI,EAAG,aAAa,EACpE,GAAI,CAACJ,EAAWQ,CAAI,EAAG,MAAM,IAAI,MAAM,4BAA4BA,GAAM,EAEzE,IAAMC,EAAM,KAAK,MAAMR,EAAaO,EAAM,OAAO,CAAC,EAC5CE,EAAMJ,EAAQG,CAAG,EACjBE,EAA0B,OAAOD,GAAQ,SAAW,CAAE,QAASA,CAAI,EAAIA,EAEvEE,EAAO,KAAK,UAAUH,EAAK,KAAM,CAAC,EAAI;AAAA,EACtCI,EAAML,EAAO,OACnBN,EAAcW,EAAKD,EAAM,OAAO,EAChC,GAAI,CACF,KAAK,MAAMX,EAAaY,EAAK,OAAO,CAAC,CACvC,OAASC,EAAP,CACA,MAAM,IAAI,MAAM,sCAAsCA,EAAE,SAAS,CACnE,CAEA,IAAIC,EACJ,OAAKR,EAAK,aACRQ,EAAa,GAAGP,SAAY,KAAK,IAAI,IACrCL,EAAaK,EAAMO,CAAU,GAE/Bb,EAAcM,EAAMI,EAAM,OAAO,EAE5BL,EAAK,YAAYS,EAAmB,EAAE,MAAM,IAAM,CAA0B,CAAC,EAE3E,CAAE,QAASL,EAAO,QAAS,QAASA,EAAO,QAAS,WAAAI,CAAW,CACxE,CAQO,SAASE,EACdR,EACAF,EAAqD,CAAC,EACpC,CAClB,IAAMC,EAAOD,EAAK,YAAcH,EAAQ,QAAQ,IAAI,EAAG,aAAa,EACpE,GAAIJ,EAAWQ,CAAI,GAAK,CAACD,EAAK,UAC5B,MAAM,IAAI,MAAM,iCAAiCC,uCAA0C,EAE7F,OAAAN,EAAcM,EAAM,KAAK,UAAUC,EAAK,KAAM,CAAC,EAAI;AAAA,EAAM,OAAO,EACzD,CAAE,KAAAD,CAAK,CAChB,CAMA,eAAeQ,GAAoC,CACjD,GAAI,CAEF,IAAME,EADMC,EAAiB,EACb,UAAU,WAAW,QAAQ,OAAQ,EAAE,GAAK,yBAC5D,MAAM,MAAM,GAAGD,WAAc,CAAE,OAAQ,MAAO,CAAC,EAAE,MAAM,IAAM,IAAI,CACnE,MAAE,CAA4C,CAChD","names":["init_config","existsSync","readFileSync","writeFileSync","copyFileSync","resolve","mutateAgentxConfig","mutator","opts","file","cfg","raw","result","json","tmp","e","backupPath","triggerLocalReload","writeAgentxConfig","url","loadDaemonConfig"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as l,existsSync as f}from"fs";import{resolve as
|
|
2
|
-
`)){let t=r.trim();if(!t||t.startsWith("#"))continue;let s=t.startsWith("export ")?t.slice(7).trim():t,i=s.indexOf("=");if(i===-1)continue;let c=s.slice(0,i).trim(),o=s.slice(i+1).trim();o.length>=2&&(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),c&&n.push([c,o])}return n}function E(e){let n={};for(let r of[".env",".env.gitlab"]){let t=
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{readFileSync as l,existsSync as f}from"fs";import{resolve as d}from"path";function a(e){let n=[];for(let r of e.split(`
|
|
2
|
+
`)){let t=r.trim();if(!t||t.startsWith("#"))continue;let s=t.startsWith("export ")?t.slice(7).trim():t,i=s.indexOf("=");if(i===-1)continue;let c=s.slice(0,i).trim(),o=s.slice(i+1).trim();o.length>=2&&(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),c&&n.push([c,o])}return n}function E(e){let n={};for(let r of[".env",".env.gitlab"]){let t=d(e,r);if(f(t))try{for(let[s,i]of a(l(t,"utf-8")))n[s]=i}catch{}}return n}var p=new Map;function g(e=process.cwd()){let n=p.get(e);if(n)return n;let r=d(e,".env"),t;if(!f(r))t=new Set;else try{t=new Set(a(l(r,"utf-8")).map(([s])=>s))}catch{t=new Set}return p.set(e,t),t}function A(e,n=process.env,r=process.cwd()){let t=E(e),s=g(r),i={...n};for(let c of s)c in t||delete i[c];for(let[c,o]of Object.entries(t))i[c]=o;return i}function u(e){return delete e.ANTHROPIC_API_KEY,delete e.ANTHROPIC_API_KEY_OLD,e}function v(e){let n=e.HOME||process.env.HOME,r=[e.PATH||"",n?`${n}/.local/bin`:"","/opt/homebrew/bin","/usr/local/bin"];return e.PATH=Array.from(new Set(r.flatMap(t=>t.split(":")).filter(Boolean))).join(":"),e}function m(){let e=v(u({...process.env}));return delete e.CLAUDECODE,e}function S(e,n="subscription"){if(n!=="api")return u(e);if(!e.ANTHROPIC_API_KEY)throw new Error(`billing "api" needs ANTHROPIC_API_KEY in the agent's environment`);return delete e.ANTHROPIC_API_KEY_OLD,delete e.CLAUDE_CODE_OAUTH_TOKEN,e}function y(e){if(f(e))for(let[n,r]of a(l(e,"utf-8")))process.env[n]===void 0&&(process.env[n]=r)}export{A as a,u as b,m as c,S as d,y as e};
|
|
3
|
+
//# sourceMappingURL=chunk-VD7IO653.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/workspace-env.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// Loads per-agent secrets from the agent's workspace and tells the runtime\n// which keys the daemon's own .env injected, so we can strip those before\n// spawning the agent's claude process. Without this, every agent inherits\n// the daemon's GITLAB_TOKEN regardless of whether their workspace has its\n// own .env.gitlab — defeating per-agent identity boundaries (each agent\n// should commit/push as itself, not as the daemon's account).\n\n/**\n * Parse a dotenv-style file. Tolerates the `export KEY=VALUE` form used by\n * shell-sourced files like .env.gitlab on peer-server.\n */\nfunction parseDotEnv(content: string): Array<[string, string]> {\n const out: Array<[string, string]> = []\n for (const raw of content.split(\"\\n\")) {\n const trimmed = raw.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const stripped = trimmed.startsWith(\"export \") ? trimmed.slice(7).trim() : trimmed\n const eq = stripped.indexOf(\"=\")\n if (eq === -1) continue\n const key = stripped.slice(0, eq).trim()\n let value = stripped.slice(eq + 1).trim()\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n value = value.slice(1, -1)\n }\n if (key) out.push([key, value])\n }\n return out\n}\n\n/**\n * Read .env then .env.gitlab from a workspace and return their merged keys.\n * .env.gitlab wins on collision — it's the more specific per-channel file.\n */\nexport function loadWorkspaceEnv(workspace: string): Record<string, string> {\n const merged: Record<string, string> = {}\n for (const fname of [\".env\", \".env.gitlab\"]) {\n const path = resolve(workspace, fname)\n if (!existsSync(path)) continue\n try {\n for (const [k, v] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n merged[k] = v\n }\n } catch { /* best-effort */ }\n }\n return merged\n}\n\n/**\n * Keys defined in the daemon's own .env file, cached per daemonCwd. The\n * runtime uses this to strip those keys from the child env before adding\n * the workspace overrides — so a daemon-level GITLAB_TOKEN never leaks to\n * an agent that hasn't put one in its own workspace.\n */\nconst daemonEnvKeysCache = new Map<string, Set<string>>()\n\nexport function getDaemonEnvKeys(daemonCwd: string = process.cwd()): Set<string> {\n const cached = daemonEnvKeysCache.get(daemonCwd)\n if (cached) return cached\n const path = resolve(daemonCwd, \".env\")\n let keys: Set<string>\n if (!existsSync(path)) {\n keys = new Set()\n } else {\n try {\n keys = new Set(parseDotEnv(readFileSync(path, \"utf-8\")).map(([k]) => k))\n } catch {\n keys = new Set()\n }\n }\n daemonEnvKeysCache.set(daemonCwd, keys)\n return keys\n}\n\n/** Test-only: clear the cache so a different daemonCwd is re-read. */\nexport function _resetDaemonEnvKeysCache(): void {\n daemonEnvKeysCache.clear()\n}\n\n/**\n * Build the env object passed to a spawned agent process. Starts from\n * parentEnv (default process.env), removes any keys that came from the\n * daemon's own .env (so daemon-level secrets don't leak), then layers in\n * workspace .env / .env.gitlab.\n *\n * - System env (PATH, HOME, USER, …) survives untouched.\n * - Daemon-level secrets (e.g. GITLAB_TOKEN in /home/peer/agentx/.env) are\n * stripped UNLESS the workspace provides its own value for that key.\n * - Workspace env (per-agent .env / .env.gitlab) wins on the final merge.\n */\nexport function buildAgentEnv(\n workspace: string,\n parentEnv: NodeJS.ProcessEnv = process.env,\n daemonCwd: string = process.cwd(),\n): NodeJS.ProcessEnv {\n const workspaceEnv = loadWorkspaceEnv(workspace)\n const daemonOwnedKeys = getDaemonEnvKeys(daemonCwd)\n const child: NodeJS.ProcessEnv = { ...parentEnv }\n for (const k of daemonOwnedKeys) {\n if (!(k in workspaceEnv)) delete child[k]\n }\n for (const [k, v] of Object.entries(workspaceEnv)) {\n child[k] = v\n }\n return child\n}\n\n// Force the `claude` CLI to use OAuth/subscription billing. When\n// ANTHROPIC_API_KEY is present (env, systemd EnvironmentFile, daemon .env not\n// stripped because the workspace also defines it), the CLI silently switches\n// to the API-key path and any usage caps on that key surface as\n// \"You have reached your specified API usage limits...\". This caused\n// claude-code-tier agents to bypass the user's subscription. The same\n// stripping pattern lives in src/agent/providers/claude-code.ts for the\n// in-process provider — keep them in sync.\nexport function stripAnthropicApiKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n return env\n}\n\n/** `env` with the folders the fleet's CLIs install to added to PATH. A\n * process started by launchd, or the MCP server Claude Code starts, does\n * not get a login shell's PATH, and `claude` usually lives in\n * ~/.local/bin. */\nexport function withToolPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const home = env.HOME || process.env.HOME\n const parts = [\n env.PATH || \"\",\n home ? `${home}/.local/bin` : \"\",\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n ]\n env.PATH = Array.from(new Set(parts.flatMap((p) => p.split(\":\")).filter(Boolean))).join(\":\")\n return env\n}\n\n/** The env for a one-shot `claude -p` call: subscription billing and a\n * PATH that can find the CLI. */\nexport function claudeCliEnv(): NodeJS.ProcessEnv {\n return withToolPath(stripAnthropicApiKey({ ...process.env }))\n}\n\n/** How an agent's `claude` CLI is billed. \"subscription\" (the default) is\n * the OAuth login shared by the fleet. \"api\" bills ANTHROPIC_API_KEY\n * instead, for agents that must not draw on that shared quota, such as\n * benchmark runs. */\nexport type ClaudeBilling = \"subscription\" | \"api\"\n\n/** Shape a `claude` spawn env for the agent's billing. Each mode removes the\n * other's credential, because the CLI silently uses whichever it finds. An\n * \"api\" agent with no key throws rather than falling back to the\n * subscription. */\nexport function claudeBillingEnv(\n env: NodeJS.ProcessEnv,\n billing: ClaudeBilling = \"subscription\",\n): NodeJS.ProcessEnv {\n if (billing !== \"api\") return stripAnthropicApiKey(env)\n if (!env.ANTHROPIC_API_KEY) {\n throw new Error('billing \"api\" needs ANTHROPIC_API_KEY in the agent\\'s environment')\n }\n delete env.ANTHROPIC_API_KEY_OLD\n delete env.CLAUDE_CODE_OAUTH_TOKEN\n return env\n}\n\n/**\n * Load a dotenv file into process.env for the CURRENT process. Variables\n * already present win, so a systemd/launchd override always beats the file.\n *\n * `agentx daemon start` has always done this; `agentx board serve` did not,\n * so `${MESH_TOKEN}` in agentx.json expanded to \"\" inside the dashboard and\n * every proxied mesh call went out with an empty Bearer (401 from peers).\n */\nexport function loadEnvFileIntoProcess(path: string): void {\n if (!existsSync(path)) return\n for (const [key, value] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n if (process.env[key] === undefined) process.env[key] = value\n }\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KACzC,OAAS,WAAAC,MAAe,OAaxB,SAASC,EAAYC,EAA0C,CAC7D,I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AAWD,CAAI,EACpB,OAAW,CAACE,EAAKC,CAAK,IAAKC,EAAYC,EAAaL,EAAM,OAAO,CAAC,EAC5D,QAAQ,IAAIE,CAAG,IAAM,SAAW,QAAQ,IAAIA,CAAG,EAAIC,EAE3D","names":["readFileSync","existsSync","resolve","parseDotEnv","content","out","raw","trimmed","stripped","eq","key","value","loadWorkspaceEnv","workspace","merged","fname","path","k","v","daemonEnvKeysCache","getDaemonEnvKeys","daemonCwd","cached","keys","buildAgentEnv","workspace","parentEnv","daemonCwd","workspaceEnv","loadWorkspaceEnv","daemonOwnedKeys","getDaemonEnvKeys","child","k","v","stripAnthropicApiKey","env","withToolPath","home","parts","p","claudeCliEnv","claudeBillingEnv","billing","loadEnvFileIntoProcess","path","existsSync","key","value","parseDotEnv","readFileSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/workspace-env.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// Loads per-agent secrets from the agent's workspace and tells the runtime\n// which keys the daemon's own .env injected, so we can strip those before\n// spawning the agent's claude process. Without this, every agent inherits\n// the daemon's GITLAB_TOKEN regardless of whether their workspace has its\n// own .env.gitlab — defeating per-agent identity boundaries (each agent\n// should commit/push as itself, not as the daemon's account).\n\n/**\n * Parse a dotenv-style file. Tolerates the `export KEY=VALUE` form used by\n * shell-sourced files like .env.gitlab on peer-server.\n */\nfunction parseDotEnv(content: string): Array<[string, string]> {\n const out: Array<[string, string]> = []\n for (const raw of content.split(\"\\n\")) {\n const trimmed = raw.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const stripped = trimmed.startsWith(\"export \") ? trimmed.slice(7).trim() : trimmed\n const eq = stripped.indexOf(\"=\")\n if (eq === -1) continue\n const key = stripped.slice(0, eq).trim()\n let value = stripped.slice(eq + 1).trim()\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n value = value.slice(1, -1)\n }\n if (key) out.push([key, value])\n }\n return out\n}\n\n/**\n * Read .env then .env.gitlab from a workspace and return their merged keys.\n * .env.gitlab wins on collision — it's the more specific per-channel file.\n */\nexport function loadWorkspaceEnv(workspace: string): Record<string, string> {\n const merged: Record<string, string> = {}\n for (const fname of [\".env\", \".env.gitlab\"]) {\n const path = resolve(workspace, fname)\n if (!existsSync(path)) continue\n try {\n for (const [k, v] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n merged[k] = v\n }\n } catch { /* best-effort */ }\n }\n return merged\n}\n\n/**\n * Keys defined in the daemon's own .env file, cached per daemonCwd. The\n * runtime uses this to strip those keys from the child env before adding\n * the workspace overrides — so a daemon-level GITLAB_TOKEN never leaks to\n * an agent that hasn't put one in its own workspace.\n */\nconst daemonEnvKeysCache = new Map<string, Set<string>>()\n\nexport function getDaemonEnvKeys(daemonCwd: string = process.cwd()): Set<string> {\n const cached = daemonEnvKeysCache.get(daemonCwd)\n if (cached) return cached\n const path = resolve(daemonCwd, \".env\")\n let keys: Set<string>\n if (!existsSync(path)) {\n keys = new Set()\n } else {\n try {\n keys = new Set(parseDotEnv(readFileSync(path, \"utf-8\")).map(([k]) => k))\n } catch {\n keys = new Set()\n }\n }\n daemonEnvKeysCache.set(daemonCwd, keys)\n return keys\n}\n\n/** Test-only: clear the cache so a different daemonCwd is re-read. */\nexport function _resetDaemonEnvKeysCache(): void {\n daemonEnvKeysCache.clear()\n}\n\n/**\n * Build the env object passed to a spawned agent process. Starts from\n * parentEnv (default process.env), removes any keys that came from the\n * daemon's own .env (so daemon-level secrets don't leak), then layers in\n * workspace .env / .env.gitlab.\n *\n * - System env (PATH, HOME, USER, …) survives untouched.\n * - Daemon-level secrets (e.g. GITLAB_TOKEN in /home/peer/agentx/.env) are\n * stripped UNLESS the workspace provides its own value for that key.\n * - Workspace env (per-agent .env / .env.gitlab) wins on the final merge.\n */\nexport function buildAgentEnv(\n workspace: string,\n parentEnv: NodeJS.ProcessEnv = process.env,\n daemonCwd: string = process.cwd(),\n): NodeJS.ProcessEnv {\n const workspaceEnv = loadWorkspaceEnv(workspace)\n const daemonOwnedKeys = getDaemonEnvKeys(daemonCwd)\n const child: NodeJS.ProcessEnv = { ...parentEnv }\n for (const k of daemonOwnedKeys) {\n if (!(k in workspaceEnv)) delete child[k]\n }\n for (const [k, v] of Object.entries(workspaceEnv)) {\n child[k] = v\n }\n return child\n}\n\n// Force the `claude` CLI to use OAuth/subscription billing. When\n// ANTHROPIC_API_KEY is present (env, systemd EnvironmentFile, daemon .env not\n// stripped because the workspace also defines it), the CLI silently switches\n// to the API-key path and any usage caps on that key surface as\n// \"You have reached your specified API usage limits...\". This caused\n// claude-code-tier agents to bypass the user's subscription. The same\n// stripping pattern lives in src/agent/providers/claude-code.ts for the\n// in-process provider — keep them in sync.\nexport function stripAnthropicApiKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n return env\n}\n\n/** `env` with the folders the fleet's CLIs install to added to PATH. A\n * process started by launchd, or the MCP server Claude Code starts, does\n * not get a login shell's PATH, and `claude` usually lives in\n * ~/.local/bin. */\nexport function withToolPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const home = env.HOME || process.env.HOME\n const parts = [\n env.PATH || \"\",\n home ? `${home}/.local/bin` : \"\",\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n ]\n env.PATH = Array.from(new Set(parts.flatMap((p) => p.split(\":\")).filter(Boolean))).join(\":\")\n return env\n}\n\n/** The env for a one-shot `claude -p` call: subscription billing, a\n * PATH that can find the CLI, and no CLAUDECODE marker. Inside an\n * agent's session (the MCP server, an agent's own shell) the marker is\n * inherited and the CLI refuses to start a nested session, which is how\n * `agentx_wiki_patch` and `agentx_wiki_interview` failed at `claude -p`\n * (#824). session-monitor and talk-model drop it for the same reason. */\nexport function claudeCliEnv(): NodeJS.ProcessEnv {\n const env = withToolPath(stripAnthropicApiKey({ ...process.env }))\n delete env.CLAUDECODE\n return env\n}\n\n/** How an agent's `claude` CLI is billed. \"subscription\" (the default) is\n * the OAuth login shared by the fleet. \"api\" bills ANTHROPIC_API_KEY\n * instead, for agents that must not draw on that shared quota, such as\n * benchmark runs. */\nexport type ClaudeBilling = \"subscription\" | \"api\"\n\n/** Shape a `claude` spawn env for the agent's billing. Each mode removes the\n * other's credential, because the CLI silently uses whichever it finds. An\n * \"api\" agent with no key throws rather than falling back to the\n * subscription. */\nexport function claudeBillingEnv(\n env: NodeJS.ProcessEnv,\n billing: ClaudeBilling = \"subscription\",\n): NodeJS.ProcessEnv {\n if (billing !== \"api\") return stripAnthropicApiKey(env)\n if (!env.ANTHROPIC_API_KEY) {\n throw new Error('billing \"api\" needs ANTHROPIC_API_KEY in the agent\\'s environment')\n }\n delete env.ANTHROPIC_API_KEY_OLD\n delete env.CLAUDE_CODE_OAUTH_TOKEN\n return env\n}\n\n/**\n * Load a dotenv file into process.env for the CURRENT process. Variables\n * already present win, so a systemd/launchd override always beats the file.\n *\n * `agentx daemon start` has always done this; `agentx board serve` did not,\n * so `${MESH_TOKEN}` in agentx.json expanded to \"\" inside the dashboard and\n * every proxied mesh call went out with an empty Bearer (401 from peers).\n */\nexport function loadEnvFileIntoProcess(path: string): void {\n if (!existsSync(path)) return\n for (const [key, value] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n if (process.env[key] === undefined) process.env[key] = value\n }\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KACzC,OAAS,WAAAC,MAAe,OAaxB,SAASC,EAAYC,EAA0C,CAC7D,IAAMC,EAA+B,CAAC,EACtC,QAAWC,KAAOF,EAAQ,MAAM;AAAA,CAAI,EAAG,CACrC,IAAMG,EAAUD,EAAI,KAAK,EACzB,GAAI,CAACC,GAAWA,EAAQ,WAAW,GAAG,EAAG,SACzC,IAAMC,EAAWD,EAAQ,WAAW,SAAS,EAAIA,EAAQ,MAAM,CAAC,EAAE,KAAK,EA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","eq","key","value","loadWorkspaceEnv","workspace","merged","fname","path","k","v","daemonEnvKeysCache","getDaemonEnvKeys","daemonCwd","cached","keys","buildAgentEnv","workspace","parentEnv","daemonCwd","workspaceEnv","loadWorkspaceEnv","daemonOwnedKeys","getDaemonEnvKeys","child","k","v","stripAnthropicApiKey","env","withToolPath","home","parts","p","claudeCliEnv","claudeBillingEnv","billing","loadEnvFileIntoProcess","path","existsSync","key","value","parseDotEnv","readFileSync"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{
|
|
1
|
+
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{ta as tt,ua as nt}from"./chunk-MRYA4J5F.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.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 wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}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 At(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 Rt(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&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(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 Ot(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(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:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(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:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(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 Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(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 Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,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),cn(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:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(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 w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.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 sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(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 qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(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 en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({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",()=>N({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 $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={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 bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.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??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.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:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.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:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-YWKLUQDC.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as h}from"./chunk-P4XGM7ZM.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
|
+
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
|
+
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
+
//# sourceMappingURL=chunk-Z3W7D5RR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync, readFileSync, writeFileSync, renameSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\nimport type { SharedWikiStore } from \"./query\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n /**\n * The wikis a query by `agentId` reads besides its own: every other\n * agent's articles and the root store's own (promoted lessons). Which\n * articles of theirs it may read is still decided per article by access.\n * Without this an agent's query missed answers the shared wiki had (#824).\n */\n sharedScope(agentId: string): SharedWikiStore[] {\n const others = this.listAgentDirs()\n .filter((id) => id !== agentId)\n .map((id) => ({ id, store: this.getAgentWiki(id) }))\n // The root store's walk also reaches agents/<id>/…; those are read\n // through their own store above.\n return [...others, { id: \"shared\", store: this.sharedStore, skip: (p: string) => p.startsWith(\"agents/\") }]\n }\n\n /** Agents with a wiki folder here, without reading the raw entries. */\n private listAgentDirs(): string[] {\n if (!existsSync(this.agentsDir)) return []\n return readdirSync(this.agentsDir)\n .filter((d) => !d.startsWith(\"_\") && !d.startsWith(\".\") && existsSync(resolve(this.agentsDir, d, this.mode)))\n .sort()\n }\n\n listAgents(entries: WikiEntry[] = this.sharedStore.listEntries()): string[] {\n const agents = new Set<string>()\n\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n /**\n * Entries absorb has not dealt with yet: no article cites them and no\n * successful absorb run has read them. Without the second check an\n * entry absorb read and chose not to cite came back on every run, and\n * a backfill kept re-reading the head of the queue (#762).\n */\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n return this.classifyEntries(agentId).pending\n }\n\n /**\n * Record every entry handed to the model in a successful absorb run,\n * cited or not. Callers must not call this for a failed run, so those\n * entries are offered again.\n */\n markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void {\n const cited = new Set(citedIds)\n const ledger = this.readLedger(agentId)\n const at = new Date().toISOString()\n for (const id of entryIds) ledger.entries[id] = { at, cited: cited.has(id) }\n\n const file = this.ledgerPath(agentId)\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(ledger, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /**\n * Counts and articles per agent, for `GET /wiki/agents` and the mesh.\n * The raw entries are read once and grouped here: reading them again\n * per agent made the endpoint take 25 to 75 s on a fleet with 30\n * agents and 10k entries, past the mesh client's 5 s timeout (#603).\n */\n summary(): AgentWikiSummary[] {\n const entries = this.sharedStore.listEntries()\n const byAgent = new Map<string, WikiEntry[]>()\n for (const e of entries) {\n const list = byAgent.get(e.agentId)\n if (list) list.push(e)\n else byAgent.set(e.agentId, [e])\n }\n return this.listAgents(entries).map(agentId => {\n const { all, cited, read, pending, articles } = this.classifyEntries(agentId, byAgent.get(agentId) ?? [])\n return {\n agentId,\n totalEntries: all.length,\n totalArticles: articles.length,\n cited: cited.length,\n readNotCited: read.length,\n unabsorbed: pending.length,\n articles,\n }\n })\n }\n\n /** Split an agent's entries into cited by an article, read but not cited, and pending. */\n private classifyEntries(agentId: string, all: WikiEntry[] = this.getAgentEntries(agentId)) {\n const articles = this.getAgentWiki(agentId).rebuildIndex().articles\n\n const citedIds = new Set<string>()\n for (const article of articles) {\n if (article.sources) {\n for (const s of article.sources) citedIds.add(s)\n }\n }\n const ledger = this.readLedger(agentId).entries\n\n const cited: WikiEntry[] = []\n const read: WikiEntry[] = []\n const pending: WikiEntry[] = []\n for (const e of all) {\n if (citedIds.has(e.id)) cited.push(e)\n else if (ledger[e.id]) read.push(e)\n else pending.push(e)\n }\n return { all, cited, read, pending, articles }\n }\n\n /**\n * The peer an agent's articles were copied from by `wiki sync --articles`,\n * or null for an agent this node absorbs itself. A copied agent is\n * read-only here: absorb and patch leave it to its home node.\n */\n syncedFrom(agentId: string): SyncedFrom | null {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n if (!existsSync(file)) return null\n try {\n return JSON.parse(readFileSync(file, \"utf-8\")) as SyncedFrom\n } catch (err) {\n // A damaged marker still means the agent lives elsewhere.\n this.log(`synced marker ${file} is not valid JSON: ${(err as Error).message}`)\n return { node: \"unknown\", peerUrl: \"\", at: \"\" }\n }\n }\n\n markSynced(agentId: string, from: SyncedFrom): void {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(from, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /** agents/<id>/_absorbed.json — shared by every mode, like the raw entries. */\n private ledgerPath(agentId: string): string {\n return resolve(this.agentsDir, agentId, \"_absorbed.json\")\n }\n\n private readLedger(agentId: string): AbsorbLedger {\n const file = this.ledgerPath(agentId)\n if (!existsSync(file)) return { entries: {} }\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\")) as AbsorbLedger\n return { entries: parsed.entries ?? {} }\n } catch (err) {\n // Treating a damaged ledger as empty would let the next run\n // overwrite it and re-queue everything it recorded.\n throw new Error(`absorb ledger ${file} is not valid JSON: ${(err as Error).message}`)\n }\n }\n}\n\nexport interface SyncedFrom {\n /** The peer's node id. */\n node: string\n peerUrl: string\n /** When the last copy finished. */\n at: string\n}\n\ninterface AbsorbLedger {\n entries: Record<string, { at: string; cited: boolean }>\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n /** Entries an article cites. */\n cited: number\n /** Entries a successful absorb run read and did not cite. */\n readNotCited: number\n /** Entries absorb has not read yet. */\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,WAAAA,MAAe,OACxB,OAAS,cAAAC,EAAY,eAAAC,EAAa,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KAgBrF,IAAMC,EAAN,KAAc,CACX,QACA,UACA,KACA,YACA,YAAsC,IAAI,IAC1C,IAER,YACEC,EAAkBR,EAAQ,QAAQ,IAAI,EAAG,cAAc,EACvDS,EAAoC,QAAQ,MAAM,KAAK,QAAS,YAAY,EAC5EC,EAAiB,QACjB,CACA,KAAK,QAAUF,EACf,KAAK,UAAYR,EAAQQ,EAAS,QAAQ,EAC1C,KAAK,KAAOE,EACZ,KAAK,IAAMD,EA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GAAGD,QACfvB,EAAcwB,EAAK,GAAG,KAAK,UAAUU,EAAM,KAAM,CAAC;AAAA,CAAK,EACvDjC,EAAWuB,EAAKD,CAAI,CACtB,CAGQ,WAAWhB,EAAyB,CAC1C,OAAOZ,EAAQ,KAAK,UAAWY,EAAS,gBAAgB,CAC1D,CAEQ,WAAWA,EAA+B,CAChD,IAAMgB,EAAO,KAAK,WAAWhB,CAAO,EACpC,GAAI,CAACX,EAAW2B,CAAI,EAAG,MAAO,CAAE,QAAS,CAAC,CAAE,EAC5C,GAAI,CAEF,MAAO,CAAE,QADM,KAAK,MAAMxB,EAAawB,EAAM,OAAO,CAAC,EAC5B,SAAW,CAAC,CAAE,CACzC,OAASU,EAAP,CAGA,MAAM,IAAI,MAAM,iBAAiBV,wBAA4BU,EAAc,SAAS,CACtF,CACF,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","readFileSync","writeFileSync","renameSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","id","p","d","entries","agents","e","dir","entryIds","citedIds","cited","ledger","at","file","tmp","byAgent","list","all","read","pending","articles","article","s","err","from"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as d}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as d}from"./chunk-2SV4RKRW.js";import{b as i,c as u,d as l,e as c}from"./chunk-HKW56YZK.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-ZLC4TSXF.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-MVD57PKP.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-D2WX3BET.js";import"./chunk-MRYA4J5F.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-VBV7Q43P.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g,ja as h,ka as i,la as j,ma as k,na as l,oa as m,pa as n,qa as o,ra as p,sa as q,ua as r}from"./chunk-MRYA4J5F.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";r();export{a as INTEGRATION_KINDS,o as WIKI_CONTRIBUTE_JOB,p as WIKI_CONTRIBUTE_MERGE_JOB,j as approvalsConfigSchema,d as callsSchema,c as cameraBotSchema,k as daemonConfigSchema,b as eventSubscriptionSchema,l as expandEnvVars,m as loadDaemonConfig,h as membersConfigSchema,g as peopleConfigSchema,f as personSchema,i as requestStatusConfigSchema,e as requestsConfigSchema,n as validateWorkspaces,q as withContributionJobs};
|
|
2
|
+
//# sourceMappingURL=config-52C3DJD2.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b}from"./chunk-TPNTFCSQ.js";import"./chunk-MRYA4J5F.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-DKQESY6F.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-HKW56YZK.js";import"./chunk-MRYA4J5F.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-BF4D4QGN.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import{a as ee}from"./chunk-FXBMFGOV.js";import"./chunk-DN3RLR5Z.js";import{f as Q,k as V}from"./chunk-GLQLCBJS.js";import"./chunk-FSW4FUMW.js";import"./chunk-VD7IO653.js";import"./chunk-LDS4SZBU.js";import"./chunk-WPNRDEHW.js";import{c as O}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-YWKLUQDC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import{b as X}from"./chunk-4VVHGR7H.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-MRYA4J5F.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
|
+
${k.join(`
|
|
4
|
+
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
5
|
+
`);s.push({id:l.taskId,at:new Date(l.startedAt).toISOString(),kind:"task",title:`task ${l.taskId}${l.channel?` \xB7 ${l.channel}`:""}`,text:y})}}return s.sort((g,l)=>g.at.localeCompare(l.at)||g.id.localeCompare(l.id))}function we(n,r,t,a,o){let c=ie(n),e=c.agents[r],d=a.length?a[0].at:new Date(o).toISOString(),u=[...new Set([...e?.processed??[],...t.map(s=>s.id)])].slice(-5e3);c.agents[r]={lastRunAt:d,processed:u},L(w(S(n),"state.json"),c)}async function Me(n,r,t,a){let o={maxPatches:a.maxPatches??_.maxPatches,maxCostUsd:a.maxCostUsd??_.maxCostUsd,maxItems:a.maxItems??_.maxItems},c=a.now??Date.now(),e=ke(n,r,t,{db:a.db,since:a.since,now:c}),d=e.length?$e(n,t):[],u={id:`${new Date(c).toISOString().replace(/[:.]/g,"-")}-${t.replace(/[^\w-]+/g,"_")}`,agentId:t,runAt:new Date(c).toISOString(),model:a.model,workIds:[],patches:[],costUsd:0,calls:0},s=[],g=new Set;for(;s.length<e.length;){if(u.patches.length>=o.maxPatches){u.stoppedBy="max-patches";break}if(u.costUsd>=o.maxCostUsd){u.stoppedBy="max-cost";break}if(s.length>=o.maxItems){u.stoppedBy="max-items";break}let l=e.slice(s.length,s.length+Math.min(he,o.maxItems-s.length)),m=xe(t,l,ve(d,l),o.maxPatches-u.patches.length),k=await a.call(m,Math.max(.01,o.maxCostUsd-u.costUsd));u.calls++,u.costUsd+=k.costUsd??0,s.push(...l);for(let y of Ae(k.text,t,{now:c})){if(u.patches.length>=o.maxPatches)break;g.has(y.id)||(g.add(y.id),u.patches.push(y))}}return u.workIds=s.map(l=>l.id),u.costUsd=Math.round(u.costUsd*1e4)/1e4,a.dryRun||(u.patches.length&&L(w(S(r),"pending",`${u.id}.json`),u),we(r,t,s,e.slice(s.length),c)),u}function $e(n,r){let t=[],a=(o,c)=>{for(let e of o.listArticles(r))e.path.includes("/_versions/")||c?.(e.path)||t.push({title:e.meta.title,aliases:e.meta.aliases??[],type:e.meta.type,lastUpdated:e.meta.lastUpdated,content:e.content})};a(n.getAgentWiki(r));for(let o of n.sharedScope(r))a(o.store,o.skip);return t}function ve(n,r){if(n.length===0)return[];let t=r.map(d=>`${d.title} ${d.text}`).join(`
|
|
6
|
+
`),a=H(t,N(n.map(d=>[d.title,...d.aliases].join(" ")))),o=H(t,N(n.map(d=>`${d.title} ${d.aliases.join(" ")} ${x(d.content,4e3)}`))),c=[],e=Math.ceil(M/2);for(let d of a.slice(0,e))c.push(d.docIndex);for(let d of o){if(c.length>=M)break;c.includes(d.docIndex)||c.push(d.docIndex)}for(let d of a.slice(e)){if(c.length>=M)break;c.includes(d.docIndex)||c.push(d.docIndex)}return c.map(d=>n[d])}function xe(n,r,t,a){let o=r.map(e=>`### ${e.at.slice(0,16)} \xB7 ${e.kind} \xB7 ${e.title}
|
|
7
|
+
${x(e.text,fe)}`).join(`
|
|
8
|
+
|
|
9
|
+
`),c=t.length?t.map(e=>`### ${e.title}${e.type?` [${e.type}]`:""}${e.lastUpdated?` (updated ${e.lastUpdated})`:""}
|
|
10
|
+
${x(e.content,me)}`).join(`
|
|
11
|
+
|
|
12
|
+
`):"(no matching pages)";return`You are agent "${n}". Below is your own work since your last wiki contribution (chat turns, and tasks with the tool calls you ran and what they returned) and the wiki pages it seems to touch. Propose small, sourced patches to the shared wiki from what you actually used or checked.
|
|
13
|
+
|
|
14
|
+
## Your work
|
|
15
|
+
|
|
16
|
+
${o}
|
|
17
|
+
|
|
18
|
+
## Current wiki pages
|
|
19
|
+
|
|
20
|
+
${c}
|
|
21
|
+
|
|
22
|
+
## Patch kinds
|
|
23
|
+
|
|
24
|
+
- "add": a fact you used or checked that the page lacks.
|
|
25
|
+
- "correct": the page states something your work shows is wrong or out of date. Put the exact wrong text from the page in "previous", and the right value in "value".
|
|
26
|
+
- "create": an entity (person, organization, project, invoice, place\u2026) you dealt with that has no page. Give a one-sentence "summary"; add its facts as separate "add" patches on the same page title.
|
|
27
|
+
|
|
28
|
+
## Rules
|
|
29
|
+
|
|
30
|
+
- Only facts your work shows you checked (a tool result, a system you read) or were told by someone who knows. No guesses, no inferences, nothing from general knowledge.
|
|
31
|
+
- Every patch names its "source": the system, command, URL or person (e.g. "invoice list in the billing app", "owner said in chat"). A patch without a source is dropped.
|
|
32
|
+
- "checkedAt" is the date and time of the work that shows the check (ISO). A patch without it is dropped.
|
|
33
|
+
- One fact per patch: an "attribute" ("phone", "role", "billing status", "due date") and its "value", copied exactly.
|
|
34
|
+
- Never rewrite or summarise a page, and never propose removing a fact.
|
|
35
|
+
- Skip facts a page already states with the same value.
|
|
36
|
+
- Put each fact on the page about its subject. If a page above is about the same thing under another name, use that page (with "correct" when it is out of date) instead of creating a new one. Create a page only when none of the pages above is about the subject.
|
|
37
|
+
- State the fact itself, not the story of how you found it.
|
|
38
|
+
- Do not record facts about the wiki, AgentX, this contribution run or your own tools, unless that is your job.
|
|
39
|
+
- Skip anything you could not verify. "Not checked" or "unknown" is not a fact.
|
|
40
|
+
- At most ${a} patches. Return [] when there is nothing worth adding.
|
|
41
|
+
|
|
42
|
+
Return ONLY a JSON array, no prose, no code fences:
|
|
43
|
+
|
|
44
|
+
[
|
|
45
|
+
{"kind": "add", "page": "Exact Page Title", "attribute": "phone", "value": "+1 555 0100", "source": "contacts app", "checkedAt": "2026-01-31T10:00:00Z"},
|
|
46
|
+
{"kind": "correct", "page": "Exact Page Title", "attribute": "billing status", "previous": "overdue", "value": "paid", "source": "invoice list", "checkedAt": "2026-01-31T10:00:00Z"},
|
|
47
|
+
{"kind": "create", "page": "New Entity Name", "pageType": "person", "summary": "One sentence.", "source": "chat with the owner", "checkedAt": "2026-01-31T10:00:00Z"}
|
|
48
|
+
]`}function Ae(n,r,t={}){let a=n.match(/\[[\s\S]*\]/);if(!a)return[];let o;try{o=JSON.parse(a[0])}catch{return[]}if(!Array.isArray(o))return[];let c=t.now??Date.now(),e=[];for(let d of o){if(!d||typeof d!="object")continue;let u=d,s=u.kind;if(s!=="add"&&s!=="correct"&&s!=="create"&&s!=="remove")continue;let g=I(u.page,120),l=I(u.source,U),m=l.replace(/[\s,;(–—-]*\bchecked\b[^;]*$/i,"").replace(/[\s,;(]+$/,"")||l,k=typeof u.checkedAt=="string"?Date.parse(u.checkedAt):NaN;if(!g||!m||!Number.isFinite(k))continue;let y=I(u.attribute,60),b=I(u.value,U),v=I(u.previous,U),A=I(u.summary,U);if((s==="add"||s==="correct")&&(!y||!b)||s==="remove"&&!y&&!v||s==="create"&&!A)continue;let C=Array.isArray(u.aliases)?u.aliases.map(p=>I(p,120)).filter(Boolean).slice(0,10):[],P=new Date(Math.min(k,c)).toISOString(),i={kind:s,page:g,attribute:y,value:b,previous:v,summary:A,source:m,checkedAt:P,agentId:r};e.push({id:le("sha1").update(JSON.stringify(i)).digest("hex").slice(0,12),kind:s,page:g,source:m,checkedAt:P,agentId:r,...y?{attribute:y}:{},...b?{value:b}:{},...v&&s!=="add"&&s!=="create"?{previous:v}:{},...A&&s==="create"?{summary:A}:{},...s==="create"&&X(u.pageType)?{pageType:u.pageType}:{},...s==="create"&&C.length?{aliases:C}:{}})}return e}function I(n,r){return typeof n=="string"?n.replace(/\s+/g," ").trim().slice(0,r):""}function x(n,r){return n.length>r?`${n.slice(0,r)}\u2026`:n}function W(n){return(n||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}function oe(n){let r=new Map;for(let t of n.listAgents()){if(n.syncedFrom(t))continue;let a=n.getAgentWiki(t);for(let o of a.listAllArticles()){if(o.path.includes("/_versions/"))continue;let c=new Set([o.meta.title,...o.meta.aliases??[]].map(W).filter(Boolean));for(let e of c){let d=r.get(e)??[];d.push({agentId:t,store:a,path:o.path,article:o}),r.set(e,d)}}}return r}function Be(n,r,t={}){let a=t.now??Date.now(),o=new Date(a).toISOString(),c=o.slice(0,10),e=ye(r),d=e.flatMap(i=>i.patches).sort((i,p)=>i.checkedAt.localeCompare(p.checkedAt)),u={at:o,batches:e.map(i=>i.id),agents:[...new Set(e.map(i=>i.agentId))].sort(),patches:d.length,applied:[],pagesUpdated:[],pagesCreated:[],contradictions:[],held:[],duplicates:[],...t.dryRun?{dryRun:!0}:{}},s=[],g=(i,p,h)=>{let f=`h-${i.id}`;s.push({id:f,patch:i,reason:p,heldAt:o,status:"held",...h?.length?{lost:h}:{}}),u.held.push({id:f,page:i.page,attribute:i.attribute,by:i.agentId,reason:p,...h?.length?{lost:h}:{}})},l=oe(n);for(let[,i]of l){let p=[...new Map(i.map(f=>[`${f.agentId}:${f.path}`,f])).values()],h=p[0]?.article.meta.title;p.length>1&&h&&!u.duplicates.some(f=>f.title===h)&&u.duplicates.push({title:h,pages:p.map(f=>`${f.agentId}/${f.path}`)})}let m=new Map;for(let i of d){if(i.kind!=="create")continue;let p=W(i.page);if(l.has(p))continue;let h=m.get(p)??{title:i.page,owner:i.agentId,summaries:[],sources:[],aliases:[],at:i.checkedAt};h.type??=i.pageType,i.summary&&!h.summaries.includes(i.summary)&&h.summaries.push(i.summary),h.sources.includes(i.source)||h.sources.push(i.source);for(let f of i.aliases??[])h.aliases.includes(f)||h.aliases.push(f);m.set(p,h)}for(let i of d){let p=W(i.page);(i.kind==="add"||i.kind==="correct")&&!l.has(p)&&!m.has(p)&&m.set(p,{title:i.page,owner:i.agentId,summaries:[],sources:[i.source],aliases:[],at:i.checkedAt})}let k=[...l.values()].map(i=>i[0]),y=new Map;for(let[i,p]of m){let h=Se(p.title,p.type,k.map(f=>({title:f.article.meta.title,type:f.article.meta.type,ref:`${f.agentId}/${f.path}`})));h&&y.set(i,h)}for(let i of y.keys())m.delete(i);let b=new O(r),v=new Map,A=new Map,C=i=>{let p=l.get(i)?.[0];if(!p)return`new:${i}`;let h=`page:${p.agentId}:${p.path}`;return A.set(h,p),h};for(let i of d){let p=W(i.page),h=y.get(p);if(h&&i.kind!=="remove"){g(i,`possible duplicate of ${h}`);continue}if(i.kind==="create")continue;if(i.kind==="remove"){g(i,"removes a fact");continue}let f=l.get(p)?.[0];if(f&&!f.store.canRead(f.article.meta,i.agentId)){g(i,"the contributing agent cannot read this page");continue}let $=f?.article.meta.title??m.get(p).title,j="planned",R=i.value;if(!t.dryRun){let T=b.write({subject:$,attribute:i.attribute,value:R,source:i.source,verifiedBy:i.agentId,verifiedAt:i.checkedAt},{now:a});if(j=T.status,T.status==="contradiction"){u.contradictions.push({page:$,attribute:i.attribute,value:R,by:i.agentId,questionId:T.questionId});continue}if(T.status==="unchanged")continue;R=T.fact.value}u.applied.push({page:$,attribute:i.attribute,value:R,by:i.agentId,status:j});let Y=v.get(C(p))??[],Z=i.kind==="correct"?i.previous:void 0;Y.push({line:{attribute:i.attribute,value:R,source:i.source,checkedAt:i.checkedAt,by:i.agentId,previous:Z},previous:Z,patch:i}),v.set(C(p),Y)}let P=new Set;for(let[i,p]of v){let h=A.get(i);if(!h)continue;let f=D(h,p,{guard:!0,today:c,dryRun:t.dryRun});if(f.lost)for(let $ of p)g($.patch,"the change would lose facts the page has",f.lost);else if(f.denied)for(let $ of p)g($.patch,`write denied for ${h.agentId}/${h.path}`);else f.changed&&(u.pagesUpdated.push(`${h.agentId}/${h.path}`),t.dryRun||P.add(h.store))}for(let[i,p]of m){let h=v.get(`new:${i}`)??[];if(!p.summaries.length&&!h.length)continue;let f=n.getAgentWiki(p.owner),$=de(f,p.title,p.type);u.pagesCreated.push(`${p.owner}/${$}`),!t.dryRun&&ae(f,$,p,h.map(j=>j.line),c)&&P.add(f)}if(!t.dryRun){for(let p of P)try{p.rebuildIndex()}catch(h){t.log?.(`index rebuild failed: ${h.message}`)}let i=S(r);if(s.length){let p=K(r,{all:!0});L(G(r),[...p,...s.filter(h=>!p.some(f=>f.id===h.id))])}ne(w(i,"merged"),{recursive:!0});for(let p of e)se(w(i,"pending",`${p.id}.json`),w(i,"merged",`${p.id}.json`));L(w(i,"reports",`${o.replace(/[:.]/g,"-")}.json`),u)}return u}function ae(n,r,t,a,o){let c=t.summaries.length?t.summaries.join(" "):`${t.title}.`,{body:e}=ue(`${c}
|
|
49
|
+
|
|
50
|
+
_Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,...t.type?{type:t.type}:{},...t.aliases.length?{aliases:t.aliases}:{},tags:[],owner:t.owner,access:"public",created:o,lastUpdated:o,sources:[J(t.owner,t.at),...a.map(d=>J(d.by,d.checkedAt))].filter((d,u,s)=>s.indexOf(d)===u)},e,t.owner)}var Ie=new Set(["the","and","for","with","von","des","les","der","die","das","une","pour","page","of","de","la","le","du","et"]);function te(n){return new Set((n.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]).filter(r=>(r.length>2||/\d/.test(r))&&!Ie.has(r)))}function Se(n,r,t){let a=te(n);if(a.size<2)return;let o;for(let c of t){if(r&&c.type&&r==="person"!=(c.type==="person"))continue;let e=te(c.title);if(e.size<2)continue;let d=m=>[...m].filter(k=>/\d/.test(k)),[u,s]=[d(a),d(e)];if(u.length&&s.length&&!u.some(m=>s.includes(m)))continue;let g=0;for(let m of a)e.has(m)&&g++;let l=g/Math.min(a.size,e.size);g>=2&&l>=.75&&(!o||l>o.score)&&(o={ref:c.ref,title:c.title,score:l})}return o?`"${o.title}" (${o.ref})`:void 0}function D(n,r,t){let a=n.article.content,{body:o,superseded:c}=ue(a,r.map(s=>s.line));for(let s of r){if(!s.previous||s.previous===s.line.value)continue;let g=ce(o,s.previous,s.line.value);g!==o&&(o=g,c.push(s.previous))}if(t.remove&&(o=Pe(o,t.remove)),o===a)return{changed:!1};if(t.guard){let s=ee(a,o,c);if(s.length)return{changed:!1,lost:s}}if(t.dryRun)return{changed:!0};let e=n.article.meta,d=r.map(s=>J(s.line.by,s.line.checkedAt));return n.store.writeArticle(n.path,{...e,lastUpdated:t.today,sources:[...e.sources,...d].filter((s,g,l)=>l.indexOf(s)===g)},o,e.owner)?{changed:!0}:{changed:!1,denied:!0}}function ce(n,r,t){if(!r)return n;let a=n.indexOf(B),o=a===-1?n:n.slice(0,a),c=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),e=[...o.matchAll(new RegExp(`(?<![\\p{L}\\p{N}])${c}(?![\\p{L}\\p{N}])`,"gu"))];if(e.length!==1)return n;let d=e[0].index;return n.slice(0,d)+t+n.slice(d+r.length)}function Pe(n,r){let t=n;if(r.attribute){let a=r.attribute.toLowerCase();t=t.split(`
|
|
51
|
+
`).filter(o=>o.match(q)?.[1].toLowerCase()!==a).join(`
|
|
52
|
+
`)}return r.text&&(t=ce(t,r.text,"")),t}function De(n,r,t,a={}){let o=K(r,{all:!0}),c=o.find(l=>l.id===t);if(!c)return{ok:!1,error:`no held patch "${t}"`};if(c.status!=="held")return{ok:!1,error:`"${t}" is already ${c.status}`};let e=c.patch,d=a.now??Date.now(),u=new Date(d).toISOString().slice(0,10),s=oe(n).get(W(e.page))?.[0];if(!s){if(e.kind==="remove")return{ok:!1,error:`no page "${e.page}" (it may have been renamed)`};let l=[];if(e.attribute&&e.value){let b=new O(r).write({subject:e.page,attribute:e.attribute,value:e.value,source:e.source,verifiedBy:e.agentId,verifiedAt:e.checkedAt},{now:d});if(b.status==="contradiction")return{ok:!1,error:`the wiki has a newer check of ${e.attribute}; answer question ${b.questionId??"(see wiki questions)"} instead`};l.push({attribute:e.attribute,value:b.fact.value,source:e.source,checkedAt:e.checkedAt,by:e.agentId})}let m=n.getAgentWiki(e.agentId),k=de(m,e.page,e.pageType),y={title:e.page,type:e.pageType,owner:e.agentId,summaries:e.summary?[e.summary]:[],sources:[e.source],aliases:e.aliases??[],at:e.checkedAt};if(!ae(m,k,y,l,u))return{ok:!1,error:`write denied for ${e.agentId}/${k}`};try{m.rebuildIndex()}catch{}return F(r,o,c,"approved",a.by,d,`${e.agentId}/${k}`)}let g;if(e.kind==="remove")g=D(s,[],{guard:!1,today:u,remove:{attribute:e.attribute,text:e.previous}});else{if(!e.attribute||!e.value)return{ok:!1,error:`"${t}" carries no fact to apply`};let l=new O(r).write({subject:s.article.meta.title,attribute:e.attribute,value:e.value,source:e.source,verifiedBy:e.agentId,verifiedAt:e.checkedAt},{now:d});if(l.status==="contradiction")return{ok:!1,error:`the wiki has a newer check of ${e.attribute}; answer question ${l.questionId??"(see wiki questions)"} instead`};let m=e.kind==="correct"?e.previous:void 0;g=D(s,[{line:{attribute:e.attribute,value:l.fact.value,source:e.source,checkedAt:e.checkedAt,by:e.agentId,previous:m},previous:m,patch:e}],{guard:!1,today:u})}if(g.denied)return{ok:!1,error:`write denied for ${s.agentId}/${s.path}`};if(g.changed)try{s.store.rebuildIndex()}catch{}return F(r,o,c,"approved",a.by,d,`${s.agentId}/${s.path}`)}function Fe(n,r,t={}){let a=K(n,{all:!0}),o=a.find(c=>c.id===r);return o?o.status!=="held"?{ok:!1,error:`"${r}" is already ${o.status}`}:F(n,a,o,"rejected",t.by,t.now??Date.now()):{ok:!1,error:`no held patch "${r}"`}}function F(n,r,t,a,o,c,e){let d={...t,status:a,decidedBy:o??"operator",decidedAt:new Date(c).toISOString()};return L(G(n),r.map(u=>u.id===t.id?d:u)),{ok:!0,held:d,...e?{page:e}:{}}}var q=/^- \*\*(.+?):\*\* /;function ue(n,r){if(r.length===0)return{body:n,superseded:[]};let t=n.replace(/\s+$/,"").split(`
|
|
53
|
+
`),a=t.findIndex(s=>s.trim()===B),o=t,c=[],e=[];if(a!==-1){o=t.slice(0,a);let s=t.slice(a+1),g=s.findIndex(l=>/^#{1,2} /.test(l));c=(g===-1?s:s.slice(0,g)).filter(l=>l.trim()),e=g===-1?[]:s.slice(g)}let d=[];for(let s of r){let g=c.findIndex(b=>b.match(q)?.[1].toLowerCase()===s.attribute.toLowerCase()),l=g===-1?void 0:Re(c[g]);g!==-1&&d.push(c[g]);let m=l&&l.value===s.value?l.previous:l?`${l.value}, checked ${l.checkedAt}`:s.previous,k=c[g]?.match(q)?.[1]??s.attribute,y=Ce({...s,attribute:k,previous:m});g===-1?c.push(y):c[g]=y}let u=[...o.some(s=>s.trim())?[...o,""]:[],B,"",...c];return e.length&&u.push("",...e),{body:u.join(`
|
|
54
|
+
`).replace(/\n{3,}/g,`
|
|
55
|
+
|
|
56
|
+
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
+
//# sourceMappingURL=contributions-5OEZWYXI.js.map
|