@duckmind/dm-darwin-x64 0.49.7 → 0.49.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dm +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 +10 -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,12 +1,12 @@
|
|
|
1
|
-
import*as c from"node:fs";import*as T from"node:path";import*as z from"node:fs";import*as w from"node:path";var P=new Map;function e($){return $ instanceof Error?$.message:String($)}function W$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function G$($){let f=w.join($,"status.json"),j;try{j=z.statSync(f)}catch(q){if(W$(q))return null;throw Error(`Failed to inspect async status file '${f}': ${e(q)}`,{cause:q instanceof Error?q:void 0})}let J=P.get(f);if(J&&J.mtime===j.mtimeMs)return J.status;let Q;try{Q=z.readFileSync(f,"utf-8")}catch(q){if(W$(q))return null;throw Error(`Failed to read async status file '${f}': ${e(q)}`,{cause:q instanceof Error?q:void 0})}let Z;try{Z=JSON.parse(Q)}catch(q){throw Error(`Failed to parse async status file '${f}': ${e(q)}`,{cause:q instanceof Error?q:void 0})}if(P.set(f,{mtime:j.mtimeMs,status:Z}),P.size>50){let q=P.keys().next().value;if(q)P.delete(q)}return Z}import*as x from"node:os";import*as I from"node:path";function h($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function n$($){let f=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let q of["USERNAME","USER","LOGNAME"]){let B=f[q];if(B)return`user-${h(B)}`}let J=$&&Object.hasOwn($,"userInfo")?$.userInfo:x.userInfo;try{let q=J?.().username;if(q)return`user-${h(q)}`}catch{}let Q=f.USERPROFILE??f.HOME;if(Q)return`home-${h(Q)}`;let Z=$&&Object.hasOwn($,"homedir")?$.homedir:x.homedir;try{let q=Z?.();if(q)return`home-${h(q)}`}catch{}return"shared"}var S=I.join(x.tmpdir(),`dm-subagents-${n$()}`),d=I.join(S,"async-subagent-results"),o$=I.join(S,"async-subagent-runs"),u$=I.join(S,"chain-runs"),r0=I.join(S,"artifacts");var t=["off","minimal","low","medium","high","xhigh"];function U$($){let f=$.lastIndexOf(":");if(f===-1)return{baseModel:$,thinkingSuffix:""};let j=t.find((J)=>J===$.substring(f+1));if(!j)return{baseModel:$,thinkingSuffix:""};return{baseModel:$.substring(0,f),thinkingSuffix:`:${j}`}}function n($){return $<1000?String($):$<1e4?`${($/1000).toFixed(1)}k`:`${Math.round($/1000)}k`}function L$($,f){let j=$?U$($):void 0,J=j?.baseModel??$,Q=t.find((q)=>q===f?.trim()),Z=j?.thinkingSuffix?j.thinkingSuffix.slice(1):Q;if(J){let q=J.lastIndexOf("/");if(q!==-1)J=J.slice(q+1)}return[J,Z?`thinking ${Z}`:void 0].filter(Boolean).join(" · ")}function g($){if($<1000)return`${$}ms`;if($<60000)return`${($/1000).toFixed(1)}s`;return`${Math.floor($/60000)}m${Math.floor($%60000/1000)}s`}function b($){let f=process.env.HOME;if(f&&$.startsWith(f))return`~${$.slice(f.length)}`;return $}function p$($){if($<1000)return"now";if($<60000)return`${Math.floor($/1000)}s`;return`${Math.floor($/60000)}m`}function o($,f,j=Date.now()){if($===void 0){if(f==="needs_attention")return"needs attention";if(f==="active_long_running")return"active but long-running";return}let J=p$(Math.max(0,j-$));if(f==="needs_attention")return`no activity for ${J}`;if(f==="active_long_running")return`active but long-running · last activity ${J} ago`;return J==="now"?"active now":`active ${J} ago`}function l$($){return $==="complete"||$==="completed"}function r$($){return $===1?"1 agent running":`${$} agents running`}function $$($,f,j={}){let J=$.filter((O)=>O.status==="running").length,Q=$.filter((O)=>l$(O.status)).length,Z=$.filter((O)=>O.status==="failed").length,q=$.filter((O)=>O.status==="paused").length,B=[`${Q}/${f} done`];if(j.showRunning!==!1&&J>0)B.unshift(r$(J));if(Z>0)B.push(`${Z} failed`);if(q>0)B.push(`${q} paused`);return B.join(" · ")}import{randomUUID as q0}from"node:crypto";import*as M from"node:fs";import*as G from"node:path";import*as A$ from"node:path";var i$=128,a$=4;function f$($){return typeof $==="string"&&$.length>0&&$.length<=i$&&!A$.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function V$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function M$($,f){return typeof $==="string"&&$.length>0?$.slice(0,f):void 0}function T$($){if(!Array.isArray($))return[];return $.map((f)=>{if(!f||typeof f!=="object")return;let j=f;if(!f$(j.runId))return;return{runId:j.runId,...V$(j.stepIndex)!==void 0?{stepIndex:V$(j.stepIndex)}:{},...M$(j.agent,128)?{agent:M$(j.agent,128)}:{}}}).filter((f)=>Boolean(f)).slice(0,a$)}import*as N from"node:fs";import*as C from"node:path";import{fileURLToPath as e$}from"node:url";import*as F from"node:os";import*as _ from"node:path";var Yf=_.join(F.homedir(),".config","mcp","mcp.json"),Hf={cursor:[_.join(F.homedir(),".cursor","mcp.json")],"claude-code":[_.join(F.homedir(),".claude","mcp.json"),_.join(F.homedir(),".claude.json"),_.join(F.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[_.join(F.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[_.join(F.homedir(),".codex","config.json")],windsurf:[_.join(F.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Uf}from"typebox/compile";function z$($,f){let j=e$($),J=C.extname(j),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(J)?J:".ts",Z=C.dirname(j);while(!N.existsSync(C.join(Z,"package.json"))){let q=C.dirname(Z);if(q===Z)throw Error(`Unable to resolve dm-subagents package root from ${j}`);Z=q}return C.join(Z,`${f}${Q}`)}var If=z$(import.meta.url,C.join("src","runs","shared","subagent-prompt-runtime")),Nf=z$(import.meta.url,C.join("src","extension","fanout-child"));import*as t$ from"node:fs";import*as y from"node:path";var $0=[10,25,50,100,200,500,1000,2000,4000],f0=new Set(["EACCES","EBUSY","EPERM"]),_$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,C$=_$?new Int32Array(_$):void 0;function j0($){if($<=0)return;if(C$)try{Atomics.wait(C$,0,0,$);return}catch{}let f=Date.now()+$;while(Date.now()<f);}function J0($){let f=$?.code;return typeof f==="string"&&f0.has(f)}function Z0($,f,j,J,Q){for(let Z=0;;Z++)try{$.renameSync(f,j);return}catch(q){let B=J[Z];if(B===void 0||!J0(q))throw q;Q(B)}}function Q0($={}){let f=$.fs??t$,j=$.now??Date.now,J=$.pid??process.pid,Q=$.random??Math.random,q=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??$0:[],B=$.wait??j0;return(O,W)=>{f.mkdirSync(y.dirname(O),{recursive:!0});let U=y.join(y.dirname(O),`.${y.basename(O)}.${J}.${j()}.${Q().toString(36).slice(2)}.tmp`);try{f.writeFileSync(U,JSON.stringify(W,null,2),"utf-8"),Z0(f,U,O,q,B)}finally{f.rmSync(U,{force:!0})}}}var R=Q0();var p=G.join(S,"nested-subagent-events"),B0="route.json",X0="registry.json",q$=65536,j$=12,k=16,J$=3;function l($){return f$($)}function O0($,f){if(!l(f))throw Error(`${$} must be a non-empty safe id token.`)}function F$($,f){O0($,f)}function Z$($,f){let j=G.resolve($),J=G.resolve(f);return J===j||J.startsWith(`${j}${G.sep}`)}function S$($){return G.dirname(G.resolve($.eventSink))}function i($){if(F$("rootRunId",$.rootRunId),F$("capabilityToken",$.capabilityToken),!Z$(p,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!Z$(p,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(S$($)!==G.dirname(G.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function b$($,f){if(!f.asyncDir)return;let j=G.resolve(f.asyncDir),J=G.resolve(S,"nested-subagent-runs",$,f.id),Q=G.relative(J,j);return j===J||!Q.startsWith("..")&&!G.isAbsolute(Q)?j:void 0}function K($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function H($,f=512){return typeof $==="string"&&$.length>0?$.slice(0,f):void 0}function K0($){if(!$||typeof $!=="object")return;let f=$,j=K(f.input),J=K(f.output),Q=K(f.total);return j!==void 0&&J!==void 0&&Q!==void 0?{input:j,output:J,total:Q}:void 0}function Y0($){if(!$||typeof $!=="object")return;let f=$,j=K(f.inputTokens),J=K(f.outputTokens),Q=K(f.costUsd);return j!==void 0&&J!==void 0&&Q!==void 0?{inputTokens:j,outputTokens:J,costUsd:Q}:void 0}function r($){if(!$||typeof $!=="object")return;let f=$,j=K(f.maxTurns),J=K(f.graceTurns),Q=K(f.turnCount),Z=f.outcome==="within-budget"||f.outcome==="wrap-up-requested"||f.outcome==="exceeded"?f.outcome:void 0;if(j===void 0||J===void 0||Q===void 0||!Z)return;return{maxTurns:j,graceTurns:J,turnCount:Q,outcome:Z,...K(f.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:K(f.wrapUpRequestedAtTurn)}:{},...K(f.exceededAtTurn)!==void 0?{exceededAtTurn:K(f.exceededAtTurn)}:{}}}function H0($,f){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:f}function W0($,f){if(!$||typeof $!=="object")return;let j=$,J=H(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,...H(j.sessionFile,2048)?{sessionFile:H(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...K(j.lastActivityAt)!==void 0?{lastActivityAt:K(j.lastActivityAt)}:{},...H(j.currentTool,128)?{currentTool:H(j.currentTool,128)}:{},...K(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:K(j.currentToolStartedAt)}:{},...H(j.currentPath,2048)?{currentPath:H(j.currentPath,2048)}:{},...K(j.turnCount)!==void 0?{turnCount:K(j.turnCount)}:{},...K(j.toolCount)!==void 0?{toolCount:K(j.toolCount)}:{},...K(j.startedAt)!==void 0?{startedAt:K(j.startedAt)}:{},...K(j.endedAt)!==void 0?{endedAt:K(j.endedAt)}:{},...H(j.error,1024)?{error:H(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...r(j.turnBudget)?{turnBudget:r(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...f<J$&&Array.isArray(j.children)?{children:j.children.map((Z)=>a(Z,f+1)).filter((Z)=>Boolean(Z)).slice(0,k)}:{}}}function a($,f=0){if(!$||typeof $!=="object")return;let j=$;if(!l(j.id)||!l(j.parentRunId))return;let J=T$(j.path),Q=Array.isArray(j.steps)?j.steps.map((B)=>W0(B,f+1)).filter((B)=>Boolean(B)).slice(0,j$):void 0,Z=K0(j.totalTokens),q=Y0(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...K(j.parentStepIndex)!==void 0?{parentStepIndex:K(j.parentStepIndex)}:{},...H(j.parentAgent,128)?{parentAgent:H(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,K(j.depth)??0),J$),path:J,state:H0(j.state,"running"),...H(j.asyncDir,2048)?{asyncDir:H(j.asyncDir,2048)}:{},...K(j.pid)!==void 0&&K(j.pid)>0&&Number.isInteger(K(j.pid))?{pid:K(j.pid)}:{},...H(j.sessionId,256)?{sessionId:H(j.sessionId,256)}:{},...H(j.sessionFile,2048)?{sessionFile:H(j.sessionFile,2048)}:{},...H(j.intercomTarget,256)?{intercomTarget:H(j.intercomTarget,256)}:{},...H(j.ownerIntercomTarget,256)?{ownerIntercomTarget:H(j.ownerIntercomTarget,256)}:{},...H(j.leafIntercomTarget,256)?{leafIntercomTarget:H(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...H(j.controlInbox,2048)?{controlInbox:H(j.controlInbox,2048)}:{},...H(j.capabilityToken,128)?{capabilityToken:H(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...H(j.agent,128)?{agent:H(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((B)=>H(B,128)).filter((B)=>Boolean(B)).slice(0,j$)}:{},...K(j.currentStep)!==void 0?{currentStep:K(j.currentStep)}:{},...K(j.chainStepCount)!==void 0?{chainStepCount:K(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...K(j.lastActivityAt)!==void 0?{lastActivityAt:K(j.lastActivityAt)}:{},...H(j.currentTool,128)?{currentTool:H(j.currentTool,128)}:{},...K(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:K(j.currentToolStartedAt)}:{},...H(j.currentPath,2048)?{currentPath:H(j.currentPath,2048)}:{},...K(j.turnCount)!==void 0?{turnCount:K(j.turnCount)}:{},...K(j.toolCount)!==void 0?{toolCount:K(j.toolCount)}:{},...Z?{totalTokens:Z}:{},...q?{totalCost:q}:{},...K(j.startedAt)!==void 0?{startedAt:K(j.startedAt)}:{},...K(j.endedAt)!==void 0?{endedAt:K(j.endedAt)}:{},...K(j.lastUpdate)!==void 0?{lastUpdate:K(j.lastUpdate)}:{},...K(j.timeoutMs)!==void 0?{timeoutMs:K(j.timeoutMs)}:{},...K(j.deadlineAt)!==void 0?{deadlineAt:K(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...r(j.turnBudget)?{turnBudget:r(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...H(j.error,1024)?{error:H(j.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...f<J$&&Array.isArray(j.children)?{children:j.children.map((B)=>a(B,f+1)).filter((B)=>Boolean(B)).slice(0,k)}:{}}}function Q$($,f){if(Buffer.byteLength($,"utf-8")>q$)return;let j;try{j=JSON.parse($)}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!==f.rootRunId||J.capabilityToken!==f.capabilityToken)return;if(!l(J.parentRunId))return;let Q=K(J.ts);if(Q===void 0)return;let Z=a(J.child);if(!Z||Z.id===f.rootRunId)return;let q={...Z,controlInbox:f.controlInbox,capabilityToken:f.capabilityToken,ownerState:Z.ownerState??"unknown"};return{type:J.type,ts:Q,rootRunId:f.rootRunId,parentRunId:J.parentRunId,...K(J.parentStepIndex)!==void 0?{parentStepIndex:K(J.parentStepIndex)}:{},capabilityToken:f.capabilityToken,child:q}}function G0($,f){if(!$.includes(`
|
|
2
|
-
`)){let j=
|
|
1
|
+
import*as m from"node:fs";import*as T from"node:path";import*as z from"node:fs";import*as P from"node:path";var D=new Map;function s($){return $ instanceof Error?$.message:String($)}function H$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function W$($){let f=P.join($,"status.json"),j;try{j=z.statSync(f)}catch(q){if(H$(q))return null;throw Error(`Failed to inspect async status file '${f}': ${s(q)}`,{cause:q instanceof Error?q:void 0})}let J=D.get(f);if(J&&J.mtime===j.mtimeMs)return J.status;let Q;try{Q=z.readFileSync(f,"utf-8")}catch(q){if(H$(q))return null;throw Error(`Failed to read async status file '${f}': ${s(q)}`,{cause:q instanceof Error?q:void 0})}let Z;try{Z=JSON.parse(Q)}catch(q){throw Error(`Failed to parse async status file '${f}': ${s(q)}`,{cause:q instanceof Error?q:void 0})}if(D.set(f,{mtime:j.mtimeMs,status:Z}),D.size>50){let q=D.keys().next().value;if(q)D.delete(q)}return Z}import*as x from"node:os";import*as I from"node:path";function c($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function o$($){let f=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let q of["USERNAME","USER","LOGNAME"]){let B=f[q];if(B)return`user-${c(B)}`}let J=$&&Object.hasOwn($,"userInfo")?$.userInfo:x.userInfo;try{let q=J?.().username;if(q)return`user-${c(q)}`}catch{}let Q=f.USERPROFILE??f.HOME;if(Q)return`home-${c(Q)}`;let Z=$&&Object.hasOwn($,"homedir")?$.homedir:x.homedir;try{let q=Z?.();if(q)return`home-${c(q)}`}catch{}return"shared"}var S=I.join(x.tmpdir(),`dm-subagents-${o$()}`),h=I.join(S,"async-subagent-results"),u$=I.join(S,"async-subagent-runs"),p$=I.join(S,"chain-runs"),a0=I.join(S,"artifacts");var e=["off","minimal","low","medium","high","xhigh"];function G$($){let f=$.lastIndexOf(":");if(f===-1)return{baseModel:$,thinkingSuffix:""};let j=e.find((J)=>J===$.substring(f+1));if(!j)return{baseModel:$,thinkingSuffix:""};return{baseModel:$.substring(0,f),thinkingSuffix:`:${j}`}}function d($){return $<1000?String($):$<1e4?`${($/1000).toFixed(1)}k`:`${Math.round($/1000)}k`}function L$($,f){let j=$?G$($):void 0,J=j?.baseModel??$,Q=e.find((q)=>q===f?.trim()),Z=j?.thinkingSuffix?j.thinkingSuffix.slice(1):Q;if(J){let q=J.lastIndexOf("/");if(q!==-1)J=J.slice(q+1)}return[J,Z?`thinking ${Z}`:void 0].filter(Boolean).join(" · ")}function w($){if($<1000)return`${$}ms`;if($<60000)return`${($/1000).toFixed(1)}s`;return`${Math.floor($/60000)}m${Math.floor($%60000/1000)}s`}function b($){let f=process.env.HOME;if(f&&$.startsWith(f))return`~${$.slice(f.length)}`;return $}function l$($){if($<1000)return"now";if($<60000)return`${Math.floor($/1000)}s`;return`${Math.floor($/60000)}m`}function n($,f,j=Date.now()){if($===void 0){if(f==="needs_attention")return"needs attention";if(f==="active_long_running")return"active but long-running";return}let J=l$(Math.max(0,j-$));if(f==="needs_attention")return`no activity for ${J}`;if(f==="active_long_running")return`active but long-running · last activity ${J} ago`;return J==="now"?"active now":`active ${J} ago`}function r$($){return $==="complete"||$==="completed"}function i$($){return $===1?"1 agent running":`${$} agents running`}function t($,f,j={}){let J=$.filter((O)=>O.status==="running").length,Q=$.filter((O)=>r$(O.status)).length,Z=$.filter((O)=>O.status==="failed").length,q=$.filter((O)=>O.status==="paused").length,B=[`${Q}/${f} done`];if(j.showRunning!==!1&&J>0)B.unshift(i$(J));if(Z>0)B.push(`${Z} failed`);if(q>0)B.push(`${q} paused`);return B.join(" · ")}import{randomUUID as X0}from"node:crypto";import*as M from"node:fs";import*as G from"node:path";import*as M$ from"node:path";var a$=128,s$=4;function $$($){return typeof $==="string"&&$.length>0&&$.length<=a$&&!M$.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function V$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function U$($,f){return typeof $==="string"&&$.length>0?$.slice(0,f):void 0}function A$($){if(!Array.isArray($))return[];return $.map((f)=>{if(!f||typeof f!=="object")return;let j=f;if(!$$(j.runId))return;return{runId:j.runId,...V$(j.stepIndex)!==void 0?{stepIndex:V$(j.stepIndex)}:{},...U$(j.agent,128)?{agent:U$(j.agent,128)}:{}}}).filter((f)=>Boolean(f)).slice(0,s$)}import*as C from"node:path";import{fileURLToPath as T$}from"node:url";import*as F from"node:os";import*as _ from"node:path";var Wf=_.join(F.homedir(),".config","mcp","mcp.json"),Gf={cursor:[_.join(F.homedir(),".cursor","mcp.json")],"claude-code":[_.join(F.homedir(),".claude","mcp.json"),_.join(F.homedir(),".claude.json"),_.join(F.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[_.join(F.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[_.join(F.homedir(),".codex","config.json")],windsurf:[_.join(F.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Uf}from"typebox/compile";function z$($,f){let j=T$($),J=C.extname(j),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(J)?J:".ts";return C.join(C.dirname(j),`${f}${Q}`)}function _$($){return C.basename(T$($)).startsWith("dm-args.")}function t$($=import.meta.url){let f=_$($)?"subagent-prompt-runtime":C.join("..","runs","shared","subagent-prompt-runtime");return z$($,f)}function $0($=import.meta.url){let f=_$($)?C.join("..","..","extension","fanout-child"):"fanout-child";return z$($,f)}var Rf=t$(),Df=$0();import*as f0 from"node:fs";import*as y from"node:path";var j0=[10,25,50,100,200,500,1000,2000,4000],J0=new Set(["EACCES","EBUSY","EPERM"]),C$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,F$=C$?new Int32Array(C$):void 0;function Z0($){if($<=0)return;if(F$)try{Atomics.wait(F$,0,0,$);return}catch{}let f=Date.now()+$;while(Date.now()<f);}function Q0($){let f=$?.code;return typeof f==="string"&&J0.has(f)}function q0($,f,j,J,Q){for(let Z=0;;Z++)try{$.renameSync(f,j);return}catch(q){let B=J[Z];if(B===void 0||!Q0(q))throw q;Q(B)}}function B0($={}){let f=$.fs??f0,j=$.now??Date.now,J=$.pid??process.pid,Q=$.random??Math.random,q=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??j0:[],B=$.wait??Z0;return(O,W)=>{f.mkdirSync(y.dirname(O),{recursive:!0});let L=y.join(y.dirname(O),`.${y.basename(O)}.${J}.${j()}.${Q().toString(36).slice(2)}.tmp`);try{f.writeFileSync(L,JSON.stringify(W,null,2),"utf-8"),q0(f,L,O,q,B)}finally{f.rmSync(L,{force:!0})}}}var N=B0();var u=G.join(S,"nested-subagent-events"),O0="route.json",K0="registry.json",Q$=65536,f$=12,g=16,j$=3;function p($){return $$($)}function Y0($,f){if(!p(f))throw Error(`${$} must be a non-empty safe id token.`)}function E$($,f){Y0($,f)}function J$($,f){let j=G.resolve($),J=G.resolve(f);return J===j||J.startsWith(`${j}${G.sep}`)}function b$($){return G.dirname(G.resolve($.eventSink))}function r($){if(E$("rootRunId",$.rootRunId),E$("capabilityToken",$.capabilityToken),!J$(u,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!J$(u,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(b$($)!==G.dirname(G.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function y$($,f){if(!f.asyncDir)return;let j=G.resolve(f.asyncDir),J=G.resolve(S,"nested-subagent-runs",$,f.id),Q=G.relative(J,j);return j===J||!Q.startsWith("..")&&!G.isAbsolute(Q)?j:void 0}function K($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function H($,f=512){return typeof $==="string"&&$.length>0?$.slice(0,f):void 0}function H0($){if(!$||typeof $!=="object")return;let f=$,j=K(f.input),J=K(f.output),Q=K(f.total);return j!==void 0&&J!==void 0&&Q!==void 0?{input:j,output:J,total:Q}:void 0}function W0($){if(!$||typeof $!=="object")return;let f=$,j=K(f.inputTokens),J=K(f.outputTokens),Q=K(f.costUsd);return j!==void 0&&J!==void 0&&Q!==void 0?{inputTokens:j,outputTokens:J,costUsd:Q}:void 0}function l($){if(!$||typeof $!=="object")return;let f=$,j=K(f.maxTurns),J=K(f.graceTurns),Q=K(f.turnCount),Z=f.outcome==="within-budget"||f.outcome==="wrap-up-requested"||f.outcome==="exceeded"?f.outcome:void 0;if(j===void 0||J===void 0||Q===void 0||!Z)return;return{maxTurns:j,graceTurns:J,turnCount:Q,outcome:Z,...K(f.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:K(f.wrapUpRequestedAtTurn)}:{},...K(f.exceededAtTurn)!==void 0?{exceededAtTurn:K(f.exceededAtTurn)}:{}}}function G0($,f){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:f}function L0($,f){if(!$||typeof $!=="object")return;let j=$,J=H(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,...H(j.sessionFile,2048)?{sessionFile:H(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...K(j.lastActivityAt)!==void 0?{lastActivityAt:K(j.lastActivityAt)}:{},...H(j.currentTool,128)?{currentTool:H(j.currentTool,128)}:{},...K(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:K(j.currentToolStartedAt)}:{},...H(j.currentPath,2048)?{currentPath:H(j.currentPath,2048)}:{},...K(j.turnCount)!==void 0?{turnCount:K(j.turnCount)}:{},...K(j.toolCount)!==void 0?{toolCount:K(j.toolCount)}:{},...K(j.startedAt)!==void 0?{startedAt:K(j.startedAt)}:{},...K(j.endedAt)!==void 0?{endedAt:K(j.endedAt)}:{},...H(j.error,1024)?{error:H(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...l(j.turnBudget)?{turnBudget:l(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...f<j$&&Array.isArray(j.children)?{children:j.children.map((Z)=>i(Z,f+1)).filter((Z)=>Boolean(Z)).slice(0,g)}:{}}}function i($,f=0){if(!$||typeof $!=="object")return;let j=$;if(!p(j.id)||!p(j.parentRunId))return;let J=A$(j.path),Q=Array.isArray(j.steps)?j.steps.map((B)=>L0(B,f+1)).filter((B)=>Boolean(B)).slice(0,f$):void 0,Z=H0(j.totalTokens),q=W0(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...K(j.parentStepIndex)!==void 0?{parentStepIndex:K(j.parentStepIndex)}:{},...H(j.parentAgent,128)?{parentAgent:H(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,K(j.depth)??0),j$),path:J,state:G0(j.state,"running"),...H(j.asyncDir,2048)?{asyncDir:H(j.asyncDir,2048)}:{},...K(j.pid)!==void 0&&K(j.pid)>0&&Number.isInteger(K(j.pid))?{pid:K(j.pid)}:{},...H(j.sessionId,256)?{sessionId:H(j.sessionId,256)}:{},...H(j.sessionFile,2048)?{sessionFile:H(j.sessionFile,2048)}:{},...H(j.intercomTarget,256)?{intercomTarget:H(j.intercomTarget,256)}:{},...H(j.ownerIntercomTarget,256)?{ownerIntercomTarget:H(j.ownerIntercomTarget,256)}:{},...H(j.leafIntercomTarget,256)?{leafIntercomTarget:H(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...H(j.controlInbox,2048)?{controlInbox:H(j.controlInbox,2048)}:{},...H(j.capabilityToken,128)?{capabilityToken:H(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...H(j.agent,128)?{agent:H(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((B)=>H(B,128)).filter((B)=>Boolean(B)).slice(0,f$)}:{},...K(j.currentStep)!==void 0?{currentStep:K(j.currentStep)}:{},...K(j.chainStepCount)!==void 0?{chainStepCount:K(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...K(j.lastActivityAt)!==void 0?{lastActivityAt:K(j.lastActivityAt)}:{},...H(j.currentTool,128)?{currentTool:H(j.currentTool,128)}:{},...K(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:K(j.currentToolStartedAt)}:{},...H(j.currentPath,2048)?{currentPath:H(j.currentPath,2048)}:{},...K(j.turnCount)!==void 0?{turnCount:K(j.turnCount)}:{},...K(j.toolCount)!==void 0?{toolCount:K(j.toolCount)}:{},...Z?{totalTokens:Z}:{},...q?{totalCost:q}:{},...K(j.startedAt)!==void 0?{startedAt:K(j.startedAt)}:{},...K(j.endedAt)!==void 0?{endedAt:K(j.endedAt)}:{},...K(j.lastUpdate)!==void 0?{lastUpdate:K(j.lastUpdate)}:{},...K(j.timeoutMs)!==void 0?{timeoutMs:K(j.timeoutMs)}:{},...K(j.deadlineAt)!==void 0?{deadlineAt:K(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...l(j.turnBudget)?{turnBudget:l(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...H(j.error,1024)?{error:H(j.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...f<j$&&Array.isArray(j.children)?{children:j.children.map((B)=>i(B,f+1)).filter((B)=>Boolean(B)).slice(0,g)}:{}}}function Z$($,f){if(Buffer.byteLength($,"utf-8")>Q$)return;let j;try{j=JSON.parse($)}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!==f.rootRunId||J.capabilityToken!==f.capabilityToken)return;if(!p(J.parentRunId))return;let Q=K(J.ts);if(Q===void 0)return;let Z=i(J.child);if(!Z||Z.id===f.rootRunId)return;let q={...Z,controlInbox:f.controlInbox,capabilityToken:f.capabilityToken,ownerState:Z.ownerState??"unknown"};return{type:J.type,ts:Q,rootRunId:f.rootRunId,parentRunId:J.parentRunId,...K(J.parentStepIndex)!==void 0?{parentStepIndex:K(J.parentStepIndex)}:{},capabilityToken:f.capabilityToken,child:q}}function V0($,f){if(!$.includes(`
|
|
2
|
+
`)){let j=Z$($.trim(),f);return j?[j]:[]}return $.split(`
|
|
3
3
|
`).slice(0,$.endsWith(`
|
|
4
|
-
`)?void 0:-1).map((j)=>j.trim()?
|
|
5
|
-
`;if(Buffer.byteLength(J,"utf-8")>
|
|
4
|
+
`)?void 0:-1).map((j)=>j.trim()?Z$(j,f):void 0).filter((j)=>Boolean(j))}function o($){return $==="complete"||$==="failed"||$==="paused"}function S$($,f){let j=f.type==="subagent.nested.completed"&&f.child.state==="running"?"complete":f.child.state,J={...f.child,state:j,lastUpdate:f.child.lastUpdate??f.ts};if(!$)return J;let Q=$.lastUpdate??0,Z=J.lastUpdate??f.ts;if(Z<Q)return $;if(o($.state)&&!o(J.state))return $;if(o($.state)&&o(J.state)&&Z===Q)return $;return{...$,...J,state:J.state,lastUpdate:Math.max(Q,Z)}}function U0($,f){let j=!1,J=(B)=>B.map((O)=>{if(O.id===f.parentRunId){let L=O.children??[],X=L.findIndex((E)=>E.id===f.child.id),V=S$(X>=0?L[X]:void 0,f),Y=X>=0?L.map((E,R)=>R===X?V:E):[...L,V];return j=!0,{...O,children:Y.slice(0,g),lastUpdate:Math.max(O.lastUpdate??0,f.ts)}}if(!O.children?.length)return O;let W=J(O.children);return W===O.children?O:{...O,children:W}}),Q=J($);if(j)return Q;let Z=Q.findIndex((B)=>B.id===f.child.id),q=S$(Z>=0?Q[Z]:void 0,f);return Z>=0?Q.map((B,O)=>O===Z?q:B):[...Q,q].slice(0,g)}function M0($,f){return{...$,updatedAt:Math.max($.updatedAt,f.ts),children:U0($.children,f)}}function x$($){return G.join(b$($),K0)}function I$(){let $;try{$=M.readdirSync(u)}catch(j){if(j.code==="ENOENT")return new Map;throw j}let f=new Map;for(let j of $){let J=G.join(u,j);try{let Q=JSON.parse(M.readFileSync(G.join(J,O0),"utf-8"));if(typeof Q.rootRunId!=="string"||typeof Q.capabilityToken!=="string")continue;if(f.has(Q.rootRunId))continue;let Z={rootRunId:Q.rootRunId,eventSink:G.join(J,"events"),controlInbox:G.join(J,"controls"),capabilityToken:Q.capabilityToken};r(Z),f.set(Q.rootRunId,Z)}catch{continue}}return f}function A0($){r($);try{let f=JSON.parse(M.readFileSync(x$($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof f.updatedAt==="number"?f.updatedAt:0,children:Array.isArray(f.children)?f.children.map((j)=>i(j)).filter((j)=>Boolean(j)):[],processedEvents:Array.isArray(f.processedEvents)?f.processedEvents.filter((j)=>typeof j==="string"):[]}}catch(f){if(f.code!=="ENOENT")throw f;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function a($){r($);let f=A0($),j=new Set(f.processedEvents),J=!1,Q=[];try{Q=M.readdirSync($.eventSink).filter((Z)=>Z.endsWith(".json")||Z.endsWith(".jsonl")).sort()}catch(Z){if(Z.code!=="ENOENT")throw Z}for(let Z of Q){if(j.has(Z))continue;let q=G.join($.eventSink,Z);if(!J$($.eventSink,q))continue;let B;try{let O=M.statSync(q);if(!O.isFile()||O.size>Q$)continue;B=M.readFileSync(q,"utf-8")}catch{continue}for(let O of V0(B,$))f=M0(f,O),J=!0;j.add(Z),J=!0}if(J)f={...f,processedEvents:[...j].slice(-1000)},N(x$($),f);return f}function T0($,f,j){let J=`${JSON.stringify(j)}
|
|
5
|
+
`;if(Buffer.byteLength(J,"utf-8")>Q$)throw Error("Nested route record exceeds the maximum size.");M.mkdirSync($,{recursive:!0,mode:448});let Q=`${String(f).padStart(13,"0")}-${X0()}.json`,Z=G.join($,`.${Q}.tmp`),q=G.join($,Q);return M.writeFileSync(Z,J,{mode:384}),M.renameSync(Z,q),q}function N$($,f){r($);let j={...f,rootRunId:$.rootRunId,capabilityToken:$.capabilityToken},J=Z$(JSON.stringify(j),$);if(!J)throw Error("Nested event record failed validation.");T0($.eventSink,J.ts,J)}function R$($,f,j){if(!f?.length)return;for(let J of f)J.children=void 0;if(!j?.length)return;for(let J of j){if(J.parentRunId!==$||J.parentStepIndex===void 0)continue;let Q=f.find((Z,q)=>(Z.index??q)===J.parentStepIndex);if(!Q)continue;Q.children??=[],Q.children=[...Q.children.filter((Z)=>Z.id!==J.id),J].slice(0,g)}}function D$($,f,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:f,...$.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((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,f$)}:{}}}function w$($){let f={total:0,running:0,paused:0,complete:0,failed:0,queued:0};for(let j of $??[]){f.total++,f[j.state]++;let J=w$([...j.children??[],...j.steps?.flatMap((Q)=>Q.children??[])??[]]);f.total+=J.total,f.running+=J.running,f.paused+=J.paused,f.complete+=J.complete,f.failed+=J.failed,f.queued+=J.queued}return f}function q$($){let f=w$($);if(f.total===0)return;let j=[f.running>0?`${f.running} running`:"",f.paused>0?`${f.paused} paused`:"",f.failed>0?`${f.failed} failed`:"",f.complete>0?`${f.complete} complete`:"",f.queued>0?`${f.queued} queued`:""].filter(Boolean);return`+${f.total} nested run${f.total===1?"":"s"}${j.length?` (${j.join(", ")})`:""}`}function z0($){if($.agent)return $.agent;if($.agents?.length)return $.agents.length===1?$.agents[0]:`${$.agents.slice(0,2).join(", ")}${$.agents.length>2?` +${$.agents.length-2}`:""}`;return $.id}function P$($){let f=[];if($.currentTool&&$.currentToolStartedAt!==void 0)f.push(`tool ${$.currentTool} ${w(Math.max(0,Date.now()-$.currentToolStartedAt))}`);else if($.currentTool)f.push(`tool ${$.currentTool}`);if($.currentPath)f.push(b($.currentPath));if($.turnCount!==void 0)f.push(`${$.turnCount} turns`);if($.toolCount!==void 0)f.push(`${$.toolCount} tools`);if($.totalTokens)f.push(`${d($.totalTokens.total)} tok`);let j=n($.lastActivityAt,$.activityState);return j||f.length?[j,...f].filter(Boolean).join(" | "):void 0}function _0($,f){let j=[],J=(Q,Z,q)=>{if(!Q?.length||j.length>=f.maxLines)return;if(Z>f.maxDepth){let B=q$(Q);if(B&&j.length<f.maxLines)j.push(`${q}↳ ${B}`);return}for(let B=0;B<Q.length;B++){let O=Q[B];if(j.length>=f.maxLines){let X=q$(Q.slice(B));if(X)j[j.length-1]=`${q}↳ ${X}`;return}let W=O.state==="running"?P$(O):void 0,L=O.error?` | error: ${O.error}`:"";if(j.push(`${q}↳ ${z0(O)} [${O.id}] ${O.state}${W?` | ${W}`:""}${L}`),f.commandHints&&j.length<f.maxLines)j.push(`${q} Status: subagent({ action: "status", id: "${O.id}" })`);if(Z===f.maxDepth){let X=q$([...O.steps?.flatMap((V)=>V.children??[])??[],...O.children??[]]);if(X&&j.length<f.maxLines)j.push(`${q} ↳ ${X}`);continue}for(let[X,V]of(O.steps??[]).entries()){if(j.length>=f.maxLines)return;let Y=V.status==="running"?P$(V):void 0;j.push(`${q} ${X+1}. ${V.agent} ${V.status}${Y?` | ${Y}`:""}${V.error?` | error: ${V.error}`:""}`),J(V.children,Z+1,`${q} `)}J(O.children,Z+1,`${q} `)}};return J($,0,f.indent),j}function B$($,f={}){return _0($,{indent:f.indent??" ",maxDepth:f.maxDepth??2,maxLines:f.maxLines??40,commandHints:f.commandHints??!1})}function C0($,f,j){if(typeof $!=="object"||$===null)return!1;let{start:J,count:Q,stepIndex:Z}=$;return typeof J==="number"&&typeof Q==="number"&&typeof Z==="number"&&Number.isInteger(J)&&Number.isInteger(Q)&&Number.isInteger(Z)&&J>=0&&Q>0&&Z>=0&&Z<j&&J+Q<=f}function k($,f,j){if(!Array.isArray($))return[];return $.filter((J)=>C0(J,f,j)).sort((J,Q)=>J.stepIndex-Q.stepIndex||J.start-Q.start)}function g$($,f,j){let J=0,Q=0;for(let Z of j){while(Q<Z.start&&J<f){if(Q===$)return J;Q++,J++}if($>=Z.start&&$<Z.start+Z.count)return Z.stepIndex;Q=Z.start+Z.count,J=Z.stepIndex+1}while(Q<=$&&J<f){if(Q===$)return J;Q++,J++}return Math.max(0,f-1)}import*as U from"node:fs";import*as A from"node:path";function X$($){return $ instanceof Error?$.message:String($)}function F0($){let f=A.join($,"runner.stderr.log"),j=65536,J;try{let Z=U.statSync(f);if(Z.size<=0)return;let q=U.openSync(f,"r");try{let B=Math.min(Z.size,65536),O=Math.max(0,Z.size-B),W=Buffer.alloc(B);U.readSync(q,W,0,B,O),J=W.toString("utf-8").trim()}finally{U.closeSync(q)}}catch{return}if(!J)return;let Q=J.split(/\r?\n/).slice(-30).join(`
|
|
6
6
|
`);return Q.length>4000?`${Q.slice(-4000)}
|
|
7
|
-
[stderr tail truncated]`:Q}function
|
|
8
|
-
`,"utf-8")}catch{}}function
|
|
7
|
+
[stderr tail truncated]`:Q}function m$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function E0($,f){try{U.mkdirSync(A.dirname($),{recursive:!0}),U.appendFileSync($,`${JSON.stringify(f)}
|
|
8
|
+
`,"utf-8")}catch{}}function S0($){let f=A.join($,"status.json"),j;try{j=U.readFileSync(f,"utf-8")}catch(J){if(m$(J))return null;throw Error(`Failed to read async status file '${f}': ${X$(J)}`,{cause:J instanceof Error?J:void 0})}try{return JSON.parse(j)}catch(J){throw Error(`Failed to parse async status file '${f}': ${X$(J)}`,{cause:J instanceof Error?J:void 0})}}function b0($){try{let f=JSON.parse(U.readFileSync($,"utf-8"));return{state:f.success?"complete":f.state==="paused"||f.exitCode===0?"paused":"failed",...Array.isArray(f.results)?{results:f.results}:{}}}catch(f){if(m$(f))return;throw Error(`Failed to read async result file '${$}': ${X$(f)}`,{cause:f instanceof Error?f:void 0})}}function y0($,f){if(f?.success===!0)return"complete";if(f?.success===!1)return"failed";return $}function x0($,f,j){let J=b0(f);if(!J)return;let Q=($.steps??[]).map((Z,q)=>{if(Z.status!=="running"&&Z.status!=="pending")return Z;let B=J.results?.[q],O=y0(J.state,B);return{...Z,status:O==="complete"?"complete":O,endedAt:Z.endedAt??j,durationMs:Z.startedAt!==void 0&&Z.durationMs===void 0?Math.max(0,j-Z.startedAt):Z.durationMs,exitCode:Z.exitCode??(O==="complete"||O==="paused"?0:1),error:O==="failed"?Z.error??B?.error:Z.error,sessionFile:Z.sessionFile??B?.sessionFile,model:Z.model??B?.model,attemptedModels:Z.attemptedModels??B?.attemptedModels,modelAttempts:Z.modelAttempts??B?.modelAttempts}});return{...$,state:J.state,activityState:void 0,lastUpdate:j,endedAt:$.endedAt??j,steps:Q}}function I0($,f,j){let J=f.startedAt??j,Q=f.agents?.length?f.agents:["subagent"],Z=f.chainStepCount,q=Z!==void 0?k(f.parallelGroups,Q.length,Z):[];return{runId:f.runId||A.basename($),...f.sessionId?{sessionId:f.sessionId}:{},mode:f.mode??"single",state:"running",pid:f.pid,startedAt:J,lastUpdate:j,currentStep:0,...Z!==void 0?{chainStepCount:Z}:{},...q.length?{parallelGroups:q}:{},steps:Q.map((B)=>({agent:B,status:"running",startedAt:J})),...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function N0($,f,j,J){let Q=$.runId||A.basename(f),Z=typeof $.pid==="number"?$.pid:"unknown",q=J??`Async runner process ${Z} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,B=F0(f),O=B?`${q}
|
|
9
9
|
|
|
10
10
|
Runner stderr tail:
|
|
11
|
-
${B}`:q,U=(($.steps?.length)?$.steps:[{agent:"subagent",status:"running"}]).map((Y)=>Y.status==="running"||Y.status==="pending"?{...Y,status:"failed",activityState:void 0,endedAt:Y.endedAt??j,durationMs:Y.startedAt!==void 0&&Y.durationMs===void 0?Math.max(0,j-Y.startedAt):Y.durationMs,exitCode:Y.exitCode??1,error:Y.error??O}:Y),X={...$,state:"failed",activityState:void 0,lastUpdate:j,endedAt:j,steps:U},L=U[$.currentStep??0]?.agent??U[0]?.agent??"subagent";return{status:X,message:O,result:{id:Q,agent:L,mode:$.mode,success:!1,state:"failed",summary:O,results:U.map((Y)=>({agent:Y.agent,output:Y.status==="complete"||Y.status==="completed"?"":O,error:Y.status==="complete"||Y.status==="completed"?void 0:Y.error??O,success:Y.status==="complete"||Y.status==="completed",model:Y.model,attemptedModels:Y.attemptedModels,modelAttempts:Y.modelAttempts,sessionFile:Y.sessionFile})),exitCode:1,timestamp:j,durationMs:Math.max(0,j-$.startedAt),asyncDir:f,sessionId:$.sessionId,sessionFile:$.sessionFile}}}function g$($,f,j,J,Q){let Z=x0(f,$,J,Q);return R(j,Z.result),R(A.join($,"status.json"),Z.status),C0(A.join($,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:J,runId:Z.status.runId,pid:f.pid,resultPath:j,message:Z.message}),{status:Z.status,repaired:!0,resultPath:j,message:Z.message}}function k$($){return $==="complete"||$==="failed"||$==="paused"}function*K$($){for(let f of $??[])yield f,yield*K$(f.children),yield*K$(f.steps?.flatMap((j)=>j.children??[]))}function m$($,f={}){let j=s($);for(let J of K$(j.children)){if(J.state!=="running"&&J.state!=="queued")continue;let Q=b$($.rootRunId,J);if(!Q)continue;let Z=Y$(Q,{...f,resultsDir:A.join(f.resultsDir??d,"nested",$.rootRunId)}),q=Z.status;if(!q)continue;if(!Z.repaired&&!k$(q.state))continue;let B=f.now?.()??Date.now();I$($,{type:k$(q.state)?"subagent.nested.completed":"subagent.nested.updated",ts:B,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,child:R$(q,Q,{id:J.id,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,depth:J.depth,path:J.path,mode:J.mode,ts:B})})}}function I0($,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 Y$($,f={}){let j=f.now?.()??Date.now(),J=F0($),Q=!J&&f.startedRun?y0($,f.startedRun,j):void 0,Z=J??Q;if(!Z)return{status:null,repaired:!1};let q=Z.runId||A.basename($),B=A.join(f.resultsDir??d,`${q}.json`);if(V.existsSync(B)){let W=Z.state==="running"||Z.state==="queued"?b0(Z,B,j):void 0;if(W)return R(A.join($,"status.json"),W),{status:W,repaired:!0,resultPath:B,message:"Existing async result file was used to repair stale running status."};return{status:Z,repaired:!1,resultPath:B}}if(Z.state!=="running"||typeof Z.pid!=="number")return{status:J??null,repaired:!1,resultPath:B};if(!J){let W=f.startedRun?.startedAt??Z.startedAt;if(j-W<(f.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:B}}if(I0(Z.pid,f.kill)!=="dead"){let W=f.staleAlivePidMs??86400000,U=Z.lastUpdate??Z.startedAt;if(j-U<=W)return{status:J??null,repaired:!1,resultPath:B};let X=`Async runner process ${Z.pid} still has a live PID, but status has not updated for ${j-U}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return g$($,Z,B,j,X)}return g$($,Z,B,j)}function m($){return $ instanceof Error?$.message:String($)}function H$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function N0($,f){let j=T.join($,f);try{return c.statSync(j).isDirectory()}catch(J){if(H$(J))return!1;throw Error(`Failed to inspect async run path '${j}': ${m(J)}`,{cause:J instanceof Error?J:void 0})}}function R0($){if(!$)return;try{return c.statSync($).mtimeMs}catch(f){if(H$(f))return;throw Error(`Failed to inspect async output file '${$}': ${m(f)}`,{cause:f instanceof Error?f:void 0})}}function D0($,f){if(f.state!=="running")return{activityState:f.activityState,lastActivityAt:f.lastActivityAt};let j=f.outputFile?T.isAbsolute(f.outputFile)?f.outputFile:T.join($,f.outputFile):void 0,J=typeof f.currentStep==="number"?f.steps?.[f.currentStep]:void 0;return{activityState:f.activityState,lastActivityAt:f.lastActivityAt??R0(j)??J?.lastActivityAt??J?.startedAt??f.startedAt}}function P0($,f,j=[],J){if(f.sessionId!==void 0&&typeof f.sessionId!=="string")throw Error(`Invalid async status '${T.join($,"status.json")}': sessionId must be a string.`);let{activityState:Q,lastActivityAt:Z}=D0($,f),q=f.steps??[],B=f.chainStepCount??q.length,O=v(f.parallelGroups,q.length,B),W=[];if(j.length===0&&J)try{W=s(J)?.children??[]}catch(X){j.push(`Nested status unavailable: ${m(X)}`)}let U=q.map((X,L)=>{let{activityState:Y,lastActivityAt:E}=X;return{index:L,agent:X.agent,...X.label?{label:X.label}:{},...X.phase?{phase:X.phase}:{},...X.outputName?{outputName:X.outputName}:{},...X.structured?{structured:X.structured}:{},status:X.status,...Y?{activityState:Y}:{},...E?{lastActivityAt:E}:{},...X.currentTool?{currentTool:X.currentTool}:{},...X.currentToolArgs?{currentToolArgs:X.currentToolArgs}:{},...X.currentToolStartedAt?{currentToolStartedAt:X.currentToolStartedAt}:{},...X.currentPath?{currentPath:X.currentPath}:{},...X.recentTools?{recentTools:X.recentTools.map((D)=>({...D}))}:{},...X.recentOutput?{recentOutput:[...X.recentOutput]}:{},...X.turnCount!==void 0?{turnCount:X.turnCount}:{},...X.toolCount!==void 0?{toolCount:X.toolCount}:{},...X.steerCount!==void 0?{steerCount:X.steerCount}:{},...X.lastSteerAt!==void 0?{lastSteerAt:X.lastSteerAt}:{},...X.durationMs!==void 0?{durationMs:X.durationMs}:{},...X.tokens?{tokens:X.tokens}:{},...X.totalCost?{totalCost:X.totalCost}:{},...X.skills?{skills:X.skills}:{},...X.model?{model:X.model}:{},...X.thinking?{thinking:X.thinking}:{},...X.attemptedModels?{attemptedModels:X.attemptedModels}:{},...X.error?{error:X.error}:{},...X.timedOut!==void 0?{timedOut:X.timedOut}:{},...X.turnBudget?{turnBudget:X.turnBudget}:{},...X.turnBudgetExceeded!==void 0?{turnBudgetExceeded:X.turnBudgetExceeded}:{},...X.wrapUpRequested!==void 0?{wrapUpRequested:X.wrapUpRequested}:{},...X.children?.length?{children:X.children}:{}}});return N$(f.runId||T.basename($),U,W),{id:f.runId||T.basename($),asyncDir:$,...f.sessionId?{sessionId:f.sessionId}:{},state:f.state,...f.error?{error:f.error}:{},activityState:Q,lastActivityAt:Z,currentTool:f.currentTool,currentToolStartedAt:f.currentToolStartedAt,currentPath:f.currentPath,turnCount:f.turnCount,toolCount:f.toolCount,steerCount:f.steerCount,lastSteerAt:f.lastSteerAt,mode:f.mode,cwd:f.cwd,startedAt:f.startedAt,lastUpdate:f.lastUpdate,endedAt:f.endedAt,...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}:{},currentStep:f.currentStep,...f.chainStepCount!==void 0?{chainStepCount:f.chainStepCount}:{},...f.pendingAppends!==void 0?{pendingAppends:f.pendingAppends}:{},...O.length?{parallelGroups:O}:{},steps:U,...W.length?{nestedChildren:W}:{},...j.length?{nestedWarnings:j}:{},...f.sessionDir?{sessionDir:f.sessionDir}:{},...f.outputFile?{outputFile:f.outputFile}:{},...f.totalTokens?{totalTokens:f.totalTokens}:{},...f.totalCost?{totalCost:f.totalCost}:{},...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function w0($){let f=(j)=>{switch(j){case"running":return 0;case"queued":return 1;case"failed":return 2;case"paused":return 2;case"complete":return 3}};return[...$].sort((j,J)=>{let Q=f(j.state)-f(J.state);if(Q!==0)return Q;let Z=j.lastUpdate??j.endedAt??j.startedAt;return(J.lastUpdate??J.endedAt??J.startedAt)-Z})}function Yj($,f={}){let j;try{j=c.readdirSync($).filter((O)=>N0($,O))}catch(O){if(H$(O))return[];throw Error(`Failed to list async runs in '${$}': ${m(O)}`,{cause:O instanceof Error?O:void 0})}let J=f.states?new Set(f.states):void 0,Q=[],Z,q=(O)=>{if(!Z)Z=x$();return Z.get(O)};for(let O of j){let W=T.join($,O),X=(f.reconcile===!1?void 0:Y$(W,{resultsDir:f.resultsDir,kill:f.kill,now:f.now}))?.status??G$(W);if(!X)continue;if(J&&!J.has(X.state))continue;if(f.sessionId&&X.sessionId!==f.sessionId)continue;let L=[],Y;try{if(Y=q(X.runId||T.basename(W)),Y)m$(Y,{resultsDir:f.resultsDir,kill:f.kill,now:f.now})}catch(D){L.push(`Nested status unavailable: ${m(D)}`)}let E=P0(W,X,L,Y);Q.push(E)}let B=w0(Q);return f.limit!==void 0?B.slice(0,f.limit):B}function c$($){let f=[];if($.currentTool&&$.currentToolStartedAt!==void 0)f.push(`tool ${$.currentTool} ${g(Math.max(0,Date.now()-$.currentToolStartedAt))}`);else if($.currentTool)f.push(`tool ${$.currentTool}`);if($.currentPath)f.push(b($.currentPath));if($.turnCount!==void 0)f.push(`${$.turnCount} turns`);if($.turnBudgetExceeded&&$.turnBudget)f.push(`turn budget exceeded ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}+${$.turnBudget.graceTurns}`);else if($.wrapUpRequested&&$.turnBudget)f.push(`wrap-up requested ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}`);else if($.turnBudget)f.push(`turn budget ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}+${$.turnBudget.graceTurns}`);if($.toolCount!==void 0)f.push(`${$.toolCount} tools`);if($.steerCount!==void 0)f.push(`${$.steerCount} steers`);if(typeof $.lastSteerAt==="number"&&Number.isFinite($.lastSteerAt))f.push(`last steer ${new Date($.lastSteerAt).toISOString()}`);let j=o($.lastActivityAt,$.activityState);return j||f.length?[j,...f].filter(Boolean).join(" | "):void 0}function g0($){let f=$.label?`${$.label} (${$.agent})`:$.agent,j=$.phase?`[${$.phase}] `:"",J=[`${$.index+1}. ${j}${f}`,$.status],Q=c$($);if(Q)J.push(Q);let Z=L$($.model,$.thinking);if(Z)J.push(Z);if($.durationMs!==void 0)J.push(g($.durationMs));if($.tokens)J.push(`${n($.tokens.total)} tok`);return J.join(" | ")}function k0($){if(!$.outputFile)return;return T.isAbsolute($.outputFile)?$.outputFile:T.join($.asyncDir,$.outputFile)}function v0($){let f=$.steps.length||1,j=$.chainStepCount??f,J=v($.parallelGroups,$.steps.length,j),Q=$.currentStep!==void 0?J.find((Z)=>$.currentStep>=Z.start&&$.currentStep<Z.start+Z.count):void 0;if(Q){let Z=$.steps.slice(Q.start,Q.start+Q.count),q=$$(Z,Q.count,{showRunning:$.state==="running"});if($.mode==="parallel")return q;return`step ${Q.stepIndex+1}/${j} · parallel group: ${q}`}if($.mode==="parallel")return $$($.steps,f,{showRunning:$.state==="running"});if($.mode==="chain"&&$.currentStep!==void 0&&J.length>0)return`step ${w$($.currentStep,j,J)+1}/${j}`;return $.currentStep!==void 0?`step ${$.currentStep+1}/${f}`:`steps ${f}`}function m0($){let f=v0($),j=$.cwd?b($.cwd):b($.asyncDir),J=c$($),Q=$.pendingAppends?` | ${$.pendingAppends} pending append${$.pendingAppends===1?"":"s"}`:"";return`${$.id} | ${$.state}${J?` | ${J}`:""} | ${$.mode} | ${f}${Q} | ${j}`}function Hj($,f="Active async runs"){if($.length===0)return`No ${f.toLowerCase()}.`;let j=[`${f}: ${$.length}`,""];for(let J of $){j.push(`- ${m0(J)}`);for(let B of J.steps)j.push(` ${g0(B)}`),j.push(...X$(B.children,{indent:" ",maxLines:12}));let Q=new Set(J.steps.flatMap((B)=>B.children?.map((O)=>O.id)??[])),Z=J.nestedChildren?.filter((B)=>!Q.has(B.id))??[];if(j.push(...X$(Z,{indent:" ",maxLines:12})),J.error)j.push(` Error: ${J.error}`);for(let B of J.nestedWarnings??[])j.push(` Warning: ${B}`);let q=k0(J);if(q)j.push(` output: ${b(q)}`);if(J.sessionFile)j.push(` session: ${b(J.sessionFile)}`);j.push("")}return j.join(`
|
|
12
|
-
`).trimEnd()}export{
|
|
11
|
+
${B}`:q,L=(($.steps?.length)?$.steps:[{agent:"subagent",status:"running"}]).map((Y)=>Y.status==="running"||Y.status==="pending"?{...Y,status:"failed",activityState:void 0,endedAt:Y.endedAt??j,durationMs:Y.startedAt!==void 0&&Y.durationMs===void 0?Math.max(0,j-Y.startedAt):Y.durationMs,exitCode:Y.exitCode??1,error:Y.error??O}:Y),X={...$,state:"failed",activityState:void 0,lastUpdate:j,endedAt:j,steps:L},V=L[$.currentStep??0]?.agent??L[0]?.agent??"subagent";return{status:X,message:O,result:{id:Q,agent:V,mode:$.mode,success:!1,state:"failed",summary:O,results:L.map((Y)=>({agent:Y.agent,output:Y.status==="complete"||Y.status==="completed"?"":O,error:Y.status==="complete"||Y.status==="completed"?void 0:Y.error??O,success:Y.status==="complete"||Y.status==="completed",model:Y.model,attemptedModels:Y.attemptedModels,modelAttempts:Y.modelAttempts,sessionFile:Y.sessionFile})),exitCode:1,timestamp:j,durationMs:Math.max(0,j-$.startedAt),asyncDir:f,sessionId:$.sessionId,sessionFile:$.sessionFile}}}function k$($,f,j,J,Q){let Z=N0(f,$,J,Q);return N(j,Z.result),N(A.join($,"status.json"),Z.status),E0(A.join($,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:J,runId:Z.status.runId,pid:f.pid,resultPath:j,message:Z.message}),{status:Z.status,repaired:!0,resultPath:j,message:Z.message}}function v$($){return $==="complete"||$==="failed"||$==="paused"}function*O$($){for(let f of $??[])yield f,yield*O$(f.children),yield*O$(f.steps?.flatMap((j)=>j.children??[]))}function c$($,f={}){let j=a($);for(let J of O$(j.children)){if(J.state!=="running"&&J.state!=="queued")continue;let Q=y$($.rootRunId,J);if(!Q)continue;let Z=K$(Q,{...f,resultsDir:A.join(f.resultsDir??h,"nested",$.rootRunId)}),q=Z.status;if(!q)continue;if(!Z.repaired&&!v$(q.state))continue;let B=f.now?.()??Date.now();N$($,{type:v$(q.state)?"subagent.nested.completed":"subagent.nested.updated",ts:B,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,child:D$(q,Q,{id:J.id,parentRunId:J.parentRunId,parentStepIndex:J.parentStepIndex,depth:J.depth,path:J.path,mode:J.mode,ts:B})})}}function R0($,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 K$($,f={}){let j=f.now?.()??Date.now(),J=S0($),Q=!J&&f.startedRun?I0($,f.startedRun,j):void 0,Z=J??Q;if(!Z)return{status:null,repaired:!1};let q=Z.runId||A.basename($),B=A.join(f.resultsDir??h,`${q}.json`);if(U.existsSync(B)){let W=Z.state==="running"||Z.state==="queued"?x0(Z,B,j):void 0;if(W)return N(A.join($,"status.json"),W),{status:W,repaired:!0,resultPath:B,message:"Existing async result file was used to repair stale running status."};return{status:Z,repaired:!1,resultPath:B}}if(Z.state!=="running"||typeof Z.pid!=="number")return{status:J??null,repaired:!1,resultPath:B};if(!J){let W=f.startedRun?.startedAt??Z.startedAt;if(j-W<(f.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:B}}if(R0(Z.pid,f.kill)!=="dead"){let W=f.staleAlivePidMs??86400000,L=Z.lastUpdate??Z.startedAt;if(j-L<=W)return{status:J??null,repaired:!1,resultPath:B};let X=`Async runner process ${Z.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 k$($,Z,B,j,X)}return k$($,Z,B,j)}function v($){return $ instanceof Error?$.message:String($)}function Y$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function D0($,f){let j=T.join($,f);try{return m.statSync(j).isDirectory()}catch(J){if(Y$(J))return!1;throw Error(`Failed to inspect async run path '${j}': ${v(J)}`,{cause:J instanceof Error?J:void 0})}}function P0($){if(!$)return;try{return m.statSync($).mtimeMs}catch(f){if(Y$(f))return;throw Error(`Failed to inspect async output file '${$}': ${v(f)}`,{cause:f instanceof Error?f:void 0})}}function w0($,f){if(f.state!=="running")return{activityState:f.activityState,lastActivityAt:f.lastActivityAt};let j=f.outputFile?T.isAbsolute(f.outputFile)?f.outputFile:T.join($,f.outputFile):void 0,J=typeof f.currentStep==="number"?f.steps?.[f.currentStep]:void 0;return{activityState:f.activityState,lastActivityAt:f.lastActivityAt??P0(j)??J?.lastActivityAt??J?.startedAt??f.startedAt}}function g0($,f,j=[],J){if(f.sessionId!==void 0&&typeof f.sessionId!=="string")throw Error(`Invalid async status '${T.join($,"status.json")}': sessionId must be a string.`);let{activityState:Q,lastActivityAt:Z}=w0($,f),q=f.steps??[],B=f.chainStepCount??q.length,O=k(f.parallelGroups,q.length,B),W=[];if(j.length===0&&J)try{W=a(J)?.children??[]}catch(X){j.push(`Nested status unavailable: ${v(X)}`)}let L=q.map((X,V)=>{let{activityState:Y,lastActivityAt:E}=X;return{index:V,agent:X.agent,...X.label?{label:X.label}:{},...X.phase?{phase:X.phase}:{},...X.outputName?{outputName:X.outputName}:{},...X.structured?{structured:X.structured}:{},status:X.status,...Y?{activityState:Y}:{},...E?{lastActivityAt:E}:{},...X.currentTool?{currentTool:X.currentTool}:{},...X.currentToolArgs?{currentToolArgs:X.currentToolArgs}:{},...X.currentToolStartedAt?{currentToolStartedAt:X.currentToolStartedAt}:{},...X.currentPath?{currentPath:X.currentPath}:{},...X.recentTools?{recentTools:X.recentTools.map((R)=>({...R}))}:{},...X.recentOutput?{recentOutput:[...X.recentOutput]}:{},...X.turnCount!==void 0?{turnCount:X.turnCount}:{},...X.toolCount!==void 0?{toolCount:X.toolCount}:{},...X.steerCount!==void 0?{steerCount:X.steerCount}:{},...X.lastSteerAt!==void 0?{lastSteerAt:X.lastSteerAt}:{},...X.durationMs!==void 0?{durationMs:X.durationMs}:{},...X.tokens?{tokens:X.tokens}:{},...X.totalCost?{totalCost:X.totalCost}:{},...X.skills?{skills:X.skills}:{},...X.model?{model:X.model}:{},...X.thinking?{thinking:X.thinking}:{},...X.attemptedModels?{attemptedModels:X.attemptedModels}:{},...X.error?{error:X.error}:{},...X.timedOut!==void 0?{timedOut:X.timedOut}:{},...X.turnBudget?{turnBudget:X.turnBudget}:{},...X.turnBudgetExceeded!==void 0?{turnBudgetExceeded:X.turnBudgetExceeded}:{},...X.wrapUpRequested!==void 0?{wrapUpRequested:X.wrapUpRequested}:{},...X.children?.length?{children:X.children}:{}}});return R$(f.runId||T.basename($),L,W),{id:f.runId||T.basename($),asyncDir:$,...f.sessionId?{sessionId:f.sessionId}:{},state:f.state,...f.error?{error:f.error}:{},activityState:Q,lastActivityAt:Z,currentTool:f.currentTool,currentToolStartedAt:f.currentToolStartedAt,currentPath:f.currentPath,turnCount:f.turnCount,toolCount:f.toolCount,steerCount:f.steerCount,lastSteerAt:f.lastSteerAt,mode:f.mode,cwd:f.cwd,startedAt:f.startedAt,lastUpdate:f.lastUpdate,endedAt:f.endedAt,...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}:{},currentStep:f.currentStep,...f.chainStepCount!==void 0?{chainStepCount:f.chainStepCount}:{},...f.pendingAppends!==void 0?{pendingAppends:f.pendingAppends}:{},...O.length?{parallelGroups:O}:{},steps:L,...W.length?{nestedChildren:W}:{},...j.length?{nestedWarnings:j}:{},...f.sessionDir?{sessionDir:f.sessionDir}:{},...f.outputFile?{outputFile:f.outputFile}:{},...f.totalTokens?{totalTokens:f.totalTokens}:{},...f.totalCost?{totalCost:f.totalCost}:{},...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function k0($){let f=(j)=>{switch(j){case"running":return 0;case"queued":return 1;case"failed":return 2;case"paused":return 2;case"complete":return 3}};return[...$].sort((j,J)=>{let Q=f(j.state)-f(J.state);if(Q!==0)return Q;let Z=j.lastUpdate??j.endedAt??j.startedAt;return(J.lastUpdate??J.endedAt??J.startedAt)-Z})}function Wj($,f={}){let j;try{j=m.readdirSync($).filter((O)=>D0($,O))}catch(O){if(Y$(O))return[];throw Error(`Failed to list async runs in '${$}': ${v(O)}`,{cause:O instanceof Error?O:void 0})}let J=f.states?new Set(f.states):void 0,Q=[],Z,q=(O)=>{if(!Z)Z=I$();return Z.get(O)};for(let O of j){let W=T.join($,O),X=(f.reconcile===!1?void 0:K$(W,{resultsDir:f.resultsDir,kill:f.kill,now:f.now}))?.status??W$(W);if(!X)continue;if(J&&!J.has(X.state))continue;if(f.sessionId&&X.sessionId!==f.sessionId)continue;let V=[],Y;try{if(Y=q(X.runId||T.basename(W)),Y)c$(Y,{resultsDir:f.resultsDir,kill:f.kill,now:f.now})}catch(R){V.push(`Nested status unavailable: ${v(R)}`)}let E=g0(W,X,V,Y);Q.push(E)}let B=k0(Q);return f.limit!==void 0?B.slice(0,f.limit):B}function h$($){let f=[];if($.currentTool&&$.currentToolStartedAt!==void 0)f.push(`tool ${$.currentTool} ${w(Math.max(0,Date.now()-$.currentToolStartedAt))}`);else if($.currentTool)f.push(`tool ${$.currentTool}`);if($.currentPath)f.push(b($.currentPath));if($.turnCount!==void 0)f.push(`${$.turnCount} turns`);if($.turnBudgetExceeded&&$.turnBudget)f.push(`turn budget exceeded ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}+${$.turnBudget.graceTurns}`);else if($.wrapUpRequested&&$.turnBudget)f.push(`wrap-up requested ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}`);else if($.turnBudget)f.push(`turn budget ${$.turnBudget.turnCount}/${$.turnBudget.maxTurns}+${$.turnBudget.graceTurns}`);if($.toolCount!==void 0)f.push(`${$.toolCount} tools`);if($.steerCount!==void 0)f.push(`${$.steerCount} steers`);if(typeof $.lastSteerAt==="number"&&Number.isFinite($.lastSteerAt))f.push(`last steer ${new Date($.lastSteerAt).toISOString()}`);let j=n($.lastActivityAt,$.activityState);return j||f.length?[j,...f].filter(Boolean).join(" | "):void 0}function v0($){let f=$.label?`${$.label} (${$.agent})`:$.agent,j=$.phase?`[${$.phase}] `:"",J=[`${$.index+1}. ${j}${f}`,$.status],Q=h$($);if(Q)J.push(Q);let Z=L$($.model,$.thinking);if(Z)J.push(Z);if($.durationMs!==void 0)J.push(w($.durationMs));if($.tokens)J.push(`${d($.tokens.total)} tok`);return J.join(" | ")}function m0($){if(!$.outputFile)return;return T.isAbsolute($.outputFile)?$.outputFile:T.join($.asyncDir,$.outputFile)}function c0($){let f=$.steps.length||1,j=$.chainStepCount??f,J=k($.parallelGroups,$.steps.length,j),Q=$.currentStep!==void 0?J.find((Z)=>$.currentStep>=Z.start&&$.currentStep<Z.start+Z.count):void 0;if(Q){let Z=$.steps.slice(Q.start,Q.start+Q.count),q=t(Z,Q.count,{showRunning:$.state==="running"});if($.mode==="parallel")return q;return`step ${Q.stepIndex+1}/${j} · parallel group: ${q}`}if($.mode==="parallel")return t($.steps,f,{showRunning:$.state==="running"});if($.mode==="chain"&&$.currentStep!==void 0&&J.length>0)return`step ${g$($.currentStep,j,J)+1}/${j}`;return $.currentStep!==void 0?`step ${$.currentStep+1}/${f}`:`steps ${f}`}function h0($){let f=c0($),j=$.cwd?b($.cwd):b($.asyncDir),J=h$($),Q=$.pendingAppends?` | ${$.pendingAppends} pending append${$.pendingAppends===1?"":"s"}`:"";return`${$.id} | ${$.state}${J?` | ${J}`:""} | ${$.mode} | ${f}${Q} | ${j}`}function Gj($,f="Active async runs"){if($.length===0)return`No ${f.toLowerCase()}.`;let j=[`${f}: ${$.length}`,""];for(let J of $){j.push(`- ${h0(J)}`);for(let B of J.steps)j.push(` ${v0(B)}`),j.push(...B$(B.children,{indent:" ",maxLines:12}));let Q=new Set(J.steps.flatMap((B)=>B.children?.map((O)=>O.id)??[])),Z=J.nestedChildren?.filter((B)=>!Q.has(B.id))??[];if(j.push(...B$(Z,{indent:" ",maxLines:12})),J.error)j.push(` Error: ${J.error}`);for(let B of J.nestedWarnings??[])j.push(` Warning: ${B}`);let q=m0(J);if(q)j.push(` output: ${b(q)}`);if(J.sessionFile)j.push(` session: ${b(J.sessionFile)}`);j.push("")}return j.join(`
|
|
12
|
+
`).trimEnd()}export{Wj as listAsyncRuns,c0 as formatAsyncRunProgressLabel,m0 as formatAsyncRunOutputPath,Gj as formatAsyncRunList};
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import*as W from"node:fs";import*as M from"node:path";import*as V from"node:fs";import*as h from"node:path";var o=new Map;function Bn(n){return n instanceof Error?n.message:String(n)}function Cn(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function p(n){let f=h.join(n,"status.json"),$;try{$=V.statSync(f)}catch(T){if(Cn(T))return null;throw Error(`Failed to inspect async status file '${f}': ${Bn(T)}`,{cause:T instanceof Error?T:void 0})}let j=o.get(f);if(j&&j.mtime===$.mtimeMs)return j.status;let A;try{A=V.readFileSync(f,"utf-8")}catch(T){if(Cn(T))return null;throw Error(`Failed to read async status file '${f}': ${Bn(T)}`,{cause:T instanceof Error?T:void 0})}let J;try{J=JSON.parse(A)}catch(T){throw Error(`Failed to parse async status file '${f}': ${Bn(T)}`,{cause:T instanceof Error?T:void 0})}if(o.set(f,{mtime:$.mtimeMs,status:J}),o.size>50){let T=o.keys().next().value;if(T)o.delete(T)}return J}import*as N from"node:os";import*as R from"node:path";function e(n){return n.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Zf(n){let f=n?.env??process.env,$=n&&Object.hasOwn(n,"getuid")?n.getuid:process.getuid?.bind(process);if(typeof $==="function")return`uid-${$()}`;for(let T of["USERNAME","USER","LOGNAME"]){let B=f[T];if(B)return`user-${e(B)}`}let j=n&&Object.hasOwn(n,"userInfo")?n.userInfo:N.userInfo;try{let T=j?.().username;if(T)return`user-${e(T)}`}catch{}let A=f.USERPROFILE??f.HOME;if(A)return`home-${e(A)}`;let J=n&&Object.hasOwn(n,"homedir")?n.homedir:N.homedir;try{let T=J?.();if(T)return`home-${e(T)}`}catch{}return"shared"}var E=R.join(N.tmpdir(),`dm-subagents-${Zf()}`),m=R.join(E,"async-subagent-results"),Zn=R.join(E,"async-subagent-runs"),Qf=R.join(E,"chain-runs"),F$=R.join(E,"artifacts");var Qn=["off","minimal","low","medium","high","xhigh"];function gn(n){let f=n.lastIndexOf(":");if(f===-1)return{baseModel:n,thinkingSuffix:""};let $=Qn.find((j)=>j===n.substring(f+1));if(!$)return{baseModel:n,thinkingSuffix:""};return{baseModel:n.substring(0,f),thinkingSuffix:`:${$}`}}function P(n){return n<1000?String(n):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`}function s(n,f){let $=n?gn(n):void 0,j=$?.baseModel??n,A=Qn.find((T)=>T===f?.trim()),J=$?.thinkingSuffix?$.thinkingSuffix.slice(1):A;if(j){let T=j.lastIndexOf("/");if(T!==-1)j=j.slice(T+1)}return[j,J?`thinking ${J}`:void 0].filter(Boolean).join(" · ")}function k(n){if(n<1000)return`${n}ms`;if(n<60000)return`${(n/1000).toFixed(1)}s`;return`${Math.floor(n/60000)}m${Math.floor(n%60000/1000)}s`}function C(n){let f=process.env.HOME;if(f&&n.startsWith(f))return`~${n.slice(f.length)}`;return n}function cf(n){if(n<1000)return"now";if(n<60000)return`${Math.floor(n/1000)}s`;return`${Math.floor(n/60000)}m`}function v(n,f,$=Date.now()){if(n===void 0){if(f==="needs_attention")return"needs attention";if(f==="active_long_running")return"active but long-running";return}let j=cf(Math.max(0,$-n));if(f==="needs_attention")return`no activity for ${j}`;if(f==="active_long_running")return`active but long-running · last activity ${j} ago`;return j==="now"?"active now":`active ${j} ago`}function Lf(n){return n==="complete"||n==="completed"}function qf(n){return n===1?"1 agent running":`${n} agents running`}function cn(n,f,$={}){let j=n.filter((O)=>O.status==="running").length,A=n.filter((O)=>Lf(O.status)).length,J=n.filter((O)=>O.status==="failed").length,T=n.filter((O)=>O.status==="paused").length,B=[`${A}/${f} done`];if($.showRunning!==!1&&j>0)B.unshift(qf(j));if(J>0)B.push(`${J} failed`);if(T>0)B.push(`${T} paused`);return B.join(" · ")}function bn(n){let f={total:0,running:0,paused:0,complete:0,failed:0,queued:0};for(let $ of n??[]){f.total++,f[$.state]++;let j=bn([...$.children??[],...$.steps?.flatMap((A)=>A.children??[])??[]]);f.total+=j.total,f.running+=j.running,f.paused+=j.paused,f.complete+=j.complete,f.failed+=j.failed,f.queued+=j.queued}return f}function Ln(n){let f=bn(n);if(f.total===0)return;let $=[f.running>0?`${f.running} running`:"",f.paused>0?`${f.paused} paused`:"",f.failed>0?`${f.failed} failed`:"",f.complete>0?`${f.complete} complete`:"",f.queued>0?`${f.queued} queued`:""].filter(Boolean);return`+${f.total} nested run${f.total===1?"":"s"}${$.length?` (${$.join(", ")})`:""}`}function Xf(n){if(n.agent)return n.agent;if(n.agents?.length)return n.agents.length===1?n.agents[0]:`${n.agents.slice(0,2).join(", ")}${n.agents.length>2?` +${n.agents.length-2}`:""}`;return n.id}function _n(n){let f=[];if(n.currentTool&&n.currentToolStartedAt!==void 0)f.push(`tool ${n.currentTool} ${k(Math.max(0,Date.now()-n.currentToolStartedAt))}`);else if(n.currentTool)f.push(`tool ${n.currentTool}`);if(n.currentPath)f.push(C(n.currentPath));if(n.turnCount!==void 0)f.push(`${n.turnCount} turns`);if(n.toolCount!==void 0)f.push(`${n.toolCount} tools`);if(n.totalTokens)f.push(`${P(n.totalTokens.total)} tok`);let $=v(n.lastActivityAt,n.activityState);return $||f.length?[$,...f].filter(Boolean).join(" | "):void 0}function Yf(n,f){let $=[],j=(A,J,T)=>{if(!A?.length||$.length>=f.maxLines)return;if(J>f.maxDepth){let B=Ln(A);if(B&&$.length<f.maxLines)$.push(`${T}↳ ${B}`);return}for(let B=0;B<A.length;B++){let O=A[B];if($.length>=f.maxLines){let Z=Ln(A.slice(B));if(Z)$[$.length-1]=`${T}↳ ${Z}`;return}let c=O.state==="running"?_n(O):void 0,L=O.error?` | error: ${O.error}`:"";if($.push(`${T}↳ ${Xf(O)} [${O.id}] ${O.state}${c?` | ${c}`:""}${L}`),f.commandHints&&$.length<f.maxLines)$.push(`${T} Status: subagent({ action: "status", id: "${O.id}" })`);if(J===f.maxDepth){let Z=Ln([...O.steps?.flatMap((Y)=>Y.children??[])??[],...O.children??[]]);if(Z&&$.length<f.maxLines)$.push(`${T} ↳ ${Z}`);continue}for(let[Z,Y]of(O.steps??[]).entries()){if($.length>=f.maxLines)return;let q=Y.status==="running"?_n(Y):void 0;$.push(`${T} ${Z+1}. ${Y.agent} ${Y.status}${q?` | ${q}`:""}${Y.error?` | error: ${Y.error}`:""}`),j(Y.children,J+1,`${T} `)}j(O.children,J+1,`${T} `)}};return j(n,0,f.indent),$}function d(n,f={}){return Yf(n,{indent:f.indent??" ",maxDepth:f.maxDepth??2,maxLines:f.maxLines??40,commandHints:f.commandHints??!1})}import*as l from"node:fs";import*as F from"node:path";import{randomUUID as gf}from"node:crypto";import*as y from"node:fs";import*as K from"node:path";import*as xn from"node:path";var Kf=128,Wf=4;function qn(n){return typeof n==="string"&&n.length>0&&n.length<=Kf&&!xn.isAbsolute(n)&&!n.includes("/")&&!n.includes("\\")&&!n.includes("..")}function zn(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function En(n,f){return typeof n==="string"&&n.length>0?n.slice(0,f):void 0}function In(n){if(!Array.isArray(n))return[];return n.map((f)=>{if(!f||typeof f!=="object")return;let $=f;if(!qn($.runId))return;return{runId:$.runId,...zn($.stepIndex)!==void 0?{stepIndex:zn($.stepIndex)}:{},...En($.agent,128)?{agent:En($.agent,128)}:{}}}).filter((f)=>Boolean(f)).slice(0,Wf)}import*as D from"node:fs";import*as b from"node:path";import{fileURLToPath as Mf}from"node:url";import*as z from"node:os";import*as _ from"node:path";var v$=_.join(z.homedir(),".config","mcp","mcp.json"),d$={cursor:[_.join(z.homedir(),".cursor","mcp.json")],"claude-code":[_.join(z.homedir(),".claude","mcp.json"),_.join(z.homedir(),".claude.json"),_.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[_.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[_.join(z.homedir(),".codex","config.json")],windsurf:[_.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as i$}from"typebox/compile";function Nn(n,f){let $=Mf(n),j=b.extname($),A=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(j)?j:".ts",J=b.dirname($);while(!D.existsSync(b.join(J,"package.json"))){let T=b.dirname(J);if(T===J)throw Error(`Unable to resolve dm-subagents package root from ${$}`);J=T}return b.join(J,`${f}${A}`)}var B0=Nn(import.meta.url,b.join("src","runs","shared","subagent-prompt-runtime")),Z0=Nn(import.meta.url,b.join("src","extension","fanout-child"));import*as Sf from"node:fs";import*as I from"node:path";var yf=[10,25,50,100,200,500,1000,2000,4000],Uf=new Set(["EACCES","EBUSY","EPERM"]),Rn=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,mn=Rn?new Int32Array(Rn):void 0;function Ff(n){if(n<=0)return;if(mn)try{Atomics.wait(mn,0,0,n);return}catch{}let f=Date.now()+n;while(Date.now()<f);}function Gf(n){let f=n?.code;return typeof f==="string"&&Uf.has(f)}function Vf(n,f,$,j,A){for(let J=0;;J++)try{n.renameSync(f,$);return}catch(T){let B=j[J];if(B===void 0||!Gf(T))throw T;A(B)}}function Cf(n={}){let f=n.fs??Sf,$=n.now??Date.now,j=n.pid??process.pid,A=n.random??Math.random,T=n.retryRenameErrors??process.platform==="win32"?n.retryDelaysMs??yf:[],B=n.wait??Ff;return(O,c)=>{f.mkdirSync(I.dirname(O),{recursive:!0});let L=I.join(I.dirname(O),`.${I.basename(O)}.${j}.${$()}.${A().toString(36).slice(2)}.tmp`);try{f.writeFileSync(L,JSON.stringify(c,null,2),"utf-8"),Vf(f,L,O,T,B)}finally{f.rmSync(L,{force:!0})}}}var w=Cf();var t=K.join(E,"nested-subagent-events"),_f="route.json",bf="registry.json",Hn=65536,Xn=12,r=16,Yn=3;function nn(n){return qn(n)}function zf(n,f){if(!nn(f))throw Error(`${n} must be a non-empty safe id token.`)}function Dn(n,f){zf(n,f)}function Kn(n,f){let $=K.resolve(n),j=K.resolve(f);return j===$||j.startsWith(`${$}${K.sep}`)}function on(n){return K.dirname(K.resolve(n.eventSink))}function $n(n){if(Dn("rootRunId",n.rootRunId),Dn("capabilityToken",n.capabilityToken),!Kn(t,n.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!Kn(t,n.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(on(n)!==K.dirname(K.resolve(n.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function hn(n,f){if(!f.asyncDir)return;let $=K.resolve(f.asyncDir),j=K.resolve(E,"nested-subagent-runs",n,f.id),A=K.relative(j,$);return $===j||!A.startsWith("..")&&!K.isAbsolute(A)?$:void 0}function Q(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function X(n,f=512){return typeof n==="string"&&n.length>0?n.slice(0,f):void 0}function Ef(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.input),j=Q(f.output),A=Q(f.total);return $!==void 0&&j!==void 0&&A!==void 0?{input:$,output:j,total:A}:void 0}function xf(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.inputTokens),j=Q(f.outputTokens),A=Q(f.costUsd);return $!==void 0&&j!==void 0&&A!==void 0?{inputTokens:$,outputTokens:j,costUsd:A}:void 0}function fn(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.maxTurns),j=Q(f.graceTurns),A=Q(f.turnCount),J=f.outcome==="within-budget"||f.outcome==="wrap-up-requested"||f.outcome==="exceeded"?f.outcome:void 0;if($===void 0||j===void 0||A===void 0||!J)return;return{maxTurns:$,graceTurns:j,turnCount:A,outcome:J,...Q(f.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:Q(f.wrapUpRequestedAtTurn)}:{},...Q(f.exceededAtTurn)!==void 0?{exceededAtTurn:Q(f.exceededAtTurn)}:{}}}function If(n,f){return n==="queued"||n==="running"||n==="complete"||n==="failed"||n==="paused"?n:f}function Nf(n,f){if(!n||typeof n!=="object")return;let $=n,j=X($.agent,128);if(!j)return;let A=$.status==="pending"||$.status==="running"||$.status==="complete"||$.status==="completed"||$.status==="failed"||$.status==="paused"?$.status:"pending";return{agent:j,status:A,...X($.sessionFile,2048)?{sessionFile:X($.sessionFile,2048)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...Q($.lastActivityAt)!==void 0?{lastActivityAt:Q($.lastActivityAt)}:{},...X($.currentTool,128)?{currentTool:X($.currentTool,128)}:{},...Q($.currentToolStartedAt)!==void 0?{currentToolStartedAt:Q($.currentToolStartedAt)}:{},...X($.currentPath,2048)?{currentPath:X($.currentPath,2048)}:{},...Q($.turnCount)!==void 0?{turnCount:Q($.turnCount)}:{},...Q($.toolCount)!==void 0?{toolCount:Q($.toolCount)}:{},...Q($.startedAt)!==void 0?{startedAt:Q($.startedAt)}:{},...Q($.endedAt)!==void 0?{endedAt:Q($.endedAt)}:{},...X($.error,1024)?{error:X($.error,1024)}:{},...$.timedOut===!0?{timedOut:!0}:{},...fn($.turnBudget)?{turnBudget:fn($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...f<Yn&&Array.isArray($.children)?{children:$.children.map((J)=>jn(J,f+1)).filter((J)=>Boolean(J)).slice(0,r)}:{}}}function jn(n,f=0){if(!n||typeof n!=="object")return;let $=n;if(!nn($.id)||!nn($.parentRunId))return;let j=In($.path),A=Array.isArray($.steps)?$.steps.map((B)=>Nf(B,f+1)).filter((B)=>Boolean(B)).slice(0,Xn):void 0,J=Ef($.totalTokens),T=xf($.totalCost);return{id:$.id,parentRunId:$.parentRunId,...Q($.parentStepIndex)!==void 0?{parentStepIndex:Q($.parentStepIndex)}:{},...X($.parentAgent,128)?{parentAgent:X($.parentAgent,128)}:{},depth:Math.min(Math.max(0,Q($.depth)??0),Yn),path:j,state:If($.state,"running"),...X($.asyncDir,2048)?{asyncDir:X($.asyncDir,2048)}:{},...Q($.pid)!==void 0&&Q($.pid)>0&&Number.isInteger(Q($.pid))?{pid:Q($.pid)}:{},...X($.sessionId,256)?{sessionId:X($.sessionId,256)}:{},...X($.sessionFile,2048)?{sessionFile:X($.sessionFile,2048)}:{},...X($.intercomTarget,256)?{intercomTarget:X($.intercomTarget,256)}:{},...X($.ownerIntercomTarget,256)?{ownerIntercomTarget:X($.ownerIntercomTarget,256)}:{},...X($.leafIntercomTarget,256)?{leafIntercomTarget:X($.leafIntercomTarget,256)}:{},...$.ownerState==="live"||$.ownerState==="gone"||$.ownerState==="unknown"?{ownerState:$.ownerState}:{},...X($.controlInbox,2048)?{controlInbox:X($.controlInbox,2048)}:{},...X($.capabilityToken,128)?{capabilityToken:X($.capabilityToken,128)}:{},...$.mode==="single"||$.mode==="parallel"||$.mode==="chain"?{mode:$.mode}:{},...X($.agent,128)?{agent:X($.agent,128)}:{},...Array.isArray($.agents)?{agents:$.agents.map((B)=>X(B,128)).filter((B)=>Boolean(B)).slice(0,Xn)}:{},...Q($.currentStep)!==void 0?{currentStep:Q($.currentStep)}:{},...Q($.chainStepCount)!==void 0?{chainStepCount:Q($.chainStepCount)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...Q($.lastActivityAt)!==void 0?{lastActivityAt:Q($.lastActivityAt)}:{},...X($.currentTool,128)?{currentTool:X($.currentTool,128)}:{},...Q($.currentToolStartedAt)!==void 0?{currentToolStartedAt:Q($.currentToolStartedAt)}:{},...X($.currentPath,2048)?{currentPath:X($.currentPath,2048)}:{},...Q($.turnCount)!==void 0?{turnCount:Q($.turnCount)}:{},...Q($.toolCount)!==void 0?{toolCount:Q($.toolCount)}:{},...J?{totalTokens:J}:{},...T?{totalCost:T}:{},...Q($.startedAt)!==void 0?{startedAt:Q($.startedAt)}:{},...Q($.endedAt)!==void 0?{endedAt:Q($.endedAt)}:{},...Q($.lastUpdate)!==void 0?{lastUpdate:Q($.lastUpdate)}:{},...Q($.timeoutMs)!==void 0?{timeoutMs:Q($.timeoutMs)}:{},...Q($.deadlineAt)!==void 0?{deadlineAt:Q($.deadlineAt)}:{},...$.timedOut===!0?{timedOut:!0}:{},...fn($.turnBudget)?{turnBudget:fn($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...X($.error,1024)?{error:X($.error,1024)}:{},...A&&A.length>0?{steps:A}:{},...f<Yn&&Array.isArray($.children)?{children:$.children.map((B)=>jn(B,f+1)).filter((B)=>Boolean(B)).slice(0,r)}:{}}}function Wn(n,f){if(Buffer.byteLength(n,"utf-8")>Hn)return;let $;try{$=JSON.parse(n)}catch{return}if(!$||typeof $!=="object")return;let j=$;if(j.type!=="subagent.nested.started"&&j.type!=="subagent.nested.updated"&&j.type!=="subagent.nested.completed")return;if(j.rootRunId!==f.rootRunId||j.capabilityToken!==f.capabilityToken)return;if(!nn(j.parentRunId))return;let A=Q(j.ts);if(A===void 0)return;let J=jn(j.child);if(!J||J.id===f.rootRunId)return;let T={...J,controlInbox:f.controlInbox,capabilityToken:f.capabilityToken,ownerState:J.ownerState??"unknown"};return{type:j.type,ts:A,rootRunId:f.rootRunId,parentRunId:j.parentRunId,...Q(j.parentStepIndex)!==void 0?{parentStepIndex:Q(j.parentStepIndex)}:{},capabilityToken:f.capabilityToken,child:T}}function Rf(n,f){if(!n.includes(`
|
|
2
|
-
`)){let $=
|
|
1
|
+
import*as W from"node:fs";import*as M from"node:path";import*as C from"node:fs";import*as o from"node:path";var w=new Map;function On(n){return n instanceof Error?n.message:String(n)}function Cn(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function l(n){let f=o.join(n,"status.json"),$;try{$=C.statSync(f)}catch(A){if(Cn(A))return null;throw Error(`Failed to inspect async status file '${f}': ${On(A)}`,{cause:A instanceof Error?A:void 0})}let j=w.get(f);if(j&&j.mtime===$.mtimeMs)return j.status;let T;try{T=C.readFileSync(f,"utf-8")}catch(A){if(Cn(A))return null;throw Error(`Failed to read async status file '${f}': ${On(A)}`,{cause:A instanceof Error?A:void 0})}let J;try{J=JSON.parse(T)}catch(A){throw Error(`Failed to parse async status file '${f}': ${On(A)}`,{cause:A instanceof Error?A:void 0})}if(w.set(f,{mtime:$.mtimeMs,status:J}),w.size>50){let A=w.keys().next().value;if(A)w.delete(A)}return J}import*as N from"node:os";import*as R from"node:path";function p(n){return n.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Qf(n){let f=n?.env??process.env,$=n&&Object.hasOwn(n,"getuid")?n.getuid:process.getuid?.bind(process);if(typeof $==="function")return`uid-${$()}`;for(let A of["USERNAME","USER","LOGNAME"]){let B=f[A];if(B)return`user-${p(B)}`}let j=n&&Object.hasOwn(n,"userInfo")?n.userInfo:N.userInfo;try{let A=j?.().username;if(A)return`user-${p(A)}`}catch{}let T=f.USERPROFILE??f.HOME;if(T)return`home-${p(T)}`;let J=n&&Object.hasOwn(n,"homedir")?n.homedir:N.homedir;try{let A=J?.();if(A)return`home-${p(A)}`}catch{}return"shared"}var E=R.join(N.tmpdir(),`dm-subagents-${Qf()}`),m=R.join(E,"async-subagent-results"),Bn=R.join(E,"async-subagent-runs"),cf=R.join(E,"chain-runs"),C$=R.join(E,"artifacts");var Zn=["off","minimal","low","medium","high","xhigh"];function Un(n){let f=n.lastIndexOf(":");if(f===-1)return{baseModel:n,thinkingSuffix:""};let $=Zn.find((j)=>j===n.substring(f+1));if(!$)return{baseModel:n,thinkingSuffix:""};return{baseModel:n.substring(0,f),thinkingSuffix:`:${$}`}}function h(n){return n<1000?String(n):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`}function e(n,f){let $=n?Un(n):void 0,j=$?.baseModel??n,T=Zn.find((A)=>A===f?.trim()),J=$?.thinkingSuffix?$.thinkingSuffix.slice(1):T;if(j){let A=j.lastIndexOf("/");if(A!==-1)j=j.slice(A+1)}return[j,J?`thinking ${J}`:void 0].filter(Boolean).join(" · ")}function P(n){if(n<1000)return`${n}ms`;if(n<60000)return`${(n/1000).toFixed(1)}s`;return`${Math.floor(n/60000)}m${Math.floor(n%60000/1000)}s`}function U(n){let f=process.env.HOME;if(f&&n.startsWith(f))return`~${n.slice(f.length)}`;return n}function Lf(n){if(n<1000)return"now";if(n<60000)return`${Math.floor(n/1000)}s`;return`${Math.floor(n/60000)}m`}function k(n,f,$=Date.now()){if(n===void 0){if(f==="needs_attention")return"needs attention";if(f==="active_long_running")return"active but long-running";return}let j=Lf(Math.max(0,$-n));if(f==="needs_attention")return`no activity for ${j}`;if(f==="active_long_running")return`active but long-running · last activity ${j} ago`;return j==="now"?"active now":`active ${j} ago`}function qf(n){return n==="complete"||n==="completed"}function Xf(n){return n===1?"1 agent running":`${n} agents running`}function Qn(n,f,$={}){let j=n.filter((O)=>O.status==="running").length,T=n.filter((O)=>qf(O.status)).length,J=n.filter((O)=>O.status==="failed").length,A=n.filter((O)=>O.status==="paused").length,B=[`${T}/${f} done`];if($.showRunning!==!1&&j>0)B.unshift(Xf(j));if(J>0)B.push(`${J} failed`);if(A>0)B.push(`${A} paused`);return B.join(" · ")}function _n(n){let f={total:0,running:0,paused:0,complete:0,failed:0,queued:0};for(let $ of n??[]){f.total++,f[$.state]++;let j=_n([...$.children??[],...$.steps?.flatMap((T)=>T.children??[])??[]]);f.total+=j.total,f.running+=j.running,f.paused+=j.paused,f.complete+=j.complete,f.failed+=j.failed,f.queued+=j.queued}return f}function cn(n){let f=_n(n);if(f.total===0)return;let $=[f.running>0?`${f.running} running`:"",f.paused>0?`${f.paused} paused`:"",f.failed>0?`${f.failed} failed`:"",f.complete>0?`${f.complete} complete`:"",f.queued>0?`${f.queued} queued`:""].filter(Boolean);return`+${f.total} nested run${f.total===1?"":"s"}${$.length?` (${$.join(", ")})`:""}`}function Yf(n){if(n.agent)return n.agent;if(n.agents?.length)return n.agents.length===1?n.agents[0]:`${n.agents.slice(0,2).join(", ")}${n.agents.length>2?` +${n.agents.length-2}`:""}`;return n.id}function gn(n){let f=[];if(n.currentTool&&n.currentToolStartedAt!==void 0)f.push(`tool ${n.currentTool} ${P(Math.max(0,Date.now()-n.currentToolStartedAt))}`);else if(n.currentTool)f.push(`tool ${n.currentTool}`);if(n.currentPath)f.push(U(n.currentPath));if(n.turnCount!==void 0)f.push(`${n.turnCount} turns`);if(n.toolCount!==void 0)f.push(`${n.toolCount} tools`);if(n.totalTokens)f.push(`${h(n.totalTokens.total)} tok`);let $=k(n.lastActivityAt,n.activityState);return $||f.length?[$,...f].filter(Boolean).join(" | "):void 0}function Kf(n,f){let $=[],j=(T,J,A)=>{if(!T?.length||$.length>=f.maxLines)return;if(J>f.maxDepth){let B=cn(T);if(B&&$.length<f.maxLines)$.push(`${A}↳ ${B}`);return}for(let B=0;B<T.length;B++){let O=T[B];if($.length>=f.maxLines){let Z=cn(T.slice(B));if(Z)$[$.length-1]=`${A}↳ ${Z}`;return}let c=O.state==="running"?gn(O):void 0,L=O.error?` | error: ${O.error}`:"";if($.push(`${A}↳ ${Yf(O)} [${O.id}] ${O.state}${c?` | ${c}`:""}${L}`),f.commandHints&&$.length<f.maxLines)$.push(`${A} Status: subagent({ action: "status", id: "${O.id}" })`);if(J===f.maxDepth){let Z=cn([...O.steps?.flatMap((Y)=>Y.children??[])??[],...O.children??[]]);if(Z&&$.length<f.maxLines)$.push(`${A} ↳ ${Z}`);continue}for(let[Z,Y]of(O.steps??[]).entries()){if($.length>=f.maxLines)return;let q=Y.status==="running"?gn(Y):void 0;$.push(`${A} ${Z+1}. ${Y.agent} ${Y.status}${q?` | ${q}`:""}${Y.error?` | error: ${Y.error}`:""}`),j(Y.children,J+1,`${A} `)}j(O.children,J+1,`${A} `)}};return j(n,0,f.indent),$}function v(n,f={}){return Kf(n,{indent:f.indent??" ",maxDepth:f.maxDepth??2,maxLines:f.maxLines??40,commandHints:f.commandHints??!1})}import*as i from"node:fs";import*as F from"node:path";import{randomUUID as bf}from"node:crypto";import*as G from"node:fs";import*as K from"node:path";import*as En from"node:path";var Wf=128,Hf=4;function Ln(n){return typeof n==="string"&&n.length>0&&n.length<=Wf&&!En.isAbsolute(n)&&!n.includes("/")&&!n.includes("\\")&&!n.includes("..")}function bn(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function zn(n,f){return typeof n==="string"&&n.length>0?n.slice(0,f):void 0}function xn(n){if(!Array.isArray(n))return[];return n.map((f)=>{if(!f||typeof f!=="object")return;let $=f;if(!Ln($.runId))return;return{runId:$.runId,...bn($.stepIndex)!==void 0?{stepIndex:bn($.stepIndex)}:{},...zn($.agent,128)?{agent:zn($.agent,128)}:{}}}).filter((f)=>Boolean(f)).slice(0,Hf)}import*as b from"node:path";import{fileURLToPath as In}from"node:url";import*as z from"node:os";import*as _ from"node:path";var r$=_.join(z.homedir(),".config","mcp","mcp.json"),u$={cursor:[_.join(z.homedir(),".cursor","mcp.json")],"claude-code":[_.join(z.homedir(),".claude","mcp.json"),_.join(z.homedir(),".claude.json"),_.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[_.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[_.join(z.homedir(),".codex","config.json")],windsurf:[_.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as p$}from"typebox/compile";function Nn(n,f){let $=In(n),j=b.extname($),T=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(j)?j:".ts";return b.join(b.dirname($),`${f}${T}`)}function Rn(n){return b.basename(In(n)).startsWith("dm-args.")}function yf(n=import.meta.url){let f=Rn(n)?"subagent-prompt-runtime":b.join("..","runs","shared","subagent-prompt-runtime");return Nn(n,f)}function Gf(n=import.meta.url){let f=Rn(n)?b.join("..","..","extension","fanout-child"):"fanout-child";return Nn(n,f)}var Q0=yf(),c0=Gf();import*as Sf from"node:fs";import*as I from"node:path";var Ff=[10,25,50,100,200,500,1000,2000,4000],Vf=new Set(["EACCES","EBUSY","EPERM"]),mn=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,Dn=mn?new Int32Array(mn):void 0;function Cf(n){if(n<=0)return;if(Dn)try{Atomics.wait(Dn,0,0,n);return}catch{}let f=Date.now()+n;while(Date.now()<f);}function Uf(n){let f=n?.code;return typeof f==="string"&&Vf.has(f)}function gf(n,f,$,j,T){for(let J=0;;J++)try{n.renameSync(f,$);return}catch(A){let B=j[J];if(B===void 0||!Uf(A))throw A;T(B)}}function _f(n={}){let f=n.fs??Sf,$=n.now??Date.now,j=n.pid??process.pid,T=n.random??Math.random,A=n.retryRenameErrors??process.platform==="win32"?n.retryDelaysMs??Ff:[],B=n.wait??Cf;return(O,c)=>{f.mkdirSync(I.dirname(O),{recursive:!0});let L=I.join(I.dirname(O),`.${I.basename(O)}.${j}.${$()}.${T().toString(36).slice(2)}.tmp`);try{f.writeFileSync(L,JSON.stringify(c,null,2),"utf-8"),gf(f,L,O,A,B)}finally{f.rmSync(L,{force:!0})}}}var D=_f();var a=K.join(E,"nested-subagent-events"),zf="route.json",Ef="registry.json",Wn=65536,qn=12,d=16,Xn=3;function t(n){return Ln(n)}function xf(n,f){if(!t(f))throw Error(`${n} must be a non-empty safe id token.`)}function wn(n,f){xf(n,f)}function Yn(n,f){let $=K.resolve(n),j=K.resolve(f);return j===$||j.startsWith(`${$}${K.sep}`)}function hn(n){return K.dirname(K.resolve(n.eventSink))}function fn(n){if(wn("rootRunId",n.rootRunId),wn("capabilityToken",n.capabilityToken),!Yn(a,n.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!Yn(a,n.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(hn(n)!==K.dirname(K.resolve(n.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function Pn(n,f){if(!f.asyncDir)return;let $=K.resolve(f.asyncDir),j=K.resolve(E,"nested-subagent-runs",n,f.id),T=K.relative(j,$);return $===j||!T.startsWith("..")&&!K.isAbsolute(T)?$:void 0}function Q(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function X(n,f=512){return typeof n==="string"&&n.length>0?n.slice(0,f):void 0}function If(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.input),j=Q(f.output),T=Q(f.total);return $!==void 0&&j!==void 0&&T!==void 0?{input:$,output:j,total:T}:void 0}function Nf(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.inputTokens),j=Q(f.outputTokens),T=Q(f.costUsd);return $!==void 0&&j!==void 0&&T!==void 0?{inputTokens:$,outputTokens:j,costUsd:T}:void 0}function nn(n){if(!n||typeof n!=="object")return;let f=n,$=Q(f.maxTurns),j=Q(f.graceTurns),T=Q(f.turnCount),J=f.outcome==="within-budget"||f.outcome==="wrap-up-requested"||f.outcome==="exceeded"?f.outcome:void 0;if($===void 0||j===void 0||T===void 0||!J)return;return{maxTurns:$,graceTurns:j,turnCount:T,outcome:J,...Q(f.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:Q(f.wrapUpRequestedAtTurn)}:{},...Q(f.exceededAtTurn)!==void 0?{exceededAtTurn:Q(f.exceededAtTurn)}:{}}}function Rf(n,f){return n==="queued"||n==="running"||n==="complete"||n==="failed"||n==="paused"?n:f}function mf(n,f){if(!n||typeof n!=="object")return;let $=n,j=X($.agent,128);if(!j)return;let T=$.status==="pending"||$.status==="running"||$.status==="complete"||$.status==="completed"||$.status==="failed"||$.status==="paused"?$.status:"pending";return{agent:j,status:T,...X($.sessionFile,2048)?{sessionFile:X($.sessionFile,2048)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...Q($.lastActivityAt)!==void 0?{lastActivityAt:Q($.lastActivityAt)}:{},...X($.currentTool,128)?{currentTool:X($.currentTool,128)}:{},...Q($.currentToolStartedAt)!==void 0?{currentToolStartedAt:Q($.currentToolStartedAt)}:{},...X($.currentPath,2048)?{currentPath:X($.currentPath,2048)}:{},...Q($.turnCount)!==void 0?{turnCount:Q($.turnCount)}:{},...Q($.toolCount)!==void 0?{toolCount:Q($.toolCount)}:{},...Q($.startedAt)!==void 0?{startedAt:Q($.startedAt)}:{},...Q($.endedAt)!==void 0?{endedAt:Q($.endedAt)}:{},...X($.error,1024)?{error:X($.error,1024)}:{},...$.timedOut===!0?{timedOut:!0}:{},...nn($.turnBudget)?{turnBudget:nn($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...f<Xn&&Array.isArray($.children)?{children:$.children.map((J)=>$n(J,f+1)).filter((J)=>Boolean(J)).slice(0,d)}:{}}}function $n(n,f=0){if(!n||typeof n!=="object")return;let $=n;if(!t($.id)||!t($.parentRunId))return;let j=xn($.path),T=Array.isArray($.steps)?$.steps.map((B)=>mf(B,f+1)).filter((B)=>Boolean(B)).slice(0,qn):void 0,J=If($.totalTokens),A=Nf($.totalCost);return{id:$.id,parentRunId:$.parentRunId,...Q($.parentStepIndex)!==void 0?{parentStepIndex:Q($.parentStepIndex)}:{},...X($.parentAgent,128)?{parentAgent:X($.parentAgent,128)}:{},depth:Math.min(Math.max(0,Q($.depth)??0),Xn),path:j,state:Rf($.state,"running"),...X($.asyncDir,2048)?{asyncDir:X($.asyncDir,2048)}:{},...Q($.pid)!==void 0&&Q($.pid)>0&&Number.isInteger(Q($.pid))?{pid:Q($.pid)}:{},...X($.sessionId,256)?{sessionId:X($.sessionId,256)}:{},...X($.sessionFile,2048)?{sessionFile:X($.sessionFile,2048)}:{},...X($.intercomTarget,256)?{intercomTarget:X($.intercomTarget,256)}:{},...X($.ownerIntercomTarget,256)?{ownerIntercomTarget:X($.ownerIntercomTarget,256)}:{},...X($.leafIntercomTarget,256)?{leafIntercomTarget:X($.leafIntercomTarget,256)}:{},...$.ownerState==="live"||$.ownerState==="gone"||$.ownerState==="unknown"?{ownerState:$.ownerState}:{},...X($.controlInbox,2048)?{controlInbox:X($.controlInbox,2048)}:{},...X($.capabilityToken,128)?{capabilityToken:X($.capabilityToken,128)}:{},...$.mode==="single"||$.mode==="parallel"||$.mode==="chain"?{mode:$.mode}:{},...X($.agent,128)?{agent:X($.agent,128)}:{},...Array.isArray($.agents)?{agents:$.agents.map((B)=>X(B,128)).filter((B)=>Boolean(B)).slice(0,qn)}:{},...Q($.currentStep)!==void 0?{currentStep:Q($.currentStep)}:{},...Q($.chainStepCount)!==void 0?{chainStepCount:Q($.chainStepCount)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...Q($.lastActivityAt)!==void 0?{lastActivityAt:Q($.lastActivityAt)}:{},...X($.currentTool,128)?{currentTool:X($.currentTool,128)}:{},...Q($.currentToolStartedAt)!==void 0?{currentToolStartedAt:Q($.currentToolStartedAt)}:{},...X($.currentPath,2048)?{currentPath:X($.currentPath,2048)}:{},...Q($.turnCount)!==void 0?{turnCount:Q($.turnCount)}:{},...Q($.toolCount)!==void 0?{toolCount:Q($.toolCount)}:{},...J?{totalTokens:J}:{},...A?{totalCost:A}:{},...Q($.startedAt)!==void 0?{startedAt:Q($.startedAt)}:{},...Q($.endedAt)!==void 0?{endedAt:Q($.endedAt)}:{},...Q($.lastUpdate)!==void 0?{lastUpdate:Q($.lastUpdate)}:{},...Q($.timeoutMs)!==void 0?{timeoutMs:Q($.timeoutMs)}:{},...Q($.deadlineAt)!==void 0?{deadlineAt:Q($.deadlineAt)}:{},...$.timedOut===!0?{timedOut:!0}:{},...nn($.turnBudget)?{turnBudget:nn($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...X($.error,1024)?{error:X($.error,1024)}:{},...T&&T.length>0?{steps:T}:{},...f<Xn&&Array.isArray($.children)?{children:$.children.map((B)=>$n(B,f+1)).filter((B)=>Boolean(B)).slice(0,d)}:{}}}function Kn(n,f){if(Buffer.byteLength(n,"utf-8")>Wn)return;let $;try{$=JSON.parse(n)}catch{return}if(!$||typeof $!=="object")return;let j=$;if(j.type!=="subagent.nested.started"&&j.type!=="subagent.nested.updated"&&j.type!=="subagent.nested.completed")return;if(j.rootRunId!==f.rootRunId||j.capabilityToken!==f.capabilityToken)return;if(!t(j.parentRunId))return;let T=Q(j.ts);if(T===void 0)return;let J=$n(j.child);if(!J||J.id===f.rootRunId)return;let A={...J,controlInbox:f.controlInbox,capabilityToken:f.capabilityToken,ownerState:J.ownerState??"unknown"};return{type:j.type,ts:T,rootRunId:f.rootRunId,parentRunId:j.parentRunId,...Q(j.parentStepIndex)!==void 0?{parentStepIndex:Q(j.parentStepIndex)}:{},capabilityToken:f.capabilityToken,child:A}}function Df(n,f){if(!n.includes(`
|
|
2
|
+
`)){let $=Kn(n.trim(),f);return $?[$]:[]}return n.split(`
|
|
3
3
|
`).slice(0,n.endsWith(`
|
|
4
|
-
`)?void 0:-1).map(($)=>$.trim()?
|
|
5
|
-
`;if(Buffer.byteLength(j,"utf-8")>
|
|
6
|
-
`);return
|
|
7
|
-
[stderr tail truncated]`:
|
|
8
|
-
`,"utf-8")}catch{}}function
|
|
4
|
+
`)?void 0:-1).map(($)=>$.trim()?Kn($,f):void 0).filter(($)=>Boolean($))}function s(n){return n==="complete"||n==="failed"||n==="paused"}function on(n,f){let $=f.type==="subagent.nested.completed"&&f.child.state==="running"?"complete":f.child.state,j={...f.child,state:$,lastUpdate:f.child.lastUpdate??f.ts};if(!n)return j;let T=n.lastUpdate??0,J=j.lastUpdate??f.ts;if(J<T)return n;if(s(n.state)&&!s(j.state))return n;if(s(n.state)&&s(j.state)&&J===T)return n;return{...n,...j,state:j.state,lastUpdate:Math.max(T,J)}}function wf(n,f){let $=!1,j=(B)=>B.map((O)=>{if(O.id===f.parentRunId){let L=O.children??[],Z=L.findIndex((y)=>y.id===f.child.id),Y=on(Z>=0?L[Z]:void 0,f),q=Z>=0?L.map((y,g)=>g===Z?Y:y):[...L,Y];return $=!0,{...O,children:q.slice(0,d),lastUpdate:Math.max(O.lastUpdate??0,f.ts)}}if(!O.children?.length)return O;let c=j(O.children);return c===O.children?O:{...O,children:c}}),T=j(n);if($)return T;let J=T.findIndex((B)=>B.id===f.child.id),A=on(J>=0?T[J]:void 0,f);return J>=0?T.map((B,O)=>O===J?A:B):[...T,A].slice(0,d)}function of(n,f){return{...n,updatedAt:Math.max(n.updatedAt,f.ts),children:wf(n.children,f)}}function kn(n){return K.join(hn(n),Ef)}function vn(){let n;try{n=G.readdirSync(a)}catch($){if($.code==="ENOENT")return new Map;throw $}let f=new Map;for(let $ of n){let j=K.join(a,$);try{let T=JSON.parse(G.readFileSync(K.join(j,zf),"utf-8"));if(typeof T.rootRunId!=="string"||typeof T.capabilityToken!=="string")continue;if(f.has(T.rootRunId))continue;let J={rootRunId:T.rootRunId,eventSink:K.join(j,"events"),controlInbox:K.join(j,"controls"),capabilityToken:T.capabilityToken};fn(J),f.set(T.rootRunId,J)}catch{continue}}return f}function hf(n){fn(n);try{let f=JSON.parse(G.readFileSync(kn(n),"utf-8"));return{rootRunId:n.rootRunId,updatedAt:typeof f.updatedAt==="number"?f.updatedAt:0,children:Array.isArray(f.children)?f.children.map(($)=>$n($)).filter(($)=>Boolean($)):[],processedEvents:Array.isArray(f.processedEvents)?f.processedEvents.filter(($)=>typeof $==="string"):[]}}catch(f){if(f.code!=="ENOENT")throw f;return{rootRunId:n.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function jn(n){fn(n);let f=hf(n),$=new Set(f.processedEvents),j=!1,T=[];try{T=G.readdirSync(n.eventSink).filter((J)=>J.endsWith(".json")||J.endsWith(".jsonl")).sort()}catch(J){if(J.code!=="ENOENT")throw J}for(let J of T){if($.has(J))continue;let A=K.join(n.eventSink,J);if(!Yn(n.eventSink,A))continue;let B;try{let O=G.statSync(A);if(!O.isFile()||O.size>Wn)continue;B=G.readFileSync(A,"utf-8")}catch{continue}for(let O of Df(B,n))f=of(f,O),j=!0;$.add(J),j=!0}if(j)f={...f,processedEvents:[...$].slice(-1000)},D(kn(n),f);return f}function Pf(n,f,$){let j=`${JSON.stringify($)}
|
|
5
|
+
`;if(Buffer.byteLength(j,"utf-8")>Wn)throw Error("Nested route record exceeds the maximum size.");G.mkdirSync(n,{recursive:!0,mode:448});let T=`${String(f).padStart(13,"0")}-${bf()}.json`,J=K.join(n,`.${T}.tmp`),A=K.join(n,T);return G.writeFileSync(J,j,{mode:384}),G.renameSync(J,A),A}function dn(n,f){fn(n);let $={...f,rootRunId:n.rootRunId,capabilityToken:n.capabilityToken},j=Kn(JSON.stringify($),n);if(!j)throw Error("Nested event record failed validation.");Pf(n.eventSink,j.ts,j)}function rn(n,f,$){if(!f?.length)return;for(let j of f)j.children=void 0;if(!$?.length)return;for(let j of $){if(j.parentRunId!==n||j.parentStepIndex===void 0)continue;let T=f.find((J,A)=>(J.index??A)===j.parentStepIndex);if(!T)continue;T.children??=[],T.children=[...T.children.filter((J)=>J.id!==j.id),j].slice(0,d)}}function un(n,f,$){return{id:n.runId||$.id,parentRunId:$.parentRunId,...$.parentStepIndex!==void 0?{parentStepIndex:$.parentStepIndex}:{},depth:$.depth,path:$.path??[{runId:$.parentRunId,...$.parentStepIndex!==void 0?{stepIndex:$.parentStepIndex}:{}}],asyncDir:f,...n.pid?{pid:n.pid}:{},...n.sessionId?{sessionId:n.sessionId}:{},mode:n.mode??$.mode,state:n.state,...n.currentStep!==void 0?{currentStep:n.currentStep}:{},...n.chainStepCount!==void 0?{chainStepCount:n.chainStepCount}:{},...n.activityState?{activityState:n.activityState}:{},...n.lastActivityAt!==void 0?{lastActivityAt:n.lastActivityAt}:{},...n.currentTool?{currentTool:n.currentTool}:{},...n.currentToolStartedAt!==void 0?{currentToolStartedAt:n.currentToolStartedAt}:{},...n.currentPath?{currentPath:n.currentPath}:{},...n.turnCount!==void 0?{turnCount:n.turnCount}:{},...n.toolCount!==void 0?{toolCount:n.toolCount}:{},...n.totalTokens?{totalTokens:n.totalTokens}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{},...n.deadlineAt!==void 0?{deadlineAt:n.deadlineAt}:{},...n.timedOut!==void 0?{timedOut:n.timedOut}:{},...n.turnBudget?{turnBudget:n.turnBudget}:{},...n.turnBudgetExceeded!==void 0?{turnBudgetExceeded:n.turnBudgetExceeded}:{},...n.wrapUpRequested!==void 0?{wrapUpRequested:n.wrapUpRequested}:{},...n.error?{error:n.error}:{},...n.startedAt!==void 0?{startedAt:n.startedAt}:{startedAt:$.ts},...n.endedAt!==void 0?{endedAt:n.endedAt}:{},lastUpdate:n.lastUpdate??$.ts,...n.sessionFile?{sessionFile:n.sessionFile}:{},...n.steps?.length?{steps:n.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,qn)}:{}}}function kf(n,f,$){if(typeof n!=="object"||n===null)return!1;let{start:j,count:T,stepIndex:J}=n;return typeof j==="number"&&typeof T==="number"&&typeof J==="number"&&Number.isInteger(j)&&Number.isInteger(T)&&Number.isInteger(J)&&j>=0&&T>0&&J>=0&&J<$&&j+T<=f}function r(n,f,$){if(!Array.isArray(n))return[];return n.filter((j)=>kf(j,f,$)).sort((j,T)=>j.stepIndex-T.stepIndex||j.start-T.start)}function ln(n,f,$){let j=0,T=0;for(let J of $){while(T<J.start&&j<f){if(T===n)return j;T++,j++}if(n>=J.start&&n<J.start+J.count)return J.stepIndex;T=J.start+J.count,j=J.stepIndex+1}while(T<=n&&j<f){if(T===n)return j;T++,j++}return Math.max(0,f-1)}import*as H from"node:fs";import*as S from"node:path";function Hn(n){return n instanceof Error?n.message:String(n)}function vf(n){let f=S.join(n,"runner.stderr.log"),$=65536,j;try{let J=H.statSync(f);if(J.size<=0)return;let A=H.openSync(f,"r");try{let B=Math.min(J.size,65536),O=Math.max(0,J.size-B),c=Buffer.alloc(B);H.readSync(A,c,0,B,O),j=c.toString("utf-8").trim()}finally{H.closeSync(A)}}catch{return}if(!j)return;let T=j.split(/\r?\n/).slice(-30).join(`
|
|
6
|
+
`);return T.length>4000?`${T.slice(-4000)}
|
|
7
|
+
[stderr tail truncated]`:T}function sn(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function df(n,f){try{H.mkdirSync(S.dirname(n),{recursive:!0}),H.appendFileSync(n,`${JSON.stringify(f)}
|
|
8
|
+
`,"utf-8")}catch{}}function rf(n){let f=S.join(n,"status.json"),$;try{$=H.readFileSync(f,"utf-8")}catch(j){if(sn(j))return null;throw Error(`Failed to read async status file '${f}': ${Hn(j)}`,{cause:j instanceof Error?j:void 0})}try{return JSON.parse($)}catch(j){throw Error(`Failed to parse async status file '${f}': ${Hn(j)}`,{cause:j instanceof Error?j:void 0})}}function uf(n){try{let f=JSON.parse(H.readFileSync(n,"utf-8"));return{state:f.success?"complete":f.state==="paused"||f.exitCode===0?"paused":"failed",...Array.isArray(f.results)?{results:f.results}:{}}}catch(f){if(sn(f))return;throw Error(`Failed to read async result file '${n}': ${Hn(f)}`,{cause:f instanceof Error?f:void 0})}}function lf(n,f){if(f?.success===!0)return"complete";if(f?.success===!1)return"failed";return n}function pf(n,f,$){let j=uf(f);if(!j)return;let T=(n.steps??[]).map((J,A)=>{if(J.status!=="running"&&J.status!=="pending")return J;let B=j.results?.[A],O=lf(j.state,B);return{...J,status:O==="complete"?"complete":O,endedAt:J.endedAt??$,durationMs:J.startedAt!==void 0&&J.durationMs===void 0?Math.max(0,$-J.startedAt):J.durationMs,exitCode:J.exitCode??(O==="complete"||O==="paused"?0:1),error:O==="failed"?J.error??B?.error:J.error,sessionFile:J.sessionFile??B?.sessionFile,model:J.model??B?.model,attemptedModels:J.attemptedModels??B?.attemptedModels,modelAttempts:J.modelAttempts??B?.modelAttempts}});return{...n,state:j.state,activityState:void 0,lastUpdate:$,endedAt:n.endedAt??$,steps:T}}function ef(n,f,$){let j=f.startedAt??$,T=f.agents?.length?f.agents:["subagent"],J=f.chainStepCount,A=J!==void 0?r(f.parallelGroups,T.length,J):[];return{runId:f.runId||S.basename(n),...f.sessionId?{sessionId:f.sessionId}:{},mode:f.mode??"single",state:"running",pid:f.pid,startedAt:j,lastUpdate:$,currentStep:0,...J!==void 0?{chainStepCount:J}:{},...A.length?{parallelGroups:A}:{},steps:T.map((B)=>({agent:B,status:"running",startedAt:j})),...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function sf(n,f,$,j){let T=n.runId||S.basename(f),J=typeof n.pid==="number"?n.pid:"unknown",A=j??`Async runner process ${J} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,B=vf(f),O=B?`${A}
|
|
9
9
|
|
|
10
10
|
Runner stderr tail:
|
|
11
|
-
${B}`:T,L=((n.steps?.length)?n.steps:[{agent:"subagent",status:"running"}]).map((q)=>q.status==="running"||q.status==="pending"?{...q,status:"failed",activityState:void 0,endedAt:q.endedAt??$,durationMs:q.startedAt!==void 0&&q.durationMs===void 0?Math.max(0,$-q.startedAt):q.durationMs,exitCode:q.exitCode??1,error:q.error??O}:q),Z={...n,state:"failed",activityState:void 0,lastUpdate:$,endedAt:$,steps:L},Y=L[n.currentStep??0]?.agent??L[0]?.agent??"subagent";return{status:Z,message:O,result:{id:A,agent:Y,mode:n.mode,success:!1,state:"failed",summary:O,results:L.map((q)=>({agent:q.agent,output:q.status==="complete"||q.status==="completed"?"":O,error:q.status==="complete"||q.status==="completed"?void 0:q.error??O,success:q.status==="complete"||q.status==="completed",model:q.model,attemptedModels:q.attemptedModels,modelAttempts:q.modelAttempts,sessionFile:q.sessionFile})),exitCode:1,timestamp:$,durationMs:Math.max(0,$-n.startedAt),asyncDir:f,sessionId:n.sessionId,sessionFile:n.sessionFile}}}function ln(n,f,$,j,A){let J=pf(f,n,j,A);return w($,J.result),w(U.join(n,"status.json"),J.status),kf(U.join(n,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:j,runId:J.status.runId,pid:f.pid,resultPath:$,message:J.message}),{status:J.status,repaired:!0,resultPath:$,message:J.message}}function pn(n){return n==="complete"||n==="failed"||n==="paused"}function*Sn(n){for(let f of n??[])yield f,yield*Sn(f.children),yield*Sn(f.steps?.flatMap(($)=>$.children??[]))}function sn(n,f={}){let $=Jn(n);for(let j of Sn($.children)){if(j.state!=="running"&&j.state!=="queued")continue;let A=hn(n.rootRunId,j);if(!A)continue;let J=yn(A,{...f,resultsDir:U.join(f.resultsDir??m,"nested",n.rootRunId)}),T=J.status;if(!T)continue;if(!J.repaired&&!pn(T.state))continue;let B=f.now?.()??Date.now();vn(n,{type:pn(T.state)?"subagent.nested.completed":"subagent.nested.updated",ts:B,parentRunId:j.parentRunId,parentStepIndex:j.parentStepIndex,child:rn(T,A,{id:j.id,parentRunId:j.parentRunId,parentStepIndex:j.parentStepIndex,depth:j.depth,path:j.path,mode:j.mode,ts:B})})}}function ef(n,f=process.kill){try{return f(n,0),"alive"}catch($){let j=typeof $==="object"&&$!==null&&"code"in $?$.code:void 0;if(j==="ESRCH")return"dead";if(j==="EPERM")return"unknown";return"unknown"}}function yn(n,f={}){let $=f.now?.()??Date.now(),j=vf(n),A=!j&&f.startedRun?lf(n,f.startedRun,$):void 0,J=j??A;if(!J)return{status:null,repaired:!1};let T=J.runId||U.basename(n),B=U.join(f.resultsDir??m,`${T}.json`);if(H.existsSync(B)){let c=J.state==="running"||J.state==="queued"?uf(J,B,$):void 0;if(c)return w(U.join(n,"status.json"),c),{status:c,repaired:!0,resultPath:B,message:"Existing async result file was used to repair stale running status."};return{status:J,repaired:!1,resultPath:B}}if(J.state!=="running"||typeof J.pid!=="number")return{status:j??null,repaired:!1,resultPath:B};if(!j){let c=f.startedRun?.startedAt??J.startedAt;if($-c<(f.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:B}}if(ef(J.pid,f.kill)!=="dead"){let c=f.staleAlivePidMs??86400000,L=J.lastUpdate??J.startedAt;if($-L<=c)return{status:j??null,repaired:!1,resultPath:B};let Z=`Async runner process ${J.pid} still has a live PID, but status has not updated for ${$-L}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return ln(n,J,B,$,Z)}return ln(n,J,B,$)}function i(n){return n instanceof Error?n.message:String(n)}function Un(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function sf(n,f){let $=F.join(n,f);try{return l.statSync($).isDirectory()}catch(j){if(Un(j))return!1;throw Error(`Failed to inspect async run path '${$}': ${i(j)}`,{cause:j instanceof Error?j:void 0})}}function af(n){if(!n)return;try{return l.statSync(n).mtimeMs}catch(f){if(Un(f))return;throw Error(`Failed to inspect async output file '${n}': ${i(f)}`,{cause:f instanceof Error?f:void 0})}}function tf(n,f){if(f.state!=="running")return{activityState:f.activityState,lastActivityAt:f.lastActivityAt};let $=f.outputFile?F.isAbsolute(f.outputFile)?f.outputFile:F.join(n,f.outputFile):void 0,j=typeof f.currentStep==="number"?f.steps?.[f.currentStep]:void 0;return{activityState:f.activityState,lastActivityAt:f.lastActivityAt??af($)??j?.lastActivityAt??j?.startedAt??f.startedAt}}function n$(n,f,$=[],j){if(f.sessionId!==void 0&&typeof f.sessionId!=="string")throw Error(`Invalid async status '${F.join(n,"status.json")}': sessionId must be a string.`);let{activityState:A,lastActivityAt:J}=tf(n,f),T=f.steps??[],B=f.chainStepCount??T.length,O=u(f.parallelGroups,T.length,B),c=[];if($.length===0&&j)try{c=Jn(j)?.children??[]}catch(Z){$.push(`Nested status unavailable: ${i(Z)}`)}let L=T.map((Z,Y)=>{let{activityState:q,lastActivityAt:S}=Z;return{index:Y,agent:Z.agent,...Z.label?{label:Z.label}:{},...Z.phase?{phase:Z.phase}:{},...Z.outputName?{outputName:Z.outputName}:{},...Z.structured?{structured:Z.structured}:{},status:Z.status,...q?{activityState:q}:{},...S?{lastActivityAt:S}:{},...Z.currentTool?{currentTool:Z.currentTool}:{},...Z.currentToolArgs?{currentToolArgs:Z.currentToolArgs}:{},...Z.currentToolStartedAt?{currentToolStartedAt:Z.currentToolStartedAt}:{},...Z.currentPath?{currentPath:Z.currentPath}:{},...Z.recentTools?{recentTools:Z.recentTools.map((g)=>({...g}))}:{},...Z.recentOutput?{recentOutput:[...Z.recentOutput]}:{},...Z.turnCount!==void 0?{turnCount:Z.turnCount}:{},...Z.toolCount!==void 0?{toolCount:Z.toolCount}:{},...Z.steerCount!==void 0?{steerCount:Z.steerCount}:{},...Z.lastSteerAt!==void 0?{lastSteerAt:Z.lastSteerAt}:{},...Z.durationMs!==void 0?{durationMs:Z.durationMs}:{},...Z.tokens?{tokens:Z.tokens}:{},...Z.totalCost?{totalCost:Z.totalCost}:{},...Z.skills?{skills:Z.skills}:{},...Z.model?{model:Z.model}:{},...Z.thinking?{thinking:Z.thinking}:{},...Z.attemptedModels?{attemptedModels:Z.attemptedModels}:{},...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}:{},...Z.children?.length?{children:Z.children}:{}}});return dn(f.runId||F.basename(n),L,c),{id:f.runId||F.basename(n),asyncDir:n,...f.sessionId?{sessionId:f.sessionId}:{},state:f.state,...f.error?{error:f.error}:{},activityState:A,lastActivityAt:J,currentTool:f.currentTool,currentToolStartedAt:f.currentToolStartedAt,currentPath:f.currentPath,turnCount:f.turnCount,toolCount:f.toolCount,steerCount:f.steerCount,lastSteerAt:f.lastSteerAt,mode:f.mode,cwd:f.cwd,startedAt:f.startedAt,lastUpdate:f.lastUpdate,endedAt:f.endedAt,...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}:{},currentStep:f.currentStep,...f.chainStepCount!==void 0?{chainStepCount:f.chainStepCount}:{},...f.pendingAppends!==void 0?{pendingAppends:f.pendingAppends}:{},...O.length?{parallelGroups:O}:{},steps:L,...c.length?{nestedChildren:c}:{},...$.length?{nestedWarnings:$}:{},...f.sessionDir?{sessionDir:f.sessionDir}:{},...f.outputFile?{outputFile:f.outputFile}:{},...f.totalTokens?{totalTokens:f.totalTokens}:{},...f.totalCost?{totalCost:f.totalCost}:{},...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function f$(n){let f=($)=>{switch($){case"running":return 0;case"queued":return 1;case"failed":return 2;case"paused":return 2;case"complete":return 3}};return[...n].sort(($,j)=>{let A=f($.state)-f(j.state);if(A!==0)return A;let J=$.lastUpdate??$.endedAt??$.startedAt;return(j.lastUpdate??j.endedAt??j.startedAt)-J})}function an(n,f={}){let $;try{$=l.readdirSync(n).filter((O)=>sf(n,O))}catch(O){if(Un(O))return[];throw Error(`Failed to list async runs in '${n}': ${i(O)}`,{cause:O instanceof Error?O:void 0})}let j=f.states?new Set(f.states):void 0,A=[],J,T=(O)=>{if(!J)J=kn();return J.get(O)};for(let O of $){let c=F.join(n,O),Z=(f.reconcile===!1?void 0:yn(c,{resultsDir:f.resultsDir,kill:f.kill,now:f.now}))?.status??p(c);if(!Z)continue;if(j&&!j.has(Z.state))continue;if(f.sessionId&&Z.sessionId!==f.sessionId)continue;let Y=[],q;try{if(q=T(Z.runId||F.basename(c)),q)sn(q,{resultsDir:f.resultsDir,kill:f.kill,now:f.now})}catch(g){Y.push(`Nested status unavailable: ${i(g)}`)}let S=n$(c,Z,Y,q);A.push(S)}let B=f$(A);return f.limit!==void 0?B.slice(0,f.limit):B}function tn(n){if(!n.outputFile)return;return F.isAbsolute(n.outputFile)?n.outputFile:F.join(n.asyncDir,n.outputFile)}function nf(n){let f=n.steps.length||1,$=n.chainStepCount??f,j=u(n.parallelGroups,n.steps.length,$),A=n.currentStep!==void 0?j.find((J)=>n.currentStep>=J.start&&n.currentStep<J.start+J.count):void 0;if(A){let J=n.steps.slice(A.start,A.start+A.count),T=cn(J,A.count,{showRunning:n.state==="running"});if(n.mode==="parallel")return T;return`step ${A.stepIndex+1}/${$} · parallel group: ${T}`}if(n.mode==="parallel")return cn(n.steps,f,{showRunning:n.state==="running"});if(n.mode==="chain"&&n.currentStep!==void 0&&j.length>0)return`step ${un(n.currentStep,$,j)+1}/${$}`;return n.currentStep!==void 0?`step ${n.currentStep+1}/${f}`:`steps ${f}`}var ff=80,$$=500,j$=262144;function Gn(n){if(n===void 0)return ff;if(!Number.isFinite(n))return ff;return Math.max(1,Math.min($$,Math.trunc(n)))}function $f(n){let f=new Set,$=[];for(let j of n){if(!j||f.has(j))continue;f.add(j),$.push(j)}return $}function J$(n,f){if(!f)return;return M.resolve(n,f)}function jf(n,f){let $=M.resolve(n),j=M.resolve(f);return j===$||j.startsWith(`${$}${M.sep}`)}function An(n){return n instanceof Error?n.message:String(n)}function Jf(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function A$(n,f){let $;try{$=W.statSync(n)}catch(A){if(Jf(A))return{path:n,lines:[],truncated:!1};return{path:n,lines:[],truncated:!1,error:An(A)}}if($.size===0)return{path:n,lines:[],truncated:!1};let j;try{let A=Math.min($.size,j$),J=$.size-A,T=Buffer.alloc(A);j=W.openSync(n,"r");let B=W.readSync(j,T,0,A,J),c=T.subarray(0,B).toString("utf-8").split(/\r?\n/);if(J>0&&c.length>0)c=c.slice(1);if(c.at(-1)==="")c=c.slice(0,-1);return{path:n,lines:c.slice(-f),truncated:J>0||c.length>f}}catch(A){return{path:n,lines:[],truncated:!1,error:An(A)}}finally{if(j!==void 0)W.closeSync(j)}}function Af(n,f,$,j){if($.length===0)return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path without a trusted root: ${n}`};let A=M.resolve(n);if(!$.some((O)=>jf(O,A)))return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path outside trusted roots: ${n}`};let J;try{J=W.lstatSync(A)}catch(O){if(Jf(O))return{path:n,lines:[],truncated:!1};return{path:n,lines:[],truncated:!1,error:An(O)}}if(J.isSymbolicLink())return{path:n,lines:[],truncated:!1,error:`Refusing to read symlink ${j} transcript path: ${n}`};if(!J.isFile())return{path:n,lines:[],truncated:!1,error:`Refusing to read non-file ${j} transcript path: ${n}`};let T,B;try{T=W.realpathSync(A),B=$.filter((O)=>W.existsSync(O)).map((O)=>W.realpathSync(O))}catch(O){return{path:n,lines:[],truncated:!1,error:An(O)}}if(!B.some((O)=>jf(O,T)))return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path outside trusted roots: ${n}`};return A$(A,f)}function Fn(n,f=240){let $;if(typeof n==="string")$=n;else $=JSON.stringify(n);return $.length>f?`${$.slice(0,f)}…`:$}function T$(n){if(typeof n==="string")return n;if(!Array.isArray(n))return"";return n.map((f)=>{if(!f||typeof f!=="object")return"";let $=f;if(typeof $.text==="string")return $.text;if($.type==="toolCall"||$.type==="tool_call")return`[tool: ${typeof $.name==="string"?$.name:typeof $.toolName==="string"?$.toolName:"tool"}${$.args===void 0?"":` ${Fn($.args)}`}]`;if($.type==="toolResult"||$.type==="tool_result")return`[tool result${$.result===void 0?"":`: ${Fn($.result)}`}]`;if($.content!==void 0)return Fn($.content);return""}).filter(Boolean).join(`
|
|
12
|
-
`)}function
|
|
13
|
-
`).trimEnd()}],details:{mode:"management",results:[]}}}function
|
|
14
|
-
`)}function
|
|
15
|
-
`);let
|
|
16
|
-
`)}function
|
|
17
|
-
`)}export{
|
|
11
|
+
${B}`:A,L=((n.steps?.length)?n.steps:[{agent:"subagent",status:"running"}]).map((q)=>q.status==="running"||q.status==="pending"?{...q,status:"failed",activityState:void 0,endedAt:q.endedAt??$,durationMs:q.startedAt!==void 0&&q.durationMs===void 0?Math.max(0,$-q.startedAt):q.durationMs,exitCode:q.exitCode??1,error:q.error??O}:q),Z={...n,state:"failed",activityState:void 0,lastUpdate:$,endedAt:$,steps:L},Y=L[n.currentStep??0]?.agent??L[0]?.agent??"subagent";return{status:Z,message:O,result:{id:T,agent:Y,mode:n.mode,success:!1,state:"failed",summary:O,results:L.map((q)=>({agent:q.agent,output:q.status==="complete"||q.status==="completed"?"":O,error:q.status==="complete"||q.status==="completed"?void 0:q.error??O,success:q.status==="complete"||q.status==="completed",model:q.model,attemptedModels:q.attemptedModels,modelAttempts:q.modelAttempts,sessionFile:q.sessionFile})),exitCode:1,timestamp:$,durationMs:Math.max(0,$-n.startedAt),asyncDir:f,sessionId:n.sessionId,sessionFile:n.sessionFile}}}function pn(n,f,$,j,T){let J=sf(f,n,j,T);return D($,J.result),D(S.join(n,"status.json"),J.status),df(S.join(n,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:j,runId:J.status.runId,pid:f.pid,resultPath:$,message:J.message}),{status:J.status,repaired:!0,resultPath:$,message:J.message}}function en(n){return n==="complete"||n==="failed"||n==="paused"}function*Mn(n){for(let f of n??[])yield f,yield*Mn(f.children),yield*Mn(f.steps?.flatMap(($)=>$.children??[]))}function an(n,f={}){let $=jn(n);for(let j of Mn($.children)){if(j.state!=="running"&&j.state!=="queued")continue;let T=Pn(n.rootRunId,j);if(!T)continue;let J=yn(T,{...f,resultsDir:S.join(f.resultsDir??m,"nested",n.rootRunId)}),A=J.status;if(!A)continue;if(!J.repaired&&!en(A.state))continue;let B=f.now?.()??Date.now();dn(n,{type:en(A.state)?"subagent.nested.completed":"subagent.nested.updated",ts:B,parentRunId:j.parentRunId,parentStepIndex:j.parentStepIndex,child:un(A,T,{id:j.id,parentRunId:j.parentRunId,parentStepIndex:j.parentStepIndex,depth:j.depth,path:j.path,mode:j.mode,ts:B})})}}function af(n,f=process.kill){try{return f(n,0),"alive"}catch($){let j=typeof $==="object"&&$!==null&&"code"in $?$.code:void 0;if(j==="ESRCH")return"dead";if(j==="EPERM")return"unknown";return"unknown"}}function yn(n,f={}){let $=f.now?.()??Date.now(),j=rf(n),T=!j&&f.startedRun?ef(n,f.startedRun,$):void 0,J=j??T;if(!J)return{status:null,repaired:!1};let A=J.runId||S.basename(n),B=S.join(f.resultsDir??m,`${A}.json`);if(H.existsSync(B)){let c=J.state==="running"||J.state==="queued"?pf(J,B,$):void 0;if(c)return D(S.join(n,"status.json"),c),{status:c,repaired:!0,resultPath:B,message:"Existing async result file was used to repair stale running status."};return{status:J,repaired:!1,resultPath:B}}if(J.state!=="running"||typeof J.pid!=="number")return{status:j??null,repaired:!1,resultPath:B};if(!j){let c=f.startedRun?.startedAt??J.startedAt;if($-c<(f.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:B}}if(af(J.pid,f.kill)!=="dead"){let c=f.staleAlivePidMs??86400000,L=J.lastUpdate??J.startedAt;if($-L<=c)return{status:j??null,repaired:!1,resultPath:B};let Z=`Async runner process ${J.pid} still has a live PID, but status has not updated for ${$-L}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return pn(n,J,B,$,Z)}return pn(n,J,B,$)}function u(n){return n instanceof Error?n.message:String(n)}function Gn(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function tf(n,f){let $=F.join(n,f);try{return i.statSync($).isDirectory()}catch(j){if(Gn(j))return!1;throw Error(`Failed to inspect async run path '${$}': ${u(j)}`,{cause:j instanceof Error?j:void 0})}}function n$(n){if(!n)return;try{return i.statSync(n).mtimeMs}catch(f){if(Gn(f))return;throw Error(`Failed to inspect async output file '${n}': ${u(f)}`,{cause:f instanceof Error?f:void 0})}}function f$(n,f){if(f.state!=="running")return{activityState:f.activityState,lastActivityAt:f.lastActivityAt};let $=f.outputFile?F.isAbsolute(f.outputFile)?f.outputFile:F.join(n,f.outputFile):void 0,j=typeof f.currentStep==="number"?f.steps?.[f.currentStep]:void 0;return{activityState:f.activityState,lastActivityAt:f.lastActivityAt??n$($)??j?.lastActivityAt??j?.startedAt??f.startedAt}}function $$(n,f,$=[],j){if(f.sessionId!==void 0&&typeof f.sessionId!=="string")throw Error(`Invalid async status '${F.join(n,"status.json")}': sessionId must be a string.`);let{activityState:T,lastActivityAt:J}=f$(n,f),A=f.steps??[],B=f.chainStepCount??A.length,O=r(f.parallelGroups,A.length,B),c=[];if($.length===0&&j)try{c=jn(j)?.children??[]}catch(Z){$.push(`Nested status unavailable: ${u(Z)}`)}let L=A.map((Z,Y)=>{let{activityState:q,lastActivityAt:y}=Z;return{index:Y,agent:Z.agent,...Z.label?{label:Z.label}:{},...Z.phase?{phase:Z.phase}:{},...Z.outputName?{outputName:Z.outputName}:{},...Z.structured?{structured:Z.structured}:{},status:Z.status,...q?{activityState:q}:{},...y?{lastActivityAt:y}:{},...Z.currentTool?{currentTool:Z.currentTool}:{},...Z.currentToolArgs?{currentToolArgs:Z.currentToolArgs}:{},...Z.currentToolStartedAt?{currentToolStartedAt:Z.currentToolStartedAt}:{},...Z.currentPath?{currentPath:Z.currentPath}:{},...Z.recentTools?{recentTools:Z.recentTools.map((g)=>({...g}))}:{},...Z.recentOutput?{recentOutput:[...Z.recentOutput]}:{},...Z.turnCount!==void 0?{turnCount:Z.turnCount}:{},...Z.toolCount!==void 0?{toolCount:Z.toolCount}:{},...Z.steerCount!==void 0?{steerCount:Z.steerCount}:{},...Z.lastSteerAt!==void 0?{lastSteerAt:Z.lastSteerAt}:{},...Z.durationMs!==void 0?{durationMs:Z.durationMs}:{},...Z.tokens?{tokens:Z.tokens}:{},...Z.totalCost?{totalCost:Z.totalCost}:{},...Z.skills?{skills:Z.skills}:{},...Z.model?{model:Z.model}:{},...Z.thinking?{thinking:Z.thinking}:{},...Z.attemptedModels?{attemptedModels:Z.attemptedModels}:{},...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}:{},...Z.children?.length?{children:Z.children}:{}}});return rn(f.runId||F.basename(n),L,c),{id:f.runId||F.basename(n),asyncDir:n,...f.sessionId?{sessionId:f.sessionId}:{},state:f.state,...f.error?{error:f.error}:{},activityState:T,lastActivityAt:J,currentTool:f.currentTool,currentToolStartedAt:f.currentToolStartedAt,currentPath:f.currentPath,turnCount:f.turnCount,toolCount:f.toolCount,steerCount:f.steerCount,lastSteerAt:f.lastSteerAt,mode:f.mode,cwd:f.cwd,startedAt:f.startedAt,lastUpdate:f.lastUpdate,endedAt:f.endedAt,...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}:{},currentStep:f.currentStep,...f.chainStepCount!==void 0?{chainStepCount:f.chainStepCount}:{},...f.pendingAppends!==void 0?{pendingAppends:f.pendingAppends}:{},...O.length?{parallelGroups:O}:{},steps:L,...c.length?{nestedChildren:c}:{},...$.length?{nestedWarnings:$}:{},...f.sessionDir?{sessionDir:f.sessionDir}:{},...f.outputFile?{outputFile:f.outputFile}:{},...f.totalTokens?{totalTokens:f.totalTokens}:{},...f.totalCost?{totalCost:f.totalCost}:{},...f.sessionFile?{sessionFile:f.sessionFile}:{}}}function j$(n){let f=($)=>{switch($){case"running":return 0;case"queued":return 1;case"failed":return 2;case"paused":return 2;case"complete":return 3}};return[...n].sort(($,j)=>{let T=f($.state)-f(j.state);if(T!==0)return T;let J=$.lastUpdate??$.endedAt??$.startedAt;return(j.lastUpdate??j.endedAt??j.startedAt)-J})}function tn(n,f={}){let $;try{$=i.readdirSync(n).filter((O)=>tf(n,O))}catch(O){if(Gn(O))return[];throw Error(`Failed to list async runs in '${n}': ${u(O)}`,{cause:O instanceof Error?O:void 0})}let j=f.states?new Set(f.states):void 0,T=[],J,A=(O)=>{if(!J)J=vn();return J.get(O)};for(let O of $){let c=F.join(n,O),Z=(f.reconcile===!1?void 0:yn(c,{resultsDir:f.resultsDir,kill:f.kill,now:f.now}))?.status??l(c);if(!Z)continue;if(j&&!j.has(Z.state))continue;if(f.sessionId&&Z.sessionId!==f.sessionId)continue;let Y=[],q;try{if(q=A(Z.runId||F.basename(c)),q)an(q,{resultsDir:f.resultsDir,kill:f.kill,now:f.now})}catch(g){Y.push(`Nested status unavailable: ${u(g)}`)}let y=$$(c,Z,Y,q);T.push(y)}let B=j$(T);return f.limit!==void 0?B.slice(0,f.limit):B}function nf(n){if(!n.outputFile)return;return F.isAbsolute(n.outputFile)?n.outputFile:F.join(n.asyncDir,n.outputFile)}function ff(n){let f=n.steps.length||1,$=n.chainStepCount??f,j=r(n.parallelGroups,n.steps.length,$),T=n.currentStep!==void 0?j.find((J)=>n.currentStep>=J.start&&n.currentStep<J.start+J.count):void 0;if(T){let J=n.steps.slice(T.start,T.start+T.count),A=Qn(J,T.count,{showRunning:n.state==="running"});if(n.mode==="parallel")return A;return`step ${T.stepIndex+1}/${$} · parallel group: ${A}`}if(n.mode==="parallel")return Qn(n.steps,f,{showRunning:n.state==="running"});if(n.mode==="chain"&&n.currentStep!==void 0&&j.length>0)return`step ${ln(n.currentStep,$,j)+1}/${$}`;return n.currentStep!==void 0?`step ${n.currentStep+1}/${f}`:`steps ${f}`}var $f=80,J$=500,T$=262144;function Fn(n){if(n===void 0)return $f;if(!Number.isFinite(n))return $f;return Math.max(1,Math.min(J$,Math.trunc(n)))}function jf(n){let f=new Set,$=[];for(let j of n){if(!j||f.has(j))continue;f.add(j),$.push(j)}return $}function A$(n,f){if(!f)return;return M.resolve(n,f)}function Jf(n,f){let $=M.resolve(n),j=M.resolve(f);return j===$||j.startsWith(`${$}${M.sep}`)}function Jn(n){return n instanceof Error?n.message:String(n)}function Tf(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}function O$(n,f){let $;try{$=W.statSync(n)}catch(T){if(Tf(T))return{path:n,lines:[],truncated:!1};return{path:n,lines:[],truncated:!1,error:Jn(T)}}if($.size===0)return{path:n,lines:[],truncated:!1};let j;try{let T=Math.min($.size,T$),J=$.size-T,A=Buffer.alloc(T);j=W.openSync(n,"r");let B=W.readSync(j,A,0,T,J),c=A.subarray(0,B).toString("utf-8").split(/\r?\n/);if(J>0&&c.length>0)c=c.slice(1);if(c.at(-1)==="")c=c.slice(0,-1);return{path:n,lines:c.slice(-f),truncated:J>0||c.length>f}}catch(T){return{path:n,lines:[],truncated:!1,error:Jn(T)}}finally{if(j!==void 0)W.closeSync(j)}}function Af(n,f,$,j){if($.length===0)return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path without a trusted root: ${n}`};let T=M.resolve(n);if(!$.some((O)=>Jf(O,T)))return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path outside trusted roots: ${n}`};let J;try{J=W.lstatSync(T)}catch(O){if(Tf(O))return{path:n,lines:[],truncated:!1};return{path:n,lines:[],truncated:!1,error:Jn(O)}}if(J.isSymbolicLink())return{path:n,lines:[],truncated:!1,error:`Refusing to read symlink ${j} transcript path: ${n}`};if(!J.isFile())return{path:n,lines:[],truncated:!1,error:`Refusing to read non-file ${j} transcript path: ${n}`};let A,B;try{A=W.realpathSync(T),B=$.filter((O)=>W.existsSync(O)).map((O)=>W.realpathSync(O))}catch(O){return{path:n,lines:[],truncated:!1,error:Jn(O)}}if(!B.some((O)=>Jf(O,A)))return{path:n,lines:[],truncated:!1,error:`Refusing to read ${j} transcript path outside trusted roots: ${n}`};return O$(T,f)}function Sn(n,f=240){let $;if(typeof n==="string")$=n;else $=JSON.stringify(n);return $.length>f?`${$.slice(0,f)}…`:$}function B$(n){if(typeof n==="string")return n;if(!Array.isArray(n))return"";return n.map((f)=>{if(!f||typeof f!=="object")return"";let $=f;if(typeof $.text==="string")return $.text;if($.type==="toolCall"||$.type==="tool_call")return`[tool: ${typeof $.name==="string"?$.name:typeof $.toolName==="string"?$.toolName:"tool"}${$.args===void 0?"":` ${Sn($.args)}`}]`;if($.type==="toolResult"||$.type==="tool_result")return`[tool result${$.result===void 0?"":`: ${Sn($.result)}`}]`;if($.content!==void 0)return Sn($.content);return""}).filter(Boolean).join(`
|
|
12
|
+
`)}function Z$(n){if(!n||typeof n!=="object")return;let f=n,$=f.message&&typeof f.message==="object"?f.message:f,j=typeof $.role==="string"?$.role:void 0;if(!j)return;let T=B$($.content).trim();if(!T)return;return`${j}: ${T}`}function Of(n,f,$){let j=Af(n,Math.max(f*4,f),$,"session"),T=[];if(j.error)T.push(`Session read failed for ${n}: ${j.error}`);let J=[],A=0;for(let B of j.lines){if(!B.trim())continue;try{let O=JSON.parse(B),c=Z$(O);if(c)J.push(c)}catch{A++}}if(A>0)T.push(`Skipped ${A} malformed session tail line${A===1?"":"s"}.`);return{lines:J.slice(-f),warnings:T}}function Tn(n){let f=[];if(n.currentTool&&n.currentToolStartedAt!==void 0)f.push(`tool ${n.currentTool} ${P(Math.max(0,Date.now()-n.currentToolStartedAt))}`);else if(n.currentTool)f.push(`tool ${n.currentTool}`);if(n.currentPath)f.push(U(n.currentPath));if(n.turnCount!==void 0)f.push(`${n.turnCount} turns`);if(n.toolCount!==void 0)f.push(`${n.toolCount} tools`);if(n.tokens?.total)f.push(`${h(n.tokens.total)} tok`);let $=k(n.lastActivityAt,n.activityState);return $||f.length?[$,...f].filter(Boolean).join(" | "):void 0}function Q$(n){if(n.mode==="single"&&n.currentAgent)return n.currentAgent;return n.mode}function c$(n){if(n.length===0)return[];let f=["Foreground runs:"],$=[...n].sort((j,T)=>T.updatedAt-j.updatedAt);for(let j of $){let T=Tn({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}}:{}}),J=j.currentAgent?` | ${j.currentAgent}${j.currentIndex!==void 0?` #${j.currentIndex}`:""}`:"";f.push(`- ${j.runId} | running | ${Q$(j)}${J}${T?` | ${T}`:""}`),f.push(` status: subagent({ action: "status", id: "${j.runId}" })`),f.push(" transcript: live in the expanded foreground result; persisted session transcript appears after completion when sessions are enabled."),f.push(...v(j.nestedChildren,{indent:" ",commandHints:!0,maxLines:12}))}return f}function L$(n){if(n.length===0)return[];let f=["Async runs:"];for(let $ of n){let j=ff($),T=Tn($),J=$.cwd?U($.cwd):U($.asyncDir),A=$.pendingAppends?` | ${$.pendingAppends} pending append${$.pendingAppends===1?"":"s"}`:"";f.push(`- ${$.id} | ${$.state}${T?` | ${T}`:""} | ${$.mode} | ${j}${A} | ${J}`),f.push(` status: subagent({ action: "status", id: "${$.id}" })`),f.push(` transcript: subagent({ action: "status", id: "${$.id}", view: "transcript" })`);for(let L of $.steps){let Z=L.label?`${L.label} (${L.agent})`:L.agent,Y=L.phase?`[${L.phase}] `:"",q=Tn(L),y=e(L.model,L.thinking),g=[`${L.index}. ${Y}${Z}`,L.status,q,y].filter(Boolean);f.push(` ${g.join(" | ")}`);let V=M.join($.asyncDir,`output-${L.index}.log`);if(W.existsSync(V))f.push(` output: ${U(V)}`);if(L.sessionFile)f.push(` session: ${U(L.sessionFile)}`);if(L.status==="running"||L.recentOutput?.length||W.existsSync(V))f.push(` transcript: subagent({ action: "status", id: "${$.id}", index: ${L.index}, view: "transcript" })`);f.push(...v(L.children,{indent:" ",commandHints:!0,maxLines:12}))}let B=new Set($.steps.flatMap((L)=>L.children?.map((Z)=>Z.id)??[])),O=$.nestedChildren?.filter((L)=>!B.has(L.id))??[];if(f.push(...v(O,{indent:" ",commandHints:!0,maxLines:12})),$.error)f.push(` error: ${$.error}`);for(let L of $.nestedWarnings??[])f.push(` warning: ${L}`);let c=nf($);if(c)f.push(` output: ${U(c)}`);if($.sessionFile)f.push(` session: ${U($.sessionFile)}`)}return f}function l0(n,f={}){if(f.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 $;try{$=tn(f.asyncDirRoot??Bn,{states:["queued","running"],sessionId:f.state?.currentSessionId??void 0,resultsDir:f.resultsDir??m,kill:f.kill,now:f.now})}catch(O){return{content:[{type:"text",text:O instanceof Error?O.message:String(O)}],isError:!0,details:{mode:"management",results:[]}}}let j=f.state?[...f.state.foregroundControls.values()]:[],T=j.length+$.length;if(T===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 J=[`Subagent fleet: ${T} active`,""],A=c$(j);if(A.length)J.push(...A,"");let B=L$($);if(B.length)J.push(...B,"");return J.push("Commands:"),J.push(' Refresh fleet: subagent({ action: "status", view: "fleet" })'),J.push(' Tail run transcript: subagent({ action: "status", id: "<run-id>", view: "transcript" })'),J.push(' Tail child transcript: subagent({ action: "status", id: "<run-id>", index: 0, view: "transcript" })'),{content:[{type:"text",text:J.join(`
|
|
13
|
+
`).trimEnd()}],details:{mode:"management",results:[]}}}function q$(n,f){if(n===void 0)return;if(!Number.isInteger(n))throw Error("Transcript index must be an integer.");if(n<0||n>=f.length)throw Error(`Transcript index ${n} is out of range for ${f.length} child step${f.length===1?"":"s"}.`);return n}function X$(n,f){let $=n.steps??[],j=q$(f.index,$);if(j===void 0){if(n.state==="running"&&typeof n.currentStep==="number"&&n.currentStep>=0&&n.currentStep<$.length)j=n.currentStep;else if($.length===1)j=0}let T=j!==void 0?$[j]:void 0,J=f.index===void 0&&$.length>1?`Tip: pass index to inspect a specific child transcript (${$.map((A,B)=>`${B}=${A.agent}`).join(", ")}).`:void 0;return{index:j,step:T,hint:J}}function Y$(n,f,$){if(f===void 0||!$)return;let j=e($.model,$.thinking);return[`${n==="parallel"?"Agent":"Step"}: ${f} (${$.agent})`,$.status,Tn($),j,$.error?`error: ${$.error}`:void 0].filter(Boolean).join(" | ")}function Vn(n,f){let $=[];for(let j of f.outputPaths)$.push(`Output: ${j}`);if(f.sessionFile)$.push(`Session: ${f.sessionFile}`);if(f.eventsPath)$.push(`Events: ${f.eventsPath}`);if(f.logPath)$.push(`Log: ${f.logPath}`);if(f.resultPath)$.push(`Result: ${f.resultPath}`);if(!$.length)return;n.push("Artifacts:");for(let j of $)n.push(` ${j}`)}function An(n,f,$,j){if(n.push(`${f}${j?" (tail truncated)":""}:`),$.length===0){n.push(" (no transcript lines available yet)");return}for(let T of $)n.push(` ${T}`)}function K$(n,f,$={}){let j=Fn($.lines),T=X$(n,$),J=T.index!==void 0?M.join(f,`output-${T.index}.log`):void 0,A=A$(f,n.outputFile),B=M.join(f,`subagent-log-${n.runId}.md`),O=T.index!==void 0?jf([J,A&&J&&M.resolve(A)===M.resolve(J)?A:void 0]):jf([A]),c=T.index!==void 0?T.step?.sessionFile:n.sessionFile,L=M.join(f,"events.jsonl"),Z=[`Run: ${n.runId}`,`State: ${n.state}`,`Mode: ${n.mode}`,Y$(n.mode,T.index,T.step),T.hint].filter((V)=>Boolean(V));Vn(Z,{outputPaths:O,sessionFile:c,eventsPath:W.existsSync(L)?L:void 0,logPath:W.existsSync(B)?B:void 0});let Y=[],q=[],y="Transcript tail",g=!1;for(let V of O){let x=Af(V,j,[f],"output");if(x.error)Y.push(`Output read failed for ${x.path}: ${x.error}`);if(x.lines.length===0)continue;q=x.lines,y=`Transcript tail from ${x.path}`,g=x.truncated;break}if(q.length===0&&T.step?.recentOutput?.length)q=T.step.recentOutput.slice(-j),y="Recent output from status.json";if(q.length===0&&c){let V=Of(c,j,$.sessionRoots??[]);if(q=V.lines,Y.push(...V.warnings),q.length>0)y=`Session transcript tail from ${c}`}if(Y.length){Z.push("Warnings:");for(let V of Y)Z.push(` ${V}`)}return An(Z,y,q,g),Z.join(`
|
|
14
|
+
`)}function p0(n,f={}){if(n.asyncDir){let J=l(n.asyncDir);if(J)return K$(J,n.asyncDir,f)}let $=Fn(f.lines),j=[`Nested run: ${n.id}`,`State: ${n.state}`,n.mode?`Mode: ${n.mode}`:void 0,n.agent?`Agent: ${n.agent}`:n.agents?.length?`Agents: ${n.agents.join(", ")}`:void 0].filter((J)=>Boolean(J));if(Vn(j,{outputPaths:[],sessionFile:n.sessionFile}),!n.sessionFile)return An(j,"Transcript tail",[],!1),j.join(`
|
|
15
|
+
`);let T=Of(n.sessionFile,$,f.sessionRoots??[]);if(T.warnings.length){j.push("Warnings:");for(let J of T.warnings)j.push(` ${J}`)}return An(j,`Session transcript tail from ${n.sessionFile}`,T.lines,!1),j.join(`
|
|
16
|
+
`)}function e0(n,f,$={}){let j=Fn($.lines),T=n.runId??n.id??M.basename(f,".json"),J=Array.isArray(n.results)?n.results:n.agent?[{agent:n.agent,output:n.output,summary:n.summary,sessionFile:n.sessionFile,state:n.state,success:n.success,exitCode:n.exitCode}]:[],A=$.index;if(A!==void 0&&!Number.isInteger(A))throw Error("Transcript index must be an integer.");if(A===void 0&&J.length===1)A=0;if(A!==void 0&&(A<0||A>=J.length))throw Error(`Transcript index ${A} is out of range for ${J.length} result child${J.length===1?"":"ren"}.`);let B=A!==void 0?J[A]:void 0,O=A!==void 0?B?.output??B?.summary??(J.length===1?n.output??n.summary:void 0)??"":n.output??n.summary??"",c=O.split(/\r?\n/).slice(-j),L=B?.sessionFile??n.sessionFile,Z=[`Run: ${T}`,`State: ${n.state??(n.success?"complete":"failed")}`,A!==void 0&&B?`Child: ${A} (${B.agent??"subagent"})`:void 0,A===void 0&&J.length>1?`Tip: pass index to inspect a specific child transcript (${J.map((Y,q)=>`${q}=${Y.agent??"subagent"}`).join(", ")}).`:void 0].filter((Y)=>Boolean(Y));return Vn(Z,{outputPaths:[],sessionFile:L,resultPath:f}),An(Z,"Result transcript tail",c.filter((Y)=>Y.trim()),O.split(/\r?\n/).length>j),Z.join(`
|
|
17
|
+
`)}export{l0 as inspectSubagentFleet,p0 as formatNestedRunTranscript,K$ as formatAsyncRunTranscript,e0 as formatAsyncResultTranscript};
|