agentix-cli 0.200.1 → 0.201.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +1 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +67 -2
- package/dist/{App-AUKNCAVD.js → App-UHSMBGRE.js} +2 -2
- package/dist/{ChatApp-KYQIQZ6Q.js → ChatApp-Z6YVST7J.js} +2 -2
- package/dist/{absorb-eval-TJN5WUYZ.js → absorb-eval-4GDAAYBL.js} +2 -2
- package/dist/{adapter-VLNSNP6C.js → adapter-IITFGDOV.js} +2 -2
- package/dist/{agent-KXHSNUNY.js → agent-T7HRXIBL.js} +2 -2
- package/dist/{board-dashboard-QKOJEHXS.js → board-dashboard-QXYD62AT.js} +4 -4
- package/dist/{chunk-TBSPEM7I.js → chunk-2BK25FAQ.js} +2 -2
- package/dist/{chunk-QISI5WM2.js → chunk-2N6LROEF.js} +2 -2
- package/dist/{chunk-ORAQRC6A.js → chunk-4LUZO3AP.js} +2 -2
- package/dist/{chunk-3I3TBJZV.js → chunk-5OREKHSP.js} +6 -6
- package/dist/{chunk-64UGFZPX.js → chunk-5TW7QEVK.js} +2 -2
- package/dist/{chunk-KE4SLJTC.js → chunk-6YWB3XTT.js} +2 -2
- package/dist/{chunk-EM72LW2F.js → chunk-7TO4QLFS.js} +2 -2
- package/dist/{chunk-K34LYNGN.js → chunk-BTI3OUFH.js} +2 -2
- package/dist/{chunk-6RJ7ERGC.js → chunk-EVRLNHIC.js} +2 -2
- package/dist/{chunk-4MJOSO7T.js → chunk-FLSEPYM3.js} +2 -2
- package/dist/{chunk-J4AMQF7D.js → chunk-H6FFWHJH.js} +2 -2
- package/dist/{chunk-SXL6R3HH.js → chunk-HUN2UIYB.js} +2 -2
- package/dist/{chunk-LBIU3OWW.js → chunk-KAAAB3W3.js} +5 -5
- package/dist/{chunk-O672XL5L.js → chunk-KUAJUHMB.js} +2 -2
- package/dist/{chunk-W764F42W.js → chunk-LCVKEIG2.js} +2 -2
- package/dist/{chunk-APULKE2J.js → chunk-LPSDAS22.js} +2 -2
- package/dist/{chunk-AHJ6FEHW.js → chunk-MXB47GPG.js} +2 -2
- package/dist/{chunk-M6EQBW2F.js → chunk-NDBM7DTN.js} +2 -2
- package/dist/{chunk-RW2JLP5P.js → chunk-O62HITS4.js} +2 -2
- package/dist/{chunk-25U5MNNF.js → chunk-OD2GONCQ.js} +2 -2
- package/dist/{chunk-AKDJGDLN.js → chunk-ORICHN2H.js} +2 -2
- package/dist/{chunk-UBLPD6DK.js → chunk-QCCVHEKZ.js} +2 -2
- package/dist/{chunk-KOZSBUXJ.js → chunk-T4BWPILH.js} +2 -2
- package/dist/{chunk-QMFNIUW7.js → chunk-TTHY22I4.js} +2 -2
- package/dist/{chunk-BNTN3LKN.js → chunk-VVFJCGX7.js} +2 -2
- package/dist/{chunk-7VHE7WLJ.js → chunk-XDFPXEXU.js} +3 -3
- package/dist/{chunk-R5TCPLWF.js → chunk-XPL6F4HL.js} +2 -2
- package/dist/{chunk-6QVUXEVK.js → chunk-YHLKEGIC.js} +2 -2
- package/dist/{chunk-QTOOFB4N.js → chunk-YV2SLQIL.js} +2 -2
- package/dist/{chunk-QTOOFB4N.js.map → chunk-YV2SLQIL.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{client-FXU56BIM.js → client-HJBH2DVH.js} +2 -2
- package/dist/{config-IOQKEH47.js → config-QBTOYJA7.js} +2 -2
- package/dist/{config-mutate-633Q77K3.js → config-mutate-G46QCYCR.js} +2 -2
- package/dist/{config-mutator-LRZHJ3UN.js → config-mutator-3FGEZPF3.js} +2 -2
- package/dist/{contributions-3AE43OSI.js → contributions-OOPYQSLO.js} +2 -2
- package/dist/{doctor-KCRL67QL.js → doctor-2KOQNH44.js} +2 -2
- package/dist/{follow-up-tool-WLDWTZRW.js → follow-up-tool-K252F4QA.js} +2 -2
- package/dist/{hub-PG4OFRIQ.js → hub-E56MSG7W.js} +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/{program-QHE7PH65.js → program-3NLSKRKW.js} +23 -23
- package/dist/{promote-DLM7N6V2.js → promote-GWDQR2DT.js} +2 -2
- package/dist/{query-TBQGAIZG.js → query-PYJN4G32.js} +2 -2
- package/dist/{query-settings-U6XNO5V4.js → query-settings-XFOY343Z.js} +2 -2
- package/dist/{registry-DGGJJOVA.js → registry-EMB3QRRL.js} +2 -2
- package/dist/{request-planner-YQ4RTZNU.js → request-planner-DP3PIMNQ.js} +2 -2
- package/dist/{review-candidates-OE5HDVWI.js → review-candidates-5HRRFPEG.js} +2 -2
- package/dist/{routing-RAG6I37K.js → routing-LX5QYMZW.js} +2 -2
- package/dist/schedule-tool-HD72JVUS.js +2 -0
- package/dist/{scheduler-TGP4B5KZ.js → scheduler-UN5ZPEK4.js} +2 -2
- package/dist/{seat-74G2KLZQ.js → seat-2RFBH5N2.js} +2 -2
- package/dist/{select-P7565K5D.js → select-MOZ2GNNR.js} +2 -2
- package/dist/{set-enabled-DE3TKKEK.js → set-enabled-IFK2TCH5.js} +2 -2
- package/dist/{sprint-tool-CK3SD4NZ.js → sprint-tool-WB2M7RHX.js} +2 -2
- package/dist/{tool-X6DAR3KL.js → tool-57ZGZ7BD.js} +2 -2
- package/dist/{tool-XGB3PMXA.js → tool-CMHNG2PN.js} +2 -2
- package/dist/{tool-DWKCESVE.js → tool-SKQNMJP2.js} +2 -2
- package/dist/{wiki-E45S2K6F.js → wiki-K77I5LJP.js} +2 -2
- package/dist/wiki-enrich-PK5XQCV3.js +2 -0
- package/package.json +1 -1
- package/dist/schedule-tool-O5FJXSKO.js +0 -2
- package/dist/wiki-enrich-LREINNTK.js +0 -2
- /package/dist/{App-AUKNCAVD.js.map → App-UHSMBGRE.js.map} +0 -0
- /package/dist/{ChatApp-KYQIQZ6Q.js.map → ChatApp-Z6YVST7J.js.map} +0 -0
- /package/dist/{absorb-eval-TJN5WUYZ.js.map → absorb-eval-4GDAAYBL.js.map} +0 -0
- /package/dist/{adapter-VLNSNP6C.js.map → adapter-IITFGDOV.js.map} +0 -0
- /package/dist/{agent-KXHSNUNY.js.map → agent-T7HRXIBL.js.map} +0 -0
- /package/dist/{board-dashboard-QKOJEHXS.js.map → board-dashboard-QXYD62AT.js.map} +0 -0
- /package/dist/{chunk-TBSPEM7I.js.map → chunk-2BK25FAQ.js.map} +0 -0
- /package/dist/{chunk-QISI5WM2.js.map → chunk-2N6LROEF.js.map} +0 -0
- /package/dist/{chunk-ORAQRC6A.js.map → chunk-4LUZO3AP.js.map} +0 -0
- /package/dist/{chunk-3I3TBJZV.js.map → chunk-5OREKHSP.js.map} +0 -0
- /package/dist/{chunk-64UGFZPX.js.map → chunk-5TW7QEVK.js.map} +0 -0
- /package/dist/{chunk-KE4SLJTC.js.map → chunk-6YWB3XTT.js.map} +0 -0
- /package/dist/{chunk-EM72LW2F.js.map → chunk-7TO4QLFS.js.map} +0 -0
- /package/dist/{chunk-K34LYNGN.js.map → chunk-BTI3OUFH.js.map} +0 -0
- /package/dist/{chunk-6RJ7ERGC.js.map → chunk-EVRLNHIC.js.map} +0 -0
- /package/dist/{chunk-4MJOSO7T.js.map → chunk-FLSEPYM3.js.map} +0 -0
- /package/dist/{chunk-J4AMQF7D.js.map → chunk-H6FFWHJH.js.map} +0 -0
- /package/dist/{chunk-SXL6R3HH.js.map → chunk-HUN2UIYB.js.map} +0 -0
- /package/dist/{chunk-LBIU3OWW.js.map → chunk-KAAAB3W3.js.map} +0 -0
- /package/dist/{chunk-O672XL5L.js.map → chunk-KUAJUHMB.js.map} +0 -0
- /package/dist/{chunk-W764F42W.js.map → chunk-LCVKEIG2.js.map} +0 -0
- /package/dist/{chunk-APULKE2J.js.map → chunk-LPSDAS22.js.map} +0 -0
- /package/dist/{chunk-AHJ6FEHW.js.map → chunk-MXB47GPG.js.map} +0 -0
- /package/dist/{chunk-M6EQBW2F.js.map → chunk-NDBM7DTN.js.map} +0 -0
- /package/dist/{chunk-RW2JLP5P.js.map → chunk-O62HITS4.js.map} +0 -0
- /package/dist/{chunk-25U5MNNF.js.map → chunk-OD2GONCQ.js.map} +0 -0
- /package/dist/{chunk-AKDJGDLN.js.map → chunk-ORICHN2H.js.map} +0 -0
- /package/dist/{chunk-UBLPD6DK.js.map → chunk-QCCVHEKZ.js.map} +0 -0
- /package/dist/{chunk-KOZSBUXJ.js.map → chunk-T4BWPILH.js.map} +0 -0
- /package/dist/{chunk-QMFNIUW7.js.map → chunk-TTHY22I4.js.map} +0 -0
- /package/dist/{chunk-BNTN3LKN.js.map → chunk-VVFJCGX7.js.map} +0 -0
- /package/dist/{chunk-7VHE7WLJ.js.map → chunk-XDFPXEXU.js.map} +0 -0
- /package/dist/{chunk-R5TCPLWF.js.map → chunk-XPL6F4HL.js.map} +0 -0
- /package/dist/{chunk-6QVUXEVK.js.map → chunk-YHLKEGIC.js.map} +0 -0
- /package/dist/{client-FXU56BIM.js.map → client-HJBH2DVH.js.map} +0 -0
- /package/dist/{config-IOQKEH47.js.map → config-QBTOYJA7.js.map} +0 -0
- /package/dist/{config-mutate-633Q77K3.js.map → config-mutate-G46QCYCR.js.map} +0 -0
- /package/dist/{config-mutator-LRZHJ3UN.js.map → config-mutator-3FGEZPF3.js.map} +0 -0
- /package/dist/{contributions-3AE43OSI.js.map → contributions-OOPYQSLO.js.map} +0 -0
- /package/dist/{doctor-KCRL67QL.js.map → doctor-2KOQNH44.js.map} +0 -0
- /package/dist/{follow-up-tool-WLDWTZRW.js.map → follow-up-tool-K252F4QA.js.map} +0 -0
- /package/dist/{hub-PG4OFRIQ.js.map → hub-E56MSG7W.js.map} +0 -0
- /package/dist/{program-QHE7PH65.js.map → program-3NLSKRKW.js.map} +0 -0
- /package/dist/{promote-DLM7N6V2.js.map → promote-GWDQR2DT.js.map} +0 -0
- /package/dist/{query-TBQGAIZG.js.map → query-PYJN4G32.js.map} +0 -0
- /package/dist/{query-settings-U6XNO5V4.js.map → query-settings-XFOY343Z.js.map} +0 -0
- /package/dist/{registry-DGGJJOVA.js.map → registry-EMB3QRRL.js.map} +0 -0
- /package/dist/{request-planner-YQ4RTZNU.js.map → request-planner-DP3PIMNQ.js.map} +0 -0
- /package/dist/{review-candidates-OE5HDVWI.js.map → review-candidates-5HRRFPEG.js.map} +0 -0
- /package/dist/{routing-RAG6I37K.js.map → routing-LX5QYMZW.js.map} +0 -0
- /package/dist/{schedule-tool-O5FJXSKO.js.map → schedule-tool-HD72JVUS.js.map} +0 -0
- /package/dist/{scheduler-TGP4B5KZ.js.map → scheduler-UN5ZPEK4.js.map} +0 -0
- /package/dist/{seat-74G2KLZQ.js.map → seat-2RFBH5N2.js.map} +0 -0
- /package/dist/{select-P7565K5D.js.map → select-MOZ2GNNR.js.map} +0 -0
- /package/dist/{set-enabled-DE3TKKEK.js.map → set-enabled-IFK2TCH5.js.map} +0 -0
- /package/dist/{sprint-tool-CK3SD4NZ.js.map → sprint-tool-WB2M7RHX.js.map} +0 -0
- /package/dist/{tool-X6DAR3KL.js.map → tool-57ZGZ7BD.js.map} +0 -0
- /package/dist/{tool-XGB3PMXA.js.map → tool-CMHNG2PN.js.map} +0 -0
- /package/dist/{tool-DWKCESVE.js.map → tool-SKQNMJP2.js.map} +0 -0
- /package/dist/{wiki-E45S2K6F.js.map → wiki-K77I5LJP.js.map} +0 -0
- /package/dist/{wiki-enrich-LREINNTK.js.map → wiki-enrich-PK5XQCV3.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{A,G as I,I as k,K as E,N as T,q as C,x as O}from"./chunk-
|
|
1
|
+
import{A,G as I,I as k,K as E,N as T,q as C,x as O}from"./chunk-OD2GONCQ.js";import{a as P}from"./chunk-OSH2PEBH.js";import{Eb as R,Ob as X}from"./chunk-YV2SLQIL.js";X();import{Command as z}from"commander";import g from"chalk";import{execFileSync as m}from"child_process";import{accessSync as _,constants as M,existsSync as w,readFileSync as b,readdirSync as S,statSync as J}from"fs";import{join as H,resolve as y}from"path";import{homedir as Z}from"os";import{createRequire as G}from"module";var x='run agentx notify "Hello" --title "Test"';function B(t,n){return t==="windows"?{fallback:"Windows PowerShell, and show its name",settings:"Open Settings \u203A System \u203A Notifications, turn notifications on, then turn on AgentX Helper and its banners.",missingFix:`${C(n)} Then ${x}.`,updateFix:`${C(n).replace(/^Put /,"Put a newer ")}`,osName:"Windows"}:{fallback:"Script Editor and show its icon",settings:"Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.",missingFix:`Run agentx desktop install, then ${x} and click Allow.`,updateFix:"Run agentx desktop install to update it.",osName:"macOS"}}async function W(t={}){let n=t.platform??process.platform,e=t.helper===void 0?I():t.helper,i=k({},{platform:n,io:{capture:t.run,helper:e}}),s=i.banner;if(!s)return{state:"unsupported",message:"Desktop banners are only shown on macOS and Windows."};let o=B(i.os,n),a=await s.status();return a==="missing"?{state:"missing",message:`AgentX Helper is not installed, so banners come from ${o.fallback}.`,fix:o.missingFix}:a==="outdated"?{state:"outdated",path:e,message:"AgentX Helper is too old to report whether it may notify.",fix:o.updateFix}:a==="not-asked"?{state:"not-asked",path:e,message:`${o.osName} has not asked yet whether AgentX Helper may notify; banners come from ${o.fallback} until it does.`,fix:`${x[0].toUpperCase()}${x.slice(1)} and click Allow when ${o.osName} asks.`}:a==="not-allowed"?{state:"not-allowed",path:e,message:`${o.osName} does not allow AgentX Helper to notify, so banners come from ${o.fallback}.`,fix:o.settings}:a==="hidden"?{state:"hidden",path:e,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:o.settings}:{state:"ready",path:e,message:"AgentX Helper posts banners with the AgentX icon."}}async function K(t={}){let n=[];await ee(n),te(n);let e=ne(n);return e&&ie(n,e),e&&ae(n,e),e&&le(n,e),e&&de(n,e),e&&oe(n,e),e&&pe(n,e),e&&await U(n,e),e&&Y(n,e),e&&await V(n,e),e&&Q(n,e),t.running!==!1&&e&&await ue(n,e),{checks:n,summary:F(n)}}var Ee=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 K({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ge(n),process.exit(e.errors>0?1:0)});async function U(t,n,e=W){if(!E(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})}async function V(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(o){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:o?.message??String(o)});return}let s=["tasks","notes","banner","sound","focus"].filter(o=>i[o]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${s.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function Q(t,n,e=process.cwd(),i=k(n)){let s=n.native?.mirror;if(!s?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let o=T(e),a=Object.values(o.items),l=a.filter(f=>f.state==="open").length,u=a.filter(f=>f.state==="failed").length;t.push({severity:o.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${s.list}"${u?`, ${u} could not be added`:""}`,detail:o.lastError?`Last error ${o.lastError.at}: ${o.lastError.message}`:void 0,fix:o.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function Y(t,n,e=process.platform,i=s=>{try{return _(s,M.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 o=s.command||"remindctl",a=o.includes("/")?i(o)?o:null:A(o,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:`${o} 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 ee(t){let n=P(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 m(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=m("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 o=e("codex");if(o){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:o})}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=m("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{G(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 te(t){if(process.platform!=="darwin")return;let n=H(Z(),"Library/LaunchAgents"),e=[];try{e=S(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return _(s,M.X_OK),!0}catch{return!1}};for(let s of e){let o=O(b(H(n,s),"utf-8")),a=A("ffmpeg",o,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 ${o}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ne(t){let n=y(process.cwd(),"agentx.json");if(!w(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{R(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 m(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 m(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 o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function ie(t,n){let e=new Set;if(N(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=D(),s=[],o=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?s.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&o.push(a)}s.length===0&&o.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(s.length>0&&t.push({severity:"fail",group:"Secrets",title:`${s.length} env var(s) referenced in agentx.json but missing`,detail:s.join(", "),fix:`Add to .env \u2014 e.g. ${s[0]}=<value>`}),o.length>0&&t.push({severity:"warn",group:"Secrets",title:`${o.length} env var(s) set but empty`,detail:o.join(", ")}))}function D(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function se(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",s=[];for(let o of t){let a=(o.token??"").trim();a?n&&a===n&&s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):s.push({severity:"warn",group:"Mesh",title:`mesh peer "${o.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&s.length===0&&s.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),s}function oe(t,n){t.push(...re(n))}function re(t,n=process.env,e=D()){let i=a=>(n[a]||e[a]||"").trim(),s=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,o=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:s(a.token)}));return se(o,i("MESH_TOKEN")||void 0)}function N(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)N(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))N(e,n)}function ae(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let o=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);try{J(o).isDirectory()||e.push(`${i}: ${o} (exists but not a directory)`)}catch{e.push(`${i}: ${o}`)}}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 le(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let a=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let f;try{f=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=f.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:s,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=f.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${h.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 de(t,n){let e=n.webhooks??[],i=[],s=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),o=new Set;try{if(w(s))for(let r of S(s))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&o.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.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 r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))o.size>0&&!o.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&o.size>0&&!o.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(s)){for(let r of S(s))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(s,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" 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(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.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 r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let f=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}f.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.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[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?f.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=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[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let j=`${p.kind}::${p.label}`;h.has(j)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(j),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${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 r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function ce(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 ue(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,o=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(o),!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=ce(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 pe(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=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=m("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,o]of e){if(!o.workspace||!w(o.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${o.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(o.workspace,".codegraph","codegraph.db");w(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 ${o.workspace}\` to build it now.`})}}function F(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 ge(t){console.log(),console.log(g.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(g.bold(" "+i));for(let o of s){let a=o.severity==="ok"?g.green("\u2713"):o.severity==="warn"?g.yellow("!"):g.red("\u2717");console.log(` ${a} ${o.title}`),o.detail&&console.log(g.dim(" "+o.detail.replace(/\n/g,`
|
|
6
6
|
`))),o.fix&&console.log(g.dim(" \u2192 "+o.fix))}console.log()}let e=F(t);e.errors>0?console.log(g.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?g.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(g.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+g.dim(" Review but not blocking.")):console.log(g.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{W as a,K as b,Ee as c,U as d,V as e,Q as f,Y as g,se as h,re as i,ce as j};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-6YWB3XTT.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ve,b as k,c as D,d as Qe,e as ue,f as me,g as L,h as fe,i as N,j,n as Ze,o as ea,p as aa,q as ta}from"./chunk-EFGAPAYZ.js";import{e as Xe,i as Ge}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Je}from"./chunk-
|
|
1
|
+
import{a as Ve,b as k,c as D,d as Qe,e as ue,f as me,g as L,h as fe,i as N,j,n as Ze,o as ea,p as aa,q as ta}from"./chunk-EFGAPAYZ.js";import{e as Xe,i as Ge}from"./chunk-QAWKN2N4.js";import{b as ge}from"./chunk-DODL5POT.js";import{a as Q,b as Je}from"./chunk-FLSEPYM3.js";import{Ja as Ue,Ka as Fe,La as qe,Na as Ke,ja as _,oa as Be,xb as Ye}from"./chunk-ORICHN2H.js";import{a as G}from"./chunk-IMLAPB7G.js";import{k as je}from"./chunk-T4BWPILH.js";import{b as V}from"./chunk-2VDO2HEK.js";import{c as He,e as Le}from"./chunk-LQE73AZR.js";import{b as We}from"./chunk-MRIVENBY.js";import{q as xe,s as Ne}from"./chunk-XPZSEDE3.js";import{ga as X}from"./chunk-BTI3OUFH.js";import{b as pe}from"./chunk-7AB3QUGH.js";import{a as q,b as J}from"./chunk-O62HITS4.js";import{a as Me}from"./chunk-XPL6F4HL.js";import{c as Re,d as Oe}from"./chunk-OWNQ2FD4.js";import{a as De}from"./chunk-ROLSSYXE.js";import{a as Pe}from"./chunk-QUFIUXMQ.js";import{Ab as le,Db as F,Eb as Ee,Ob as ce,Za as ze,eb as Za,ja as de,ka as Ie,ua as Qa}from"./chunk-YV2SLQIL.js";import{existsSync as K,readFileSync as ca,writeFileSync as pa,appendFileSync as st,mkdirSync as dt}from"fs";import{dirname as lt,resolve as M}from"path";import{fileURLToPath as ct}from"url";import{hostname as pt}from"os";import{spawn as xt}from"child_process";var he=`:root {
|
|
2
2
|
/* --- Brand (agentina) --------------------------------------------- */
|
|
3
3
|
--ax-blue: #2979FF;
|
|
4
4
|
--ax-blue-d: #1B5FD9;
|
|
@@ -2904,4 +2904,4 @@ ${a}=${t}
|
|
|
2904
2904
|
${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function ri(e,a){return Ua(e,a,de,"ORDER BY created_at")}function ni(e,a,t=50){return Ua(e,a,[...de,...Ie],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}Za();var Te="member:",gr=90,ur="members",mr="tailscale-user-login",fr=400,hr=60*60*1e3;function br(e){let a=e.scopes.find(t=>t.startsWith(Te));return a?a.slice(Te.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?br(t):null;return t&&r?{rec:t,personId:r}:null}function pi(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${Te}${t.id}`],expiresInDays:gr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var vr=Math.round(He/6e4);function wr(e){return e==="client"?"Your project":"My work"}function xi(e){let a=wr(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${Le(e.code)}`,` The code works once, for ${vr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
|
|
2905
2905
|
`)}var yr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",kr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function $r(e){if(!Ya(e))return null;let a=Ka(e,mr).toLowerCase();return a?a.slice(0,80):null}function _r(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function Sr(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Ar(e){return e.identities.map(ze).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function gi(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=_r(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await V(e,2048);s=b.code,d=Sr(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Tr(t,a.minMs??fr),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=$r(e),f=Ar(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:yr}};let C=d||"Unnamed machine",y=u.name.slice(0,40),v=Ne(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:ur},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:C,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:C}),n(`[member] ${g} paired "${C}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:C,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:kr}})}var se="this machine is not paired",Cr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function ui(e,a){return a.state==="pending"&&a.cardId?Ja(xe(e,a.cardId)):null}function mi(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:se};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:se};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:se};if(d.state==="pending"){let c=d.cardId?xe(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:se}}else return{ok:!1,status:403,error:Cr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=hr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function fi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Tr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ir(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function vi(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function wi(e){let{summary:a}=Q(t=>Ir(t,e?.channel,!!e?.enabled));return{summary:a}}var ki="https://myaccount.google.com/apppasswords";function $i(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function _i(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function Si(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function Ti(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function Ii(e,a){return je({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function zi(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
|
|
2906
2906
|
`)}}function Pi(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ri(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Oi(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Di(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var zr="https://ntfy.sh";function Hi(e){return{enabled:!!e?.enabled,server:e?.server||zr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Li(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}export{he as a,ia as b,ve as c,tt as d,rt as e,nt as f,xa as g,gt as h,Sn as i,An as j,Cn as k,$o as l,ir as m,Co as n,Eo as o,Ba as p,Qo as q,Zo as r,On as s,Dn as t,Ct as u,zt as v,we as w,Mn as x,Hn as y,Et as z,Un as A,Fn as B,qn as C,ti as D,ri as E,ni as F,gr as G,ur as H,pi as I,vr as J,wr as K,xi as L,yr as M,kr as N,$r as O,_r as P,Sr as Q,Ar as R,gi as S,Ja as T,ui as U,mi as V,Xa as W,fi as X,Ga as Y,Ir as Z,vi as _,wi as $,ki as aa,$i as ba,_i as ca,Si as da,Ti as ea,Ii as fa,zi as ga,Pi as ha,Ri as ia,Oi as ja,Di as ka,Hi as la,Li as ma,Gt as na,uo as oa,wo as pa,yo as qa};
|
|
2907
|
-
//# sourceMappingURL=chunk-
|
|
2907
|
+
//# sourceMappingURL=chunk-7TO4QLFS.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as pe}from"./chunk-7AB3QUGH.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{c as Ft}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ht,c as Bt}from"./chunk-VJVXEVZ7.js";import{b as jt,f as Mt,g as Et,j as _t,l as Lt,m as Ut,s as Kt}from"./chunk-
|
|
1
|
+
import{a as pe}from"./chunk-7AB3QUGH.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{c as Ft}from"./chunk-SZDACK6O.js";import{b as Le}from"./chunk-AFRHKA7B.js";import{b as Ht,c as Bt}from"./chunk-VJVXEVZ7.js";import{b as jt,f as Mt,g as Et,j as _t,l as Lt,m as Ut,s as Kt}from"./chunk-TTHY22I4.js";import{b as Ot,d as Nt,e as Dt}from"./chunk-5ONH4ITT.js";import{e as Pt,g as Tt,h as Wt,i as _e}from"./chunk-JRAG37V5.js";import{y as St,z as Ir}from"./chunk-EVRLNHIC.js";import{b as $t,f as br}from"./chunk-72SZI2UW.js";import{a as te,b as xt}from"./chunk-A7JSRDJL.js";import{a as At,b as Ee,d as Ce,e as Rt,f as Fe}from"./chunk-BERWTVG2.js";import{c as It,d as vt}from"./chunk-AHWWJ7AF.js";import{ja as Me,ua as kr}from"./chunk-YV2SLQIL.js";import{j as je,r as yr}from"./chunk-UEEB3UTU.js";import{existsSync as vr,mkdirSync as qt,readFileSync as $r,writeFileSync as Sr,renameSync as Ar}from"fs";import{resolve as Jt,dirname as Rr}from"path";var zt=class{filePath;log;constructor(e={}){let t=e.baseDir??Jt(process.cwd(),".agentx");this.filePath=Jt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),qt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!vr(this.filePath))return{version:1,overrides:{}};try{let e=$r(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){qt(Rr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Sr(t,JSON.stringify(e,null,2)),Ar(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Zt,writeFileSync as Ue,appendFileSync as Wr,mkdirSync as Or,existsSync as Xt,statSync as Nr}from"fs";import{resolve as fe}from"path";var Yt="[Agent Memory \u2014 persistent facts from past conversations]",xr=2400;function Gt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Pr(n,e=Date.now()){let t=Nt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Gt(t,Pt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Tr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(te(n.content))return{line:`- [${n.category}] ${xt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Wt(n,e);return{line:`- [${n.category}] ${Gt(o,Tt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Vt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Yt.length,a=!1;for(let i of n){let d=e.length>0?Dt(i.content,e):null,l,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),l=Pr(d,t),c=d.id}else l=Tr(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?_e.length:0;if(s+f+l.line.length>xr)break;r.push({fact:i,...l,...c?{wikiRef:c}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Qt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[_e]:[];return[Yt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var en=200,Dr=7,tn=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=fe(e,".agentx/memory"),this.ledger=new Ot(fe(e,".agentx/wiki")),Xt(this.memoryDir)||Or(this.memoryDir,{recursive:!0})}filePath(e){return fe(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ee(t.content)||te(t.content))return!1;let r=t.source.trust??At(t.source.channel),o=t.review??Rt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Wr(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Xt(t))return[];try{let{mtimeMs:r,size:o}=Nr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Zt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Fe);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=fe(this.memoryDir,`${t}_bm25_cache.json`),i=vt(s,a),d=It(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Qt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Vt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Ue(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -39,4 +39,4 @@ ${n.text}`}async function xe(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
39
39
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(ht(this.file))try{let e=JSON.parse(wt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){er(rr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${sr(4).toString("hex")}.tmp`;nr(t,JSON.stringify(e,null,2)+`
|
|
40
40
|
`,{encoding:"utf-8",mode:384}),tr(t,this.file)}};import{extname as si}from"path";var ar=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,dr=/<agentx-artifact>[\s\S]*$/i;function _l(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(ar,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,c=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(dr,""):s).trim(),artifacts:r}}function Ll(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(ar,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(dr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ii={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Ul={bytes:20*1024*1024,perMessage:20,pathChars:512};function Hl(n){return ii[si(n).toLowerCase()]??null}var ai=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
41
41
|
`);function Bl(n,e,t){return n==="app"&&e&&t!==!1?ai:void 0}import{lstatSync as kt,mkdirSync as di,readdirSync as li,realpathSync as yt,unlinkSync as ui}from"fs";import{join as Ne,resolve as lr}from"path";var ur=".agentx/outbox",ci=7*24*60*60*1e3;function pi(n,e){try{let t=yt(lr(e,n)),r=Ne(t,ur);return yt(r)===r&&kt(r).isDirectory()?r:null}catch{return null}}function zl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=yt(lr(t,n));kt(Ne(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||di(Ne(o,ur),{recursive:!0})}catch{return 0}let r=pi(n,t);return r?cr(r,(e.now??Date.now())-(e.maxAgeMs??ci)):0}function cr(n,e){let t=0;for(let r of li(n)){let o=Ne(n,r);try{let s=kt(o);s.isDirectory()?t+=cr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(ui(o),t++)}catch{}}return t}export{zt as a,tn as b,nn as c,Wi as d,Er as e,Oi as f,Fr as g,ji as h,Mi as i,Ei as j,Ci as k,Fi as l,_i as m,Li as n,Ur as o,Ui as p,Hi as q,Ji as r,qe as s,Gr as t,zi as u,Yi as v,Vr as w,Gi as x,un as y,Zi as z,Xi as A,pn as B,fn as C,to as D,oa as E,sa as F,da as G,la as H,x as I,ne as J,S as K,ze as L,yo as M,Ve as N,L as O,Xe as P,tt as Q,pt as R,As as S,Os as T,gt as U,Eo as V,qs as W,al as X,dl as Y,ll as Z,ul as _,cl as $,Js as aa,zs as ba,pl as ca,fl as da,gl as ea,ml as fa,yl as ga,kl as ha,bl as ia,Il as ja,vl as ka,$l as la,Sl as ma,Al as na,Rl as oa,xl as pa,Pl as qa,Xs as ra,Tl as sa,Wl as ta,Ol as ua,Nl as va,ir as wa,_l as xa,Ll as ya,Ul as za,Hl as Aa,Bl as Ba,ur as Ca,zl as Da};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
42
|
+
//# sourceMappingURL=chunk-BTI3OUFH.js.map
|
|
@@ -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-DCIYOPJF.js";import{Nb as tt,Ob as nt}from"./chunk-
|
|
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-DCIYOPJF.js";import{Nb as tt,Ob as nt}from"./chunk-YV2SLQIL.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-EVRLNHIC.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Eb as l,Ob as m}from"./chunk-
|
|
1
|
+
import{Eb as l,Ob as m}from"./chunk-YV2SLQIL.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
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
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-
|
|
4
|
+
//# sourceMappingURL=chunk-FLSEPYM3.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-EVRLNHIC.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-H6FFWHJH.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-XDFPXEXU.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
|
|
2
2
|
`)}).join(`
|
|
3
3
|
|
|
4
4
|
---
|
|
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
|
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
16
|
`}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-HUN2UIYB.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ba as ko,Da as vo,G as uo,N as Ft,O as lo,V as Ut,X as go,a as Kr,b as zr,d as On,f as tt,ha as po,i as ro,ia as mo,j as oo,ja as fo,k as Nt,la as ho,ma as yo,n as Bt,na as wo,oa as bo,q as io,r as ao,ra as xo,sa as So,v as co,va as Io,wa as To}from"./chunk-
|
|
1
|
+
import{Ba as ko,Da as vo,G as uo,N as Ft,O as lo,V as Ut,X as go,a as Kr,b as zr,d as On,f as tt,ha as po,i as ro,ia as mo,j as oo,ja as fo,k as Nt,la as ho,ma as yo,n as Bt,na as wo,oa as bo,q as io,r as ao,ra as xo,sa as So,v as co,va as Io,wa as To}from"./chunk-BTI3OUFH.js";import{b as Jr}from"./chunk-MEFPXHQJ.js";import{a as Bn}from"./chunk-W4YR2RO2.js";import{a as Gr}from"./chunk-VJVXEVZ7.js";import{b as Xr,d as Nn,e as Zr,f as Lt,i as Vr}from"./chunk-TTHY22I4.js";import{h as Wr,i as qr}from"./chunk-BE64IJWM.js";import{a as Dn,b as Qr}from"./chunk-J3SOEFRE.js";import{a as Ln,b as Yr}from"./chunk-SIU6STB2.js";import{e as eo,i as to,j as no,k as so}from"./chunk-X5C5W3E4.js";import{d as Fr}from"./chunk-HPRLRD4P.js";import{a as jr}from"./chunk-XPL6F4HL.js";import{g as Ur,h as Hr}from"./chunk-NDBM7DTN.js";import{c as vr,f as Ar}from"./chunk-H6FFWHJH.js";import{s as Tr,v as Dt,w as kr,y as xe,z as Pn}from"./chunk-EVRLNHIC.js";import{a as et,b as Ue,f as Ot}from"./chunk-72SZI2UW.js";import{a as Fe,b as Cn}from"./chunk-FCPTN6NF.js";import{a as $r,c as Cr}from"./chunk-MYVHVJWZ.js";import{e as He,h as Mr,i as Re}from"./chunk-QUFIUXMQ.js";import{a as Rr,b as _r,c as Pr,d as Er,l as Or}from"./chunk-AV7T3SYT.js";import{a as Dr,b as Br}from"./chunk-2HBEZV7L.js";import{a as Nr,b as En}from"./chunk-A7JSRDJL.js";import{c as Lr}from"./chunk-BERWTVG2.js";import{c as ur,d as lr}from"./chunk-AHWWJ7AF.js";import{e as Me}from"./chunk-DSYKYZMT.js";import{$a as wr,Ia as hr,La as _n,Na as hc,Ob as wc,Qa as yr,Va as yc,ab as Et,bb as br,cb as Ve,db as xr,eb as Sr,kb as Ir}from"./chunk-YV2SLQIL.js";import{f as fr,g as Ze,h as mc}from"./chunk-VJ5HC63R.js";import{j as Rn,r as fc}from"./chunk-UEEB3UTU.js";import{a as gr,b as me,c as pr,d as mr,e as Mn}from"./chunk-VQRY4IDI.js";Pn();Ot();var Ht="tool-set",Ao=["answer","code","full"],$o={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},bc=.1;function Mo(n){return{task:Co(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Co(n.agentPrompt,600)}:{}}}var Ro={bundle:Ue({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function _o(n,e=bc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Fn(s.answer),o=Fn(s.code),i=Fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Po(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>$o.answer.includes(t))?"answer":e.every(t=>$o.code.includes(t))?"code":"full"}function Eo(n,e){return Ao.indexOf(n)<Ao.indexOf(e)}function Fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Co(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Oo=!1;function Do(n,e){let t=Dt(Ht);if(t!=="off")return t==="active"&&!Oo&&(Oo=!0,e(`[decisions] seat "${Ht}" is set to active, but only shadow is built: it records and changes nothing`)),xe(Ht,Mo(n),Ro,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=_o(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Lo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Po(r);kr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Eo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function xc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function No(n,e){let t=xc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Un(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Pn();Ot();var Bo="session-continuity",Fo={continues:et("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:et("Does the new request refer to something stated earlier in the conversation?")};function Uo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Hn(n.message,1200),previousRequest:n.previousMessage?Hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Ho(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Xt}from"execa";import{spawn as Sc}from"node:child_process";import{createHash as Ic}from"node:crypto";import{createInterface as Tc}from"node:readline";var Se=class extends Error{},kc=n=>Sc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),jn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Tc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Wn=class{constructor(e=kc,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=Ic("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([S],[E])=>S.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Se("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let S=[...this.entries].find(([,E])=>!E.connection.busy);if(!S)throw new Se("Codex warm process capacity reached");S[1].connection.close(),this.entries.delete(S[0])}try{r={fingerprint:s,connection:new jn(e,this.launchProcess)}}catch{throw new Se("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let S={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...S,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let U=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return U.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await U,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(S){if(i.close(),!a&&!e.signal?.aborted)throw new Se(S.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:S.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},jo=new Wn;import{execFile as Kc}from"child_process";import{StringDecoder as it}from"string_decoder";import{mkdtempSync as ii,readFileSync as ai,rmSync as di}from"fs";import{join as Jt}from"path";import{tmpdir as ci}from"os";function jt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Wt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function qt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var _e=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var Wo=null;function Gt(){return Wo}function Om(n){Wo=n}function nt(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function vc(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var je=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},qo=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=nt(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=vc(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new je(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new je(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=nt(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=nt(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=nt(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=nt(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Ac}from"child_process";import{randomUUID as $c}from"crypto";import{existsSync as Cc,readFileSync as Mc}from"fs";import{resolve as Rc}from"path";function _c(n){let e=Rc(n,"CLAUDE.md");if(!Cc(e))return null;try{let t=Mc(e,"utf8");return Or(t)}catch{return null}}var Pc=20*60*1e3,Ec=5e3,st=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},rt=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Oc(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Go=class{constructor(e={}){this.opts=e}spawn(e,t){return new qn(e,t,this.opts)}},qn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Ac(r,o,{cwd:t.workspace,env:Re(Oc({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:_c(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new _e;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=$c(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??Pc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new st(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new rt(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ec);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};Mn();fc();Cn();import{resolve as Ko,join as zo}from"path";var Dc=4e3;function Kt(n){try{let e=zo(Ko(n.root),".agentx","db.sqlite"),t=Rn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Fe(),r=n.input.command?n.input.command.slice(0,Dc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function Jc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};b.stdout?.on("data",v=>{L+=j.write(v);let x=L.split(`
|
|
32
32
|
`);L=x.pop()||"";for(let B of x)J(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let C=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if(C.exitCode!==0||h){let v=C,x;return v.timedOut?x=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?x=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?x=si():x=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let U=/ENOENT|spawn opencode/i.test(E?.message||"")?si():E?.message;return{content:l,...Z(U||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{S?.(),y?.release(A)}}async function ou(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Ie(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function iu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",S=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0};if(r){let{generateStream:J}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,E=e.context?.sender,U=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&U?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Er(n),R=Object.keys(_).length>0,M={task:S,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0};if(r){let{generateStream:J}=await import("./agent-T7HRXIBL.js"),C="",v,x,B,W;for await(let P of J(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")C+=P.text,r(P.text,C);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(x=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==C){let Q=P.result.content.slice(C.length);Q?(C=P.result.content,r(Q,C)):C=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!C?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((x===void 0||B===void 0)&&v&&(x=Math.round(v*.7),B=v-x),{content:C||"Done.",tokensUsed:v,usage:x!==void 0||B!==void 0?{inputTokens:x||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-T7HRXIBL.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var au=1e3;async function du(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),au),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function cu(n,e,t,s,r,o,i){let a=Gt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Zt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let C=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>C}catch(C){return C instanceof je,null}f&&Qn(e.agentId,n,e.model,s,"persistent");let h=Ie(n,e,t),y="",A,S,E,U,b,_,R,M="",L="",N=C=>{if(!i||!C)return;let v;if(L&&C.startsWith(L)?v=C.slice(L.length):v=M&&!M.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${C}`:C,L=C,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let C=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:C})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let x=v.raw.message?.content??[];for(let W of x)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(U=W)}}if(v.type==="result"){let x=v.raw;if(x.is_error){let B=Z(typeof x.result=="string"?x.result:"claude error");A=B.error,S=B.errorKind}else typeof x.result=="string"&&x.result.length>0&&(y=x.result,M||N(x.result));typeof x.session_id=="string"&&(R=x.session_id),x.usage&&(E={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(b=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=qt(x.modelUsage)||_}}}catch(C){if(j)A="task cancelled by operator",S="cancelled";else if(J)if(C instanceof rt)A=`Claude Code was stopped mid-turn (${C.reason}), before its time limit`,S="interrupted";else if(C instanceof st){let v=Z(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,S=v.errorKind}else{let v=Z(`persistent claude process error: ${C?.message||String(C)}`);A=v.error,S=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!A&&(A="task cancelled by operator",S="cancelled"),{content:j?"":y,error:A,errorKind:S,duration:Date.now()-c,usage:E,contextTokens:U,numTurns:b,billedModel:_,claudeSessionId:R}}function bi(n){let e=me(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Xo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ti(t.args,n.taskId,n.agentId)}function uu(n){return me(n.autonomy)||!!n.personLimits}async function lu(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,c=a&&Yo(a,n.tier)||e.personLimits&&ni(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${mr(a)}
|
|
@@ -167,7 +167,7 @@ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt
|
|
|
167
167
|
${e.message}`),e.queuedAt=void 0}let E=Wi({message:e.message,home:e.context?.home}),U=ji(d.runningTasks,E,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});U&&(this.log(`[${e.agentId}] ${U.slice(0,160)}`),e.message=`${U}
|
|
168
168
|
${e.message}`),d.totalTasks++,d.lastActive=new Date;let b={...E.length?{homes:E}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(b),e.runningTaskId=b.id;let _=Et(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(b.id,e.context??{}),e.onStart)try{e.onStart(b.id)}catch{}let R=new AbortController;this.taskAborts.set(b.id,{agentId:e.agentId,channel:b.channel,chatId:typeof b.chatId=="string"?b.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:Lt()?.rootId,workflowRunId:e.workflowRunId??(typeof b.chatId=="string"&&b.chatId.startsWith("workflow:")&&b.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(b.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>Ld&&(M.buffer=M.buffer.slice(M.buffer.length-Ld));for(let m of M.subscribers)try{m(g)}catch{}}},N=Fe();e.taskId=N,b.traceId=N;let j=this.taskAborts.get(b.id);j&&(j.traceId=N);let q=new Map,J=(g,m,T)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:T,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},C=0,v=!1,x=()=>{v||(v=!0,C&&J("first-event",C,"ok"))},B;if(t){let g=ym();B=m=>{x();let T=g(m);if(T&&L(T),Fd(N,e.agentId,m),Bd(q,m),us(m,void 0,e.model||d.def.model),cs(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(x(),Fd(N,e.agentId,g),Bd(q,g),us(g,void 0,e.model||d.def.model),cs(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,P=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;P?.unref?.();let Q=(d.def.preSpawnTimeoutSec??dm)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${b.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Le(R.signal).message;/^timed out/.test(g)&&(te=b.step??"start"),this.log(`[${e.agentId}] task ${b.id} aborted in step "${b.step??"start"}" \u2014 ${g} ${D()}`)},{once:!0});let ne=g=>{b.step=g,this.log(`[${e.agentId}] step ${g} ${D()}`)},le=(g,m,T=0)=>{if(R.signal.aborted)return Promise.reject(Le(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),C=Date.now());let k=Date.now(),F=Za(m(),tm[g]??0,g);return Ya(F,R.signal,T).then(K=>(J(g,k,"ok"),K),K=>{throw J(g,k,"error"),K instanceof ze&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},bt=async(g,m,T,k=0)=>{try{return await le(g,m,k)}catch(F){if(F instanceof ze)return T();throw F}},Rs=!1,wn=!1,_s=g=>{if(!(!Rs||wn)){wn=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-b.startedAt.getTime(),error:g?.error||(R.signal.aborted?Le(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(b.id)?!0:void 0,stopped:!this.interruptedRuns.has(b.id)&&(this.stoppedRuns.has(b.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Ps=!1,Es=g=>{if(Ps)return;Ps=!0,_s(g),this.runReleases.delete(b.id),P&&clearTimeout(P),oe(),d.activeTasks--,this.admissionTickets.get(e)?.release();let m=d.runningTasks.findIndex(k=>k.id===b.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(b.id),this.taskAborts.delete(b.id);let T=this.runEndWaiters.get(b.id);this.runEndWaiters.delete(b.id);for(let k of T??[])try{k()}catch{}M.done=!0,M.endedAt=new Date;for(let k of M.subscribers)try{k(`
|
|
169
169
|
[task finished]
|
|
170
|
-
`)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),im).unref?.();try{let k=M.endedAt,F={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:F.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of k){let $e=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:$e,queuedAt:X.queuedAt??X.timestamp}).then(we=>(tt(we.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,we)),we=>{throw K(),we}).catch(we=>{this.log(`[${e.agentId}] queued message failed: ${we.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Es),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:jd,selectRequestContext:Wd}=await import("./request-planner-YQ4RTZNU.js"),Os=bt("request-gate",()=>jd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),bn=!1;Os.then(()=>{bn=!0},()=>{bn=!0});let I=l,xn=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Xe=Ia(this.config.session,w,d.def.tier),xt=Ta(this.config.session),ge=e.isolated===!0,Ye=!ge&&Xe==="lean"&&xt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let St=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await bt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let qd=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;Qa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:qd,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,xn,e.message);let Ds=Date.now(),Ls={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ds).toISOString(),taskId:N,resumeOrigin:Oi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:_n(e.context),..._?{person:_}:{},humanRoot:Ze(e.context),pickup:hr(e.context),operator:yr(e.context),dueAt:Xa(e.context),taskType:gn(e.context)};V().emit("task:started",Ls),Rs=!0;let ee,Sn,Ns=this.classifier;if(Ns&&w!=="a2a"&&!ue){ne("classify");let g=Date.now();Sn=Ns.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let Bs=async g=>{if(!Sn)return;let m;await Promise.race([Sn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await Bs(Qp);let ke=this.config.workflows?.matching,ye,Fs,Us=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Us?.enabled&&(Us.agents[e.agentId]??!0)&&!i&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ke?.suggestThreshold??.65)&&(Fs=go(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ke?.enabled&&!i)try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ke.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ke.mode} reasons=${m.reasons.join(",")||"n/a"}`),ke.mode==="auto"&&m.confidence>=ke.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ve=po(this.config.workflows,e.agentId)&&mo(e)?this.workflowRuns:void 0;if(ve&&!ye&&!i&&this.workflowAutoRunner&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ke?.autoRunThreshold??.85;m&&m.confidence>=T&&(ye={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let de=ve?em():void 0,Gd=de?fo(de):void 0,Kd=this.wikiHub.getAgentWiki(e.agentId),Hs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),js=this.memoryStore.buildContext(Hs),Ws=this.memoryStore.contextFacts(Hs),zd=this.patternStore.findRelevant(e.message,e.agentId,5),Jd=this.patternStore.buildContext(zd),qs="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],F=k.length?T.filter(K=>!k.some(X=>Ve(X,K.frontmatter.name))):T;qs=m(F,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,St)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=No({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:St??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${Un(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${Un(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await bt("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Qd=process.env.AGENTX_CONTEXT_SURGERY==="1",Xd=ue?{maxMessages:8,maxChars:2400}:Qd&&Dd(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Yd=!H&&!ue?mm(Kd,e.agentId,{notesInbox:pm(this.config)}):void 0,It=!H&&!Ye?this.sessions.buildHistoryContext(e.agentId,w,I,Xd):void 0,Zd=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Gs,Ks=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new lt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=fs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Gs=hs(m),Ks=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Me&&Me.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],F=It===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${It.length}c/${It.split(`
|
|
170
|
+
`)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),im).unref?.();try{let k=M.endedAt,F={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(F);let K=(F.responseText||F.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:F.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let F=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:F,at:new Date().toISOString()});for(let X of k){let $e=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:$e,queuedAt:X.queuedAt??X.timestamp}).then(we=>(tt(we.error)||K(),this.postQueuedResponseToChannel(e.agentId,$e,we)),we=>{throw K(),we}).catch(we=>{this.log(`[${e.agentId}] queued message failed: ${we.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Es),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:jd,selectRequestContext:Wd}=await import("./request-planner-DP3PIMNQ.js"),Os=bt("request-gate",()=>jd(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),bn=!1;Os.then(()=>{bn=!0},()=>{bn=!0});let I=l,xn=e.context?.sender||"User",ue=d.def.tier==="codex-cli",Xe=Ia(this.config.session,w,d.def.tier),xt=Ta(this.config.session),ge=e.isolated===!0,Ye=!ge&&Xe==="lean"&&xt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let St=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await bt("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let qd=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;Qa({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:qd,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,xn,e.message);let Ds=Date.now(),Ls={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Ds).toISOString(),taskId:N,resumeOrigin:Oi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:_n(e.context),..._?{person:_}:{},humanRoot:Ze(e.context),pickup:hr(e.context),operator:yr(e.context),dueAt:Xa(e.context),taskType:gn(e.context)};V().emit("task:started",Ls),Rs=!0;let ee,Sn,Ns=this.classifier;if(Ns&&w!=="a2a"&&!ue){ne("classify");let g=Date.now();Sn=Ns.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let Bs=async g=>{if(!Sn)return;let m;await Promise.race([Sn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await Bs(Qp);let ke=this.config.workflows?.matching,ye,Fs,Us=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Us?.enabled&&(Us.agents[e.agentId]??!0)&&!i&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ke?.suggestThreshold??.65)&&(Fs=go(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ke?.enabled&&!i)try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ke.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ke.mode} reasons=${m.reasons.join(",")||"n/a"}`),ke.mode==="auto"&&m.confidence>=ke.autoRunThreshold&&(this.workflowAutoRunner?ye={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ve=po(this.config.workflows,e.agentId)&&mo(e)?this.workflowRuns:void 0;if(ve&&!ye&&!i&&this.workflowAutoRunner&&Ze(e.context))try{let g=new Ft({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ut({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ke?.autoRunThreshold??.85;m&&m.confidence>=T&&(ye={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let de=ve?em():void 0,Gd=de?fo(de):void 0,Kd=this.wikiHub.getAgentWiki(e.agentId),Hs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),js=this.memoryStore.buildContext(Hs),Ws=this.memoryStore.contextFacts(Hs),zd=this.patternStore.findRelevant(e.message,e.agentId,5),Jd=this.patternStore.buildContext(zd),qs="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],F=k.length?T.filter(K=>!k.some(X=>Ve(X,K.frontmatter.name))):T;qs=m(F,e.message)}catch{}let H=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,St)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=No({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:St??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${Un(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,H,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${Un(m)}`)}}if(H&&d.def.tier==="claude-code"){let g=H;await bt("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(H=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Qd=process.env.AGENTX_CONTEXT_SURGERY==="1",Xd=ue?{maxMessages:8,maxChars:2400}:Qd&&Dd(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Yd=!H&&!ue?mm(Kd,e.agentId,{notesInbox:pm(this.config)}):void 0,It=!H&&!Ye?this.sessions.buildHistoryContext(e.agentId,w,I,Xd):void 0,Zd=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Gs,Ks=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new lt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=fs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Gs=hs(m),Ks=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Me&&Me.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],F=It===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${It.length}c/${It.split(`
|
|
171
171
|
`).length}L`,K=`[${e.agentId}] ${w}:${I} ${F} | session.messages=${m.length}`+(m.length>0?` first=${T.timestamp.slice(11,19)}(${T.role}:${(T.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Me.cat("context",K)}catch(g){Me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let zs;if(d.def.contextReferences&&!H)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,F]=await le("references",()=>Promise.all([Dn(d.def.workspace),Ln(d.def.workspace)]));if(k.byId.size===0&&F.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Dn(process.cwd()),Ln(process.cwd())]));m={refs:K,recipes:X}}else m={refs:k,recipes:F};this.referencesCache.set(g,m)}let T=Yr({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);T.cards.length>0&&(zs=Qr(T.cards,500*4)),T.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${T.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Js=ge||Ye?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),Qs,Tt=ge?null:Ti(e.message);if(Tt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:Tt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Tt.lookbackDays}d on this chat (cue-triggered)]`],T=[...g.turns].sort((k,F)=>k.ts.localeCompare(F.ts));for(let k of T){let F=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${F} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),Qs=m.join(`
|
|
172
172
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Tt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Vd=ue?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Xs,Ys,Zs=!1;bn||ne("request-gate");let Ae=await Os;if(Ae.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Vd==="planner"&&!ge&&!Ae.active&&!Ye&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Zs=!0,Xs=m.sessionHistory,js=m.memoryContext,Ws=m.memoryFacts,Js=m.crossChatContext,Ys=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Zs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let In=`${e.agentId}:${w}:${I}`,kt=Pr(e.message);kt&&(kt==="default"?(this.activeSouls.delete(In),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(In,kt),this.log(`[${e.agentId}] Soul switched to: ${kt}`)));let ec=this.activeSouls.get(In),tc=Rr(d.def.workspace,ec),nc=_r(tc),sc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),rc=rm(d.def.tier),oc=wm(d.def.richMessages,e.context?.via==="voice"?"voice":w),ic=d.def.tier==="claude-code"&&(ge||Xe!=="lean"||ka(xt)),Vs="";if(d.def.workspace&&!ic){let g=G(d.def.workspace,"CLAUDE.md");if(ae(g))try{let m=yt(g,"utf-8");Vs=`[Project CLAUDE.md]
|
|
173
173
|
${m.length>4e3?m.slice(0,4e3)+`
|
|
@@ -181,9 +181,9 @@ ${$e}`),m+=$e.length}catch{}}}let ac=Tn.length>0?Tn.join(`
|
|
|
181
181
|
|
|
182
182
|
`)||void 0,At={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:xn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ye||Dd(w,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ue?void 0:Jd||void 0,procedureContext:[Gs,Fs].filter(Boolean).join(`
|
|
183
183
|
|
|
184
|
-
`)||void 0,workflowRunContext:Gd,references:zs,skillInjection:qs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Xs??It,memoryContext:js||void 0,crossChatContext:Js||void 0,longMemoryRecall:Qs||void 0,contextOnDemand:Ye&&!H?Ra(w,I):void 0,wikiContext:Yd,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Ls)}catch{return}})(),rotationMemo:Zd,eventDigest:H?void 0:gm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=ko(w,!H,d.def.richMessages);return g?fm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(At,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let $t=e.model?void 0:Ar({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?St:null});$t?.downgraded&&this.log(`[${e.agentId}] ${$t.reason}`);let er=vr(d.def.tier,this.config.decisions.routing),tr=$t?.downgraded?Promise.resolve($t.model):!e.model&&er&&(!Ae.active||Ae.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
184
|
+
`)||void 0,workflowRunContext:Gd,references:zs,skillInjection:qs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Xs??It,memoryContext:js||void 0,crossChatContext:Js||void 0,longMemoryRecall:Qs||void 0,contextOnDemand:Ye&&!H?Ra(w,I):void 0,wikiContext:Yd,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Ls)}catch{return}})(),rotationMemo:Zd,eventDigest:H?void 0:gm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=ko(w,!H,d.def.richMessages);return g?fm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(At,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let $t=e.model?void 0:Ar({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?St:null});$t?.downgraded&&this.log(`[${e.agentId}] ${$t.reason}`);let er=vr(d.def.tier,this.config.decisions.routing),tr=$t?.downgraded?Promise.resolve($t.model):!e.model&&er&&(!Ae.active||Ae.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-LX5QYMZW.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?St:null,cheapModel:er}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),nr=!1;tr.then(()=>{nr=!0});let Ct=Ae.active&&Ae.preprocess?await bt("select-context",()=>Wd(At),()=>({input:At,excluded:[]})):{input:At,excluded:[]};Ct.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ct.excluded.join(", ")}`);let Mt=Ei(Ct.input,ue?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),dc=Gr(Mt,{memory:Ws,procedures:Ks,wikiContext:Ct.input.wikiContext}),vn=(Mt?.length??0)+(kn?.length??0)+(e.message?.length??0),Rt={history:Mt?.length??0,sysPrompt:kn?.length??0,message:e.message?.length??0},sr=ma(e.agentId,w,I);fa(sr,vn,Rt);let rr=ha(sr);rr&&this.log(`[${e.agentId}] ${rr}`),vn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${vn} bytes (history=${Rt.history}, sysPrompt=${Rt.sysPrompt}, message=${Rt.message})`),nr||ne("route-model");let or=await tr,ir=d.def.tier!=="claude-code"?void 0:ge?$a():Xe==="lean"?Aa(d.def.workspace,xt,void 0,w):Ma(d.def.workspace);Xe==="lean"&&!ge&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${_a(Xe,xt,w)}`);let ar=d.def.tier==="claude-code"&&!H?Do({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,cc={...e,systemPromptAppend:kn,...ir?{claudeArgs:ir}:{},...or?{model:or}:{}},se,dr=Ka({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),uc=B,cr=!1,An=!0;B=g=>{if(dr.observe(g),de&&An)for(let m of yo(g))ho(m.name,m.input)||(An=!1);uc?.(g)};try{let g=this.workflowAutoRunner;if(ye&&g){let O=ye;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${ye.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:ye.workflowId,workflowRunId:z.runId,workflowMatchConfidence:ye.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(de&&ve)try{let O=bo(ve,e.resumedFrom);wo(ve,{runId:de,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),cr=!0,b.workflow={runId:de,workflowId:lo}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${de} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=d.def.persistentProcess?Gt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!H||z,Be=[Vi(pe),ga(pe,void 0,e.model||d.def.model)].find(Ce=>Ce&&Ce.abort);if(Be){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Be.reason}`);let Ce={content:"",error:Be.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Be.message}`;for(let pc of M.subscribers)try{pc(M.buffer)}catch{}}return Ce}ra();let ce=pa();return ce&&this.log(`[${e.agentId}] ${ce}`),null},T=Bt(e.agentId,void 0,Nt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return d.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(d.def,e);if(k.route==="local"){let O=m();if(O)return d.errors++,se=O,O}let F=d.def.tier==="claude-code",K=F?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,$e=F?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},we=()=>{X&&(L(`
|
|
185
185
|
`),X=!1)},lc=F?K:K?(O,z)=>{we(),K(O,z)}:void 0,$=await le("agent",async()=>{if(k.route!=="local"){let z=await this.runCloudSession(d.def,e,k,N);if(z)return z;let pe=m();if(pe)return pe}let O=await this.inTaskWorktree(d.def,cc);return xi(O.def,O.task,this.providers,lc,Mt,O.fresh?void 0:H,B,R.signal,$e)},am);if(!$.error){let O=hm(d.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([pe,Ne])=>`${pe}=${Ne}`).join(", ")||"none";$.error=`tool_required_not_called: ${O} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}ar&&Lo(ar,{toolUses:q,eventsSeen:v,error:$.error,agentId:e.agentId},O=>this.log(O));let _t=this.interruptedRuns.get(b.id);_t&&($.content="",$.error=_t,$.errorKind="interrupted");let $n=_t?void 0:this.stoppedRuns.get(b.id);$n&&($.content="",$.error=$n,$.errorKind="stopped"),se=$;let be=$.usage?Wr($.usage):void 0,gc=$.billedModel||e.model||d.def.model||void 0,Pt=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,gc,d.def.tier):void 0);if(wn=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-Ds,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:_t?!0:void 0,stopped:$n?!0:void 0,inputTokens:be?.inputTokens,outputTokens:be?.outputTokens,cacheReadTokens:be?.cacheReadTokens,cacheCreateTokens:be?.cacheCreateTokens,tier2InputTokens:be?.tier2InputTokens,tier2OutputTokens:be?.tier2OutputTokens,tier2CacheReadTokens:be?.tier2CacheReadTokens,tier2CacheCreateTokens:be?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:Ae.arm,numTurns:$.numTurns,costUsd:Pt!==void 0&&Number.isFinite(Pt)&&Pt>0?Pt:void 0,injectedContext:dc,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let O=$.error?`[error] ${$.error}`:$.content;M.buffer=O;for(let z of M.subscribers)try{z(O)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,$.content),Ja({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:$.content,taskId:N}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,$.usage,$.contextTokens),$.usage){let ce=$.contextTokens,Ce=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ce??Ce)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ce??"n/a"} tokens (cumulative turn total=${Ce}) \u2014 next turn will rotate`)}let O=Dr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}),z=G(this.wikiHub.getBaseDir(),Ai);O.capture||$i(z,e.agentId,O,ce=>this.log(ce)),O.capture&&(await Bs(Xp),Ci(z,e.agentId,()=>{let ce=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ce,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
186
186
|
|
|
187
187
|
Agent: ${$.content}`,meta:lm(ee,e.context)})},ce=>this.log(ce)),Br(e.agentId,e.message,$.content,{channel:w,chatId:I,sender:xn},this.memoryStore).catch(()=>{}),zi(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=$.billedModel||e.model||d.def.model,Ne=e.context?.channel,Be=Ne&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ne}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,pe,Ne,Be),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${D()}`)}return $}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=jt(g.message);return se={content:"",error:Wt(m),errorKind:m.kind},se}finally{if(dr.stop(),cr&&de&&ve)try{let g=se?.usage,m=xo(ve,de,{error:se?se.error||void 0:R.signal.aborted?Le(R.signal).message:"run ended before completion",canceled:So(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:An,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${de} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${de} (non-fatal): ${g?.message||g}`)}_s(se),Es(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?om(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Io(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Qe,this.safe(e.agentId),t);ae(s)||Yp(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Vp(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Qe,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of he(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),S=t-1-A;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Qe);if(!ae(e))return 0;let t=0;for(let s of he(e)){let r=G(e,s),o;try{o=he(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=he(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(yt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=um){let t=G(process.cwd(),Qe);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of he(t)){let i=G(t,o),a;try{a=he(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Zp(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Qe,this.safe(e));if(!ae(s))return[];let r=he(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=he(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(yt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Qe,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=he(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(yt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Bt(t,void 0,Nt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Bn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||tt(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){nm.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Zt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:wr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{tt(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function wm(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
188
188
|
`)}export{jo as a,Om as b,qo as c,_c as d,Go as e,Kt as f,Jm as g,Zm as h,Vm as i,rf as j,Zt as k,Vc as l,yi as m,ru as n,ou as o,iu as p,xi as q,en as r,Ai as s,Of as t,tn as u,Ru as v,Ff as w,Uf as x,jf as y,sn as z,Gf as A,ss as B,V as C,Ji as D,Ju as E,Zu as F,Yi as G,ah as H,Zi as I,na as J,Sh as K,Ih as L,da as M,Th as N,ca as O,dn as P,_h as Q,Ph as R,lt as S,ug as T,lg as U,gg as V,pg as W,mg as X,fs as Y,gn as Z,dy as _,mn as $,pn as aa,sd as ba,pt as ca,rd as da,fy as ea,hy as fa,yy as ga,wy as ha,by as ia,xy as ja,Sy as ka,Kg as la,hd as ma,Je as na,sm as oa,rm as pa,ob as qa,ib as ra,om as sa,cm as ta,lm as ua,gm as va,mm as wa,Ms as xa,Nd as ya,Bd as za,hm as Aa,Fd as Ba,Ud as Ca,wm as Da};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
189
|
+
//# sourceMappingURL=chunk-KAAAB3W3.js.map
|