@duckmind/dm-windows-x64 0.60.6 → 0.60.9
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/dm.exe +0 -0
- package/extensions/.dm-extensions.json +70 -123
- package/extensions/dm-9router-ext/src/index.js +410 -5
- package/extensions/dm-caveman/extensions/caveman.js +283 -12
- package/extensions/dm-cliproxy/index.js +182 -2
- package/extensions/dm-cliproxy/scripts/check-config-migration.js +66 -8
- package/extensions/dm-cliproxy/src/apply.js +228 -1
- package/extensions/dm-cliproxy/src/cache.js +42 -1
- package/extensions/dm-cliproxy/src/commands.js +50 -2
- package/extensions/dm-cliproxy/src/compat.js +81 -1
- package/extensions/dm-cliproxy/src/config.js +192 -2
- package/extensions/dm-cliproxy/src/conflicts.js +46 -1
- package/extensions/dm-cliproxy/src/fetch-models.js +190 -1
- package/extensions/dm-cliproxy/src/fetch-usage.js +41 -1
- package/extensions/dm-cliproxy/src/log.js +23 -1
- package/extensions/dm-cliproxy/src/status-quota.js +77 -1
- package/extensions/dm-cliproxy/src/ui-frame.js +50 -1
- package/extensions/dm-cliproxy/src/ui-hub/hub.js +199 -2
- package/extensions/dm-cliproxy/src/ui-hub/index.js +26 -2
- package/extensions/dm-cliproxy/src/ui-hub/shell.js +46 -1
- package/extensions/dm-cliproxy/src/ui-hub/view-diagnostics.js +69 -1
- package/extensions/dm-cliproxy/src/ui-hub/view-models.js +379 -1
- package/extensions/dm-cliproxy/src/ui-hub/view-usage.js +106 -1
- package/extensions/dm-cliproxy/src/ui-picker/catalog.js +41 -1
- package/extensions/dm-cliproxy/src/ui-picker/mutate.js +115 -1
- package/extensions/dm-cliproxy/src/ui-picker/prompt-confirm.js +35 -1
- package/extensions/dm-cliproxy/src/ui-picker/prompt-name.js +62 -1
- package/extensions/dm-cliproxy/src/ui-picker/providers.js +45 -1
- package/extensions/dm-cliproxy/src/ui-picker/render-text.js +34 -1
- package/extensions/dm-cliproxy/src/ui-picker/rows.js +57 -1
- package/extensions/dm-cliproxy/src/ui-setup.js +260 -2
- package/extensions/dm-cliproxy/src/ui-usage.js +151 -1
- package/extensions/dm-cliproxy/src/usage-shared-cache.js +97 -1
- package/extensions/dm-context/src/context.js +144 -1
- package/extensions/dm-context/src/index.js +339 -7
- package/extensions/dm-context/src/utils.js +9 -1
- package/extensions/dm-cua/bin/browser-cua.mjs +73 -8
- package/extensions/dm-cua/index.js +75 -6
- package/extensions/dm-cua/src/browser-cua-lib.mjs +490 -6
- package/extensions/dm-cua/src/browser-install.mjs +331 -2
- package/extensions/dm-fff/src/index.js +688 -12
- package/extensions/dm-fff/src/query.js +60 -1
- package/extensions/dm-goal/src/goal.js +894 -23
- package/extensions/dm-image2/index.js +103 -9
- package/extensions/dm-image2/src/image-lib.mjs +1275 -8
- package/extensions/dm-subagents/install.mjs +62 -8
- package/extensions/dm-subagents/src/agents/agent-management.js +1190 -36
- package/extensions/dm-subagents/src/agents/agent-memory.js +216 -6
- package/extensions/dm-subagents/src/agents/agent-scope.js +5 -1
- package/extensions/dm-subagents/src/agents/agent-selection.js +20 -1
- package/extensions/dm-subagents/src/agents/agent-serializer.js +120 -5
- package/extensions/dm-subagents/src/agents/agents.js +1139 -11
- package/extensions/dm-subagents/src/agents/chain-serializer.js +299 -11
- package/extensions/dm-subagents/src/agents/frontmatter.js +65 -6
- package/extensions/dm-subagents/src/agents/identity.js +29 -1
- package/extensions/dm-subagents/src/agents/proactive-skills.js +141 -1
- package/extensions/dm-subagents/src/agents/skills.js +614 -6
- package/extensions/dm-subagents/src/extension/config.js +35 -2
- package/extensions/dm-subagents/src/extension/control-notices.js +69 -4
- package/extensions/dm-subagents/src/extension/doctor.js +172 -15
- package/extensions/dm-subagents/src/extension/fanout-child.js +158 -231
- package/extensions/dm-subagents/src/extension/index.js +521 -359
- package/extensions/dm-subagents/src/extension/rpc.js +266 -7
- package/extensions/dm-subagents/src/extension/schemas.js +275 -1
- package/extensions/dm-subagents/src/extension/tool-description.js +111 -6
- package/extensions/dm-subagents/src/intercom/intercom-bridge.js +126 -4
- package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +452 -5
- package/extensions/dm-subagents/src/intercom/result-intercom.js +319 -3
- package/extensions/dm-subagents/src/profiles/profiles.js +458 -3
- package/extensions/dm-subagents/src/runs/background/async-execution.js +834 -40
- package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +435 -14
- package/extensions/dm-subagents/src/runs/background/async-resume.js +334 -8
- package/extensions/dm-subagents/src/runs/background/async-status.js +313 -12
- package/extensions/dm-subagents/src/runs/background/chain-append.js +245 -2
- package/extensions/dm-subagents/src/runs/background/chain-root-attachment.js +136 -1
- package/extensions/dm-subagents/src/runs/background/completion-batcher.js +94 -1
- package/extensions/dm-subagents/src/runs/background/completion-dedupe.js +54 -1
- package/extensions/dm-subagents/src/runs/background/control-channel.js +190 -1
- package/extensions/dm-subagents/src/runs/background/fleet-view.js +483 -17
- package/extensions/dm-subagents/src/runs/background/notify.js +129 -3
- package/extensions/dm-subagents/src/runs/background/parallel-groups.js +34 -1
- package/extensions/dm-subagents/src/runs/background/result-watcher.js +236 -6
- package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +76 -4
- package/extensions/dm-subagents/src/runs/background/run-status.js +427 -23
- package/extensions/dm-subagents/src/runs/background/scheduled-runs.js +487 -4
- package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +306 -9
- package/extensions/dm-subagents/src/runs/background/subagent-runner.js +2849 -73
- package/extensions/dm-subagents/src/runs/background/top-level-async.js +5 -1
- package/extensions/dm-subagents/src/runs/background/wait.js +206 -11
- package/extensions/dm-subagents/src/runs/foreground/chain-clarify.js +1013 -12
- package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +980 -101
- package/extensions/dm-subagents/src/runs/foreground/execution.js +1165 -45
- package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +3157 -222
- package/extensions/dm-subagents/src/runs/shared/acceptance.js +835 -3
- package/extensions/dm-subagents/src/runs/shared/chain-outputs.js +104 -1
- package/extensions/dm-subagents/src/runs/shared/completion-guard.js +116 -3
- package/extensions/dm-subagents/src/runs/shared/dm-args.js +208 -1
- package/extensions/dm-subagents/src/runs/shared/dm-spawn.js +90 -1
- package/extensions/dm-subagents/src/runs/shared/dynamic-fanout.js +282 -1
- package/extensions/dm-subagents/src/runs/shared/long-running-guard.js +148 -1
- package/extensions/dm-subagents/src/runs/shared/mcp-direct-tool-allowlist.js +305 -1
- package/extensions/dm-subagents/src/runs/shared/model-fallback.js +194 -1
- package/extensions/dm-subagents/src/runs/shared/model-scope.js +65 -1
- package/extensions/dm-subagents/src/runs/shared/nested-events.js +851 -8
- package/extensions/dm-subagents/src/runs/shared/nested-path.js +41 -1
- package/extensions/dm-subagents/src/runs/shared/nested-render.js +105 -1
- package/extensions/dm-subagents/src/runs/shared/parallel-utils.js +81 -4
- package/extensions/dm-subagents/src/runs/shared/run-history.js +51 -4
- package/extensions/dm-subagents/src/runs/shared/single-output.js +149 -8
- package/extensions/dm-subagents/src/runs/shared/structured-output.js +58 -1
- package/extensions/dm-subagents/src/runs/shared/subagent-control.js +166 -5
- package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +329 -13
- package/extensions/dm-subagents/src/runs/shared/tool-budget.js +73 -1
- package/extensions/dm-subagents/src/runs/shared/turn-budget.js +47 -4
- package/extensions/dm-subagents/src/runs/shared/workflow-graph.js +196 -1
- package/extensions/dm-subagents/src/runs/shared/worktree.js +435 -3
- package/extensions/dm-subagents/src/shared/artifacts.js +92 -2
- package/extensions/dm-subagents/src/shared/atomic-json.js +55 -1
- package/extensions/dm-subagents/src/shared/child-transcript.js +167 -5
- package/extensions/dm-subagents/src/shared/file-coalescer.js +25 -1
- package/extensions/dm-subagents/src/shared/fork-context.js +147 -4
- package/extensions/dm-subagents/src/shared/formatters.js +98 -7
- package/extensions/dm-subagents/src/shared/jsonl-writer.js +56 -2
- package/extensions/dm-subagents/src/shared/model-info.js +62 -1
- package/extensions/dm-subagents/src/shared/post-exit-stdio-guard.js +68 -1
- package/extensions/dm-subagents/src/shared/session-identity.js +6 -1
- package/extensions/dm-subagents/src/shared/session-tokens.js +39 -2
- package/extensions/dm-subagents/src/shared/settings.js +198 -11
- package/extensions/dm-subagents/src/shared/status-format.js +53 -1
- package/extensions/dm-subagents/src/shared/types.js +184 -6
- package/extensions/dm-subagents/src/shared/utils.js +462 -2
- package/extensions/dm-subagents/src/slash/prompt-template-bridge.js +288 -1
- package/extensions/dm-subagents/src/slash/prompt-workflows.js +297 -7
- package/extensions/dm-subagents/src/slash/slash-bridge.js +118 -1
- package/extensions/dm-subagents/src/slash/slash-commands.js +1287 -31
- package/extensions/dm-subagents/src/slash/slash-live-state.js +240 -4
- package/extensions/dm-subagents/src/tui/render-helpers.js +64 -1
- package/extensions/dm-subagents/src/tui/render.js +1542 -4
- package/extensions/dm-usage/index.js +1294 -9
- package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +40 -9
- package/extensions/greedysearch-dm/bin/cdp-headless.mjs +5 -2
- package/extensions/greedysearch-dm/bin/cdp-visible.mjs +5 -2
- package/extensions/greedysearch-dm/bin/cdp.mjs +896 -30
- package/extensions/greedysearch-dm/bin/gschrome.mjs +30 -2
- package/extensions/greedysearch-dm/bin/kill-visible.mjs +7 -2
- package/extensions/greedysearch-dm/bin/launch-visible.mjs +13 -2
- package/extensions/greedysearch-dm/bin/launch.mjs +282 -10
- package/extensions/greedysearch-dm/bin/mcp.mjs +386 -361
- package/extensions/greedysearch-dm/bin/search.mjs +620 -540
- package/extensions/greedysearch-dm/bin/visible.mjs +22 -2
- package/extensions/greedysearch-dm/extractors/bing-copilot.mjs +329 -579
- package/extensions/greedysearch-dm/extractors/chatgpt.mjs +301 -583
- package/extensions/greedysearch-dm/extractors/common.mjs +408 -32
- package/extensions/greedysearch-dm/extractors/consensus.mjs +376 -365
- package/extensions/greedysearch-dm/extractors/consent.mjs +303 -14
- package/extensions/greedysearch-dm/extractors/gemini.mjs +228 -592
- package/extensions/greedysearch-dm/extractors/google-ai.mjs +78 -499
- package/extensions/greedysearch-dm/extractors/logically.mjs +270 -347
- package/extensions/greedysearch-dm/extractors/perplexity.mjs +243 -581
- package/extensions/greedysearch-dm/extractors/selectors.mjs +32 -1
- package/extensions/greedysearch-dm/extractors/semantic-scholar.mjs +130 -317
- package/extensions/greedysearch-dm/index.js +123 -23
- package/extensions/greedysearch-dm/src/fetcher.mjs +576 -2
- package/extensions/greedysearch-dm/src/formatters/results.js +95 -10
- package/extensions/greedysearch-dm/src/formatters/sources.js +57 -1
- package/extensions/greedysearch-dm/src/formatters/synthesis.js +49 -1
- package/extensions/greedysearch-dm/src/github.mjs +222 -7
- package/extensions/greedysearch-dm/src/reddit.mjs +145 -14
- package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +340 -9
- package/extensions/greedysearch-dm/src/search/challenge-detect.mjs +112 -4
- package/extensions/greedysearch-dm/src/search/chrome.mjs +486 -285
- package/extensions/greedysearch-dm/src/search/constants.mjs +109 -8
- package/extensions/greedysearch-dm/src/search/defaults.mjs +10 -1
- package/extensions/greedysearch-dm/src/search/engines.mjs +79 -9
- package/extensions/greedysearch-dm/src/search/fetch-source.mjs +441 -349
- package/extensions/greedysearch-dm/src/search/file-sources.mjs +29 -7
- package/extensions/greedysearch-dm/src/search/minimize.mjs +86 -1
- package/extensions/greedysearch-dm/src/search/output.mjs +51 -5
- package/extensions/greedysearch-dm/src/search/paths.mjs +48 -1
- package/extensions/greedysearch-dm/src/search/pdf.mjs +63 -2
- package/extensions/greedysearch-dm/src/search/port-pid.mjs +69 -1
- package/extensions/greedysearch-dm/src/search/progress.mjs +109 -2
- package/extensions/greedysearch-dm/src/search/query.mjs +21 -1
- package/extensions/greedysearch-dm/src/search/recovery.mjs +49 -1
- package/extensions/greedysearch-dm/src/search/research.mjs +2227 -458
- package/extensions/greedysearch-dm/src/search/scale-aware.mjs +61 -11
- package/extensions/greedysearch-dm/src/search/simple-research.mjs +396 -805
- package/extensions/greedysearch-dm/src/search/sources.mjs +412 -1
- package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +127 -12
- package/extensions/greedysearch-dm/src/search/synthesis.mjs +202 -12
- package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +209 -23
- package/extensions/greedysearch-dm/src/tools/shared.js +226 -10
- package/extensions/greedysearch-dm/src/utils/content.mjs +35 -4
- package/extensions/greedysearch-dm/src/utils/helpers.js +22 -1
- package/extensions/greedysearch-dm/src/utils/node-runtime.mjs +10 -1
- package/extensions/greedysearch-dm/src/utils/system-cmds.mjs +61 -1
- package/package.json +1 -1
|
@@ -1,23 +1,427 @@
|
|
|
1
|
-
import*as I from"node:fs";import*as qf from"node:path";import*as Bf from"node:fs";import*as N from"node:path";import*as R from"node:fs";import*as jf from"node:path";var $f=new Map;function yf(f){return f instanceof Error?f.message:String(f)}function X$(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function Hf(f){let $=jf.join(f,"status.json"),j;try{j=R.statSync($)}catch(B){if(X$(B))return null;throw Error(`Failed to inspect async status file '${$}': ${yf(B)}`,{cause:B instanceof Error?B:void 0})}let J=$f.get($);if(J&&J.mtime===j.mtimeMs)return J.status;let Z;try{Z=R.readFileSync($,"utf-8")}catch(B){if(X$(B))return null;throw Error(`Failed to read async status file '${$}': ${yf(B)}`,{cause:B instanceof Error?B:void 0})}let Q;try{Q=JSON.parse(Z)}catch(B){throw Error(`Failed to parse async status file '${$}': ${yf(B)}`,{cause:B instanceof Error?B:void 0})}if($f.set($,{mtime:j.mtimeMs,status:Q}),$f.size>50){let B=$f.keys().next().value;if(B)$f.delete(B)}return Q}import*as r from"node:os";import*as a from"node:path";function Kf(f){return f.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function X0(f){let $=f?.env??process.env,j=f&&Object.hasOwn(f,"getuid")?f.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let B of["USERNAME","USER","LOGNAME"]){let X=$[B];if(X)return`user-${Kf(X)}`}let J=f&&Object.hasOwn(f,"userInfo")?f.userInfo:r.userInfo;try{let B=J?.().username;if(B)return`user-${Kf(B)}`}catch{}let Z=$.USERPROFILE??$.HOME;if(Z)return`home-${Kf(Z)}`;let Q=f&&Object.hasOwn(f,"homedir")?f.homedir:r.homedir;try{let B=Q?.();if(B)return`home-${Kf(B)}`}catch{}return"shared"}var v=a.join(r.tmpdir(),`dm-subagents-${X0()}`),w=a.join(v,"async-subagent-results"),h=a.join(v,"async-subagent-runs"),Y0=a.join(v,"chain-runs"),xj=a.join(v,"artifacts");var Ef=["off","minimal","low","medium","high","xhigh"];function H$(f){let $=f.lastIndexOf(":");if($===-1)return{baseModel:f,thinkingSuffix:""};let j=Ef.find((J)=>J===f.substring($+1));if(!j)return{baseModel:f,thinkingSuffix:""};return{baseModel:f.substring(0,$),thinkingSuffix:`:${j}`}}function s(f){return f<1000?String(f):f<1e4?`${(f/1000).toFixed(1)}k`:`${Math.round(f/1000)}k`}function d(f,$){let j=f?H$(f):void 0,J=j?.baseModel??f,Z=Ef.find((B)=>B===$?.trim()),Q=j?.thinkingSuffix?j.thinkingSuffix.slice(1):Z;if(J){let B=J.lastIndexOf("/");if(B!==-1)J=J.slice(B+1)}return[J,Q?`thinking ${Q}`:void 0].filter(Boolean).join(" · ")}function u(f){if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${Math.floor(f/60000)}m${Math.floor(f%60000/1000)}s`}function _(f){let $=process.env.HOME;if($&&f.startsWith($))return`~${f.slice($.length)}`;return f}function H0(f){if(f<1000)return"now";if(f<60000)return`${Math.floor(f/1000)}s`;return`${Math.floor(f/60000)}m`}function k(f,$,j=Date.now()){if(f===void 0){if($==="needs_attention")return"needs attention";if($==="active_long_running")return"active but long-running";return}let J=H0(Math.max(0,j-f));if($==="needs_attention")return`no activity for ${J}`;if($==="active_long_running")return`active but long-running · last activity ${J} ago`;return J==="now"?"active now":`active ${J} ago`}function K0(f){return f==="complete"||f==="completed"}function W0(f){return f===1?"1 agent running":`${f} agents running`}function gf(f,$,j={}){let J=f.filter((Y)=>Y.status==="running").length,Z=f.filter((Y)=>K0(Y.status)).length,Q=f.filter((Y)=>Y.status==="failed").length,B=f.filter((Y)=>Y.status==="paused").length,X=[`${Z}/${$} done`];if(j.showRunning!==!1&&J>0)X.unshift(W0(J));if(Q>0)X.push(`${Q} failed`);if(B>0)X.push(`${B} paused`);return X.join(" · ")}import{randomUUID as q0}from"node:crypto";import*as F from"node:fs";import*as M from"node:path";import*as L$ from"node:path";var L0=128,O0=4;function Nf(f){return typeof f==="string"&&f.length>0&&f.length<=L0&&!L$.isAbsolute(f)&&!f.includes("/")&&!f.includes("\\")&&!f.includes("..")}function K$(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function W$(f,$){return typeof f==="string"&&f.length>0?f.slice(0,$):void 0}function O$(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(!$||typeof $!=="object")return;let j=$;if(!Nf(j.runId))return;return{runId:j.runId,...K$(j.stepIndex)!==void 0?{stepIndex:K$(j.stepIndex)}:{},...W$(j.agent,128)?{agent:W$(j.agent,128)}:{}}}).filter(($)=>Boolean($)).slice(0,O0)}import*as n from"node:path";import{fileURLToPath as G$}from"node:url";import*as P from"node:os";import*as c from"node:path";var rj=c.join(P.homedir(),".config","mcp","mcp.json"),aj={cursor:[c.join(P.homedir(),".cursor","mcp.json")],"claude-code":[c.join(P.homedir(),".claude","mcp.json"),c.join(P.homedir(),".claude.json"),c.join(P.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[c.join(P.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[c.join(P.homedir(),".codex","config.json")],windsurf:[c.join(P.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as tj}from"typebox/compile";function M$(f,$){let j=G$(f),J=n.extname(j),Z=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(J)?J:".ts";return n.join(n.dirname(j),`${$}${Z}`)}function V$(f){return n.basename(G$(f)).startsWith("dm-args.")}function M0(f=import.meta.url){let $=V$(f)?"subagent-prompt-runtime":n.join("..","runs","shared","subagent-prompt-runtime");return M$(f,$)}function V0(f=import.meta.url){let $=V$(f)?n.join("..","..","extension","fanout-child"):"fanout-child";return M$(f,$)}var O1=M0(),G1=V0();import*as U0 from"node:fs";import*as l from"node:path";var z0=[10,25,50,100,200,500,1000,2000,4000],T0=new Set(["EACCES","EBUSY","EPERM"]),U$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,z$=U$?new Int32Array(U$):void 0;function C0(f){if(f<=0)return;if(z$)try{Atomics.wait(z$,0,0,f);return}catch{}let $=Date.now()+f;while(Date.now()<$);}function F0(f){let $=f?.code;return typeof $==="string"&&T0.has($)}function b0(f,$,j,J,Z){for(let Q=0;;Q++)try{f.renameSync($,j);return}catch(B){let X=J[Q];if(X===void 0||!F0(B))throw B;Z(X)}}function S0(f={}){let $=f.fs??U0,j=f.now??Date.now,J=f.pid??process.pid,Z=f.random??Math.random,B=f.retryRenameErrors??process.platform==="win32"?f.retryDelaysMs??z0:[],X=f.wait??C0;return(Y,K)=>{$.mkdirSync(l.dirname(Y),{recursive:!0});let A=l.join(l.dirname(Y),`.${l.basename(Y)}.${J}.${j()}.${Z().toString(36).slice(2)}.tmp`);try{$.writeFileSync(A,JSON.stringify(K,null,2),"utf-8"),b0($,A,Y,B,X)}finally{$.rmSync(A,{force:!0})}}}var i=S0();var o=M.join(v,"nested-subagent-events"),nf="route.json",_0="registry.json",If=65536,Rf=12,Jf=16,xf=3;function Lf(f){return Nf(f)}function Df(f,$){if(!Lf($))throw Error(`${f} must be a non-empty safe id token.`)}function Of(f,$){Df(f,$)}function wf(f,$){let j=M.resolve(f),J=M.resolve($);return J===j||J.startsWith(`${j}${M.sep}`)}function C$(f){return M.dirname(M.resolve(f.eventSink))}function e(f){if(Of("rootRunId",f.rootRunId),Of("capabilityToken",f.capabilityToken),!wf(o,f.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!wf(o,f.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(C$(f)!==M.dirname(M.resolve(f.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function F$(f,$){if(!$.asyncDir)return;let j=M.resolve($.asyncDir),J=M.resolve(v,"nested-subagent-runs",f,$.id),Z=M.relative(J,j);return j===J||!Z.startsWith("..")&&!M.isAbsolute(Z)?j:void 0}function L(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function G(f,$=512){return typeof f==="string"&&f.length>0?f.slice(0,$):void 0}function y0(f){if(!f||typeof f!=="object")return;let $=f,j=L($.input),J=L($.output),Z=L($.total);return j!==void 0&&J!==void 0&&Z!==void 0?{input:j,output:J,total:Z}:void 0}function E0(f){if(!f||typeof f!=="object")return;let $=f,j=L($.inputTokens),J=L($.outputTokens),Z=L($.costUsd);return j!==void 0&&J!==void 0&&Z!==void 0?{inputTokens:j,outputTokens:J,costUsd:Z}:void 0}function Gf(f){if(!f||typeof f!=="object")return;let $=f,j=L($.maxTurns),J=L($.graceTurns),Z=L($.turnCount),Q=$.outcome==="within-budget"||$.outcome==="wrap-up-requested"||$.outcome==="exceeded"?$.outcome:void 0;if(j===void 0||J===void 0||Z===void 0||!Q)return;return{maxTurns:j,graceTurns:J,turnCount:Z,outcome:Q,...L($.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:L($.wrapUpRequestedAtTurn)}:{},...L($.exceededAtTurn)!==void 0?{exceededAtTurn:L($.exceededAtTurn)}:{}}}function g0(f,$){return f==="queued"||f==="running"||f==="complete"||f==="failed"||f==="paused"?f:$}function N0(f,$){if(!f||typeof f!=="object")return;let j=f,J=G(j.agent,128);if(!J)return;let Z=j.status==="pending"||j.status==="running"||j.status==="complete"||j.status==="completed"||j.status==="failed"||j.status==="paused"?j.status:"pending";return{agent:J,status:Z,...G(j.sessionFile,2048)?{sessionFile:G(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...L(j.lastActivityAt)!==void 0?{lastActivityAt:L(j.lastActivityAt)}:{},...G(j.currentTool,128)?{currentTool:G(j.currentTool,128)}:{},...L(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:L(j.currentToolStartedAt)}:{},...G(j.currentPath,2048)?{currentPath:G(j.currentPath,2048)}:{},...L(j.turnCount)!==void 0?{turnCount:L(j.turnCount)}:{},...L(j.toolCount)!==void 0?{toolCount:L(j.toolCount)}:{},...L(j.startedAt)!==void 0?{startedAt:L(j.startedAt)}:{},...L(j.endedAt)!==void 0?{endedAt:L(j.endedAt)}:{},...G(j.error,1024)?{error:G(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...Gf(j.turnBudget)?{turnBudget:Gf(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...$<xf&&Array.isArray(j.children)?{children:j.children.map((Q)=>Vf(Q,$+1)).filter((Q)=>Boolean(Q)).slice(0,Jf)}:{}}}function Vf(f,$=0){if(!f||typeof f!=="object")return;let j=f;if(!Lf(j.id)||!Lf(j.parentRunId))return;let J=O$(j.path),Z=Array.isArray(j.steps)?j.steps.map((X)=>N0(X,$+1)).filter((X)=>Boolean(X)).slice(0,Rf):void 0,Q=y0(j.totalTokens),B=E0(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...L(j.parentStepIndex)!==void 0?{parentStepIndex:L(j.parentStepIndex)}:{},...G(j.parentAgent,128)?{parentAgent:G(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,L(j.depth)??0),xf),path:J,state:g0(j.state,"running"),...G(j.asyncDir,2048)?{asyncDir:G(j.asyncDir,2048)}:{},...L(j.pid)!==void 0&&L(j.pid)>0&&Number.isInteger(L(j.pid))?{pid:L(j.pid)}:{},...G(j.sessionId,256)?{sessionId:G(j.sessionId,256)}:{},...G(j.sessionFile,2048)?{sessionFile:G(j.sessionFile,2048)}:{},...G(j.intercomTarget,256)?{intercomTarget:G(j.intercomTarget,256)}:{},...G(j.ownerIntercomTarget,256)?{ownerIntercomTarget:G(j.ownerIntercomTarget,256)}:{},...G(j.leafIntercomTarget,256)?{leafIntercomTarget:G(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...G(j.controlInbox,2048)?{controlInbox:G(j.controlInbox,2048)}:{},...G(j.capabilityToken,128)?{capabilityToken:G(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...G(j.agent,128)?{agent:G(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((X)=>G(X,128)).filter((X)=>Boolean(X)).slice(0,Rf)}:{},...L(j.currentStep)!==void 0?{currentStep:L(j.currentStep)}:{},...L(j.chainStepCount)!==void 0?{chainStepCount:L(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...L(j.lastActivityAt)!==void 0?{lastActivityAt:L(j.lastActivityAt)}:{},...G(j.currentTool,128)?{currentTool:G(j.currentTool,128)}:{},...L(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:L(j.currentToolStartedAt)}:{},...G(j.currentPath,2048)?{currentPath:G(j.currentPath,2048)}:{},...L(j.turnCount)!==void 0?{turnCount:L(j.turnCount)}:{},...L(j.toolCount)!==void 0?{toolCount:L(j.toolCount)}:{},...Q?{totalTokens:Q}:{},...B?{totalCost:B}:{},...L(j.startedAt)!==void 0?{startedAt:L(j.startedAt)}:{},...L(j.endedAt)!==void 0?{endedAt:L(j.endedAt)}:{},...L(j.lastUpdate)!==void 0?{lastUpdate:L(j.lastUpdate)}:{},...L(j.timeoutMs)!==void 0?{timeoutMs:L(j.timeoutMs)}:{},...L(j.deadlineAt)!==void 0?{deadlineAt:L(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...Gf(j.turnBudget)?{turnBudget:Gf(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...G(j.error,1024)?{error:G(j.error,1024)}:{},...Z&&Z.length>0?{steps:Z}:{},...$<xf&&Array.isArray(j.children)?{children:j.children.map((X)=>Vf(X,$+1)).filter((X)=>Boolean(X)).slice(0,Jf)}:{}}}function kf(f,$){if(Buffer.byteLength(f,"utf-8")>If)return;let j;try{j=JSON.parse(f)}catch{return}if(!j||typeof j!=="object")return;let J=j;if(J.type!=="subagent.nested.started"&&J.type!=="subagent.nested.updated"&&J.type!=="subagent.nested.completed")return;if(J.rootRunId!==$.rootRunId||J.capabilityToken!==$.capabilityToken)return;if(!Lf(J.parentRunId))return;let Z=L(J.ts);if(Z===void 0)return;let Q=Vf(J.child);if(!Q||Q.id===$.rootRunId)return;let B={...Q,controlInbox:$.controlInbox,capabilityToken:$.capabilityToken,ownerState:Q.ownerState??"unknown"};return{type:J.type,ts:Z,rootRunId:$.rootRunId,parentRunId:J.parentRunId,...L(J.parentStepIndex)!==void 0?{parentStepIndex:L(J.parentStepIndex)}:{},capabilityToken:$.capabilityToken,child:B}}function R0(f,$){if(!f.includes(`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
${X}`:B,A=((f.steps?.length)?f.steps:[{agent:"subagent",status:"running"}]).map((W)=>W.status==="running"||W.status==="pending"?{...W,status:"failed",activityState:void 0,endedAt:W.endedAt??j,durationMs:W.startedAt!==void 0&&W.durationMs===void 0?Math.max(0,j-W.startedAt):W.durationMs,exitCode:W.exitCode??1,error:W.error??Y}:W),H={...f,state:"failed",activityState:void 0,lastUpdate:j,endedAt:j,steps:A},O=A[f.currentStep??0]?.agent??A[0]?.agent??"subagent";return{status:H,message:Y,result:{id:Z,agent:O,mode:f.mode,success:!1,state:"failed",summary:Y,results:A.map((W)=>({agent:W.agent,output:W.status==="complete"||W.status==="completed"?"":Y,error:W.status==="complete"||W.status==="completed"?void 0:W.error??Y,success:W.status==="complete"||W.status==="completed",model:W.model,attemptedModels:W.attemptedModels,modelAttempts:W.modelAttempts,sessionFile:W.sessionFile})),exitCode:1,timestamp:j,durationMs:Math.max(0,j-f.startedAt),asyncDir:$,sessionId:f.sessionId,sessionFile:f.sessionFile}}}function N$(f,$,j,J,Z){let Q=i0($,f,J,Z);return i(j,Q.result),i(E.join(f,"status.json"),Q.status),v0(E.join(f,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:J,runId:Q.status.runId,pid:$.pid,resultPath:j,message:Q.message}),{status:Q.status,repaired:!0,resultPath:j,message:Q.message}}function R$(f){return f==="complete"||f==="failed"||f==="paused"}function*of(f){for(let $ of f??[])yield $,yield*of($.children),yield*of($.steps?.flatMap((j)=>j.children??[]))}function Zf(f,$={}){let j=t(f);for(let J of of(j.children)){if(J.state!=="running"&&J.state!=="queued")continue;let Z=F$(f.rootRunId,J);if(!Z)continue;let Q=ff(Z,{...$,resultsDir:E.join($.resultsDir??w,"nested",f.rootRunId)}),B=Q.status;if(!B)continue;if(!Q.repaired&&!R$(B.state))continue;let X=$.now?.()??Date.now();_$(f,{type:R$(B.state)?"subagent.nested.completed":"subagent.nested.updated",ts:X,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,child:y$(B,Z,{id:J.id,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,depth:J.depth,path:J.path,mode:J.mode,ts:X})})}}function p0(f,$=process.kill){try{return $(f,0),"alive"}catch(j){let J=typeof j==="object"&&j!==null&&"code"in j?j.code:void 0;if(J==="ESRCH")return"dead";if(J==="EPERM")return"unknown";return"unknown"}}function ff(f,$={}){let j=$.now?.()??Date.now(),J=h0(f),Z=!J&&$.startedRun?l0(f,$.startedRun,j):void 0,Q=J??Z;if(!Q)return{status:null,repaired:!1};let B=Q.runId||E.basename(f),X=E.join($.resultsDir??w,`${B}.json`);if(q.existsSync(X)){let K=Q.state==="running"||Q.state==="queued"?u0(Q,X,j):void 0;if(K)return i(E.join(f,"status.json"),K),{status:K,repaired:!0,resultPath:X,message:"Existing async result file was used to repair stale running status."};return{status:Q,repaired:!1,resultPath:X}}if(Q.state!=="running"||typeof Q.pid!=="number")return{status:J??null,repaired:!1,resultPath:X};if(!J){let K=$.startedRun?.startedAt??Q.startedAt;if(j-K<($.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:X}}if(p0(Q.pid,$.kill)!=="dead"){let K=$.staleAlivePidMs??86400000,A=Q.lastUpdate??Q.startedAt;if(j-A<=K)return{status:J??null,repaired:!1,resultPath:X};let H=`Async runner process ${Q.pid} still has a live PID, but status has not updated for ${j-A}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return N$(f,Q,X,j,H)}return N$(f,Q,X,j)}function Qf(f){return f instanceof Error?f.message:String(f)}function df(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function r0(f,$){let j=N.join(f,$);try{return Bf.statSync(j).isDirectory()}catch(J){if(df(J))return!1;throw Error(`Failed to inspect async run path '${j}': ${Qf(J)}`,{cause:J instanceof Error?J:void 0})}}function a0(f){if(!f)return;try{return Bf.statSync(f).mtimeMs}catch($){if(df($))return;throw Error(`Failed to inspect async output file '${f}': ${Qf($)}`,{cause:$ instanceof Error?$:void 0})}}function s0(f,$){if($.state!=="running")return{activityState:$.activityState,lastActivityAt:$.lastActivityAt};let j=$.outputFile?N.isAbsolute($.outputFile)?$.outputFile:N.join(f,$.outputFile):void 0,J=typeof $.currentStep==="number"?$.steps?.[$.currentStep]:void 0;return{activityState:$.activityState,lastActivityAt:$.lastActivityAt??a0(j)??J?.lastActivityAt??J?.startedAt??$.startedAt}}function e0(f,$,j=[],J){if($.sessionId!==void 0&&typeof $.sessionId!=="string")throw Error(`Invalid async status '${N.join(f,"status.json")}': sessionId must be a string.`);let{activityState:Z,lastActivityAt:Q}=s0(f,$),B=$.steps??[],X=$.chainStepCount??B.length,Y=p($.parallelGroups,B.length,X),K=[];if(j.length===0&&J)try{K=t(J)?.children??[]}catch(H){j.push(`Nested status unavailable: ${Qf(H)}`)}let A=B.map((H,O)=>{let{activityState:W,lastActivityAt:U}=H;return{index:O,agent:H.agent,...H.label?{label:H.label}:{},...H.phase?{phase:H.phase}:{},...H.outputName?{outputName:H.outputName}:{},...H.structured?{structured:H.structured}:{},status:H.status,...W?{activityState:W}:{},...U?{lastActivityAt:U}:{},...H.currentTool?{currentTool:H.currentTool}:{},...H.currentToolArgs?{currentToolArgs:H.currentToolArgs}:{},...H.currentToolStartedAt?{currentToolStartedAt:H.currentToolStartedAt}:{},...H.currentPath?{currentPath:H.currentPath}:{},...H.recentTools?{recentTools:H.recentTools.map((C)=>({...C}))}:{},...H.recentOutput?{recentOutput:[...H.recentOutput]}:{},...H.turnCount!==void 0?{turnCount:H.turnCount}:{},...H.toolCount!==void 0?{toolCount:H.toolCount}:{},...H.steerCount!==void 0?{steerCount:H.steerCount}:{},...H.lastSteerAt!==void 0?{lastSteerAt:H.lastSteerAt}:{},...H.durationMs!==void 0?{durationMs:H.durationMs}:{},...H.tokens?{tokens:H.tokens}:{},...H.totalCost?{totalCost:H.totalCost}:{},...H.skills?{skills:H.skills}:{},...H.model?{model:H.model}:{},...H.thinking?{thinking:H.thinking}:{},...H.attemptedModels?{attemptedModels:H.attemptedModels}:{},...H.error?{error:H.error}:{},...H.timedOut!==void 0?{timedOut:H.timedOut}:{},...H.turnBudget?{turnBudget:H.turnBudget}:{},...H.turnBudgetExceeded!==void 0?{turnBudgetExceeded:H.turnBudgetExceeded}:{},...H.wrapUpRequested!==void 0?{wrapUpRequested:H.wrapUpRequested}:{},...H.children?.length?{children:H.children}:{}}});return Uf($.runId||N.basename(f),A,K),{id:$.runId||N.basename(f),asyncDir:f,...$.sessionId?{sessionId:$.sessionId}:{},state:$.state,...$.error?{error:$.error}:{},activityState:Z,lastActivityAt:Q,currentTool:$.currentTool,currentToolStartedAt:$.currentToolStartedAt,currentPath:$.currentPath,turnCount:$.turnCount,toolCount:$.toolCount,steerCount:$.steerCount,lastSteerAt:$.lastSteerAt,mode:$.mode,cwd:$.cwd,startedAt:$.startedAt,lastUpdate:$.lastUpdate,endedAt:$.endedAt,...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...$.timedOut!==void 0?{timedOut:$.timedOut}:{},...$.turnBudget?{turnBudget:$.turnBudget}:{},...$.turnBudgetExceeded!==void 0?{turnBudgetExceeded:$.turnBudgetExceeded}:{},...$.wrapUpRequested!==void 0?{wrapUpRequested:$.wrapUpRequested}:{},currentStep:$.currentStep,...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.pendingAppends!==void 0?{pendingAppends:$.pendingAppends}:{},...Y.length?{parallelGroups:Y}:{},steps:A,...K.length?{nestedChildren:K}:{},...j.length?{nestedWarnings:j}:{},...$.sessionDir?{sessionDir:$.sessionDir}:{},...$.outputFile?{outputFile:$.outputFile}:{},...$.totalTokens?{totalTokens:$.totalTokens}:{},...$.totalCost?{totalCost:$.totalCost}:{},...$.sessionFile?{sessionFile:$.sessionFile}:{}}}function t0(f){let $=(j)=>{switch(j){case"running":return 0;case"queued":return 1;case"failed":return 2;case"paused":return 2;case"complete":return 3}};return[...f].sort((j,J)=>{let Z=$(j.state)-$(J.state);if(Z!==0)return Z;let Q=j.lastUpdate??j.endedAt??j.startedAt;return(J.lastUpdate??J.endedAt??J.startedAt)-Q})}function Tf(f,$={}){let j;try{j=Bf.readdirSync(f).filter((Y)=>r0(f,Y))}catch(Y){if(df(Y))return[];throw Error(`Failed to list async runs in '${f}': ${Qf(Y)}`,{cause:Y instanceof Error?Y:void 0})}let J=$.states?new Set($.states):void 0,Z=[],Q,B=(Y)=>{if(!Q)Q=S$();return Q.get(Y)};for(let Y of j){let K=N.join(f,Y),H=($.reconcile===!1?void 0:ff(K,{resultsDir:$.resultsDir,kill:$.kill,now:$.now}))?.status??Hf(K);if(!H)continue;if(J&&!J.has(H.state))continue;if($.sessionId&&H.sessionId!==$.sessionId)continue;let O=[],W;try{if(W=B(H.runId||N.basename(K)),W)Zf(W,{resultsDir:$.resultsDir,kill:$.kill,now:$.now})}catch(C){O.push(`Nested status unavailable: ${Qf(C)}`)}let U=e0(K,H,O,W);Z.push(U)}let X=t0(Z);return $.limit!==void 0?X.slice(0,$.limit):X}function w$(f){let $=[];if(f.currentTool&&f.currentToolStartedAt!==void 0)$.push(`tool ${f.currentTool} ${u(Math.max(0,Date.now()-f.currentToolStartedAt))}`);else if(f.currentTool)$.push(`tool ${f.currentTool}`);if(f.currentPath)$.push(_(f.currentPath));if(f.turnCount!==void 0)$.push(`${f.turnCount} turns`);if(f.turnBudgetExceeded&&f.turnBudget)$.push(`turn budget exceeded ${f.turnBudget.turnCount}/${f.turnBudget.maxTurns}+${f.turnBudget.graceTurns}`);else if(f.wrapUpRequested&&f.turnBudget)$.push(`wrap-up requested ${f.turnBudget.turnCount}/${f.turnBudget.maxTurns}`);else if(f.turnBudget)$.push(`turn budget ${f.turnBudget.turnCount}/${f.turnBudget.maxTurns}+${f.turnBudget.graceTurns}`);if(f.toolCount!==void 0)$.push(`${f.toolCount} tools`);if(f.steerCount!==void 0)$.push(`${f.steerCount} steers`);if(typeof f.lastSteerAt==="number"&&Number.isFinite(f.lastSteerAt))$.push(`last steer ${new Date(f.lastSteerAt).toISOString()}`);let j=k(f.lastActivityAt,f.activityState);return j||$.length?[j,...$].filter(Boolean).join(" | "):void 0}function fj(f){let $=f.label?`${f.label} (${f.agent})`:f.agent,j=f.phase?`[${f.phase}] `:"",J=[`${f.index+1}. ${j}${$}`,f.status],Z=w$(f);if(Z)J.push(Z);let Q=d(f.model,f.thinking);if(Q)J.push(Q);if(f.durationMs!==void 0)J.push(u(f.durationMs));if(f.tokens)J.push(`${s(f.tokens.total)} tok`);return J.join(" | ")}function Af(f){if(!f.outputFile)return;return N.isAbsolute(f.outputFile)?f.outputFile:N.join(f.asyncDir,f.outputFile)}function Xf(f){let $=f.steps.length||1,j=f.chainStepCount??$,J=p(f.parallelGroups,f.steps.length,j),Z=f.currentStep!==void 0?J.find((Q)=>f.currentStep>=Q.start&&f.currentStep<Q.start+Q.count):void 0;if(Z){let Q=f.steps.slice(Z.start,Z.start+Z.count),B=gf(Q,Z.count,{showRunning:f.state==="running"});if(f.mode==="parallel")return B;return`step ${Z.stepIndex+1}/${j} · parallel group: ${B}`}if(f.mode==="parallel")return gf(f.steps,$,{showRunning:f.state==="running"});if(f.mode==="chain"&&f.currentStep!==void 0&&J.length>0)return`step ${zf(f.currentStep,j,J)+1}/${j}`;return f.currentStep!==void 0?`step ${f.currentStep+1}/${$}`:`steps ${$}`}function $j(f){let $=Xf(f),j=f.cwd?_(f.cwd):_(f.asyncDir),J=w$(f),Z=f.pendingAppends?` | ${f.pendingAppends} pending append${f.pendingAppends===1?"":"s"}`:"";return`${f.id} | ${f.state}${J?` | ${J}`:""} | ${f.mode} | ${$}${Z} | ${j}`}function k$(f,$="Active async runs"){if(f.length===0)return`No ${$.toLowerCase()}.`;let j=[`${$}: ${f.length}`,""];for(let J of f){j.push(`- ${$j(J)}`);for(let X of J.steps)j.push(` ${fj(X)}`),j.push(...x(X.children,{indent:" ",maxLines:12}));let Z=new Set(J.steps.flatMap((X)=>X.children?.map((Y)=>Y.id)??[])),Q=J.nestedChildren?.filter((X)=>!Z.has(X.id))??[];if(j.push(...x(Q,{indent:" ",maxLines:12})),J.error)j.push(` Error: ${J.error}`);for(let X of J.nestedWarnings??[])j.push(` Warning: ${X}`);let B=Af(J);if(B)j.push(` output: ${_(B)}`);if(J.sessionFile)j.push(` session: ${_(J.sessionFile)}`);j.push("")}return j.join(`
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns } from "./async-status.js";
|
|
4
|
+
import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.js";
|
|
5
|
+
import { formatNestedRunStatusLines } from "../shared/nested-render.js";
|
|
6
|
+
import { formatModelThinking } from "../../shared/formatters.js";
|
|
7
|
+
import { formatActivityLabel } from "../../shared/status-format.js";
|
|
8
|
+
import { ASYNC_DIR, RESULTS_DIR } from "../../shared/types.js";
|
|
9
|
+
import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
|
|
10
|
+
import { resolveAsyncRunLocation } from "./async-resume.js";
|
|
11
|
+
import { resolveSubagentRunId } from "./run-id-resolver.js";
|
|
12
|
+
import { flatToLogicalStepIndex, normalizeParallelGroups } from "./parallel-groups.js";
|
|
13
|
+
import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.js";
|
|
14
|
+
import { attachRootChildrenToSteps, findNestedRouteForRootId, projectNestedRegistryForRoot } from "../shared/nested-events.js";
|
|
15
|
+
function hasExistingSessionFile(value) {
|
|
16
|
+
return typeof value === "string" && fs.existsSync(value);
|
|
17
|
+
}
|
|
18
|
+
function formatResumeGuidance(runId, children, fallbackSessionFile) {
|
|
19
|
+
const knownChildren = children.map((child, index) => ({ child, index })).filter(({ child }) => typeof child.agent === "string");
|
|
20
|
+
if (!runId || knownChildren.length === 0)
|
|
21
|
+
return "Resume: unavailable; no child session file was persisted.";
|
|
22
|
+
const singleSessionFile = knownChildren[0]?.child.sessionFile ?? fallbackSessionFile;
|
|
23
|
+
if (children.length === 1 && knownChildren.length === 1 && hasExistingSessionFile(singleSessionFile)) {
|
|
24
|
+
return `Revive: subagent({ action: "resume", id: "${runId}", message: "..." })`;
|
|
25
|
+
}
|
|
26
|
+
const childWithSession = knownChildren.find(({ child }) => hasExistingSessionFile(child.sessionFile));
|
|
27
|
+
if (childWithSession) {
|
|
28
|
+
return `Revive child: subagent({ action: "resume", id: "${runId}", index: ${childWithSession.index}, message: "..." })`;
|
|
29
|
+
}
|
|
30
|
+
return "Resume: unavailable; no child session file was persisted.";
|
|
31
|
+
}
|
|
32
|
+
function stepLineLabel(status, index) {
|
|
33
|
+
const steps = status.steps ?? [];
|
|
34
|
+
if (status.mode === "parallel")
|
|
35
|
+
return `Agent ${index + 1}/${steps.length || 1}`;
|
|
36
|
+
if (status.mode === "chain") {
|
|
37
|
+
const chainStepCount = status.chainStepCount ?? (steps.length || 1);
|
|
38
|
+
const groups = normalizeParallelGroups(status.parallelGroups, steps.length, chainStepCount);
|
|
39
|
+
const group = groups.find((candidate) => index >= candidate.start && index < candidate.start + candidate.count);
|
|
40
|
+
if (group)
|
|
41
|
+
return `Step ${group.stepIndex + 1}/${chainStepCount} Agent ${index - group.start + 1}/${group.count}`;
|
|
42
|
+
return `Step ${flatToLogicalStepIndex(index, chainStepCount, groups) + 1}/${chainStepCount}`;
|
|
43
|
+
}
|
|
44
|
+
return `Step ${index + 1}`;
|
|
45
|
+
}
|
|
46
|
+
function nestedRunDisplayName(run) {
|
|
47
|
+
if (run.agent)
|
|
48
|
+
return run.agent;
|
|
49
|
+
if (run.agents?.length)
|
|
50
|
+
return run.agents.join(", ");
|
|
51
|
+
return run.id;
|
|
52
|
+
}
|
|
53
|
+
function formatSteeringSummary(input) {
|
|
54
|
+
const parts = [];
|
|
55
|
+
if (input.steerCount !== undefined)
|
|
56
|
+
parts.push(`${input.steerCount} steer${input.steerCount === 1 ? "" : "s"}`);
|
|
57
|
+
if (typeof input.lastSteerAt === "number" && Number.isFinite(input.lastSteerAt))
|
|
58
|
+
parts.push(`last ${new Date(input.lastSteerAt).toISOString()}`);
|
|
59
|
+
return parts.length ? parts.join(", ") : undefined;
|
|
60
|
+
}
|
|
61
|
+
function rememberedForegroundChildOutput(child) {
|
|
62
|
+
const outputPath = child.artifactPaths?.outputPath;
|
|
63
|
+
if (outputPath && fs.existsSync(outputPath)) {
|
|
64
|
+
try {
|
|
65
|
+
const artifactOutput = fs.readFileSync(outputPath, "utf-8").trim();
|
|
66
|
+
if (artifactOutput)
|
|
67
|
+
return artifactOutput;
|
|
68
|
+
} catch {}
|
|
69
|
+
}
|
|
70
|
+
return child.finalOutput ?? "";
|
|
71
|
+
}
|
|
72
|
+
function formatRememberedForegroundStatus(run) {
|
|
73
|
+
const lines = [
|
|
74
|
+
`Run: ${run.runId}`,
|
|
75
|
+
"State: remembered foreground",
|
|
76
|
+
`Mode: ${run.mode}`,
|
|
77
|
+
`Updated: ${new Date(run.updatedAt).toISOString()}`,
|
|
78
|
+
`Cwd: ${run.cwd}`
|
|
79
|
+
];
|
|
80
|
+
for (const child of run.children) {
|
|
81
|
+
const output = rememberedForegroundChildOutput(child).trim().split(/\r?\n/).find((line) => line.trim());
|
|
82
|
+
const parts = [
|
|
83
|
+
`${child.index + 1}. ${child.agent} ${child.status}`,
|
|
84
|
+
child.exitCode !== undefined ? `exit ${child.exitCode}` : undefined,
|
|
85
|
+
child.detachedReason ? `detached: ${child.detachedReason}` : undefined,
|
|
86
|
+
output ? `output: ${output.slice(0, 160)}` : undefined
|
|
87
|
+
].filter(Boolean);
|
|
88
|
+
lines.push(parts.join(", "));
|
|
89
|
+
if (child.sessionFile)
|
|
90
|
+
lines.push(` Session: ${child.sessionFile}`);
|
|
91
|
+
if (child.transcriptPath)
|
|
92
|
+
lines.push(` Transcript: ${child.transcriptPath}`);
|
|
93
|
+
if (child.artifactPaths?.outputPath)
|
|
94
|
+
lines.push(` Output: ${child.artifactPaths.outputPath}`);
|
|
95
|
+
if (child.transcriptError)
|
|
96
|
+
lines.push(` Transcript warning: ${child.transcriptError}`);
|
|
97
|
+
}
|
|
98
|
+
lines.push("", `Status: subagent({ action: "status", id: "${run.runId}" })`);
|
|
99
|
+
if (run.children.length === 1)
|
|
100
|
+
lines.push(`Transcript: subagent({ action: "status", id: "${run.runId}", view: "transcript" })`);
|
|
101
|
+
else
|
|
102
|
+
lines.push(`Transcript: subagent({ action: "status", id: "${run.runId}", index: 0, view: "transcript" })`);
|
|
103
|
+
const resumable = run.children.find((child) => child.status !== "detached" && hasExistingSessionFile(child.sessionFile));
|
|
104
|
+
if (resumable) {
|
|
105
|
+
lines.push(run.children.length === 1 ? `Revive: subagent({ action: "resume", id: "${run.runId}", message: "..." })` : `Revive child: subagent({ action: "resume", id: "${run.runId}", index: ${resumable.index}, message: "..." })`);
|
|
106
|
+
} else if (run.children.some((child) => child.status === "detached")) {
|
|
107
|
+
lines.push("Recovery: child detached for intercom coordination; status will show recovered output after the child exits when DM can observe it.");
|
|
108
|
+
} else {
|
|
109
|
+
lines.push("Resume: unavailable; no child session file was persisted.");
|
|
110
|
+
}
|
|
111
|
+
return lines.join(`
|
|
112
|
+
`);
|
|
113
|
+
}
|
|
114
|
+
function formatRememberedForegroundTranscript(run, options) {
|
|
115
|
+
let index = options.index;
|
|
116
|
+
if (index !== undefined && !Number.isInteger(index))
|
|
117
|
+
throw new Error("Transcript index must be an integer.");
|
|
118
|
+
if (index === undefined && run.children.length === 1)
|
|
119
|
+
index = 0;
|
|
120
|
+
if (index === undefined)
|
|
121
|
+
return `Transcript view requires index for foreground run '${run.runId}' with ${run.children.length} children.`;
|
|
122
|
+
if (index < 0 || index >= run.children.length)
|
|
123
|
+
throw new Error(`Transcript index ${index} is out of range for ${run.children.length} foreground children.`);
|
|
124
|
+
const child = run.children[index];
|
|
125
|
+
const lineLimit = Math.max(1, Math.min(options.lines ?? 80, 1000));
|
|
126
|
+
const outputLines = rememberedForegroundChildOutput(child).split(/\r?\n/).filter((line) => line.trim()).slice(-lineLimit);
|
|
127
|
+
const lines = [
|
|
128
|
+
`Run: ${run.runId}`,
|
|
129
|
+
`State: ${child.status}`,
|
|
130
|
+
`Child: ${index} (${child.agent})`,
|
|
131
|
+
child.sessionFile ? `Session: ${child.sessionFile}` : undefined,
|
|
132
|
+
child.transcriptPath ? `Transcript: ${child.transcriptPath}` : undefined,
|
|
133
|
+
child.artifactPaths?.outputPath ? `Output: ${child.artifactPaths.outputPath}` : undefined
|
|
134
|
+
].filter((line) => Boolean(line));
|
|
135
|
+
lines.push("Result transcript tail:");
|
|
136
|
+
if (outputLines.length === 0)
|
|
137
|
+
lines.push(" (no recovered final output available yet)");
|
|
138
|
+
else
|
|
139
|
+
for (const line of outputLines)
|
|
140
|
+
lines.push(` ${line}`);
|
|
141
|
+
return lines.join(`
|
|
142
|
+
`);
|
|
143
|
+
}
|
|
144
|
+
function formatNestedExactStatus(rootRunId, run) {
|
|
145
|
+
const lines = [
|
|
146
|
+
`Nested run: ${run.id}`,
|
|
147
|
+
`Root: ${rootRunId}`,
|
|
148
|
+
`Parent: ${run.parentRunId}${run.parentStepIndex !== undefined ? ` step ${run.parentStepIndex + 1}` : ""}`,
|
|
149
|
+
`State: ${run.state}`,
|
|
150
|
+
run.activityState || run.lastActivityAt ? `Activity: ${formatActivityLabel(run.lastActivityAt, run.activityState)}` : undefined,
|
|
151
|
+
run.mode ? `Mode: ${run.mode}` : undefined,
|
|
152
|
+
`Agent: ${nestedRunDisplayName(run)}`,
|
|
153
|
+
run.currentStep !== undefined ? `Progress: step ${run.currentStep + 1}/${run.chainStepCount ?? run.steps?.length ?? 1}` : undefined,
|
|
154
|
+
run.turnBudget ? `Turn budget: ${run.turnBudget.turnCount}/${run.turnBudget.maxTurns}+${run.turnBudget.graceTurns} (${run.turnBudget.outcome})` : undefined,
|
|
155
|
+
run.asyncDir ? `Dir: ${run.asyncDir}` : undefined,
|
|
156
|
+
run.sessionFile ? `Session: ${run.sessionFile}` : undefined,
|
|
157
|
+
run.error ? `Error: ${run.error}` : undefined
|
|
158
|
+
].filter((line) => Boolean(line));
|
|
159
|
+
if (run.path.length) {
|
|
160
|
+
lines.push(`Path: ${run.path.map((part) => `${part.runId}${part.stepIndex !== undefined ? `:${part.stepIndex + 1}` : ""}${part.agent ? `:${part.agent}` : ""}`).join(" > ")} > ${run.id}`);
|
|
161
|
+
}
|
|
162
|
+
if (run.steps?.length) {
|
|
163
|
+
lines.push("Steps:");
|
|
164
|
+
for (const [index, step] of run.steps.entries()) {
|
|
165
|
+
const activity = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
|
|
166
|
+
const budget = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
167
|
+
lines.push(` ${index + 1}. ${step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
|
|
168
|
+
lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true }));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
lines.push(...formatNestedRunStatusLines(run.children, { indent: " ", commandHints: true }));
|
|
172
|
+
lines.push("Commands:", ` Status: subagent({ action: "status", id: "${run.id}" })`, ` Interrupt: subagent({ action: "interrupt", id: "${run.id}" })`, ` Resume: subagent({ action: "resume", id: "${run.id}", message: "..." })`, ` Steer: subagent({ action: "steer", id: "${run.id}", message: "..." })`, ` Root status: subagent({ action: "status", id: "${rootRunId}" })`);
|
|
173
|
+
return lines.join(`
|
|
174
|
+
`);
|
|
175
|
+
}
|
|
176
|
+
export function inspectSubagentStatus(params, deps = {}) {
|
|
177
|
+
const asyncDirRoot = deps.asyncDirRoot ?? ASYNC_DIR;
|
|
178
|
+
const resultsDir = deps.resultsDir ?? RESULTS_DIR;
|
|
179
|
+
const currentSessionId = deps.state?.currentSessionId ?? undefined;
|
|
180
|
+
if (params.view && params.view !== "fleet" && params.view !== "transcript") {
|
|
181
|
+
return {
|
|
182
|
+
content: [{ type: "text", text: `Unknown status view: ${params.view}. Valid: fleet, transcript.` }],
|
|
183
|
+
isError: true,
|
|
184
|
+
details: { mode: "single", results: [] }
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
if (params.view === "fleet") {
|
|
188
|
+
return inspectSubagentFleet(params, { asyncDirRoot, resultsDir, kill: deps.kill, now: deps.now, state: deps.state, childSafe: Boolean(deps.nested) });
|
|
189
|
+
}
|
|
190
|
+
if (!params.id && !params.runId && !params.dir) {
|
|
191
|
+
if (deps.nested) {
|
|
192
|
+
return {
|
|
193
|
+
content: [{ type: "text", text: "Child-safe subagent status requires an id when no foreground run is active." }],
|
|
194
|
+
isError: true,
|
|
195
|
+
details: { mode: "single", results: [] }
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
const runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: currentSessionId, resultsDir, kill: deps.kill, now: deps.now });
|
|
200
|
+
if (params.view === "transcript") {
|
|
201
|
+
if (runs.length === 1)
|
|
202
|
+
return inspectSubagentStatus({ ...params, id: runs[0].id }, deps);
|
|
203
|
+
return {
|
|
204
|
+
content: [{ type: "text", text: runs.length === 0 ? "No active async run transcript is available." : `Transcript view requires an id when ${runs.length} active async runs exist. Use subagent({ action: "status", view: "fleet" }) to choose one.` }],
|
|
205
|
+
isError: true,
|
|
206
|
+
details: { mode: "single", results: [] }
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
content: [{ type: "text", text: formatAsyncRunList(runs) }],
|
|
211
|
+
details: { mode: "single", results: [] }
|
|
212
|
+
};
|
|
213
|
+
} catch (error) {
|
|
214
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
215
|
+
return {
|
|
216
|
+
content: [{ type: "text", text: message }],
|
|
217
|
+
isError: true,
|
|
218
|
+
details: { mode: "single", results: [] }
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
let location;
|
|
223
|
+
try {
|
|
224
|
+
const requestedId = params.id ?? params.runId;
|
|
225
|
+
if (!params.dir && requestedId) {
|
|
226
|
+
const resolved = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
|
|
227
|
+
if (resolved?.kind === "foreground") {
|
|
228
|
+
const run = deps.state?.foregroundRuns?.get(resolved.id);
|
|
229
|
+
if (run) {
|
|
230
|
+
try {
|
|
231
|
+
return {
|
|
232
|
+
content: [{ type: "text", text: params.view === "transcript" ? formatRememberedForegroundTranscript(run, { index: params.index, lines: params.lines }) : formatRememberedForegroundStatus(run) }],
|
|
233
|
+
details: { mode: "single", results: [] }
|
|
234
|
+
};
|
|
235
|
+
} catch (error) {
|
|
236
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
237
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (resolved?.kind === "nested") {
|
|
242
|
+
reconcileNestedAsyncDescendants(resolved.match.route, { resultsDir, kill: deps.kill, now: deps.now });
|
|
243
|
+
const refreshed = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
|
|
244
|
+
const nested = refreshed?.kind === "nested" ? refreshed : resolved;
|
|
245
|
+
if (params.view === "transcript") {
|
|
246
|
+
try {
|
|
247
|
+
return { content: [{ type: "text", text: formatNestedRunTranscript(nested.match.run, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
|
|
248
|
+
} catch (error) {
|
|
249
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
250
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return { content: [{ type: "text", text: formatNestedExactStatus(nested.match.rootRunId, nested.match.run) }], details: { mode: "single", results: [] } };
|
|
254
|
+
}
|
|
255
|
+
if (resolved?.kind === "async")
|
|
256
|
+
location = resolved.location;
|
|
257
|
+
else
|
|
258
|
+
location = { asyncDir: null, resultPath: null, resolvedId: requestedId };
|
|
259
|
+
} else {
|
|
260
|
+
location = resolveAsyncRunLocation(params, asyncDirRoot, resultsDir);
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
264
|
+
return {
|
|
265
|
+
content: [{ type: "text", text: message }],
|
|
266
|
+
isError: true,
|
|
267
|
+
details: { mode: "single", results: [] }
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const { asyncDir, resultPath, resolvedId } = location;
|
|
271
|
+
if (!asyncDir && !resultPath) {
|
|
272
|
+
return {
|
|
273
|
+
content: [{ type: "text", text: "Async run not found. Provide id or dir." }],
|
|
274
|
+
isError: true,
|
|
275
|
+
details: { mode: "single", results: [] }
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
if (asyncDir) {
|
|
279
|
+
let reconciliation;
|
|
280
|
+
try {
|
|
281
|
+
reconciliation = reconcileAsyncRun(asyncDir, { resultsDir, kill: deps.kill, now: deps.now });
|
|
282
|
+
} catch (error) {
|
|
283
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
284
|
+
return {
|
|
285
|
+
content: [{ type: "text", text: message }],
|
|
286
|
+
isError: true,
|
|
287
|
+
details: { mode: "single", results: [] }
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
const status = reconciliation.status;
|
|
291
|
+
const effectiveRunId = status?.runId ?? resolvedId ?? "unknown";
|
|
292
|
+
const logPath = path.join(asyncDir, `subagent-log-${effectiveRunId}.md`);
|
|
293
|
+
const eventsPath = path.join(asyncDir, "events.jsonl");
|
|
294
|
+
if (status) {
|
|
295
|
+
if (params.view === "transcript") {
|
|
296
|
+
if (currentSessionId && status.sessionId !== currentSessionId) {
|
|
297
|
+
return {
|
|
298
|
+
content: [{ type: "text", text: "Transcript view is only available for async runs owned by the current session." }],
|
|
299
|
+
isError: true,
|
|
300
|
+
details: { mode: "single", results: [] }
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
return { content: [{ type: "text", text: formatAsyncRunTranscript(status, asyncDir, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
|
|
305
|
+
} catch (error) {
|
|
306
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
307
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
let nestedChildren = [];
|
|
311
|
+
let nestedWarning;
|
|
312
|
+
try {
|
|
313
|
+
const nestedRoute = findNestedRouteForRootId(status.runId);
|
|
314
|
+
if (nestedRoute)
|
|
315
|
+
reconcileNestedAsyncDescendants(nestedRoute, { resultsDir, kill: deps.kill, now: deps.now });
|
|
316
|
+
nestedChildren = projectNestedRegistryForRoot(status.runId)?.children ?? [];
|
|
317
|
+
attachRootChildrenToSteps(status.runId, status.steps, nestedChildren);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
nestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
320
|
+
}
|
|
321
|
+
const outputPath = formatAsyncRunOutputPath({ asyncDir, outputFile: status.outputFile });
|
|
322
|
+
const progressLabel = formatAsyncRunProgressLabel({
|
|
323
|
+
mode: status.mode,
|
|
324
|
+
state: status.state,
|
|
325
|
+
currentStep: status.currentStep,
|
|
326
|
+
chainStepCount: status.chainStepCount,
|
|
327
|
+
parallelGroups: status.parallelGroups,
|
|
328
|
+
steps: (status.steps ?? []).map((step, index) => ({ index, agent: step.agent, status: step.status }))
|
|
329
|
+
});
|
|
330
|
+
const started = new Date(status.startedAt).toISOString();
|
|
331
|
+
const updated = status.lastUpdate ? new Date(status.lastUpdate).toISOString() : "n/a";
|
|
332
|
+
const statusActivityText = status.state === "running" ? formatActivityLabel(status.lastActivityAt, status.activityState) : undefined;
|
|
333
|
+
const steeringText = formatSteeringSummary(status);
|
|
334
|
+
const lines = [
|
|
335
|
+
`Run: ${status.runId}`,
|
|
336
|
+
`State: ${status.state}`,
|
|
337
|
+
status.error ? `Error: ${status.error}` : undefined,
|
|
338
|
+
statusActivityText ? `Activity: ${statusActivityText}` : undefined,
|
|
339
|
+
steeringText ? `Steering: ${steeringText}` : undefined,
|
|
340
|
+
`Mode: ${status.mode}`,
|
|
341
|
+
`Progress: ${progressLabel}`,
|
|
342
|
+
status.pendingAppends ? `Pending appends: ${status.pendingAppends}` : undefined,
|
|
343
|
+
`Started: ${started}`,
|
|
344
|
+
`Updated: ${updated}`,
|
|
345
|
+
status.turnBudget ? `Turn budget: ${status.turnBudget.turnCount}/${status.turnBudget.maxTurns}+${status.turnBudget.graceTurns} (${status.turnBudget.outcome})` : undefined,
|
|
346
|
+
`Dir: ${asyncDir}`,
|
|
347
|
+
outputPath ? `Output: ${outputPath}` : undefined,
|
|
348
|
+
reconciliation.message ? `Diagnosis: ${reconciliation.message}` : undefined,
|
|
349
|
+
reconciliation.resultPath && fs.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : undefined
|
|
350
|
+
].filter((line) => Boolean(line));
|
|
351
|
+
for (const [index, step] of (status.steps ?? []).entries()) {
|
|
352
|
+
const stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
|
|
353
|
+
const modelThinking = formatModelThinking(step.model, step.thinking);
|
|
354
|
+
const modelText = modelThinking ? ` (${modelThinking})` : "";
|
|
355
|
+
const steeringText = formatSteeringSummary(step);
|
|
356
|
+
const steeringSuffix = steeringText ? `, steering: ${steeringText}` : "";
|
|
357
|
+
const errorText = step.error ? `, error: ${step.error}` : "";
|
|
358
|
+
const acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "";
|
|
359
|
+
const budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
360
|
+
const display = step.label ? `${step.label} (${step.agent})` : step.agent;
|
|
361
|
+
const phase = step.phase ? `[${step.phase}] ` : "";
|
|
362
|
+
lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
|
|
363
|
+
lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 20 }));
|
|
364
|
+
const stepOutputPath = path.join(asyncDir, `output-${index}.log`);
|
|
365
|
+
if (stepOutputPath !== outputPath && fs.existsSync(stepOutputPath))
|
|
366
|
+
lines.push(` Output: ${stepOutputPath}`);
|
|
367
|
+
if (step.status === "running") {
|
|
368
|
+
lines.push(` Intercom target: ${resolveSubagentIntercomTarget(status.runId, step.agent, index)} (if registered)`);
|
|
369
|
+
lines.push(` Steer: subagent({ action: "steer", id: "${status.runId}", index: ${index}, message: "..." })`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? []));
|
|
373
|
+
const unattached = nestedChildren.filter((child) => !attached.has(child.id));
|
|
374
|
+
lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: true, maxLines: 20 }));
|
|
375
|
+
if (nestedWarning)
|
|
376
|
+
lines.push(`Warning: ${nestedWarning}`);
|
|
377
|
+
if (status.sessionFile)
|
|
378
|
+
lines.push(`Session: ${status.sessionFile}`);
|
|
379
|
+
if (status.state === "running")
|
|
380
|
+
lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`);
|
|
381
|
+
if (status.state !== "running") {
|
|
382
|
+
lines.push(formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile));
|
|
383
|
+
}
|
|
384
|
+
if (fs.existsSync(logPath))
|
|
385
|
+
lines.push(`Log: ${logPath}`);
|
|
386
|
+
if (fs.existsSync(eventsPath))
|
|
387
|
+
lines.push(`Events: ${eventsPath}`);
|
|
388
|
+
return { content: [{ type: "text", text: lines.join(`
|
|
389
|
+
`) }], details: { mode: "single", results: [] } };
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (resultPath) {
|
|
393
|
+
try {
|
|
394
|
+
const raw = fs.readFileSync(resultPath, "utf-8");
|
|
395
|
+
const data = JSON.parse(raw);
|
|
396
|
+
if (params.view === "transcript") {
|
|
397
|
+
try {
|
|
398
|
+
return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
|
|
399
|
+
} catch (error) {
|
|
400
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
401
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const status = data.success ? "complete" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
|
|
405
|
+
const runId = data.runId ?? data.id ?? resolvedId;
|
|
406
|
+
const lines = [`Run: ${runId}`, `State: ${status}`, `Result: ${resultPath}`];
|
|
407
|
+
const children = Array.isArray(data.results) ? data.results : data.agent ? [{ agent: data.agent, sessionFile: data.sessionFile }] : [];
|
|
408
|
+
lines.push(formatResumeGuidance(runId, children, data.sessionFile));
|
|
409
|
+
if (data.summary)
|
|
410
|
+
lines.push("", data.summary);
|
|
411
|
+
return { content: [{ type: "text", text: lines.join(`
|
|
412
|
+
`) }], details: { mode: "single", results: [] } };
|
|
413
|
+
} catch (error) {
|
|
414
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
415
|
+
return {
|
|
416
|
+
content: [{ type: "text", text: `Failed to read async result file: ${message}` }],
|
|
417
|
+
isError: true,
|
|
418
|
+
details: { mode: "single", results: [] }
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
content: [{ type: "text", text: "Status file not found." }],
|
|
424
|
+
isError: true,
|
|
425
|
+
details: { mode: "single", results: [] }
|
|
426
|
+
};
|
|
427
|
+
}
|