@duckmind/dm-darwin-x64 0.49.8 → 0.50.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/dm +0 -0
- package/extensions/.dm-extensions.json +44 -15
- package/extensions/dm-cliproxy/NOTICE.md +12 -0
- package/extensions/dm-cliproxy/index.js +2 -0
- package/extensions/dm-cliproxy/package.json +20 -0
- package/extensions/dm-cliproxy/scripts/check-config-migration.js +8 -0
- package/extensions/dm-cliproxy/src/apply.js +1 -0
- package/extensions/dm-cliproxy/src/cache.js +1 -0
- package/extensions/dm-cliproxy/src/commands.js +2 -0
- package/extensions/dm-cliproxy/src/compat.js +1 -0
- package/extensions/dm-cliproxy/src/config.js +2 -0
- package/extensions/dm-cliproxy/src/conflicts.js +1 -0
- package/extensions/dm-cliproxy/src/fetch-models.js +1 -0
- package/extensions/dm-cliproxy/src/fetch-usage.js +1 -0
- package/extensions/dm-cliproxy/src/log.js +1 -0
- package/extensions/dm-cliproxy/src/status-quota.js +1 -0
- package/extensions/dm-cliproxy/src/ui-frame.js +1 -0
- package/extensions/dm-cliproxy/src/ui-hub/hub.js +2 -0
- package/extensions/dm-cliproxy/src/ui-hub/index.js +2 -0
- package/extensions/dm-cliproxy/src/ui-hub/shell.js +1 -0
- package/extensions/dm-cliproxy/src/ui-hub/types.js +0 -0
- package/extensions/dm-cliproxy/src/ui-hub/view-diagnostics.js +1 -0
- package/extensions/dm-cliproxy/src/ui-hub/view-models.js +1 -0
- package/extensions/dm-cliproxy/src/ui-hub/view-usage.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/catalog.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/mutate.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/prompt-confirm.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/prompt-name.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/providers.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/render-text.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/rows.js +1 -0
- package/extensions/dm-cliproxy/src/ui-picker/types.js +0 -0
- package/extensions/dm-cliproxy/src/ui-setup.js +2 -0
- package/extensions/dm-cliproxy/src/ui-usage.js +1 -0
- package/extensions/dm-cliproxy/src/usage-shared-cache.js +1 -0
- package/extensions/dm-subagents/src/extension/doctor.js +10 -10
- package/extensions/dm-subagents/src/extension/fanout-child.js +129 -129
- package/extensions/dm-subagents/src/extension/index.js +179 -179
- package/extensions/dm-subagents/src/extension/rpc.js +5 -5
- package/extensions/dm-subagents/src/extension/schemas.js +1 -1
- package/extensions/dm-subagents/src/extension/tool-description.js +2 -2
- package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -5
- package/extensions/dm-subagents/src/runs/background/async-execution.js +19 -19
- package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +10 -10
- package/extensions/dm-subagents/src/runs/background/async-resume.js +5 -5
- package/extensions/dm-subagents/src/runs/background/async-status.js +8 -8
- package/extensions/dm-subagents/src/runs/background/fleet-view.js +14 -14
- package/extensions/dm-subagents/src/runs/background/result-watcher.js +5 -5
- package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +3 -3
- package/extensions/dm-subagents/src/runs/background/run-status.js +20 -20
- package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +7 -7
- package/extensions/dm-subagents/src/runs/background/subagent-runner.js +38 -38
- package/extensions/dm-subagents/src/runs/background/wait.js +7 -7
- package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +58 -58
- package/extensions/dm-subagents/src/runs/foreground/execution.js +36 -36
- package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +129 -129
- package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -1
- package/extensions/dm-subagents/src/runs/shared/nested-events.js +6 -6
- package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -13
- package/package.json +1 -1
- package/extensions/dm-9router-ext/package.json +0 -23
- package/extensions/dm-9router-ext/src/index.js +0 -5
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import*as I from"node:fs";import*as _f 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 jf=new Map;function Ef(f){return f instanceof Error?f.message:String(f)}function Y$(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function Kf(f){let $=Jf.join(f,"status.json"),j;try{j=R.statSync($)}catch(A){if(Y$(A))return null;throw Error(`Failed to inspect async status file '${$}': ${Ef(A)}`,{cause:A instanceof Error?A:void 0})}let J=jf.get($);if(J&&J.mtime===j.mtimeMs)return J.status;let Q;try{Q=R.readFileSync($,"utf-8")}catch(A){if(Y$(A))return null;throw Error(`Failed to read async status file '${$}': ${Ef(A)}`,{cause:A instanceof Error?A:void 0})}let Z;try{Z=JSON.parse(Q)}catch(A){throw Error(`Failed to parse async status file '${$}': ${Ef(A)}`,{cause:A instanceof Error?A:void 0})}if(jf.set($,{mtime:j.mtimeMs,status:Z}),jf.size>50){let A=jf.keys().next().value;if(A)jf.delete(A)}return Z}import*as r from"node:os";import*as a from"node:path";function Wf(f){return f.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function B0(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 A of["USERNAME","USER","LOGNAME"]){let X=$[A];if(X)return`user-${Wf(X)}`}let J=f&&Object.hasOwn(f,"userInfo")?f.userInfo:r.userInfo;try{let A=J?.().username;if(A)return`user-${Wf(A)}`}catch{}let Q=$.USERPROFILE??$.HOME;if(Q)return`home-${Wf(Q)}`;let Z=f&&Object.hasOwn(f,"homedir")?f.homedir:r.homedir;try{let A=Z?.();if(A)return`home-${Wf(A)}`}catch{}return"shared"}var v=a.join(r.tmpdir(),`dm-subagents-${B0()}`),w=a.join(v,"async-subagent-results"),h=a.join(v,"async-subagent-runs"),X0=a.join(v,"chain-runs"),Nj=a.join(v,"artifacts");var gf=["off","minimal","low","medium","high","xhigh"];function K$(f){let $=f.lastIndexOf(":");if($===-1)return{baseModel:f,thinkingSuffix:""};let j=gf.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?K$(f):void 0,J=j?.baseModel??f,Q=gf.find((A)=>A===$?.trim()),Z=j?.thinkingSuffix?j.thinkingSuffix.slice(1):Q;if(J){let A=J.lastIndexOf("/");if(A!==-1)J=J.slice(A+1)}return[J,Z?`thinking ${Z}`: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 Y0(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=Y0(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 H0(f){return f==="complete"||f==="completed"}function K0(f){return f===1?"1 agent running":`${f} agents running`}function Nf(f,$,j={}){let J=f.filter((Y)=>Y.status==="running").length,Q=f.filter((Y)=>H0(Y.status)).length,Z=f.filter((Y)=>Y.status==="failed").length,A=f.filter((Y)=>Y.status==="paused").length,X=[`${Q}/${$} done`];if(j.showRunning!==!1&&J>0)X.unshift(K0(J));if(Z>0)X.push(`${Z} failed`);if(A>0)X.push(`${A} paused`);return X.join(" · ")}import{randomUUID as b0}from"node:crypto";import*as F from"node:fs";import*as G from"node:path";import*as O$ from"node:path";var W0=128,L0=4;function Rf(f){return typeof f==="string"&&f.length>0&&f.length<=W0&&!O$.isAbsolute(f)&&!f.includes("/")&&!f.includes("\\")&&!f.includes("..")}function W$(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function L$(f,$){return typeof f==="string"&&f.length>0?f.slice(0,$):void 0}function U$(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(!$||typeof $!=="object")return;let j=$;if(!Rf(j.runId))return;return{runId:j.runId,...W$(j.stepIndex)!==void 0?{stepIndex:W$(j.stepIndex)}:{},...L$(j.agent,128)?{agent:L$(j.agent,128)}:{}}}).filter(($)=>Boolean($)).slice(0,L0)}import*as e from"node:fs";import*as D from"node:path";import{fileURLToPath as U0}from"node:url";import*as m from"node:os";import*as c from"node:path";var ij=c.join(m.homedir(),".config","mcp","mcp.json"),pj={cursor:[c.join(m.homedir(),".cursor","mcp.json")],"claude-code":[c.join(m.homedir(),".claude","mcp.json"),c.join(m.homedir(),".claude.json"),c.join(m.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[c.join(m.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[c.join(m.homedir(),".codex","config.json")],windsurf:[c.join(m.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as sj}from"typebox/compile";function G$(f,$){let j=U0(f),J=D.extname(j),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(J)?J:".ts",Z=D.dirname(j);while(!e.existsSync(D.join(Z,"package.json"))){let A=D.dirname(Z);if(A===Z)throw Error(`Unable to resolve dm-subagents package root from ${j}`);Z=A}return D.join(Z,`${$}${Q}`)}var W1=G$(import.meta.url,D.join("src","runs","shared","subagent-prompt-runtime")),L1=G$(import.meta.url,D.join("src","extension","fanout-child"));import*as G0 from"node:fs";import*as l from"node:path";var M0=[10,25,50,100,200,500,1000,2000,4000],V0=new Set(["EACCES","EBUSY","EPERM"]),M$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,V$=M$?new Int32Array(M$):void 0;function z0(f){if(f<=0)return;if(V$)try{Atomics.wait(V$,0,0,f);return}catch{}let $=Date.now()+f;while(Date.now()<$);}function T0(f){let $=f?.code;return typeof $==="string"&&V0.has($)}function C0(f,$,j,J,Q){for(let Z=0;;Z++)try{f.renameSync($,j);return}catch(A){let X=J[Z];if(X===void 0||!T0(A))throw A;Q(X)}}function F0(f={}){let $=f.fs??G0,j=f.now??Date.now,J=f.pid??process.pid,Q=f.random??Math.random,A=f.retryRenameErrors??process.platform==="win32"?f.retryDelaysMs??M0:[],X=f.wait??z0;return(Y,K)=>{$.mkdirSync(l.dirname(Y),{recursive:!0});let B=l.join(l.dirname(Y),`.${l.basename(Y)}.${J}.${j()}.${Q().toString(36).slice(2)}.tmp`);try{$.writeFileSync(B,JSON.stringify(K,null,2),"utf-8"),C0($,B,Y,A,X)}finally{$.rmSync(B,{force:!0})}}}var i=F0();var o=G.join(v,"nested-subagent-events"),If="route.json",S0="registry.json",nf=65536,xf=12,Zf=16,wf=3;function Of(f){return Rf(f)}function mf(f,$){if(!Of($))throw Error(`${f} must be a non-empty safe id token.`)}function Uf(f,$){mf(f,$)}function kf(f,$){let j=G.resolve(f),J=G.resolve($);return J===j||J.startsWith(`${j}${G.sep}`)}function T$(f){return G.dirname(G.resolve(f.eventSink))}function t(f){if(Uf("rootRunId",f.rootRunId),Uf("capabilityToken",f.capabilityToken),!kf(o,f.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!kf(o,f.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(T$(f)!==G.dirname(G.resolve(f.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function C$(f,$){if(!$.asyncDir)return;let j=G.resolve($.asyncDir),J=G.resolve(v,"nested-subagent-runs",f,$.id),Q=G.relative(J,j);return j===J||!Q.startsWith("..")&&!G.isAbsolute(Q)?j:void 0}function L(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function U(f,$=512){return typeof f==="string"&&f.length>0?f.slice(0,$):void 0}function q0(f){if(!f||typeof f!=="object")return;let $=f,j=L($.input),J=L($.output),Q=L($.total);return j!==void 0&&J!==void 0&&Q!==void 0?{input:j,output:J,total:Q}:void 0}function _0(f){if(!f||typeof f!=="object")return;let $=f,j=L($.inputTokens),J=L($.outputTokens),Q=L($.costUsd);return j!==void 0&&J!==void 0&&Q!==void 0?{inputTokens:j,outputTokens:J,costUsd:Q}:void 0}function Gf(f){if(!f||typeof f!=="object")return;let $=f,j=L($.maxTurns),J=L($.graceTurns),Q=L($.turnCount),Z=$.outcome==="within-budget"||$.outcome==="wrap-up-requested"||$.outcome==="exceeded"?$.outcome:void 0;if(j===void 0||J===void 0||Q===void 0||!Z)return;return{maxTurns:j,graceTurns:J,turnCount:Q,outcome:Z,...L($.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:L($.wrapUpRequestedAtTurn)}:{},...L($.exceededAtTurn)!==void 0?{exceededAtTurn:L($.exceededAtTurn)}:{}}}function y0(f,$){return f==="queued"||f==="running"||f==="complete"||f==="failed"||f==="paused"?f:$}function E0(f,$){if(!f||typeof f!=="object")return;let j=f,J=U(j.agent,128);if(!J)return;let Q=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:Q,...U(j.sessionFile,2048)?{sessionFile:U(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...L(j.lastActivityAt)!==void 0?{lastActivityAt:L(j.lastActivityAt)}:{},...U(j.currentTool,128)?{currentTool:U(j.currentTool,128)}:{},...L(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:L(j.currentToolStartedAt)}:{},...U(j.currentPath,2048)?{currentPath:U(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)}:{},...U(j.error,1024)?{error:U(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}:{},...$<wf&&Array.isArray(j.children)?{children:j.children.map((Z)=>Vf(Z,$+1)).filter((Z)=>Boolean(Z)).slice(0,Zf)}:{}}}function Vf(f,$=0){if(!f||typeof f!=="object")return;let j=f;if(!Of(j.id)||!Of(j.parentRunId))return;let J=U$(j.path),Q=Array.isArray(j.steps)?j.steps.map((X)=>E0(X,$+1)).filter((X)=>Boolean(X)).slice(0,xf):void 0,Z=q0(j.totalTokens),A=_0(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...L(j.parentStepIndex)!==void 0?{parentStepIndex:L(j.parentStepIndex)}:{},...U(j.parentAgent,128)?{parentAgent:U(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,L(j.depth)??0),wf),path:J,state:y0(j.state,"running"),...U(j.asyncDir,2048)?{asyncDir:U(j.asyncDir,2048)}:{},...L(j.pid)!==void 0&&L(j.pid)>0&&Number.isInteger(L(j.pid))?{pid:L(j.pid)}:{},...U(j.sessionId,256)?{sessionId:U(j.sessionId,256)}:{},...U(j.sessionFile,2048)?{sessionFile:U(j.sessionFile,2048)}:{},...U(j.intercomTarget,256)?{intercomTarget:U(j.intercomTarget,256)}:{},...U(j.ownerIntercomTarget,256)?{ownerIntercomTarget:U(j.ownerIntercomTarget,256)}:{},...U(j.leafIntercomTarget,256)?{leafIntercomTarget:U(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...U(j.controlInbox,2048)?{controlInbox:U(j.controlInbox,2048)}:{},...U(j.capabilityToken,128)?{capabilityToken:U(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...U(j.agent,128)?{agent:U(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((X)=>U(X,128)).filter((X)=>Boolean(X)).slice(0,xf)}:{},...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)}:{},...U(j.currentTool,128)?{currentTool:U(j.currentTool,128)}:{},...L(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:L(j.currentToolStartedAt)}:{},...U(j.currentPath,2048)?{currentPath:U(j.currentPath,2048)}:{},...L(j.turnCount)!==void 0?{turnCount:L(j.turnCount)}:{},...L(j.toolCount)!==void 0?{toolCount:L(j.toolCount)}:{},...Z?{totalTokens:Z}:{},...A?{totalCost:A}:{},...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}:{},...U(j.error,1024)?{error:U(j.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...$<wf&&Array.isArray(j.children)?{children:j.children.map((X)=>Vf(X,$+1)).filter((X)=>Boolean(X)).slice(0,Zf)}:{}}}function cf(f,$){if(Buffer.byteLength(f,"utf-8")>nf)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(!Of(J.parentRunId))return;let Q=L(J.ts);if(Q===void 0)return;let Z=Vf(J.child);if(!Z||Z.id===$.rootRunId)return;let A={...Z,controlInbox:$.controlInbox,capabilityToken:$.capabilityToken,ownerState:Z.ownerState??"unknown"};return{type:J.type,ts:Q,rootRunId:$.rootRunId,parentRunId:J.parentRunId,...L(J.parentStepIndex)!==void 0?{parentStepIndex:L(J.parentStepIndex)}:{},capabilityToken:$.capabilityToken,child:A}}function g0(f,$){if(!f.includes(`
|
|
2
|
-
`)){let j=
|
|
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
|
+
`)){let j=kf(f.trim(),$);return j?[j]:[]}return f.split(`
|
|
3
3
|
`).slice(0,f.endsWith(`
|
|
4
|
-
`)?void 0:-1).map((j)=>j.trim()?
|
|
5
|
-
`;if(Buffer.byteLength(J,"utf-8")>
|
|
6
|
-
`);return
|
|
7
|
-
[stderr tail truncated]`:
|
|
8
|
-
`,"utf-8")}catch{}}function
|
|
4
|
+
`)?void 0:-1).map((j)=>j.trim()?kf(j,$):void 0).filter((j)=>Boolean(j))}function Wf(f){return f==="complete"||f==="failed"||f==="paused"}function T$(f,$){let j=$.type==="subagent.nested.completed"&&$.child.state==="running"?"complete":$.child.state,J={...$.child,state:j,lastUpdate:$.child.lastUpdate??$.ts};if(!f)return J;let Z=f.lastUpdate??0,Q=J.lastUpdate??$.ts;if(Q<Z)return f;if(Wf(f.state)&&!Wf(J.state))return f;if(Wf(f.state)&&Wf(J.state)&&Q===Z)return f;return{...f,...J,state:J.state,lastUpdate:Math.max(Z,Q)}}function x0(f,$){let j=!1,J=(X)=>X.map((Y)=>{if(Y.id===$.parentRunId){let A=Y.children??[],H=A.findIndex((U)=>U.id===$.child.id),O=T$(H>=0?A[H]:void 0,$),W=H>=0?A.map((U,C)=>C===H?O:U):[...A,O];return j=!0,{...Y,children:W.slice(0,Jf),lastUpdate:Math.max(Y.lastUpdate??0,$.ts)}}if(!Y.children?.length)return Y;let K=J(Y.children);return K===Y.children?Y:{...Y,children:K}}),Z=J(f);if(j)return Z;let Q=Z.findIndex((X)=>X.id===$.child.id),B=T$(Q>=0?Z[Q]:void 0,$);return Q>=0?Z.map((X,Y)=>Y===Q?B:X):[...Z,B].slice(0,Jf)}function w0(f,$){return{...f,updatedAt:Math.max(f.updatedAt,$.ts),children:x0(f.children,$)}}function b$(f){return M.join(C$(f),_0)}function Pf(f){Of("rootRunId",f);let $;try{$=F.readdirSync(o)}catch(j){if(j.code==="ENOENT")return;throw j}for(let j of $){if(!j.startsWith(`${f}-`))continue;let J=M.join(o,j);try{let Z=JSON.parse(F.readFileSync(M.join(J,nf),"utf-8"));if(Z.rootRunId!==f||typeof Z.capabilityToken!=="string")continue;let Q={rootRunId:f,eventSink:M.join(J,"events"),controlInbox:M.join(J,"controls"),capabilityToken:Z.capabilityToken};return e(Q),Q}catch{continue}}return}function S$(){let f;try{f=F.readdirSync(o)}catch(j){if(j.code==="ENOENT")return new Map;throw j}let $=new Map;for(let j of f){let J=M.join(o,j);try{let Z=JSON.parse(F.readFileSync(M.join(J,nf),"utf-8"));if(typeof Z.rootRunId!=="string"||typeof Z.capabilityToken!=="string")continue;if($.has(Z.rootRunId))continue;let Q={rootRunId:Z.rootRunId,eventSink:M.join(J,"events"),controlInbox:M.join(J,"controls"),capabilityToken:Z.capabilityToken};e(Q),$.set(Z.rootRunId,Q)}catch{continue}}return $}function q$(f){let $=Pf(f);return $?t($):void 0}function Mf(f,$=[]){for(let j of f??[])$.push(j),Mf(j.children,$),Mf(j.steps?.flatMap((J)=>J.children??[]),$);return $}function cf(f,$,j=[]){if(!$)return Mf(f,j);for(let J of f??[]){if(J.parentRunId===$.parentRunId&&($.parentStepIndex===void 0||J.parentStepIndex===$.parentStepIndex)){Mf([J],j);continue}cf(J.children,$,j),cf(J.steps?.flatMap((Z)=>Z.children??[]),$,j)}return j}function k0(){let f;try{f=F.readdirSync(o)}catch(j){if(j.code==="ENOENT")return[];throw j}let $=[];for(let j of f){let J=M.join(o,j);try{let Z=JSON.parse(F.readFileSync(M.join(J,nf),"utf-8"));if(typeof Z.rootRunId!=="string"||typeof Z.capabilityToken!=="string")continue;let Q={rootRunId:Z.rootRunId,eventSink:M.join(J,"events"),controlInbox:M.join(J,"controls"),capabilityToken:Z.capabilityToken};e(Q),$.push(Q)}catch{continue}}return $}function mf(f,$={}){Of("id",f);let j=[];for(let J of $.scope?.routes??k0())try{let Z=t(J);for(let Q of cf(Z.children,$.scope?.descendantOf))if($.prefix?Q.id.startsWith(f):Q.id===f)j.push({rootRunId:J.rootRunId,route:J,run:Q})}catch{continue}return j}function c0(f){e(f);try{let $=JSON.parse(F.readFileSync(b$(f),"utf-8"));return{rootRunId:f.rootRunId,updatedAt:typeof $.updatedAt==="number"?$.updatedAt:0,children:Array.isArray($.children)?$.children.map((j)=>Vf(j)).filter((j)=>Boolean(j)):[],processedEvents:Array.isArray($.processedEvents)?$.processedEvents.filter((j)=>typeof j==="string"):[]}}catch($){if($.code!=="ENOENT")throw $;return{rootRunId:f.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function t(f){e(f);let $=c0(f),j=new Set($.processedEvents),J=!1,Z=[];try{Z=F.readdirSync(f.eventSink).filter((Q)=>Q.endsWith(".json")||Q.endsWith(".jsonl")).sort()}catch(Q){if(Q.code!=="ENOENT")throw Q}for(let Q of Z){if(j.has(Q))continue;let B=M.join(f.eventSink,Q);if(!wf(f.eventSink,B))continue;let X;try{let Y=F.statSync(B);if(!Y.isFile()||Y.size>If)continue;X=F.readFileSync(B,"utf-8")}catch{continue}for(let Y of R0(X,f))$=w0($,Y),J=!0;j.add(Q),J=!0}if(J)$={...$,processedEvents:[...j].slice(-1000)},i(b$(f),$);return $}function n0(f,$,j){let J=`${JSON.stringify(j)}
|
|
5
|
+
`;if(Buffer.byteLength(J,"utf-8")>If)throw Error("Nested route record exceeds the maximum size.");F.mkdirSync(f,{recursive:!0,mode:448});let Z=`${String($).padStart(13,"0")}-${q0()}.json`,Q=M.join(f,`.${Z}.tmp`),B=M.join(f,Z);return F.writeFileSync(Q,J,{mode:384}),F.renameSync(Q,B),B}function _$(f,$){e(f);let j={...$,rootRunId:f.rootRunId,capabilityToken:f.capabilityToken},J=kf(JSON.stringify(j),f);if(!J)throw Error("Nested event record failed validation.");n0(f.eventSink,J.ts,J)}function Uf(f,$,j){if(!$?.length)return;for(let J of $)J.children=void 0;if(!j?.length)return;for(let J of j){if(J.parentRunId!==f||J.parentStepIndex===void 0)continue;let Z=$.find((Q,B)=>(Q.index??B)===J.parentStepIndex);if(!Z)continue;Z.children??=[],Z.children=[...Z.children.filter((Q)=>Q.id!==J.id),J].slice(0,Jf)}}function y$(f,$,j){return{id:f.runId||j.id,parentRunId:j.parentRunId,...j.parentStepIndex!==void 0?{parentStepIndex:j.parentStepIndex}:{},depth:j.depth,path:j.path??[{runId:j.parentRunId,...j.parentStepIndex!==void 0?{stepIndex:j.parentStepIndex}:{}}],asyncDir:$,...f.pid?{pid:f.pid}:{},...f.sessionId?{sessionId:f.sessionId}:{},mode:f.mode??j.mode,state:f.state,...f.currentStep!==void 0?{currentStep:f.currentStep}:{},...f.chainStepCount!==void 0?{chainStepCount:f.chainStepCount}:{},...f.activityState?{activityState:f.activityState}:{},...f.lastActivityAt!==void 0?{lastActivityAt:f.lastActivityAt}:{},...f.currentTool?{currentTool:f.currentTool}:{},...f.currentToolStartedAt!==void 0?{currentToolStartedAt:f.currentToolStartedAt}:{},...f.currentPath?{currentPath:f.currentPath}:{},...f.turnCount!==void 0?{turnCount:f.turnCount}:{},...f.toolCount!==void 0?{toolCount:f.toolCount}:{},...f.totalTokens?{totalTokens:f.totalTokens}:{},...f.timeoutMs!==void 0?{timeoutMs:f.timeoutMs}:{},...f.deadlineAt!==void 0?{deadlineAt:f.deadlineAt}:{},...f.timedOut!==void 0?{timedOut:f.timedOut}:{},...f.turnBudget?{turnBudget:f.turnBudget}:{},...f.turnBudgetExceeded!==void 0?{turnBudgetExceeded:f.turnBudgetExceeded}:{},...f.wrapUpRequested!==void 0?{wrapUpRequested:f.wrapUpRequested}:{},...f.error?{error:f.error}:{},...f.startedAt!==void 0?{startedAt:f.startedAt}:{startedAt:j.ts},...f.endedAt!==void 0?{endedAt:f.endedAt}:{},lastUpdate:f.lastUpdate??j.ts,...f.sessionFile?{sessionFile:f.sessionFile}:{},...f.steps?.length?{steps:f.steps.map((J)=>({agent:J.agent,status:J.status,...J.sessionFile?{sessionFile:J.sessionFile}:{},...J.activityState?{activityState:J.activityState}:{},...J.lastActivityAt!==void 0?{lastActivityAt:J.lastActivityAt}:{},...J.currentTool?{currentTool:J.currentTool}:{},...J.currentToolStartedAt!==void 0?{currentToolStartedAt:J.currentToolStartedAt}:{},...J.currentPath?{currentPath:J.currentPath}:{},...J.turnCount!==void 0?{turnCount:J.turnCount}:{},...J.toolCount!==void 0?{toolCount:J.toolCount}:{},...J.startedAt!==void 0?{startedAt:J.startedAt}:{},...J.endedAt!==void 0?{endedAt:J.endedAt}:{},...J.error?{error:J.error}:{},...J.timedOut!==void 0?{timedOut:J.timedOut}:{},...J.turnBudget?{turnBudget:J.turnBudget}:{},...J.turnBudgetExceeded!==void 0?{turnBudgetExceeded:J.turnBudgetExceeded}:{},...J.wrapUpRequested!==void 0?{wrapUpRequested:J.wrapUpRequested}:{}})).slice(0,Rf)}:{}}}function g$(f){let $={total:0,running:0,paused:0,complete:0,failed:0,queued:0};for(let j of f??[]){$.total++,$[j.state]++;let J=g$([...j.children??[],...j.steps?.flatMap((Z)=>Z.children??[])??[]]);$.total+=J.total,$.running+=J.running,$.paused+=J.paused,$.complete+=J.complete,$.failed+=J.failed,$.queued+=J.queued}return $}function vf(f){let $=g$(f);if($.total===0)return;let j=[$.running>0?`${$.running} running`:"",$.paused>0?`${$.paused} paused`:"",$.failed>0?`${$.failed} failed`:"",$.complete>0?`${$.complete} complete`:"",$.queued>0?`${$.queued} queued`:""].filter(Boolean);return`+${$.total} nested run${$.total===1?"":"s"}${j.length?` (${j.join(", ")})`:""}`}function I0(f){if(f.agent)return f.agent;if(f.agents?.length)return f.agents.length===1?f.agents[0]:`${f.agents.slice(0,2).join(", ")}${f.agents.length>2?` +${f.agents.length-2}`:""}`;return f.id}function E$(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.toolCount!==void 0)$.push(`${f.toolCount} tools`);if(f.totalTokens)$.push(`${s(f.totalTokens.total)} tok`);let j=k(f.lastActivityAt,f.activityState);return j||$.length?[j,...$].filter(Boolean).join(" | "):void 0}function D0(f,$){let j=[],J=(Z,Q,B)=>{if(!Z?.length||j.length>=$.maxLines)return;if(Q>$.maxDepth){let X=vf(Z);if(X&&j.length<$.maxLines)j.push(`${B}↳ ${X}`);return}for(let X=0;X<Z.length;X++){let Y=Z[X];if(j.length>=$.maxLines){let H=vf(Z.slice(X));if(H)j[j.length-1]=`${B}↳ ${H}`;return}let K=Y.state==="running"?E$(Y):void 0,A=Y.error?` | error: ${Y.error}`:"";if(j.push(`${B}↳ ${I0(Y)} [${Y.id}] ${Y.state}${K?` | ${K}`:""}${A}`),$.commandHints&&j.length<$.maxLines)j.push(`${B} Status: subagent({ action: "status", id: "${Y.id}" })`);if(Q===$.maxDepth){let H=vf([...Y.steps?.flatMap((O)=>O.children??[])??[],...Y.children??[]]);if(H&&j.length<$.maxLines)j.push(`${B} ↳ ${H}`);continue}for(let[H,O]of(Y.steps??[]).entries()){if(j.length>=$.maxLines)return;let W=O.status==="running"?E$(O):void 0;j.push(`${B} ${H+1}. ${O.agent} ${O.status}${W?` | ${W}`:""}${O.error?` | error: ${O.error}`:""}`),J(O.children,Q+1,`${B} `)}J(Y.children,Q+1,`${B} `)}};return J(f,0,$.indent),j}function x(f,$={}){return D0(f,{indent:$.indent??" ",maxDepth:$.maxDepth??2,maxLines:$.maxLines??40,commandHints:$.commandHints??!1})}function P0(f,$,j){if(typeof f!=="object"||f===null)return!1;let{start:J,count:Z,stepIndex:Q}=f;return typeof J==="number"&&typeof Z==="number"&&typeof Q==="number"&&Number.isInteger(J)&&Number.isInteger(Z)&&Number.isInteger(Q)&&J>=0&&Z>0&&Q>=0&&Q<j&&J+Z<=$}function p(f,$,j){if(!Array.isArray(f))return[];return f.filter((J)=>P0(J,$,j)).sort((J,Z)=>J.stepIndex-Z.stepIndex||J.start-Z.start)}function zf(f,$,j){let J=0,Z=0;for(let Q of j){while(Z<Q.start&&J<$){if(Z===f)return J;Z++,J++}if(f>=Q.start&&f<Q.start+Q.count)return Q.stepIndex;Z=Q.start+Q.count,J=Q.stepIndex+1}while(Z<=f&&J<$){if(Z===f)return J;Z++,J++}return Math.max(0,$-1)}import*as q from"node:fs";import*as E from"node:path";function hf(f){return f instanceof Error?f.message:String(f)}function m0(f){let $=E.join(f,"runner.stderr.log"),j=65536,J;try{let Q=q.statSync($);if(Q.size<=0)return;let B=q.openSync($,"r");try{let X=Math.min(Q.size,65536),Y=Math.max(0,Q.size-X),K=Buffer.alloc(X);q.readSync(B,K,0,X,Y),J=K.toString("utf-8").trim()}finally{q.closeSync(B)}}catch{return}if(!J)return;let Z=J.split(/\r?\n/).slice(-30).join(`
|
|
6
|
+
`);return Z.length>4000?`${Z.slice(-4000)}
|
|
7
|
+
[stderr tail truncated]`:Z}function x$(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function v0(f,$){try{q.mkdirSync(E.dirname(f),{recursive:!0}),q.appendFileSync(f,`${JSON.stringify($)}
|
|
8
|
+
`,"utf-8")}catch{}}function h0(f){let $=E.join(f,"status.json"),j;try{j=q.readFileSync($,"utf-8")}catch(J){if(x$(J))return null;throw Error(`Failed to read async status file '${$}': ${hf(J)}`,{cause:J instanceof Error?J:void 0})}try{return JSON.parse(j)}catch(J){throw Error(`Failed to parse async status file '${$}': ${hf(J)}`,{cause:J instanceof Error?J:void 0})}}function o0(f){try{let $=JSON.parse(q.readFileSync(f,"utf-8"));return{state:$.success?"complete":$.state==="paused"||$.exitCode===0?"paused":"failed",...Array.isArray($.results)?{results:$.results}:{}}}catch($){if(x$($))return;throw Error(`Failed to read async result file '${f}': ${hf($)}`,{cause:$ instanceof Error?$:void 0})}}function d0(f,$){if($?.success===!0)return"complete";if($?.success===!1)return"failed";return f}function u0(f,$,j){let J=o0($);if(!J)return;let Z=(f.steps??[]).map((Q,B)=>{if(Q.status!=="running"&&Q.status!=="pending")return Q;let X=J.results?.[B],Y=d0(J.state,X);return{...Q,status:Y==="complete"?"complete":Y,endedAt:Q.endedAt??j,durationMs:Q.startedAt!==void 0&&Q.durationMs===void 0?Math.max(0,j-Q.startedAt):Q.durationMs,exitCode:Q.exitCode??(Y==="complete"||Y==="paused"?0:1),error:Y==="failed"?Q.error??X?.error:Q.error,sessionFile:Q.sessionFile??X?.sessionFile,model:Q.model??X?.model,attemptedModels:Q.attemptedModels??X?.attemptedModels,modelAttempts:Q.modelAttempts??X?.modelAttempts}});return{...f,state:J.state,activityState:void 0,lastUpdate:j,endedAt:f.endedAt??j,steps:Z}}function l0(f,$,j){let J=$.startedAt??j,Z=$.agents?.length?$.agents:["subagent"],Q=$.chainStepCount,B=Q!==void 0?p($.parallelGroups,Z.length,Q):[];return{runId:$.runId||E.basename(f),...$.sessionId?{sessionId:$.sessionId}:{},mode:$.mode??"single",state:"running",pid:$.pid,startedAt:J,lastUpdate:j,currentStep:0,...Q!==void 0?{chainStepCount:Q}:{},...B.length?{parallelGroups:B}:{},steps:Z.map((X)=>({agent:X,status:"running",startedAt:J})),...$.sessionFile?{sessionFile:$.sessionFile}:{}}}function i0(f,$,j,J){let Z=f.runId||E.basename($),Q=typeof f.pid==="number"?f.pid:"unknown",B=J??`Async runner process ${Q} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,X=m0($),Y=X?`${B}
|
|
9
9
|
|
|
10
10
|
Runner stderr tail:
|
|
11
|
-
${X}`:A,B=((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:B},O=B[f.currentStep??0]?.agent??B[0]?.agent??"subagent";return{status:H,message:Y,result:{id:Q,agent:O,mode:f.mode,success:!1,state:"failed",summary:Y,results:B.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 g$(f,$,j,J,Q){let Z=u0($,f,J,Q);return i(j,Z.result),i(E.join(f,"status.json"),Z.status),m0(E.join(f,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:J,runId:Z.status.runId,pid:$.pid,resultPath:j,message:Z.message}),{status:Z.status,repaired:!0,resultPath:j,message:Z.message}}function N$(f){return f==="complete"||f==="failed"||f==="paused"}function*df(f){for(let $ of f??[])yield $,yield*df($.children),yield*df($.steps?.flatMap((j)=>j.children??[]))}function Qf(f,$={}){let j=ff(f);for(let J of df(j.children)){if(J.state!=="running"&&J.state!=="queued")continue;let Q=C$(f.rootRunId,J);if(!Q)continue;let Z=$f(Q,{...$,resultsDir:E.join($.resultsDir??w,"nested",f.rootRunId)}),A=Z.status;if(!A)continue;if(!Z.repaired&&!N$(A.state))continue;let X=$.now?.()??Date.now();q$(f,{type:N$(A.state)?"subagent.nested.completed":"subagent.nested.updated",ts:X,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,child:_$(A,Q,{id:J.id,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,depth:J.depth,path:J.path,mode:J.mode,ts:X})})}}function l0(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 $f(f,$={}){let j=$.now?.()??Date.now(),J=P0(f),Q=!J&&$.startedRun?d0(f,$.startedRun,j):void 0,Z=J??Q;if(!Z)return{status:null,repaired:!1};let A=Z.runId||E.basename(f),X=E.join($.resultsDir??w,`${A}.json`);if(q.existsSync(X)){let K=Z.state==="running"||Z.state==="queued"?o0(Z,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:Z,repaired:!1,resultPath:X}}if(Z.state!=="running"||typeof Z.pid!=="number")return{status:J??null,repaired:!1,resultPath:X};if(!J){let K=$.startedRun?.startedAt??Z.startedAt;if(j-K<($.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:X}}if(l0(Z.pid,$.kill)!=="dead"){let K=$.staleAlivePidMs??86400000,B=Z.lastUpdate??Z.startedAt;if(j-B<=K)return{status:J??null,repaired:!1,resultPath:X};let H=`Async runner process ${Z.pid} still has a live PID, but status has not updated for ${j-B}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return g$(f,Z,X,j,H)}return g$(f,Z,X,j)}function Af(f){return f instanceof Error?f.message:String(f)}function uf(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function i0(f,$){let j=N.join(f,$);try{return Bf.statSync(j).isDirectory()}catch(J){if(uf(J))return!1;throw Error(`Failed to inspect async run path '${j}': ${Af(J)}`,{cause:J instanceof Error?J:void 0})}}function p0(f){if(!f)return;try{return Bf.statSync(f).mtimeMs}catch($){if(uf($))return;throw Error(`Failed to inspect async output file '${f}': ${Af($)}`,{cause:$ instanceof Error?$:void 0})}}function r0(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??p0(j)??J?.lastActivityAt??J?.startedAt??$.startedAt}}function a0(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:Q,lastActivityAt:Z}=r0(f,$),A=$.steps??[],X=$.chainStepCount??A.length,Y=p($.parallelGroups,A.length,X),K=[];if(j.length===0&&J)try{K=ff(J)?.children??[]}catch(H){j.push(`Nested status unavailable: ${Af(H)}`)}let B=A.map((H,O)=>{let{activityState:W,lastActivityAt:V}=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}:{},...V?{lastActivityAt:V}:{},...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 zf($.runId||N.basename(f),B,K),{id:$.runId||N.basename(f),asyncDir:f,...$.sessionId?{sessionId:$.sessionId}:{},state:$.state,...$.error?{error:$.error}:{},activityState:Q,lastActivityAt:Z,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:B,...K.length?{nestedChildren:K}:{},...j.length?{nestedWarnings:j}:{},...$.sessionDir?{sessionDir:$.sessionDir}:{},...$.outputFile?{outputFile:$.outputFile}:{},...$.totalTokens?{totalTokens:$.totalTokens}:{},...$.totalCost?{totalCost:$.totalCost}:{},...$.sessionFile?{sessionFile:$.sessionFile}:{}}}function s0(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 Q=$(j.state)-$(J.state);if(Q!==0)return Q;let Z=j.lastUpdate??j.endedAt??j.startedAt;return(J.lastUpdate??J.endedAt??J.startedAt)-Z})}function Cf(f,$={}){let j;try{j=Bf.readdirSync(f).filter((Y)=>i0(f,Y))}catch(Y){if(uf(Y))return[];throw Error(`Failed to list async runs in '${f}': ${Af(Y)}`,{cause:Y instanceof Error?Y:void 0})}let J=$.states?new Set($.states):void 0,Q=[],Z,A=(Y)=>{if(!Z)Z=b$();return Z.get(Y)};for(let Y of j){let K=N.join(f,Y),H=($.reconcile===!1?void 0:$f(K,{resultsDir:$.resultsDir,kill:$.kill,now:$.now}))?.status??Kf(K);if(!H)continue;if(J&&!J.has(H.state))continue;if($.sessionId&&H.sessionId!==$.sessionId)continue;let O=[],W;try{if(W=A(H.runId||N.basename(K)),W)Qf(W,{resultsDir:$.resultsDir,kill:$.kill,now:$.now})}catch(C){O.push(`Nested status unavailable: ${Af(C)}`)}let V=a0(K,H,O,W);Q.push(V)}let X=s0(Q);return $.limit!==void 0?X.slice(0,$.limit):X}function x$(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 e0(f){let $=f.label?`${f.label} (${f.agent})`:f.agent,j=f.phase?`[${f.phase}] `:"",J=[`${f.index+1}. ${j}${$}`,f.status],Q=x$(f);if(Q)J.push(Q);let Z=d(f.model,f.thinking);if(Z)J.push(Z);if(f.durationMs!==void 0)J.push(u(f.durationMs));if(f.tokens)J.push(`${s(f.tokens.total)} tok`);return J.join(" | ")}function Xf(f){if(!f.outputFile)return;return N.isAbsolute(f.outputFile)?f.outputFile:N.join(f.asyncDir,f.outputFile)}function Yf(f){let $=f.steps.length||1,j=f.chainStepCount??$,J=p(f.parallelGroups,f.steps.length,j),Q=f.currentStep!==void 0?J.find((Z)=>f.currentStep>=Z.start&&f.currentStep<Z.start+Z.count):void 0;if(Q){let Z=f.steps.slice(Q.start,Q.start+Q.count),A=Nf(Z,Q.count,{showRunning:f.state==="running"});if(f.mode==="parallel")return A;return`step ${Q.stepIndex+1}/${j} · parallel group: ${A}`}if(f.mode==="parallel")return Nf(f.steps,$,{showRunning:f.state==="running"});if(f.mode==="chain"&&f.currentStep!==void 0&&J.length>0)return`step ${Tf(f.currentStep,j,J)+1}/${j}`;return f.currentStep!==void 0?`step ${f.currentStep+1}/${$}`:`steps ${$}`}function t0(f){let $=Yf(f),j=f.cwd?_(f.cwd):_(f.asyncDir),J=x$(f),Q=f.pendingAppends?` | ${f.pendingAppends} pending append${f.pendingAppends===1?"":"s"}`:"";return`${f.id} | ${f.state}${J?` | ${J}`:""} | ${f.mode} | ${$}${Q} | ${j}`}function w$(f,$="Active async runs"){if(f.length===0)return`No ${$.toLowerCase()}.`;let j=[`${$}: ${f.length}`,""];for(let J of f){j.push(`- ${t0(J)}`);for(let X of J.steps)j.push(` ${e0(X)}`),j.push(...x(X.children,{indent:" ",maxLines:12}));let Q=new Set(J.steps.flatMap((X)=>X.children?.map((Y)=>Y.id)??[])),Z=J.nestedChildren?.filter((X)=>!Q.has(X.id))??[];if(j.push(...x(Z,{indent:" ",maxLines:12})),J.error)j.push(` Error: ${J.error}`);for(let X of J.nestedWarnings??[])j.push(` Warning: ${X}`);let A=Xf(J);if(A)j.push(` output: ${_(A)}`);if(J.sessionFile)j.push(` session: ${_(J.sessionFile)}`);j.push("")}return j.join(`
|
|
12
|
-
`).trimEnd()}import*as b from"node:fs";import*as y from"node:path";var
|
|
13
|
-
`)}function
|
|
14
|
-
`).trimEnd()}],details:{mode:"management",results:[]}}}function
|
|
15
|
-
`)}function
|
|
16
|
-
`);let
|
|
17
|
-
`)}function
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
20
|
-
`)}function
|
|
21
|
-
`)}function
|
|
22
|
-
`)}],details:{mode:"single",results:[]}}}}if(X)try{let K=I.readFileSync(X,"utf-8"),
|
|
23
|
-
`)}],details:{mode:"single",results:[]}}}catch(K){return{content:[{type:"text",text:`Failed to read async result file: ${K instanceof Error?K.message:String(K)}`}],isError:!0,details:{mode:"single",results:[]}}}return{content:[{type:"text",text:"Status file not found."}],isError:!0,details:{mode:"single",results:[]}}}export{
|
|
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
|
+
`).trimEnd()}import*as b from"node:fs";import*as y from"node:path";var c$=80,jj=500,Jj=262144;function lf(f){if(f===void 0)return c$;if(!Number.isFinite(f))return c$;return Math.max(1,Math.min(jj,Math.trunc(f)))}function n$(f){let $=new Set,j=[];for(let J of f){if(!J||$.has(J))continue;$.add(J),j.push(J)}return j}function Zj(f,$){if(!$)return;return y.resolve(f,$)}function I$(f,$){let j=y.resolve(f),J=y.resolve($);return J===j||J.startsWith(`${j}${y.sep}`)}function Cf(f){return f instanceof Error?f.message:String(f)}function D$(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="ENOENT"}function Qj(f,$){let j;try{j=b.statSync(f)}catch(Z){if(D$(Z))return{path:f,lines:[],truncated:!1};return{path:f,lines:[],truncated:!1,error:Cf(Z)}}if(j.size===0)return{path:f,lines:[],truncated:!1};let J;try{let Z=Math.min(j.size,Jj),Q=j.size-Z,B=Buffer.alloc(Z);J=b.openSync(f,"r");let X=b.readSync(J,B,0,Z,Q),K=B.subarray(0,X).toString("utf-8").split(/\r?\n/);if(Q>0&&K.length>0)K=K.slice(1);if(K.at(-1)==="")K=K.slice(0,-1);return{path:f,lines:K.slice(-$),truncated:Q>0||K.length>$}}catch(Z){return{path:f,lines:[],truncated:!1,error:Cf(Z)}}finally{if(J!==void 0)b.closeSync(J)}}function P$(f,$,j,J){if(j.length===0)return{path:f,lines:[],truncated:!1,error:`Refusing to read ${J} transcript path without a trusted root: ${f}`};let Z=y.resolve(f);if(!j.some((Y)=>I$(Y,Z)))return{path:f,lines:[],truncated:!1,error:`Refusing to read ${J} transcript path outside trusted roots: ${f}`};let Q;try{Q=b.lstatSync(Z)}catch(Y){if(D$(Y))return{path:f,lines:[],truncated:!1};return{path:f,lines:[],truncated:!1,error:Cf(Y)}}if(Q.isSymbolicLink())return{path:f,lines:[],truncated:!1,error:`Refusing to read symlink ${J} transcript path: ${f}`};if(!Q.isFile())return{path:f,lines:[],truncated:!1,error:`Refusing to read non-file ${J} transcript path: ${f}`};let B,X;try{B=b.realpathSync(Z),X=j.filter((Y)=>b.existsSync(Y)).map((Y)=>b.realpathSync(Y))}catch(Y){return{path:f,lines:[],truncated:!1,error:Cf(Y)}}if(!X.some((Y)=>I$(Y,B)))return{path:f,lines:[],truncated:!1,error:`Refusing to read ${J} transcript path outside trusted roots: ${f}`};return Qj(Z,$)}function uf(f,$=240){let j;if(typeof f==="string")j=f;else j=JSON.stringify(f);return j.length>$?`${j.slice(0,$)}…`:j}function Bj(f){if(typeof f==="string")return f;if(!Array.isArray(f))return"";return f.map(($)=>{if(!$||typeof $!=="object")return"";let j=$;if(typeof j.text==="string")return j.text;if(j.type==="toolCall"||j.type==="tool_call")return`[tool: ${typeof j.name==="string"?j.name:typeof j.toolName==="string"?j.toolName:"tool"}${j.args===void 0?"":` ${uf(j.args)}`}]`;if(j.type==="toolResult"||j.type==="tool_result")return`[tool result${j.result===void 0?"":`: ${uf(j.result)}`}]`;if(j.content!==void 0)return uf(j.content);return""}).filter(Boolean).join(`
|
|
13
|
+
`)}function Aj(f){if(!f||typeof f!=="object")return;let $=f,j=$.message&&typeof $.message==="object"?$.message:$,J=typeof j.role==="string"?j.role:void 0;if(!J)return;let Z=Bj(j.content).trim();if(!Z)return;return`${J}: ${Z}`}function m$(f,$,j){let J=P$(f,Math.max($*4,$),j,"session"),Z=[];if(J.error)Z.push(`Session read failed for ${f}: ${J.error}`);let Q=[],B=0;for(let X of J.lines){if(!X.trim())continue;try{let Y=JSON.parse(X),K=Aj(Y);if(K)Q.push(K)}catch{B++}}if(B>0)Z.push(`Skipped ${B} malformed session tail line${B===1?"":"s"}.`);return{lines:Q.slice(-$),warnings:Z}}function Ff(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.toolCount!==void 0)$.push(`${f.toolCount} tools`);if(f.tokens?.total)$.push(`${s(f.tokens.total)} tok`);let j=k(f.lastActivityAt,f.activityState);return j||$.length?[j,...$].filter(Boolean).join(" | "):void 0}function Xj(f){if(f.mode==="single"&&f.currentAgent)return f.currentAgent;return f.mode}function Yj(f){if(f.length===0)return[];let $=["Foreground runs:"],j=[...f].sort((J,Z)=>Z.updatedAt-J.updatedAt);for(let J of j){let Z=Ff({activityState:J.currentActivityState,lastActivityAt:J.lastActivityAt,currentTool:J.currentTool,currentToolStartedAt:J.currentToolStartedAt,currentPath:J.currentPath,turnCount:J.turnCount,toolCount:J.toolCount,...J.tokens!==void 0?{tokens:{total:J.tokens}}:{}}),Q=J.currentAgent?` | ${J.currentAgent}${J.currentIndex!==void 0?` #${J.currentIndex}`:""}`:"";$.push(`- ${J.runId} | running | ${Xj(J)}${Q}${Z?` | ${Z}`:""}`),$.push(` status: subagent({ action: "status", id: "${J.runId}" })`),$.push(" transcript: live in the expanded foreground result; persisted session transcript appears after completion when sessions are enabled."),$.push(...x(J.nestedChildren,{indent:" ",commandHints:!0,maxLines:12}))}return $}function Hj(f){if(f.length===0)return[];let $=["Async runs:"];for(let j of f){let J=Xf(j),Z=Ff(j),Q=j.cwd?_(j.cwd):_(j.asyncDir),B=j.pendingAppends?` | ${j.pendingAppends} pending append${j.pendingAppends===1?"":"s"}`:"";$.push(`- ${j.id} | ${j.state}${Z?` | ${Z}`:""} | ${j.mode} | ${J}${B} | ${Q}`),$.push(` status: subagent({ action: "status", id: "${j.id}" })`),$.push(` transcript: subagent({ action: "status", id: "${j.id}", view: "transcript" })`);for(let A of j.steps){let H=A.label?`${A.label} (${A.agent})`:A.agent,O=A.phase?`[${A.phase}] `:"",W=Ff(A),U=d(A.model,A.thinking),C=[`${A.index}. ${O}${H}`,A.status,W,U].filter(Boolean);$.push(` ${C.join(" | ")}`);let S=y.join(j.asyncDir,`output-${A.index}.log`);if(b.existsSync(S))$.push(` output: ${_(S)}`);if(A.sessionFile)$.push(` session: ${_(A.sessionFile)}`);if(A.status==="running"||A.recentOutput?.length||b.existsSync(S))$.push(` transcript: subagent({ action: "status", id: "${j.id}", index: ${A.index}, view: "transcript" })`);$.push(...x(A.children,{indent:" ",commandHints:!0,maxLines:12}))}let X=new Set(j.steps.flatMap((A)=>A.children?.map((H)=>H.id)??[])),Y=j.nestedChildren?.filter((A)=>!X.has(A.id))??[];if($.push(...x(Y,{indent:" ",commandHints:!0,maxLines:12})),j.error)$.push(` error: ${j.error}`);for(let A of j.nestedWarnings??[])$.push(` warning: ${A}`);let K=Af(j);if(K)$.push(` output: ${_(K)}`);if(j.sessionFile)$.push(` session: ${_(j.sessionFile)}`)}return $}function v$(f,$={}){if($.childSafe)return{content:[{type:"text",text:'Child-safe subagent fleet view is unavailable without an explicit run id. Use subagent({ action: "status", id: "..." }) for the delegated run you can see.'}],isError:!0,details:{mode:"management",results:[]}};let j;try{j=Tf($.asyncDirRoot??h,{states:["queued","running"],sessionId:$.state?.currentSessionId??void 0,resultsDir:$.resultsDir??w,kill:$.kill,now:$.now})}catch(Y){return{content:[{type:"text",text:Y instanceof Error?Y.message:String(Y)}],isError:!0,details:{mode:"management",results:[]}}}let J=$.state?[...$.state.foregroundControls.values()]:[],Z=J.length+j.length;if(Z===0)return{content:[{type:"text",text:'No active subagent fleet. Background runs that already finished are available through completion notifications or subagent({ action: "status", id: "..." }).'}],details:{mode:"management",results:[]}};let Q=[`Subagent fleet: ${Z} active`,""],B=Yj(J);if(B.length)Q.push(...B,"");let X=Hj(j);if(X.length)Q.push(...X,"");return Q.push("Commands:"),Q.push(' Refresh fleet: subagent({ action: "status", view: "fleet" })'),Q.push(' Tail run transcript: subagent({ action: "status", id: "<run-id>", view: "transcript" })'),Q.push(' Tail child transcript: subagent({ action: "status", id: "<run-id>", index: 0, view: "transcript" })'),{content:[{type:"text",text:Q.join(`
|
|
14
|
+
`).trimEnd()}],details:{mode:"management",results:[]}}}function Kj(f,$){if(f===void 0)return;if(!Number.isInteger(f))throw Error("Transcript index must be an integer.");if(f<0||f>=$.length)throw Error(`Transcript index ${f} is out of range for ${$.length} child step${$.length===1?"":"s"}.`);return f}function Wj(f,$){let j=f.steps??[],J=Kj($.index,j);if(J===void 0){if(f.state==="running"&&typeof f.currentStep==="number"&&f.currentStep>=0&&f.currentStep<j.length)J=f.currentStep;else if(j.length===1)J=0}let Z=J!==void 0?j[J]:void 0,Q=$.index===void 0&&j.length>1?`Tip: pass index to inspect a specific child transcript (${j.map((B,X)=>`${X}=${B.agent}`).join(", ")}).`:void 0;return{index:J,step:Z,hint:Q}}function Lj(f,$,j){if($===void 0||!j)return;let J=d(j.model,j.thinking);return[`${f==="parallel"?"Agent":"Step"}: ${$} (${j.agent})`,j.status,Ff(j),J,j.error?`error: ${j.error}`:void 0].filter(Boolean).join(" | ")}function pf(f,$){let j=[];for(let J of $.outputPaths)j.push(`Output: ${J}`);if($.sessionFile)j.push(`Session: ${$.sessionFile}`);if($.eventsPath)j.push(`Events: ${$.eventsPath}`);if($.logPath)j.push(`Log: ${$.logPath}`);if($.resultPath)j.push(`Result: ${$.resultPath}`);if(!j.length)return;f.push("Artifacts:");for(let J of j)f.push(` ${J}`)}function bf(f,$,j,J){if(f.push(`${$}${J?" (tail truncated)":""}:`),j.length===0){f.push(" (no transcript lines available yet)");return}for(let Z of j)f.push(` ${Z}`)}function rf(f,$,j={}){let J=lf(j.lines),Z=Wj(f,j),Q=Z.index!==void 0?y.join($,`output-${Z.index}.log`):void 0,B=Zj($,f.outputFile),X=y.join($,`subagent-log-${f.runId}.md`),Y=Z.index!==void 0?n$([Q,B&&Q&&y.resolve(B)===y.resolve(Q)?B:void 0]):n$([B]),K=Z.index!==void 0?Z.step?.sessionFile:f.sessionFile,A=y.join($,"events.jsonl"),H=[`Run: ${f.runId}`,`State: ${f.state}`,`Mode: ${f.mode}`,Lj(f.mode,Z.index,Z.step),Z.hint].filter((S)=>Boolean(S));pf(H,{outputPaths:Y,sessionFile:K,eventsPath:b.existsSync(A)?A:void 0,logPath:b.existsSync(X)?X:void 0});let O=[],W=[],U="Transcript tail",C=!1;for(let S of Y){let D=P$(S,J,[$],"output");if(D.error)O.push(`Output read failed for ${D.path}: ${D.error}`);if(D.lines.length===0)continue;W=D.lines,U=`Transcript tail from ${D.path}`,C=D.truncated;break}if(W.length===0&&Z.step?.recentOutput?.length)W=Z.step.recentOutput.slice(-J),U="Recent output from status.json";if(W.length===0&&K){let S=m$(K,J,j.sessionRoots??[]);if(W=S.lines,O.push(...S.warnings),W.length>0)U=`Session transcript tail from ${K}`}if(O.length){H.push("Warnings:");for(let S of O)H.push(` ${S}`)}return bf(H,U,W,C),H.join(`
|
|
15
|
+
`)}function h$(f,$={}){if(f.asyncDir){let Q=Hf(f.asyncDir);if(Q)return rf(Q,f.asyncDir,$)}let j=lf($.lines),J=[`Nested run: ${f.id}`,`State: ${f.state}`,f.mode?`Mode: ${f.mode}`:void 0,f.agent?`Agent: ${f.agent}`:f.agents?.length?`Agents: ${f.agents.join(", ")}`:void 0].filter((Q)=>Boolean(Q));if(pf(J,{outputPaths:[],sessionFile:f.sessionFile}),!f.sessionFile)return bf(J,"Transcript tail",[],!1),J.join(`
|
|
16
|
+
`);let Z=m$(f.sessionFile,j,$.sessionRoots??[]);if(Z.warnings.length){J.push("Warnings:");for(let Q of Z.warnings)J.push(` ${Q}`)}return bf(J,`Session transcript tail from ${f.sessionFile}`,Z.lines,!1),J.join(`
|
|
17
|
+
`)}function o$(f,$,j={}){let J=lf(j.lines),Z=f.runId??f.id??y.basename($,".json"),Q=Array.isArray(f.results)?f.results:f.agent?[{agent:f.agent,output:f.output,summary:f.summary,sessionFile:f.sessionFile,state:f.state,success:f.success,exitCode:f.exitCode}]:[],B=j.index;if(B!==void 0&&!Number.isInteger(B))throw Error("Transcript index must be an integer.");if(B===void 0&&Q.length===1)B=0;if(B!==void 0&&(B<0||B>=Q.length))throw Error(`Transcript index ${B} is out of range for ${Q.length} result child${Q.length===1?"":"ren"}.`);let X=B!==void 0?Q[B]:void 0,Y=B!==void 0?X?.output??X?.summary??(Q.length===1?f.output??f.summary:void 0)??"":f.output??f.summary??"",K=Y.split(/\r?\n/).slice(-J),A=X?.sessionFile??f.sessionFile,H=[`Run: ${Z}`,`State: ${f.state??(f.success?"complete":"failed")}`,B!==void 0&&X?`Child: ${B} (${X.agent??"subagent"})`:void 0,B===void 0&&Q.length>1?`Tip: pass index to inspect a specific child transcript (${Q.map((O,W)=>`${W}=${O.agent??"subagent"}`).join(", ")}).`:void 0].filter((O)=>Boolean(O));return pf(H,{outputPaths:[],sessionFile:A,resultPath:$}),bf(H,"Result transcript tail",K.filter((O)=>O.trim()),Y.split(/\r?\n/).length>J),H.join(`
|
|
18
|
+
`)}function d$(f){return f.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}function af(f,$,j){let J=j!==void 0?`-${j+1}`:"";return`subagent-${d$($)}-${d$(f)}${J}`}import*as m from"node:fs";import*as T from"node:path";var AJ=process.platform==="win32"?"SIGBREAK":"SIGUSR2";var OJ=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function sf(f,$){if(f===void 0)return;if(f.trim()==="")throw Error(`${$} must not be empty.`);if(T.isAbsolute(f)||/[\\/]/.test(f)||f.includes(".."))throw Error(`${$} must be an async run id or prefix, not a path.`);return f}function Sf(f,$,j){let J=T.resolve(f),Z=T.resolve($),Q=T.relative(J,Z);if(Q===""||!Q.startsWith("..")&&!T.isAbsolute(Q))return;throw Error(`${j} must be inside ${J}.`)}function u$(f,$,j=""){if(!m.existsSync(f))return[];return m.readdirSync(f).filter((J)=>J.startsWith($)&&(!j||J.endsWith(j))).map((J)=>j?J.slice(0,-j.length):J).sort()}function ef(f,$){let j=T.join(f,`${$}.json`);return Sf(f,j,"Async result file"),m.existsSync(j)?j:null}function tf(f,$,j){let J=sf(f,"id");if(!J)return[];let Z=T.resolve($),Q=T.resolve(j);return[...new Set([...u$(Z,J),...u$(Q,J,".json")])].sort().map((X)=>{let Y=T.join(Z,X);return Sf(Z,Y,"Async run directory"),{id:X,location:{asyncDir:m.existsSync(Y)?Y:null,resultPath:ef(Q,X),resolvedId:X}}})}function l$(f,$,j){let J=T.resolve($),Z=T.resolve(j),Q=sf(f.id,"id")??sf(f.runId,"runId");if(f.dir){let K=T.resolve(f.dir);Sf(J,K,"Async run directory");let A=Q??T.basename(K);if(Q&&Q!==T.basename(K))throw Error(`Async run id '${Q}' does not match directory '${T.basename(K)}'.`);return{asyncDir:K,resultPath:ef(Z,A),resolvedId:A}}if(!Q)return{asyncDir:null,resultPath:null};let B=T.join(J,Q);Sf(J,B,"Async run directory");let X=ef(Z,Q);if(m.existsSync(B)||X)return{asyncDir:m.existsSync(B)?B:null,resultPath:X,resolvedId:Q};let Y=tf(Q,J,Z);if(Y.length===0)return{asyncDir:null,resultPath:null,resolvedId:Q};if(Y.length>1)throw Error(`Ambiguous async run id prefix '${Q}' matched: ${Y.map((K)=>K.id).join(", ")}. Provide a longer id.`);return Y[0].location}import*as Yf from"node:fs";import*as f$ from"node:path";function Oj(f,$,j){let J=f$.join($,f),Z=f$.join(j,`${f}.json`);if(!Yf.existsSync(J)&&!Yf.existsSync(Z))return;return{asyncDir:Yf.existsSync(J)?J:null,resultPath:Yf.existsSync(Z)?Z:null,resolvedId:f}}function Gj(f){if(!f)return[];return[...new Set([...f.foregroundControls.keys(),...f.foregroundRuns?.keys()??[]])]}function Mj(f){if(!f)return;let $=[],j=new Set,J=(Z)=>{if(!Z)return;let Q=`${Z.rootRunId}:${Z.eventSink}:${Z.controlInbox}`;if(j.has(Q))return;j.add(Q),$.push(Z)};for(let Z of f.foregroundControls.values())J(Z.nestedRoute);for(let Z of f.asyncJobs.values())J(Z.nestedRoute);return{routes:$}}function Vj(f,$,j){return tf(f,$,j)}function $$(f,$={}){Df("id",f);let j=$.asyncDirRoot??h,J=$.resultsDir??w,Z=$.nested??Mj($.state);if($.state?.foregroundControls.has(f)||$.state?.foregroundRuns?.has(f))return{kind:"foreground",id:f};let Q=Oj(f,j,J);if(Q)return{kind:"async",id:f,location:Q};let B=mf(f,Z?{scope:Z}:{});if(B.length>1)throw Error(`Nested run id '${f}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);if(B[0])return{kind:"nested",id:f,match:B[0]};let X=[];for(let A of Gj($.state).filter((H)=>H.startsWith(f)))X.push({kind:"foreground",id:A});for(let A of Vj(f,j,J))X.push({kind:"async",id:A.id,location:A.location});for(let A of mf(f,Z?{prefix:!0,scope:Z}:{prefix:!0}))X.push({kind:"nested",id:A.run.id,match:A});let K=[...new Map(X.map((A)=>[`${A.kind}:${A.id}`,A])).values()];if(K.length>1)throw Error(`Ambiguous subagent run id prefix '${f}' matched: ${K.map((A)=>`${A.kind}:${A.id}`).join(", ")}. Provide a longer id.`);return K[0]}function j$(f){return typeof f==="string"&&I.existsSync(f)}function i$(f,$,j){let J=$.map((B,X)=>({child:B,index:X})).filter(({child:B})=>typeof B.agent==="string");if(!f||J.length===0)return"Resume: unavailable; no child session file was persisted.";let Z=J[0]?.child.sessionFile??j;if($.length===1&&J.length===1&&j$(Z))return`Revive: subagent({ action: "resume", id: "${f}", message: "..." })`;let Q=J.find(({child:B})=>j$(B.sessionFile));if(Q)return`Revive child: subagent({ action: "resume", id: "${f}", index: ${Q.index}, message: "..." })`;return"Resume: unavailable; no child session file was persisted."}function Uj(f,$){let j=f.steps??[];if(f.mode==="parallel")return`Agent ${$+1}/${j.length||1}`;if(f.mode==="chain"){let J=f.chainStepCount??(j.length||1),Z=p(f.parallelGroups,j.length,J),Q=Z.find((B)=>$>=B.start&&$<B.start+B.count);if(Q)return`Step ${Q.stepIndex+1}/${J} Agent ${$-Q.start+1}/${Q.count}`;return`Step ${zf($,J,Z)+1}/${J}`}return`Step ${$+1}`}function zj(f){if(f.agent)return f.agent;if(f.agents?.length)return f.agents.join(", ");return f.id}function p$(f){let $=[];if(f.steerCount!==void 0)$.push(`${f.steerCount} steer${f.steerCount===1?"":"s"}`);if(typeof f.lastSteerAt==="number"&&Number.isFinite(f.lastSteerAt))$.push(`last ${new Date(f.lastSteerAt).toISOString()}`);return $.length?$.join(", "):void 0}function r$(f){let $=f.artifactPaths?.outputPath;if($&&I.existsSync($))try{let j=I.readFileSync($,"utf-8").trim();if(j)return j}catch{}return f.finalOutput??""}function Tj(f){let $=[`Run: ${f.runId}`,"State: remembered foreground",`Mode: ${f.mode}`,`Updated: ${new Date(f.updatedAt).toISOString()}`,`Cwd: ${f.cwd}`];for(let J of f.children){let Z=r$(J).trim().split(/\r?\n/).find((B)=>B.trim()),Q=[`${J.index+1}. ${J.agent} ${J.status}`,J.exitCode!==void 0?`exit ${J.exitCode}`:void 0,J.detachedReason?`detached: ${J.detachedReason}`:void 0,Z?`output: ${Z.slice(0,160)}`:void 0].filter(Boolean);if($.push(Q.join(", ")),J.sessionFile)$.push(` Session: ${J.sessionFile}`);if(J.transcriptPath)$.push(` Transcript: ${J.transcriptPath}`);if(J.artifactPaths?.outputPath)$.push(` Output: ${J.artifactPaths.outputPath}`);if(J.transcriptError)$.push(` Transcript warning: ${J.transcriptError}`)}if($.push("",`Status: subagent({ action: "status", id: "${f.runId}" })`),f.children.length===1)$.push(`Transcript: subagent({ action: "status", id: "${f.runId}", view: "transcript" })`);else $.push(`Transcript: subagent({ action: "status", id: "${f.runId}", index: 0, view: "transcript" })`);let j=f.children.find((J)=>J.status!=="detached"&&j$(J.sessionFile));if(j)$.push(f.children.length===1?`Revive: subagent({ action: "resume", id: "${f.runId}", message: "..." })`:`Revive child: subagent({ action: "resume", id: "${f.runId}", index: ${j.index}, message: "..." })`);else if(f.children.some((J)=>J.status==="detached"))$.push("Recovery: child detached for intercom coordination; status will show recovered output after the child exits when DM can observe it.");else $.push("Resume: unavailable; no child session file was persisted.");return $.join(`
|
|
19
|
+
`)}function Cj(f,$){let j=$.index;if(j!==void 0&&!Number.isInteger(j))throw Error("Transcript index must be an integer.");if(j===void 0&&f.children.length===1)j=0;if(j===void 0)return`Transcript view requires index for foreground run '${f.runId}' with ${f.children.length} children.`;if(j<0||j>=f.children.length)throw Error(`Transcript index ${j} is out of range for ${f.children.length} foreground children.`);let J=f.children[j],Z=Math.max(1,Math.min($.lines??80,1000)),Q=r$(J).split(/\r?\n/).filter((X)=>X.trim()).slice(-Z),B=[`Run: ${f.runId}`,`State: ${J.status}`,`Child: ${j} (${J.agent})`,J.sessionFile?`Session: ${J.sessionFile}`:void 0,J.transcriptPath?`Transcript: ${J.transcriptPath}`:void 0,J.artifactPaths?.outputPath?`Output: ${J.artifactPaths.outputPath}`:void 0].filter((X)=>Boolean(X));if(B.push("Result transcript tail:"),Q.length===0)B.push(" (no recovered final output available yet)");else for(let X of Q)B.push(` ${X}`);return B.join(`
|
|
20
|
+
`)}function Fj(f,$){let j=[`Nested run: ${$.id}`,`Root: ${f}`,`Parent: ${$.parentRunId}${$.parentStepIndex!==void 0?` step ${$.parentStepIndex+1}`:""}`,`State: ${$.state}`,$.activityState||$.lastActivityAt?`Activity: ${k($.lastActivityAt,$.activityState)}`:void 0,$.mode?`Mode: ${$.mode}`:void 0,`Agent: ${zj($)}`,$.currentStep!==void 0?`Progress: step ${$.currentStep+1}/${$.chainStepCount??$.steps?.length??1}`:void 0,$.turnBudget?`Turn budget: ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}+${$.turnBudget.graceTurns} (${$.turnBudget.outcome})`:void 0,$.asyncDir?`Dir: ${$.asyncDir}`:void 0,$.sessionFile?`Session: ${$.sessionFile}`:void 0,$.error?`Error: ${$.error}`:void 0].filter((J)=>Boolean(J));if($.path.length)j.push(`Path: ${$.path.map((J)=>`${J.runId}${J.stepIndex!==void 0?`:${J.stepIndex+1}`:""}${J.agent?`:${J.agent}`:""}`).join(" > ")} > ${$.id}`);if($.steps?.length){j.push("Steps:");for(let[J,Z]of $.steps.entries()){let Q=Z.status==="running"?k(Z.lastActivityAt,Z.activityState):void 0,B=Z.turnBudget?`, turn budget: ${Z.turnBudget.turnCount}/${Z.turnBudget.maxTurns}+${Z.turnBudget.graceTurns} (${Z.turnBudget.outcome})`:"";j.push(` ${J+1}. ${Z.agent} ${Z.status}${Q?`, ${Q}`:""}${B}${Z.error?`, error: ${Z.error}`:""}`),j.push(...x(Z.children,{indent:" ",commandHints:!0}))}}return j.push(...x($.children,{indent:" ",commandHints:!0})),j.push("Commands:",` Status: subagent({ action: "status", id: "${$.id}" })`,` Interrupt: subagent({ action: "interrupt", id: "${$.id}" })`,` Resume: subagent({ action: "resume", id: "${$.id}", message: "..." })`,` Steer: subagent({ action: "steer", id: "${$.id}", message: "..." })`,` Root status: subagent({ action: "status", id: "${f}" })`),j.join(`
|
|
21
|
+
`)}function bj(f,$={}){let j=$.asyncDirRoot??h,J=$.resultsDir??w,Z=$.state?.currentSessionId??void 0;if(f.view&&f.view!=="fleet"&&f.view!=="transcript")return{content:[{type:"text",text:`Unknown status view: ${f.view}. Valid: fleet, transcript.`}],isError:!0,details:{mode:"single",results:[]}};if(f.view==="fleet")return v$(f,{asyncDirRoot:j,resultsDir:J,kill:$.kill,now:$.now,state:$.state,childSafe:Boolean($.nested)});if(!f.id&&!f.runId&&!f.dir){if($.nested)return{content:[{type:"text",text:"Child-safe subagent status requires an id when no foreground run is active."}],isError:!0,details:{mode:"single",results:[]}};try{let K=Tf(j,{states:["queued","running"],sessionId:Z,resultsDir:J,kill:$.kill,now:$.now});if(f.view==="transcript"){if(K.length===1)return bj({...f,id:K[0].id},$);return{content:[{type:"text",text:K.length===0?"No active async run transcript is available.":`Transcript view requires an id when ${K.length} active async runs exist. Use subagent({ action: "status", view: "fleet" }) to choose one.`}],isError:!0,details:{mode:"single",results:[]}}}return{content:[{type:"text",text:k$(K)}],details:{mode:"single",results:[]}}}catch(K){return{content:[{type:"text",text:K instanceof Error?K.message:String(K)}],isError:!0,details:{mode:"single",results:[]}}}}let Q;try{let K=f.id??f.runId;if(!f.dir&&K){let A=$$(K,{asyncDirRoot:j,resultsDir:J,state:$.state,nested:$.nested});if(A?.kind==="foreground"){let H=$.state?.foregroundRuns?.get(A.id);if(H)try{return{content:[{type:"text",text:f.view==="transcript"?Cj(H,{index:f.index,lines:f.lines}):Tj(H)}],details:{mode:"single",results:[]}}}catch(O){return{content:[{type:"text",text:O instanceof Error?O.message:String(O)}],isError:!0,details:{mode:"single",results:[]}}}}if(A?.kind==="nested"){Zf(A.match.route,{resultsDir:J,kill:$.kill,now:$.now});let H=$$(K,{asyncDirRoot:j,resultsDir:J,state:$.state,nested:$.nested}),O=H?.kind==="nested"?H:A;if(f.view==="transcript")try{return{content:[{type:"text",text:h$(O.match.run,{index:f.index,lines:f.lines,sessionRoots:$.sessionRoots})}],details:{mode:"single",results:[]}}}catch(W){return{content:[{type:"text",text:W instanceof Error?W.message:String(W)}],isError:!0,details:{mode:"single",results:[]}}}return{content:[{type:"text",text:Fj(O.match.rootRunId,O.match.run)}],details:{mode:"single",results:[]}}}if(A?.kind==="async")Q=A.location;else Q={asyncDir:null,resultPath:null,resolvedId:K}}else Q=l$(f,j,J)}catch(K){return{content:[{type:"text",text:K instanceof Error?K.message:String(K)}],isError:!0,details:{mode:"single",results:[]}}}let{asyncDir:B,resultPath:X,resolvedId:Y}=Q;if(!B&&!X)return{content:[{type:"text",text:"Async run not found. Provide id or dir."}],isError:!0,details:{mode:"single",results:[]}};if(B){let K;try{K=ff(B,{resultsDir:J,kill:$.kill,now:$.now})}catch(U){return{content:[{type:"text",text:U instanceof Error?U.message:String(U)}],isError:!0,details:{mode:"single",results:[]}}}let A=K.status,H=A?.runId??Y??"unknown",O=qf.join(B,`subagent-log-${H}.md`),W=qf.join(B,"events.jsonl");if(A){if(f.view==="transcript"){if(Z&&A.sessionId!==Z)return{content:[{type:"text",text:"Transcript view is only available for async runs owned by the current session."}],isError:!0,details:{mode:"single",results:[]}};try{return{content:[{type:"text",text:rf(A,B,{index:f.index,lines:f.lines,sessionRoots:$.sessionRoots})}],details:{mode:"single",results:[]}}}catch(z){return{content:[{type:"text",text:z instanceof Error?z.message:String(z)}],isError:!0,details:{mode:"single",results:[]}}}}let U=[],C;try{let z=Pf(A.runId);if(z)Zf(z,{resultsDir:J,kill:$.kill,now:$.now});U=q$(A.runId)?.children??[],Uf(A.runId,A.steps,U)}catch(z){C=`Nested status unavailable: ${z instanceof Error?z.message:String(z)}`}let S=Af({asyncDir:B,outputFile:A.outputFile}),D=Xf({mode:A.mode,state:A.state,currentStep:A.currentStep,chainStepCount:A.chainStepCount,parallelGroups:A.parallelGroups,steps:(A.steps??[]).map((z,V)=>({index:V,agent:z.agent,status:z.status}))}),a$=new Date(A.startedAt).toISOString(),s$=A.lastUpdate?new Date(A.lastUpdate).toISOString():"n/a",J$=A.state==="running"?k(A.lastActivityAt,A.activityState):void 0,Z$=p$(A),g=[`Run: ${A.runId}`,`State: ${A.state}`,A.error?`Error: ${A.error}`:void 0,J$?`Activity: ${J$}`:void 0,Z$?`Steering: ${Z$}`:void 0,`Mode: ${A.mode}`,`Progress: ${D}`,A.pendingAppends?`Pending appends: ${A.pendingAppends}`:void 0,`Started: ${a$}`,`Updated: ${s$}`,A.turnBudget?`Turn budget: ${A.turnBudget.turnCount}/${A.turnBudget.maxTurns}+${A.turnBudget.graceTurns} (${A.turnBudget.outcome})`:void 0,`Dir: ${B}`,S?`Output: ${S}`:void 0,K.message?`Diagnosis: ${K.message}`:void 0,K.resultPath&&I.existsSync(K.resultPath)?`Result: ${K.resultPath}`:void 0].filter((z)=>Boolean(z));for(let[z,V]of(A.steps??[]).entries()){let Q$=V.status==="running"?k(V.lastActivityAt,V.activityState):void 0,B$=d(V.model,V.thinking),f0=B$?` (${B$})`:"",A$=p$(V),$0=A$?`, steering: ${A$}`:"",j0=V.error?`, error: ${V.error}`:"",J0=V.acceptance?.status?`, acceptance: ${V.acceptance.status}`:"",Z0=V.turnBudget?`, turn budget: ${V.turnBudget.turnCount}/${V.turnBudget.maxTurns}+${V.turnBudget.graceTurns} (${V.turnBudget.outcome})`:"",Q0=V.label?`${V.label} (${V.agent})`:V.agent,B0=V.phase?`[${V.phase}] `:"";g.push(`${Uj(A,z)}: ${B0}${Q0} ${V.status}${f0}${Q$?`, ${Q$}`:""}${$0}${J0}${Z0}${j0}`),g.push(...x(V.children,{indent:" ",commandHints:!0,maxLines:20}));let _f=qf.join(B,`output-${z}.log`);if(_f!==S&&I.existsSync(_f))g.push(` Output: ${_f}`);if(V.status==="running")g.push(` Intercom target: ${af(A.runId,V.agent,z)} (if registered)`),g.push(` Steer: subagent({ action: "steer", id: "${A.runId}", index: ${z}, message: "..." })`)}let e$=new Set((A.steps??[]).flatMap((z)=>z.children?.map((V)=>V.id)??[])),t$=U.filter((z)=>!e$.has(z.id));if(g.push(...x(t$,{indent:"",commandHints:!0,maxLines:20})),C)g.push(`Warning: ${C}`);if(A.sessionFile)g.push(`Session: ${A.sessionFile}`);if(A.state==="running")g.push(`Steer running child: subagent({ action: "steer", id: "${A.runId}", message: "..." })`);if(A.state!=="running")g.push(i$(A.runId,A.steps??[],A.sessionFile));if(I.existsSync(O))g.push(`Log: ${O}`);if(I.existsSync(W))g.push(`Events: ${W}`);return{content:[{type:"text",text:g.join(`
|
|
22
|
+
`)}],details:{mode:"single",results:[]}}}}if(X)try{let K=I.readFileSync(X,"utf-8"),A=JSON.parse(K);if(f.view==="transcript")try{return{content:[{type:"text",text:o$(A,X,{index:f.index,lines:f.lines})}],details:{mode:"single",results:[]}}}catch(C){return{content:[{type:"text",text:C instanceof Error?C.message:String(C)}],isError:!0,details:{mode:"single",results:[]}}}let H=A.success?"complete":A.state==="paused"||A.exitCode===0?"paused":"failed",O=A.runId??A.id??Y,W=[`Run: ${O}`,`State: ${H}`,`Result: ${X}`],U=Array.isArray(A.results)?A.results:A.agent?[{agent:A.agent,sessionFile:A.sessionFile}]:[];if(W.push(i$(O,U,A.sessionFile)),A.summary)W.push("",A.summary);return{content:[{type:"text",text:W.join(`
|
|
23
|
+
`)}],details:{mode:"single",results:[]}}}catch(K){return{content:[{type:"text",text:`Failed to read async result file: ${K instanceof Error?K.message:String(K)}`}],isError:!0,details:{mode:"single",results:[]}}}return{content:[{type:"text",text:"Status file not found."}],isError:!0,details:{mode:"single",results:[]}}}export{bj as inspectSubagentStatus};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import*as H from"node:fs";import*as L from"node:path";import*as H$ from"node:fs";import*as C from"node:path";var U$=[10,25,50,100,200,500,1000,2000,4000],V$=new Set(["EACCES","EBUSY","EPERM"]),u=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,l=u?new Int32Array(u):void 0;function L$($){if($<=0)return;if(l)try{Atomics.wait(l,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function M$($){let J=$?.code;return typeof J==="string"&&V$.has(J)}function f$($,J,j,Z,W){for(let Q=0;;Q++)try{$.renameSync(J,j);return}catch(B){let O=Z[Q];if(O===void 0||!M$(B))throw B;W(O)}}function A$($={}){let J=$.fs??H$,j=$.now??Date.now,Z=$.pid??process.pid,W=$.random??Math.random,B=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??U$:[],O=$.wait??L$;return(K,U)=>{J.mkdirSync(C.dirname(K),{recursive:!0});let V=C.join(C.dirname(K),`.${C.basename(K)}.${Z}.${j()}.${W().toString(36).slice(2)}.tmp`);try{J.writeFileSync(V,JSON.stringify(U,null,2),"utf-8"),f$(J,V,K,B,O)}finally{J.rmSync(V,{force:!0})}}}var _=A$();import*as E from"node:os";import*as y from"node:path";function I($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function z$($){let J=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let B of["USERNAME","USER","LOGNAME"]){let O=J[B];if(O)return`user-${I(O)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:E.userInfo;try{let B=Z?.().username;if(B)return`user-${I(B)}`}catch{}let W=J.USERPROFILE??J.HOME;if(W)return`home-${I(W)}`;let Q=$&&Object.hasOwn($,"homedir")?$.homedir:E.homedir;try{let B=Q?.();if(B)return`home-${I(B)}`}catch{}return"shared"}var T=y.join(E.tmpdir(),`dm-subagents-${z$()}`),N=y.join(T,"async-subagent-results"),F$=y.join(T,"async-subagent-runs"),T$=y.join(T,"chain-runs"),t$=y.join(T,"artifacts");function C$($,J,j){if(typeof $!=="object"||$===null)return!1;let{start:Z,count:W,stepIndex:Q}=$;return typeof Z==="number"&&typeof W==="number"&&typeof Q==="number"&&Number.isInteger(Z)&&Number.isInteger(W)&&Number.isInteger(Q)&&Z>=0&&W>0&&Q>=0&&Q<j&&Z+W<=J}function r($,J,j){if(!Array.isArray($))return[];return $.filter((Z)=>C$(Z,J,j)).sort((Z,W)=>Z.stepIndex-W.stepIndex||Z.start-W.start)}import{randomUUID as N$}from"node:crypto";import*as M from"node:fs";import*as q from"node:path";import*as a from"node:path";var _$=128,E$=4;function v($){return typeof $==="string"&&$.length>0&&$.length<=_$&&!a.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function i($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function s($,J){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function e($){if(!Array.isArray($))return[];return $.map((J)=>{if(!J||typeof J!=="object")return;let j=J;if(!v(j.runId))return;return{runId:j.runId,...i(j.stepIndex)!==void 0?{stepIndex:i(j.stepIndex)}:{},...s(j.agent,128)?{agent:s(j.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,E$)}import*as S from"node:fs";import*as A from"node:path";import{fileURLToPath as I$}from"node:url";import*as z from"node:os";import*as f from"node:path";var yj=f.join(z.homedir(),".config","mcp","mcp.json"),Sj={cursor:[f.join(z.homedir(),".cursor","mcp.json")],"claude-code":[f.join(z.homedir(),".claude","mcp.json"),f.join(z.homedir(),".claude.json"),f.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[f.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[f.join(z.homedir(),".codex","config.json")],windsurf:[f.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Nj}from"typebox/compile";function t($,J){let j=I$($),Z=A.extname(j),W=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts",Q=A.dirname(j);while(!S.existsSync(A.join(Q,"package.json"))){let B=A.dirname(Q);if(B===Q)throw Error(`Unable to resolve dm-subagents package root from ${j}`);Q=B}return A.join(Q,`${J}${W}`)}var pj=t(import.meta.url,A.join("src","runs","shared","subagent-prompt-runtime")),uj=t(import.meta.url,A.join("src","extension","fanout-child"));var $$=q.join(T,"nested-subagent-events");var R$="registry.json",d=65536,g=12,x=16,c=3;function D($){return v($)}function x$($,J){if(!D(J))throw Error(`${$} must be a non-empty safe id token.`)}function j$($,J){x$($,J)}function m($,J){let j=q.resolve($),Z=q.resolve(J);return Z===j||Z.startsWith(`${j}${q.sep}`)}function Z$($){return q.dirname(q.resolve($.eventSink))}function n($){if(j$("rootRunId",$.rootRunId),j$("capabilityToken",$.capabilityToken),!m($$,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!m($$,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(Z$($)!==q.dirname(q.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function Q$($,J){if(!J.asyncDir)return;let j=q.resolve(J.asyncDir),Z=q.resolve(T,"nested-subagent-runs",$,J.id),W=q.relative(Z,j);return j===Z||!W.startsWith("..")&&!q.isAbsolute(W)?j:void 0}function X($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Y($,J=512){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function D$($){if(!$||typeof $!=="object")return;let J=$,j=X(J.input),Z=X(J.output),W=X(J.total);return j!==void 0&&Z!==void 0&&W!==void 0?{input:j,output:Z,total:W}:void 0}function P$($){if(!$||typeof $!=="object")return;let J=$,j=X(J.inputTokens),Z=X(J.outputTokens),W=X(J.costUsd);return j!==void 0&&Z!==void 0&&W!==void 0?{inputTokens:j,outputTokens:Z,costUsd:W}:void 0}function P($){if(!$||typeof $!=="object")return;let J=$,j=X(J.maxTurns),Z=X(J.graceTurns),W=X(J.turnCount),Q=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if(j===void 0||Z===void 0||W===void 0||!Q)return;return{maxTurns:j,graceTurns:Z,turnCount:W,outcome:Q,...X(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:X(J.wrapUpRequestedAtTurn)}:{},...X(J.exceededAtTurn)!==void 0?{exceededAtTurn:X(J.exceededAtTurn)}:{}}}function w$($,J){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:J}function k$($,J){if(!$||typeof $!=="object")return;let j=$,Z=Y(j.agent,128);if(!Z)return;let W=j.status==="pending"||j.status==="running"||j.status==="complete"||j.status==="completed"||j.status==="failed"||j.status==="paused"?j.status:"pending";return{agent:Z,status:W,...Y(j.sessionFile,2048)?{sessionFile:Y(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...Y(j.currentTool,128)?{currentTool:Y(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...Y(j.currentPath,2048)?{currentPath:Y(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...Y(j.error,1024)?{error:Y(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...P(j.turnBudget)?{turnBudget:P(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<c&&Array.isArray(j.children)?{children:j.children.map((Q)=>w(Q,J+1)).filter((Q)=>Boolean(Q)).slice(0,x)}:{}}}function w($,J=0){if(!$||typeof $!=="object")return;let j=$;if(!D(j.id)||!D(j.parentRunId))return;let Z=e(j.path),W=Array.isArray(j.steps)?j.steps.map((O)=>k$(O,J+1)).filter((O)=>Boolean(O)).slice(0,g):void 0,Q=D$(j.totalTokens),B=P$(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...X(j.parentStepIndex)!==void 0?{parentStepIndex:X(j.parentStepIndex)}:{},...Y(j.parentAgent,128)?{parentAgent:Y(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,X(j.depth)??0),c),path:Z,state:w$(j.state,"running"),...Y(j.asyncDir,2048)?{asyncDir:Y(j.asyncDir,2048)}:{},...X(j.pid)!==void 0&&X(j.pid)>0&&Number.isInteger(X(j.pid))?{pid:X(j.pid)}:{},...Y(j.sessionId,256)?{sessionId:Y(j.sessionId,256)}:{},...Y(j.sessionFile,2048)?{sessionFile:Y(j.sessionFile,2048)}:{},...Y(j.intercomTarget,256)?{intercomTarget:Y(j.intercomTarget,256)}:{},...Y(j.ownerIntercomTarget,256)?{ownerIntercomTarget:Y(j.ownerIntercomTarget,256)}:{},...Y(j.leafIntercomTarget,256)?{leafIntercomTarget:Y(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...Y(j.controlInbox,2048)?{controlInbox:Y(j.controlInbox,2048)}:{},...Y(j.capabilityToken,128)?{capabilityToken:Y(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...Y(j.agent,128)?{agent:Y(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((O)=>Y(O,128)).filter((O)=>Boolean(O)).slice(0,g)}:{},...X(j.currentStep)!==void 0?{currentStep:X(j.currentStep)}:{},...X(j.chainStepCount)!==void 0?{chainStepCount:X(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...Y(j.currentTool,128)?{currentTool:Y(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...Y(j.currentPath,2048)?{currentPath:Y(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...Q?{totalTokens:Q}:{},...B?{totalCost:B}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...X(j.lastUpdate)!==void 0?{lastUpdate:X(j.lastUpdate)}:{},...X(j.timeoutMs)!==void 0?{timeoutMs:X(j.timeoutMs)}:{},...X(j.deadlineAt)!==void 0?{deadlineAt:X(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...P(j.turnBudget)?{turnBudget:P(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...Y(j.error,1024)?{error:Y(j.error,1024)}:{},...W&&W.length>0?{steps:W}:{},...J<c&&Array.isArray(j.children)?{children:j.children.map((O)=>w(O,J+1)).filter((O)=>Boolean(O)).slice(0,x)}:{}}}function h($,J){if(Buffer.byteLength($,"utf-8")>d)return;let j;try{j=JSON.parse($)}catch{return}if(!j||typeof j!=="object")return;let Z=j;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==J.rootRunId||Z.capabilityToken!==J.capabilityToken)return;if(!D(Z.parentRunId))return;let W=X(Z.ts);if(W===void 0)return;let Q=w(Z.child);if(!Q||Q.id===J.rootRunId)return;let B={...Q,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:Q.ownerState??"unknown"};return{type:Z.type,ts:W,rootRunId:J.rootRunId,parentRunId:Z.parentRunId,...X(Z.parentStepIndex)!==void 0?{parentStepIndex:X(Z.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:B}}function v$($,J){if(!$.includes(`
|
|
2
|
-
`)){let j=
|
|
1
|
+
import*as H from"node:fs";import*as U from"node:path";import*as V$ from"node:fs";import*as C from"node:path";var L$=[10,25,50,100,200,500,1000,2000,4000],U$=new Set(["EACCES","EBUSY","EPERM"]),p=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,u=p?new Int32Array(p):void 0;function M$($){if($<=0)return;if(u)try{Atomics.wait(u,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function f$($){let J=$?.code;return typeof J==="string"&&U$.has(J)}function A$($,J,j,Z,W){for(let Q=0;;Q++)try{$.renameSync(J,j);return}catch(B){let O=Z[Q];if(O===void 0||!f$(B))throw B;W(O)}}function z$($={}){let J=$.fs??V$,j=$.now??Date.now,Z=$.pid??process.pid,W=$.random??Math.random,B=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??L$:[],O=$.wait??M$;return(K,V)=>{J.mkdirSync(C.dirname(K),{recursive:!0});let L=C.join(C.dirname(K),`.${C.basename(K)}.${Z}.${j()}.${W().toString(36).slice(2)}.tmp`);try{J.writeFileSync(L,JSON.stringify(V,null,2),"utf-8"),A$(J,L,K,B,O)}finally{J.rmSync(L,{force:!0})}}}var _=z$();import*as E from"node:os";import*as y from"node:path";function b($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function T$($){let J=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let B of["USERNAME","USER","LOGNAME"]){let O=J[B];if(O)return`user-${b(O)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:E.userInfo;try{let B=Z?.().username;if(B)return`user-${b(B)}`}catch{}let W=J.USERPROFILE??J.HOME;if(W)return`home-${b(W)}`;let Q=$&&Object.hasOwn($,"homedir")?$.homedir:E.homedir;try{let B=Q?.();if(B)return`home-${b(B)}`}catch{}return"shared"}var F=y.join(E.tmpdir(),`dm-subagents-${T$()}`),I=y.join(F,"async-subagent-results"),F$=y.join(F,"async-subagent-runs"),C$=y.join(F,"chain-runs"),jj=y.join(F,"artifacts");function _$($,J,j){if(typeof $!=="object"||$===null)return!1;let{start:Z,count:W,stepIndex:Q}=$;return typeof Z==="number"&&typeof W==="number"&&typeof Q==="number"&&Number.isInteger(Z)&&Number.isInteger(W)&&Number.isInteger(Q)&&Z>=0&&W>0&&Q>=0&&Q<j&&Z+W<=J}function r($,J,j){if(!Array.isArray($))return[];return $.filter((Z)=>_$(Z,J,j)).sort((Z,W)=>Z.stepIndex-W.stepIndex||Z.start-W.start)}import{randomUUID as x$}from"node:crypto";import*as M from"node:fs";import*as q from"node:path";import*as s from"node:path";var E$=128,y$=4;function k($){return typeof $==="string"&&$.length>0&&$.length<=E$&&!s.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function l($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function i($,J){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function a($){if(!Array.isArray($))return[];return $.map((J)=>{if(!J||typeof J!=="object")return;let j=J;if(!k(j.runId))return;return{runId:j.runId,...l(j.stepIndex)!==void 0?{stepIndex:l(j.stepIndex)}:{},...i(j.agent,128)?{agent:i(j.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,y$)}import*as A from"node:path";import{fileURLToPath as e}from"node:url";import*as z from"node:os";import*as f from"node:path";var bj=f.join(z.homedir(),".config","mcp","mcp.json"),Ij={cursor:[f.join(z.homedir(),".cursor","mcp.json")],"claude-code":[f.join(z.homedir(),".claude","mcp.json"),f.join(z.homedir(),".claude.json"),f.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[f.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[f.join(z.homedir(),".codex","config.json")],windsurf:[f.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as xj}from"typebox/compile";function t($,J){let j=e($),Z=A.extname(j),W=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts";return A.join(A.dirname(j),`${J}${W}`)}function $$($){return A.basename(e($)).startsWith("dm-args.")}function N$($=import.meta.url){let J=$$($)?"subagent-prompt-runtime":A.join("..","runs","shared","subagent-prompt-runtime");return t($,J)}function R$($=import.meta.url){let J=$$($)?A.join("..","..","extension","fanout-child"):"fanout-child";return t($,J)}var rj=N$(),lj=R$();var j$=q.join(F,"nested-subagent-events");var D$="registry.json",h=65536,v=12,R=16,g=3;function x($){return k($)}function P$($,J){if(!x(J))throw Error(`${$} must be a non-empty safe id token.`)}function J$($,J){P$($,J)}function c($,J){let j=q.resolve($),Z=q.resolve(J);return Z===j||Z.startsWith(`${j}${q.sep}`)}function Q$($){return q.dirname(q.resolve($.eventSink))}function d($){if(J$("rootRunId",$.rootRunId),J$("capabilityToken",$.capabilityToken),!c(j$,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!c(j$,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(Q$($)!==q.dirname(q.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function W$($,J){if(!J.asyncDir)return;let j=q.resolve(J.asyncDir),Z=q.resolve(F,"nested-subagent-runs",$,J.id),W=q.relative(Z,j);return j===Z||!W.startsWith("..")&&!q.isAbsolute(W)?j:void 0}function X($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Y($,J=512){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function w$($){if(!$||typeof $!=="object")return;let J=$,j=X(J.input),Z=X(J.output),W=X(J.total);return j!==void 0&&Z!==void 0&&W!==void 0?{input:j,output:Z,total:W}:void 0}function k$($){if(!$||typeof $!=="object")return;let J=$,j=X(J.inputTokens),Z=X(J.outputTokens),W=X(J.costUsd);return j!==void 0&&Z!==void 0&&W!==void 0?{inputTokens:j,outputTokens:Z,costUsd:W}:void 0}function D($){if(!$||typeof $!=="object")return;let J=$,j=X(J.maxTurns),Z=X(J.graceTurns),W=X(J.turnCount),Q=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if(j===void 0||Z===void 0||W===void 0||!Q)return;return{maxTurns:j,graceTurns:Z,turnCount:W,outcome:Q,...X(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:X(J.wrapUpRequestedAtTurn)}:{},...X(J.exceededAtTurn)!==void 0?{exceededAtTurn:X(J.exceededAtTurn)}:{}}}function v$($,J){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:J}function g$($,J){if(!$||typeof $!=="object")return;let j=$,Z=Y(j.agent,128);if(!Z)return;let W=j.status==="pending"||j.status==="running"||j.status==="complete"||j.status==="completed"||j.status==="failed"||j.status==="paused"?j.status:"pending";return{agent:Z,status:W,...Y(j.sessionFile,2048)?{sessionFile:Y(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...Y(j.currentTool,128)?{currentTool:Y(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...Y(j.currentPath,2048)?{currentPath:Y(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...Y(j.error,1024)?{error:Y(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...D(j.turnBudget)?{turnBudget:D(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<g&&Array.isArray(j.children)?{children:j.children.map((Q)=>P(Q,J+1)).filter((Q)=>Boolean(Q)).slice(0,R)}:{}}}function P($,J=0){if(!$||typeof $!=="object")return;let j=$;if(!x(j.id)||!x(j.parentRunId))return;let Z=a(j.path),W=Array.isArray(j.steps)?j.steps.map((O)=>g$(O,J+1)).filter((O)=>Boolean(O)).slice(0,v):void 0,Q=w$(j.totalTokens),B=k$(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...X(j.parentStepIndex)!==void 0?{parentStepIndex:X(j.parentStepIndex)}:{},...Y(j.parentAgent,128)?{parentAgent:Y(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,X(j.depth)??0),g),path:Z,state:v$(j.state,"running"),...Y(j.asyncDir,2048)?{asyncDir:Y(j.asyncDir,2048)}:{},...X(j.pid)!==void 0&&X(j.pid)>0&&Number.isInteger(X(j.pid))?{pid:X(j.pid)}:{},...Y(j.sessionId,256)?{sessionId:Y(j.sessionId,256)}:{},...Y(j.sessionFile,2048)?{sessionFile:Y(j.sessionFile,2048)}:{},...Y(j.intercomTarget,256)?{intercomTarget:Y(j.intercomTarget,256)}:{},...Y(j.ownerIntercomTarget,256)?{ownerIntercomTarget:Y(j.ownerIntercomTarget,256)}:{},...Y(j.leafIntercomTarget,256)?{leafIntercomTarget:Y(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...Y(j.controlInbox,2048)?{controlInbox:Y(j.controlInbox,2048)}:{},...Y(j.capabilityToken,128)?{capabilityToken:Y(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...Y(j.agent,128)?{agent:Y(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((O)=>Y(O,128)).filter((O)=>Boolean(O)).slice(0,v)}:{},...X(j.currentStep)!==void 0?{currentStep:X(j.currentStep)}:{},...X(j.chainStepCount)!==void 0?{chainStepCount:X(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...Y(j.currentTool,128)?{currentTool:Y(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...Y(j.currentPath,2048)?{currentPath:Y(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...Q?{totalTokens:Q}:{},...B?{totalCost:B}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...X(j.lastUpdate)!==void 0?{lastUpdate:X(j.lastUpdate)}:{},...X(j.timeoutMs)!==void 0?{timeoutMs:X(j.timeoutMs)}:{},...X(j.deadlineAt)!==void 0?{deadlineAt:X(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...D(j.turnBudget)?{turnBudget:D(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...Y(j.error,1024)?{error:Y(j.error,1024)}:{},...W&&W.length>0?{steps:W}:{},...J<g&&Array.isArray(j.children)?{children:j.children.map((O)=>P(O,J+1)).filter((O)=>Boolean(O)).slice(0,R)}:{}}}function m($,J){if(Buffer.byteLength($,"utf-8")>h)return;let j;try{j=JSON.parse($)}catch{return}if(!j||typeof j!=="object")return;let Z=j;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==J.rootRunId||Z.capabilityToken!==J.capabilityToken)return;if(!x(Z.parentRunId))return;let W=X(Z.ts);if(W===void 0)return;let Q=P(Z.child);if(!Q||Q.id===J.rootRunId)return;let B={...Q,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:Q.ownerState??"unknown"};return{type:Z.type,ts:W,rootRunId:J.rootRunId,parentRunId:Z.parentRunId,...X(Z.parentStepIndex)!==void 0?{parentStepIndex:X(Z.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:B}}function c$($,J){if(!$.includes(`
|
|
2
|
+
`)){let j=m($.trim(),J);return j?[j]:[]}return $.split(`
|
|
3
3
|
`).slice(0,$.endsWith(`
|
|
4
|
-
`)?void 0:-1).map((j)=>j.trim()?
|
|
5
|
-
`;if(Buffer.byteLength(Z,"utf-8")>
|
|
4
|
+
`)?void 0:-1).map((j)=>j.trim()?m(j,J):void 0).filter((j)=>Boolean(j))}function N($){return $==="complete"||$==="failed"||$==="paused"}function Z$($,J){let j=J.type==="subagent.nested.completed"&&J.child.state==="running"?"complete":J.child.state,Z={...J.child,state:j,lastUpdate:J.child.lastUpdate??J.ts};if(!$)return Z;let W=$.lastUpdate??0,Q=Z.lastUpdate??J.ts;if(Q<W)return $;if(N($.state)&&!N(Z.state))return $;if(N($.state)&&N(Z.state)&&Q===W)return $;return{...$,...Z,state:Z.state,lastUpdate:Math.max(W,Q)}}function m$($,J){let j=!1,Z=(O)=>O.map((K)=>{if(K.id===J.parentRunId){let L=K.children??[],T=L.findIndex((w)=>w.id===J.child.id),S=Z$(T>=0?L[T]:void 0,J),G=T>=0?L.map((w,H$)=>H$===T?S:w):[...L,S];return j=!0,{...K,children:G.slice(0,R),lastUpdate:Math.max(K.lastUpdate??0,J.ts)}}if(!K.children?.length)return K;let V=Z(K.children);return V===K.children?K:{...K,children:V}}),W=Z($);if(j)return W;let Q=W.findIndex((O)=>O.id===J.child.id),B=Z$(Q>=0?W[Q]:void 0,J);return Q>=0?W.map((O,K)=>K===Q?B:O):[...W,B].slice(0,R)}function h$($,J){return{...$,updatedAt:Math.max($.updatedAt,J.ts),children:m$($.children,J)}}function O$($){return q.join(Q$($),D$)}function d$($){d($);try{let J=JSON.parse(M.readFileSync(O$($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof J.updatedAt==="number"?J.updatedAt:0,children:Array.isArray(J.children)?J.children.map((j)=>P(j)).filter((j)=>Boolean(j)):[],processedEvents:Array.isArray(J.processedEvents)?J.processedEvents.filter((j)=>typeof j==="string"):[]}}catch(J){if(J.code!=="ENOENT")throw J;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function X$($){d($);let J=d$($),j=new Set(J.processedEvents),Z=!1,W=[];try{W=M.readdirSync($.eventSink).filter((Q)=>Q.endsWith(".json")||Q.endsWith(".jsonl")).sort()}catch(Q){if(Q.code!=="ENOENT")throw Q}for(let Q of W){if(j.has(Q))continue;let B=q.join($.eventSink,Q);if(!c($.eventSink,B))continue;let O;try{let K=M.statSync(B);if(!K.isFile()||K.size>h)continue;O=M.readFileSync(B,"utf-8")}catch{continue}for(let K of c$(O,$))J=h$(J,K),Z=!0;j.add(Q),Z=!0}if(Z)J={...J,processedEvents:[...j].slice(-1000)},_(O$($),J);return J}function n$($,J,j){let Z=`${JSON.stringify(j)}
|
|
5
|
+
`;if(Buffer.byteLength(Z,"utf-8")>h)throw Error("Nested route record exceeds the maximum size.");M.mkdirSync($,{recursive:!0,mode:448});let W=`${String(J).padStart(13,"0")}-${x$()}.json`,Q=q.join($,`.${W}.tmp`),B=q.join($,W);return M.writeFileSync(Q,Z,{mode:384}),M.renameSync(Q,B),B}function B$($,J){d($);let j={...J,rootRunId:$.rootRunId,capabilityToken:$.capabilityToken},Z=m(JSON.stringify(j),$);if(!Z)throw Error("Nested event record failed validation.");n$($.eventSink,Z.ts,Z)}function K$($,J,j){return{id:$.runId||j.id,parentRunId:j.parentRunId,...j.parentStepIndex!==void 0?{parentStepIndex:j.parentStepIndex}:{},depth:j.depth,path:j.path??[{runId:j.parentRunId,...j.parentStepIndex!==void 0?{stepIndex:j.parentStepIndex}:{}}],asyncDir:J,...$.pid?{pid:$.pid}:{},...$.sessionId?{sessionId:$.sessionId}:{},mode:$.mode??j.mode,state:$.state,...$.currentStep!==void 0?{currentStep:$.currentStep}:{},...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.activityState?{activityState:$.activityState}:{},...$.lastActivityAt!==void 0?{lastActivityAt:$.lastActivityAt}:{},...$.currentTool?{currentTool:$.currentTool}:{},...$.currentToolStartedAt!==void 0?{currentToolStartedAt:$.currentToolStartedAt}:{},...$.currentPath?{currentPath:$.currentPath}:{},...$.turnCount!==void 0?{turnCount:$.turnCount}:{},...$.toolCount!==void 0?{toolCount:$.toolCount}:{},...$.totalTokens?{totalTokens:$.totalTokens}:{},...$.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}:{},...$.error?{error:$.error}:{},...$.startedAt!==void 0?{startedAt:$.startedAt}:{startedAt:j.ts},...$.endedAt!==void 0?{endedAt:$.endedAt}:{},lastUpdate:$.lastUpdate??j.ts,...$.sessionFile?{sessionFile:$.sessionFile}:{},...$.steps?.length?{steps:$.steps.map((Z)=>({agent:Z.agent,status:Z.status,...Z.sessionFile?{sessionFile:Z.sessionFile}:{},...Z.activityState?{activityState:Z.activityState}:{},...Z.lastActivityAt!==void 0?{lastActivityAt:Z.lastActivityAt}:{},...Z.currentTool?{currentTool:Z.currentTool}:{},...Z.currentToolStartedAt!==void 0?{currentToolStartedAt:Z.currentToolStartedAt}:{},...Z.currentPath?{currentPath:Z.currentPath}:{},...Z.turnCount!==void 0?{turnCount:Z.turnCount}:{},...Z.toolCount!==void 0?{toolCount:Z.toolCount}:{},...Z.startedAt!==void 0?{startedAt:Z.startedAt}:{},...Z.endedAt!==void 0?{endedAt:Z.endedAt}:{},...Z.error?{error:Z.error}:{},...Z.timedOut!==void 0?{timedOut:Z.timedOut}:{},...Z.turnBudget?{turnBudget:Z.turnBudget}:{},...Z.turnBudgetExceeded!==void 0?{turnBudgetExceeded:Z.turnBudgetExceeded}:{},...Z.wrapUpRequested!==void 0?{wrapUpRequested:Z.wrapUpRequested}:{}})).slice(0,v)}:{}}}function n($){return $ instanceof Error?$.message:String($)}function o$($){let J=U.join($,"runner.stderr.log"),j=65536,Z;try{let Q=H.statSync(J);if(Q.size<=0)return;let B=H.openSync(J,"r");try{let O=Math.min(Q.size,65536),K=Math.max(0,Q.size-O),V=Buffer.alloc(O);H.readSync(B,V,0,O,K),Z=V.toString("utf-8").trim()}finally{H.closeSync(B)}}catch{return}if(!Z)return;let W=Z.split(/\r?\n/).slice(-30).join(`
|
|
6
6
|
`);return W.length>4000?`${W.slice(-4000)}
|
|
7
|
-
[stderr tail truncated]`:W}function
|
|
8
|
-
`,"utf-8")}catch{}}function
|
|
7
|
+
[stderr tail truncated]`:W}function q$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function p$($,J){try{H.mkdirSync(U.dirname($),{recursive:!0}),H.appendFileSync($,`${JSON.stringify(J)}
|
|
8
|
+
`,"utf-8")}catch{}}function u$($){let J=U.join($,"status.json"),j;try{j=H.readFileSync(J,"utf-8")}catch(Z){if(q$(Z))return null;throw Error(`Failed to read async status file '${J}': ${n(Z)}`,{cause:Z instanceof Error?Z:void 0})}try{return JSON.parse(j)}catch(Z){throw Error(`Failed to parse async status file '${J}': ${n(Z)}`,{cause:Z instanceof Error?Z:void 0})}}function r$($){try{let J=JSON.parse(H.readFileSync($,"utf-8"));return{state:J.success?"complete":J.state==="paused"||J.exitCode===0?"paused":"failed",...Array.isArray(J.results)?{results:J.results}:{}}}catch(J){if(q$(J))return;throw Error(`Failed to read async result file '${$}': ${n(J)}`,{cause:J instanceof Error?J:void 0})}}function l$($,J){if(J?.success===!0)return"complete";if(J?.success===!1)return"failed";return $}function i$($,J,j){let Z=r$(J);if(!Z)return;let W=($.steps??[]).map((Q,B)=>{if(Q.status!=="running"&&Q.status!=="pending")return Q;let O=Z.results?.[B],K=l$(Z.state,O);return{...Q,status:K==="complete"?"complete":K,endedAt:Q.endedAt??j,durationMs:Q.startedAt!==void 0&&Q.durationMs===void 0?Math.max(0,j-Q.startedAt):Q.durationMs,exitCode:Q.exitCode??(K==="complete"||K==="paused"?0:1),error:K==="failed"?Q.error??O?.error:Q.error,sessionFile:Q.sessionFile??O?.sessionFile,model:Q.model??O?.model,attemptedModels:Q.attemptedModels??O?.attemptedModels,modelAttempts:Q.modelAttempts??O?.modelAttempts}});return{...$,state:Z.state,activityState:void 0,lastUpdate:j,endedAt:$.endedAt??j,steps:W}}function s$($,J,j){let Z=J.startedAt??j,W=J.agents?.length?J.agents:["subagent"],Q=J.chainStepCount,B=Q!==void 0?r(J.parallelGroups,W.length,Q):[];return{runId:J.runId||U.basename($),...J.sessionId?{sessionId:J.sessionId}:{},mode:J.mode??"single",state:"running",pid:J.pid,startedAt:Z,lastUpdate:j,currentStep:0,...Q!==void 0?{chainStepCount:Q}:{},...B.length?{parallelGroups:B}:{},steps:W.map((O)=>({agent:O,status:"running",startedAt:Z})),...J.sessionFile?{sessionFile:J.sessionFile}:{}}}function a$($,J,j,Z){let W=$.runId||U.basename(J),Q=typeof $.pid==="number"?$.pid:"unknown",B=Z??`Async runner process ${Q} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,O=o$(J),K=O?`${B}
|
|
9
9
|
|
|
10
10
|
Runner stderr tail:
|
|
11
|
-
${O}`:B,
|
|
11
|
+
${O}`:B,L=(($.steps?.length)?$.steps:[{agent:"subagent",status:"running"}]).map((G)=>G.status==="running"||G.status==="pending"?{...G,status:"failed",activityState:void 0,endedAt:G.endedAt??j,durationMs:G.startedAt!==void 0&&G.durationMs===void 0?Math.max(0,j-G.startedAt):G.durationMs,exitCode:G.exitCode??1,error:G.error??K}:G),T={...$,state:"failed",activityState:void 0,lastUpdate:j,endedAt:j,steps:L},S=L[$.currentStep??0]?.agent??L[0]?.agent??"subagent";return{status:T,message:K,result:{id:W,agent:S,mode:$.mode,success:!1,state:"failed",summary:K,results:L.map((G)=>({agent:G.agent,output:G.status==="complete"||G.status==="completed"?"":K,error:G.status==="complete"||G.status==="completed"?void 0:G.error??K,success:G.status==="complete"||G.status==="completed",model:G.model,attemptedModels:G.attemptedModels,modelAttempts:G.modelAttempts,sessionFile:G.sessionFile})),exitCode:1,timestamp:j,durationMs:Math.max(0,j-$.startedAt),asyncDir:J,sessionId:$.sessionId,sessionFile:$.sessionFile}}}function Y$($,J,j,Z,W){let Q=a$(J,$,Z,W);return _(j,Q.result),_(U.join($,"status.json"),Q.status),p$(U.join($,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:Z,runId:Q.status.runId,pid:J.pid,resultPath:j,message:Q.message}),{status:Q.status,repaired:!0,resultPath:j,message:Q.message}}function G$($){return $==="complete"||$==="failed"||$==="paused"}function*o($){for(let J of $??[])yield J,yield*o(J.children),yield*o(J.steps?.flatMap((j)=>j.children??[]))}function V0($,J={}){let j=X$($);for(let Z of o(j.children)){if(Z.state!=="running"&&Z.state!=="queued")continue;let W=W$($.rootRunId,Z);if(!W)continue;let Q=t$(W,{...J,resultsDir:U.join(J.resultsDir??I,"nested",$.rootRunId)}),B=Q.status;if(!B)continue;if(!Q.repaired&&!G$(B.state))continue;let O=J.now?.()??Date.now();B$($,{type:G$(B.state)?"subagent.nested.completed":"subagent.nested.updated",ts:O,parentRunId:Z.parentRunId,parentStepIndex:Z.parentStepIndex,child:K$(B,W,{id:Z.id,parentRunId:Z.parentRunId,parentStepIndex:Z.parentStepIndex,depth:Z.depth,path:Z.path,mode:Z.mode,ts:O})})}}function e$($,J=process.kill){try{return J($,0),"alive"}catch(j){let Z=typeof j==="object"&&j!==null&&"code"in j?j.code:void 0;if(Z==="ESRCH")return"dead";if(Z==="EPERM")return"unknown";return"unknown"}}function t$($,J={}){let j=J.now?.()??Date.now(),Z=u$($),W=!Z&&J.startedRun?s$($,J.startedRun,j):void 0,Q=Z??W;if(!Q)return{status:null,repaired:!1};let B=Q.runId||U.basename($),O=U.join(J.resultsDir??I,`${B}.json`);if(H.existsSync(O)){let V=Q.state==="running"||Q.state==="queued"?i$(Q,O,j):void 0;if(V)return _(U.join($,"status.json"),V),{status:V,repaired:!0,resultPath:O,message:"Existing async result file was used to repair stale running status."};return{status:Q,repaired:!1,resultPath:O}}if(Q.state!=="running"||typeof Q.pid!=="number")return{status:Z??null,repaired:!1,resultPath:O};if(!Z){let V=J.startedRun?.startedAt??Q.startedAt;if(j-V<(J.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:O}}if(e$(Q.pid,J.kill)!=="dead"){let V=J.staleAlivePidMs??86400000,L=Q.lastUpdate??Q.startedAt;if(j-L<=V)return{status:Z??null,repaired:!1,resultPath:O};let T=`Async runner process ${Q.pid} still has a live PID, but status has not updated for ${j-L}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return Y$($,Q,O,j,T)}return Y$($,Q,O,j)}export{V0 as reconcileNestedAsyncDescendants,t$ as reconcileAsyncRun,e$ as checkPidLiveness};
|