@duckmind/dm-darwin-x64 0.49.0 → 0.49.7

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.
Files changed (38) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +14 -4
  3. package/extensions/dm-subagents/src/extension/doctor.js +10 -10
  4. package/extensions/dm-subagents/src/extension/fanout-child.js +97 -97
  5. package/extensions/dm-subagents/src/extension/index.js +121 -121
  6. package/extensions/dm-subagents/src/extension/rpc.js +5 -5
  7. package/extensions/dm-subagents/src/extension/schemas.js +1 -1
  8. package/extensions/dm-subagents/src/extension/tool-description.js +2 -2
  9. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -5
  10. package/extensions/dm-subagents/src/runs/background/async-execution.js +19 -19
  11. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +9 -9
  12. package/extensions/dm-subagents/src/runs/background/async-resume.js +5 -5
  13. package/extensions/dm-subagents/src/runs/background/async-status.js +8 -8
  14. package/extensions/dm-subagents/src/runs/background/fleet-view.js +13 -13
  15. package/extensions/dm-subagents/src/runs/background/result-watcher.js +5 -5
  16. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +3 -3
  17. package/extensions/dm-subagents/src/runs/background/run-status.js +19 -19
  18. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +7 -7
  19. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +35 -35
  20. package/extensions/dm-subagents/src/runs/background/wait.js +7 -7
  21. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +32 -32
  22. package/extensions/dm-subagents/src/runs/foreground/execution.js +26 -26
  23. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +96 -96
  24. package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -1
  25. package/extensions/dm-subagents/src/runs/shared/nested-events.js +6 -6
  26. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -13
  27. package/extensions/dm-subagents/src/shared/fork-context.js +4 -4
  28. package/package.json +1 -1
  29. package/extensions/dm-caveman/LICENSE +0 -21
  30. package/extensions/dm-cli-anything/LICENSE +0 -201
  31. package/extensions/dm-goal/LICENSE +0 -21
  32. package/extensions/dm-grill-me/LICENSE +0 -21
  33. package/extensions/dm-subagents/banner.png +0 -0
  34. package/extensions/dm-tasks/LICENSE +0 -21
  35. package/extensions/dm-usage/LICENSE +0 -21
  36. package/extensions/dm-usage/insights-screenshot.png +0 -0
  37. package/extensions/dm-usage/screenshot.png +0 -0
  38. package/extensions/greedysearch-dm/LICENSE +0 -21
@@ -1,8 +1,8 @@
1
- import*as Aj from"node:fs";import*as x$ from"node:path";function o($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function n($){if(typeof $!=="number")return;return Number.isFinite($)?$:void 0}function Q$($,J){let j=o($.id);if(j)return`id:${j}`;let Q=o($.sessionId)??"no-session",Z=o($.agent)??"unknown",f=n($.timestamp),B=n($.taskIndex),W=n($.totalTasks),O=typeof $.success==="boolean"?$.success?"1":"0":"?";return["meta",Q,Z,f!==void 0?String(f):"no-ts",B!==void 0?String(B):"-",W!==void 0?String(W):"-",O,J].join(":")}function m$($,J,j){for(let[Q,Z]of $.entries())if(J-Z>j)$.delete(Q)}function f$($,J,j,Q){if(m$($,j,Q),$.has(J))return!0;return $.set(J,j),!1}var c$={setTimeout:($,J)=>setTimeout($,J),clearTimeout:($)=>clearTimeout($)};function X$($,J,j=c$){let Q=new Map;return{schedule(Z,f=J){if(Q.has(Z))return!1;let B=j.setTimeout(()=>{Q.delete(Z),$(Z)},f);return Q.set(Z,B),!0},clear(){for(let Z of Q.values())j.clearTimeout(Z);Q.clear()}}}import*as b from"node:os";import*as R from"node:path";var B$="subagent:async-complete";var W$="subagent:result-intercom",Y$="subagent:result-intercom-delivery";function w($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function h$($){let J=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let B of["USERNAME","USER","LOGNAME"]){let W=J[B];if(W)return`user-${w(W)}`}let Q=$&&Object.hasOwn($,"userInfo")?$.userInfo:b.userInfo;try{let B=Q?.().username;if(B)return`user-${w(B)}`}catch{}let Z=J.USERPROFILE??J.HOME;if(Z)return`home-${w(Z)}`;let f=$&&Object.hasOwn($,"homedir")?$.homedir:b.homedir;try{let B=f?.();if(B)return`home-${w(B)}`}catch{}return"shared"}var S=R.join(b.tmpdir(),`dm-subagents-${h$()}`),o$=R.join(S,"async-subagent-results"),n$=R.join(S,"async-subagent-runs"),d$=R.join(S,"chain-runs"),bj=R.join(S,"artifacts");import{randomUUID as p$}from"node:crypto";import*as K$ from"node:fs";function O$($){if($.detached)return"detached";if($.interrupted||$.state==="paused")return"paused";if(typeof $.success==="boolean")return $.success?"completed":"failed";if($.state==="complete")return"completed";if($.state==="failed")return"failed";if(typeof $.exitCode==="number")return $.exitCode===0?"completed":"failed";return"failed"}function p($){let J={completed:0,failed:0,paused:0,detached:0};for(let j of $)J[j.status]+=1;return J}function q$($){let J=[$.completed?`${$.completed} completed`:void 0,$.failed?`${$.failed} failed`:void 0,$.paused?`${$.paused} paused`:void 0,$.detached?`${$.detached} detached`:void 0].filter((j)=>Boolean(j));return J.length?J.join(", "):"0 results"}function u$($){let J=p($);if(J.failed>0)return"failed";if(J.paused>0)return"paused";if(J.completed>0)return"completed";if(J.detached>0)return"detached";return"failed"}function d($,J=0){return{id:$.id,parentRunId:$.parentRunId,...$.parentStepIndex!==void 0?{parentStepIndex:$.parentStepIndex}:{},...$.parentAgent?{parentAgent:$.parentAgent}:{},depth:$.depth,path:$.path.slice(0,4).map((j)=>({runId:j.runId,...j.stepIndex!==void 0?{stepIndex:j.stepIndex}:{},...j.agent?{agent:j.agent}:{}})),...$.asyncDir?{asyncDir:$.asyncDir}:{},...$.sessionId?{sessionId:$.sessionId}:{},...$.sessionFile?{sessionFile:$.sessionFile}:{},...$.intercomTarget?{intercomTarget:$.intercomTarget}:{},...$.ownerIntercomTarget?{ownerIntercomTarget:$.ownerIntercomTarget}:{},...$.leafIntercomTarget?{leafIntercomTarget:$.leafIntercomTarget}:{},...$.ownerState?{ownerState:$.ownerState}:{},...$.mode?{mode:$.mode}:{},state:$.state,...$.agent?{agent:$.agent}:{},...$.agents?.length?{agents:$.agents.slice(0,12)}:{},...$.currentStep!==void 0?{currentStep:$.currentStep}:{},...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.parallelGroups?.length?{parallelGroups:$.parallelGroups.slice(0,8)}:{},...$.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}:{},...$.startedAt!==void 0?{startedAt:$.startedAt}:{},...$.endedAt!==void 0?{endedAt:$.endedAt}:{},...$.lastUpdate!==void 0?{lastUpdate:$.lastUpdate}:{},...$.error?{error:$.error}:{},...$.steps?.length?{steps:$.steps.slice(0,12).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<2&&j.children?.length?{children:j.children.slice(0,8).map((Q)=>d(Q,J+1))}:{}}))}:{},...J<2&&$.children?.length?{children:$.children.slice(0,8).map((j)=>d(j,J+1))}:{}}}function C($){if(!$?.length)return;return $.slice(0,16).map((J)=>d(J))}function H$($,J,j){let Q=C(j);if(!Q?.length)return J.map((Z)=>({...Z,children:C(Z.children)}));return J.map((Z,f)=>{let B=Z.index??f,W=new Set(Z.children?.map((U)=>U.id)??[]),O=Q.filter((U)=>U.parentRunId===$&&U.parentStepIndex===B&&!W.has(U.id)),L=J.length===1?Q.filter((U)=>U.parentRunId===$&&U.parentStepIndex===void 0&&!W.has(U.id)):[],M=C([...Z.children??[],...O,...L]);return M?.length?{...Z,children:M}:{...Z,children:void 0}})}function r$($){if(!$?.length)return[];let J=["Nested subagents:"],j=10,Q=(Z,f)=>{for(let B of Z??[]){if(j<=0){J.push(`${f}↳ +more nested runs; inspect status for full tree`);return}j--;let W=B.agent??B.agents?.join("+")??B.id;if(J.push(`${f}↳ ${W} — ${B.state} [${B.id}]`),B.sessionFile)J.push(`${f} Session: ${B.sessionFile}`);Q(B.children,`${f} `);for(let O of B.steps??[])Q(O.children,`${f} `)}};return Q($,""),J}function l$($){if($.source!=="async"||!$.asyncId)return;let J=$.children.filter((j)=>typeof j.sessionPath==="string"&&K$.existsSync(j.sessionPath));if($.children.length===1&&J.length===1)return`Revive: subagent({ action: "resume", id: "${$.asyncId}", message: "..." })`;if(J.length>0){let j=J[0]?.index??$.children.indexOf(J[0]);return`Revive child: subagent({ action: "resume", id: "${$.asyncId}", index: ${j}, message: "..." })`}return"Resume: unavailable; no child session file was persisted."}function i$($){let J=p($.children),j=["subagent results","",`Run: ${$.runId}`,`Mode: ${$.mode}`,`Status: ${$.status}`,`Children: ${q$(J)}`];if($.mode==="chain"&&typeof $.chainSteps==="number")j.push(`Chain steps: ${$.chainSteps}`);if($.asyncId)j.push(`Async id: ${$.asyncId}`);if($.asyncDir)j.push(`Async dir: ${$.asyncDir}`);let Q=l$($);if(Q)j.push(Q);if($.children.some((Z)=>Z.intercomTarget))j.push(""),j.push($.source==="async"?"Previous intercom targets below identify child sessions used while they were running. Inspect artifacts or session logs if resume is unavailable.":"Intercom targets below identify child sessions used while they were running; completed child sessions may no longer be reachable. Inspect artifacts or session logs for follow-up.");for(let Z=0;Z<$.children.length;Z++){let f=$.children[Z];if(j.push(""),j.push(`${Z+1}. ${f.agent} — ${f.status}`),f.intercomTarget)j.push(`${$.source==="async"?"Previous intercom target":"Run intercom target"}: ${f.intercomTarget}`);if(f.artifactPath)j.push(`Output artifact: ${f.artifactPath}`);if(f.sessionPath)j.push(`Session: ${f.sessionPath}`);j.push(...r$(f.children)),j.push("Summary:"),j.push(f.summary)}return j.join(`
2
- `)}function U$($){let J=$.children.map((B)=>({...B,summary:B.summary.trim()||"(no output)",children:C(B.children)})),j=u$(J),Q=q$(p(J)),Z=J[0],f={to:$.to,runId:$.runId,mode:$.mode,status:j,summary:Q,source:$.source,children:J,...$.asyncId?{asyncId:$.asyncId}:{},...$.asyncDir?{asyncDir:$.asyncDir}:{},...typeof $.chainSteps==="number"?{chainSteps:$.chainSteps}:{},...Z?.agent?{agent:Z.agent}:{},...Z?.index!==void 0?{index:Z.index}:{},...Z?.artifactPath?{artifactPath:Z.artifactPath}:{},...Z?.sessionPath?{sessionPath:Z.sessionPath}:{},message:""};return f.message=i$(f),f}async function G$($,J,j=500){return s$($,J.to,J.message,j,J)}async function s$($,J,j,Q=500,Z={}){if(typeof $.on!=="function"||typeof $.emit!=="function")return!1;let f=typeof Z.requestId==="string"?Z.requestId:p$();return new Promise((B)=>{let W=!1,O,L,M=(U)=>{if(W)return;if(W=!0,L)clearTimeout(L);O?.(),B(U)};O=$.on(Y$,(U)=>{if(!U||typeof U!=="object")return;let y=U;if(y.requestId!==f)return;M(y.delivered===!0)}),L=setTimeout(()=>M(!1),Q);try{$.emit(W$,{...Z,to:J,message:j,requestId:f})}catch{M(!1)}})}import*as F from"node:fs";import*as G from"node:path";import*as L$ from"node:path";var a$=128,e$=4;function u($){return typeof $==="string"&&$.length>0&&$.length<=a$&&!L$.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function M$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function V$($,J){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function F$($){if(!Array.isArray($))return[];return $.map((J)=>{if(!J||typeof J!=="object")return;let j=J;if(!u(j.runId))return;return{runId:j.runId,...M$(j.stepIndex)!==void 0?{stepIndex:M$(j.stepIndex)}:{},...V$(j.agent,128)?{agent:V$(j.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,e$)}import*as I from"node:path";import{fileURLToPath as T$}from"node:url";import*as z from"node:os";import*as T from"node:path";var Z0=T.join(z.homedir(),".config","mcp","mcp.json"),Q0={cursor:[T.join(z.homedir(),".cursor","mcp.json")],"claude-code":[T.join(z.homedir(),".claude","mcp.json"),T.join(z.homedir(),".claude.json"),T.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[T.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[T.join(z.homedir(),".codex","config.json")],windsurf:[T.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as B0}from"typebox/compile";var A0=I.join(I.dirname(T$(import.meta.url)),"subagent-prompt-runtime.ts"),_0=I.join(I.dirname(T$(import.meta.url)),"..","..","extension","fanout-child.ts");import*as Jj from"node:fs";import*as E from"node:path";var Zj=[10,25,50,100,200,500,1000,2000,4000],Qj=new Set(["EACCES","EBUSY","EPERM"]),z$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,A$=z$?new Int32Array(z$):void 0;function fj($){if($<=0)return;if(A$)try{Atomics.wait(A$,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function Xj($){let J=$?.code;return typeof J==="string"&&Qj.has(J)}function Bj($,J,j,Q,Z){for(let f=0;;f++)try{$.renameSync(J,j);return}catch(B){let W=Q[f];if(W===void 0||!Xj(B))throw B;Z(W)}}function Wj($={}){let J=$.fs??Jj,j=$.now??Date.now,Q=$.pid??process.pid,Z=$.random??Math.random,B=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??Zj:[],W=$.wait??fj;return(O,L)=>{J.mkdirSync(E.dirname(O),{recursive:!0});let M=E.join(E.dirname(O),`.${E.basename(O)}.${Q}.${j()}.${Z().toString(36).slice(2)}.tmp`);try{J.writeFileSync(M,JSON.stringify(L,null,2),"utf-8"),Bj(J,M,O,B,W)}finally{J.rmSync(M,{force:!0})}}}var _$=Wj();var k=G.join(S,"nested-subagent-events"),Yj="route.json",Kj="registry.json",y$=65536,S$=12,g=16,r=3;function v($){return u($)}function Oj($,J){if(!v(J))throw Error(`${$} must be a non-empty safe id token.`)}function l($,J){Oj($,J)}function i($,J){let j=G.resolve($),Q=G.resolve(J);return Q===j||Q.startsWith(`${j}${G.sep}`)}function b$($){return G.dirname(G.resolve($.eventSink))}function s($){if(l("rootRunId",$.rootRunId),l("capabilityToken",$.capabilityToken),!i(k,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!i(k,$.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 X($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function K($,J=512){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function qj($){if(!$||typeof $!=="object")return;let J=$,j=X(J.input),Q=X(J.output),Z=X(J.total);return j!==void 0&&Q!==void 0&&Z!==void 0?{input:j,output:Q,total:Z}:void 0}function Hj($){if(!$||typeof $!=="object")return;let J=$,j=X(J.inputTokens),Q=X(J.outputTokens),Z=X(J.costUsd);return j!==void 0&&Q!==void 0&&Z!==void 0?{inputTokens:j,outputTokens:Q,costUsd:Z}:void 0}function m($){if(!$||typeof $!=="object")return;let J=$,j=X(J.maxTurns),Q=X(J.graceTurns),Z=X(J.turnCount),f=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if(j===void 0||Q===void 0||Z===void 0||!f)return;return{maxTurns:j,graceTurns:Q,turnCount:Z,outcome:f,...X(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:X(J.wrapUpRequestedAtTurn)}:{},...X(J.exceededAtTurn)!==void 0?{exceededAtTurn:X(J.exceededAtTurn)}:{}}}function Uj($,J){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:J}function Gj($,J){if(!$||typeof $!=="object")return;let j=$,Q=K(j.agent,128);if(!Q)return;let Z=j.status==="pending"||j.status==="running"||j.status==="complete"||j.status==="completed"||j.status==="failed"||j.status==="paused"?j.status:"pending";return{agent:Q,status:Z,...K(j.sessionFile,2048)?{sessionFile:K(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...K(j.currentTool,128)?{currentTool:K(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...K(j.currentPath,2048)?{currentPath:K(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...K(j.error,1024)?{error:K(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...m(j.turnBudget)?{turnBudget:m(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<r&&Array.isArray(j.children)?{children:j.children.map((f)=>D(f,J+1)).filter((f)=>Boolean(f)).slice(0,g)}:{}}}function D($,J=0){if(!$||typeof $!=="object")return;let j=$;if(!v(j.id)||!v(j.parentRunId))return;let Q=F$(j.path),Z=Array.isArray(j.steps)?j.steps.map((W)=>Gj(W,J+1)).filter((W)=>Boolean(W)).slice(0,S$):void 0,f=qj(j.totalTokens),B=Hj(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...X(j.parentStepIndex)!==void 0?{parentStepIndex:X(j.parentStepIndex)}:{},...K(j.parentAgent,128)?{parentAgent:K(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,X(j.depth)??0),r),path:Q,state:Uj(j.state,"running"),...K(j.asyncDir,2048)?{asyncDir:K(j.asyncDir,2048)}:{},...X(j.pid)!==void 0&&X(j.pid)>0&&Number.isInteger(X(j.pid))?{pid:X(j.pid)}:{},...K(j.sessionId,256)?{sessionId:K(j.sessionId,256)}:{},...K(j.sessionFile,2048)?{sessionFile:K(j.sessionFile,2048)}:{},...K(j.intercomTarget,256)?{intercomTarget:K(j.intercomTarget,256)}:{},...K(j.ownerIntercomTarget,256)?{ownerIntercomTarget:K(j.ownerIntercomTarget,256)}:{},...K(j.leafIntercomTarget,256)?{leafIntercomTarget:K(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...K(j.controlInbox,2048)?{controlInbox:K(j.controlInbox,2048)}:{},...K(j.capabilityToken,128)?{capabilityToken:K(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...K(j.agent,128)?{agent:K(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((W)=>K(W,128)).filter((W)=>Boolean(W)).slice(0,S$)}:{},...X(j.currentStep)!==void 0?{currentStep:X(j.currentStep)}:{},...X(j.chainStepCount)!==void 0?{chainStepCount:X(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...X(j.lastActivityAt)!==void 0?{lastActivityAt:X(j.lastActivityAt)}:{},...K(j.currentTool,128)?{currentTool:K(j.currentTool,128)}:{},...X(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:X(j.currentToolStartedAt)}:{},...K(j.currentPath,2048)?{currentPath:K(j.currentPath,2048)}:{},...X(j.turnCount)!==void 0?{turnCount:X(j.turnCount)}:{},...X(j.toolCount)!==void 0?{toolCount:X(j.toolCount)}:{},...f?{totalTokens:f}:{},...B?{totalCost:B}:{},...X(j.startedAt)!==void 0?{startedAt:X(j.startedAt)}:{},...X(j.endedAt)!==void 0?{endedAt:X(j.endedAt)}:{},...X(j.lastUpdate)!==void 0?{lastUpdate:X(j.lastUpdate)}:{},...X(j.timeoutMs)!==void 0?{timeoutMs:X(j.timeoutMs)}:{},...X(j.deadlineAt)!==void 0?{deadlineAt:X(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...m(j.turnBudget)?{turnBudget:m(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...K(j.error,1024)?{error:K(j.error,1024)}:{},...Z&&Z.length>0?{steps:Z}:{},...J<r&&Array.isArray(j.children)?{children:j.children.map((W)=>D(W,J+1)).filter((W)=>Boolean(W)).slice(0,g)}:{}}}function C$($,J){if(Buffer.byteLength($,"utf-8")>y$)return;let j;try{j=JSON.parse($)}catch{return}if(!j||typeof j!=="object")return;let Q=j;if(Q.type!=="subagent.nested.started"&&Q.type!=="subagent.nested.updated"&&Q.type!=="subagent.nested.completed")return;if(Q.rootRunId!==J.rootRunId||Q.capabilityToken!==J.capabilityToken)return;if(!v(Q.parentRunId))return;let Z=X(Q.ts);if(Z===void 0)return;let f=D(Q.child);if(!f||f.id===J.rootRunId)return;let B={...f,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:f.ownerState??"unknown"};return{type:Q.type,ts:Z,rootRunId:J.rootRunId,parentRunId:Q.parentRunId,...X(Q.parentStepIndex)!==void 0?{parentStepIndex:X(Q.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:B}}function Mj($,J){if(!$.includes(`
3
- `)){let j=C$($.trim(),J);return j?[j]:[]}return $.split(`
1
+ import*as Sj from"node:fs";import*as w$ from"node:path";function n($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function d($){if(typeof $!=="number")return;return Number.isFinite($)?$:void 0}function X$($,J){let j=n($.id);if(j)return`id:${j}`;let Z=n($.sessionId)??"no-session",Q=n($.agent)??"unknown",X=d($.timestamp),B=d($.taskIndex),f=d($.totalTasks),O=typeof $.success==="boolean"?$.success?"1":"0":"?";return["meta",Z,Q,X!==void 0?String(X):"no-ts",B!==void 0?String(B):"-",f!==void 0?String(f):"-",O,J].join(":")}function c$($,J,j){for(let[Z,Q]of $.entries())if(J-Q>j)$.delete(Z)}function B$($,J,j,Z){if(c$($,j,Z),$.has(J))return!0;return $.set(J,j),!1}var h$={setTimeout:($,J)=>setTimeout($,J),clearTimeout:($)=>clearTimeout($)};function W$($,J,j=h$){let Z=new Map;return{schedule(Q,X=J){if(Z.has(Q))return!1;let B=j.setTimeout(()=>{Z.delete(Q),$(Q)},X);return Z.set(Q,B),!0},clear(){for(let Q of Z.values())j.clearTimeout(Q);Z.clear()}}}import*as R from"node:os";import*as I from"node:path";var f$="subagent:async-complete";var Y$="subagent:result-intercom",K$="subagent:result-intercom-delivery";function P($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function o$($){let J=$?.env??process.env,j=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof j==="function")return`uid-${j()}`;for(let B of["USERNAME","USER","LOGNAME"]){let f=J[B];if(f)return`user-${P(f)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:R.userInfo;try{let B=Z?.().username;if(B)return`user-${P(B)}`}catch{}let Q=J.USERPROFILE??J.HOME;if(Q)return`home-${P(Q)}`;let X=$&&Object.hasOwn($,"homedir")?$.homedir:R.homedir;try{let B=X?.();if(B)return`home-${P(B)}`}catch{}return"shared"}var C=I.join(R.tmpdir(),`dm-subagents-${o$()}`),n$=I.join(C,"async-subagent-results"),d$=I.join(C,"async-subagent-runs"),p$=I.join(C,"chain-runs"),Ij=I.join(C,"artifacts");import{randomUUID as u$}from"node:crypto";import*as O$ from"node:fs";function q$($){if($.detached)return"detached";if($.interrupted||$.state==="paused")return"paused";if(typeof $.success==="boolean")return $.success?"completed":"failed";if($.state==="complete")return"completed";if($.state==="failed")return"failed";if(typeof $.exitCode==="number")return $.exitCode===0?"completed":"failed";return"failed"}function u($){let J={completed:0,failed:0,paused:0,detached:0};for(let j of $)J[j.status]+=1;return J}function H$($){let J=[$.completed?`${$.completed} completed`:void 0,$.failed?`${$.failed} failed`:void 0,$.paused?`${$.paused} paused`:void 0,$.detached?`${$.detached} detached`:void 0].filter((j)=>Boolean(j));return J.length?J.join(", "):"0 results"}function r$($){let J=u($);if(J.failed>0)return"failed";if(J.paused>0)return"paused";if(J.completed>0)return"completed";if(J.detached>0)return"detached";return"failed"}function p($,J=0){return{id:$.id,parentRunId:$.parentRunId,...$.parentStepIndex!==void 0?{parentStepIndex:$.parentStepIndex}:{},...$.parentAgent?{parentAgent:$.parentAgent}:{},depth:$.depth,path:$.path.slice(0,4).map((j)=>({runId:j.runId,...j.stepIndex!==void 0?{stepIndex:j.stepIndex}:{},...j.agent?{agent:j.agent}:{}})),...$.asyncDir?{asyncDir:$.asyncDir}:{},...$.sessionId?{sessionId:$.sessionId}:{},...$.sessionFile?{sessionFile:$.sessionFile}:{},...$.intercomTarget?{intercomTarget:$.intercomTarget}:{},...$.ownerIntercomTarget?{ownerIntercomTarget:$.ownerIntercomTarget}:{},...$.leafIntercomTarget?{leafIntercomTarget:$.leafIntercomTarget}:{},...$.ownerState?{ownerState:$.ownerState}:{},...$.mode?{mode:$.mode}:{},state:$.state,...$.agent?{agent:$.agent}:{},...$.agents?.length?{agents:$.agents.slice(0,12)}:{},...$.currentStep!==void 0?{currentStep:$.currentStep}:{},...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.parallelGroups?.length?{parallelGroups:$.parallelGroups.slice(0,8)}:{},...$.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}:{},...$.startedAt!==void 0?{startedAt:$.startedAt}:{},...$.endedAt!==void 0?{endedAt:$.endedAt}:{},...$.lastUpdate!==void 0?{lastUpdate:$.lastUpdate}:{},...$.error?{error:$.error}:{},...$.steps?.length?{steps:$.steps.slice(0,12).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<2&&j.children?.length?{children:j.children.slice(0,8).map((Z)=>p(Z,J+1))}:{}}))}:{},...J<2&&$.children?.length?{children:$.children.slice(0,8).map((j)=>p(j,J+1))}:{}}}function E($){if(!$?.length)return;return $.slice(0,16).map((J)=>p(J))}function G$($,J,j){let Z=E(j);if(!Z?.length)return J.map((Q)=>({...Q,children:E(Q.children)}));return J.map((Q,X)=>{let B=Q.index??X,f=new Set(Q.children?.map((G)=>G.id)??[]),O=Z.filter((G)=>G.parentRunId===$&&G.parentStepIndex===B&&!f.has(G.id)),L=J.length===1?Z.filter((G)=>G.parentRunId===$&&G.parentStepIndex===void 0&&!f.has(G.id)):[],M=E([...Q.children??[],...O,...L]);return M?.length?{...Q,children:M}:{...Q,children:void 0}})}function l$($){if(!$?.length)return[];let J=["Nested subagents:"],j=10,Z=(Q,X)=>{for(let B of Q??[]){if(j<=0){J.push(`${X}↳ +more nested runs; inspect status for full tree`);return}j--;let f=B.agent??B.agents?.join("+")??B.id;if(J.push(`${X}↳ ${f} — ${B.state} [${B.id}]`),B.sessionFile)J.push(`${X} Session: ${B.sessionFile}`);Z(B.children,`${X} `);for(let O of B.steps??[])Z(O.children,`${X} `)}};return Z($,""),J}function i$($){if($.source!=="async"||!$.asyncId)return;let J=$.children.filter((j)=>typeof j.sessionPath==="string"&&O$.existsSync(j.sessionPath));if($.children.length===1&&J.length===1)return`Revive: subagent({ action: "resume", id: "${$.asyncId}", message: "..." })`;if(J.length>0){let j=J[0]?.index??$.children.indexOf(J[0]);return`Revive child: subagent({ action: "resume", id: "${$.asyncId}", index: ${j}, message: "..." })`}return"Resume: unavailable; no child session file was persisted."}function s$($){let J=u($.children),j=["subagent results","",`Run: ${$.runId}`,`Mode: ${$.mode}`,`Status: ${$.status}`,`Children: ${H$(J)}`];if($.mode==="chain"&&typeof $.chainSteps==="number")j.push(`Chain steps: ${$.chainSteps}`);if($.asyncId)j.push(`Async id: ${$.asyncId}`);if($.asyncDir)j.push(`Async dir: ${$.asyncDir}`);let Z=i$($);if(Z)j.push(Z);if($.children.some((Q)=>Q.intercomTarget))j.push(""),j.push($.source==="async"?"Previous intercom targets below identify child sessions used while they were running. Inspect artifacts or session logs if resume is unavailable.":"Intercom targets below identify child sessions used while they were running; completed child sessions may no longer be reachable. Inspect artifacts or session logs for follow-up.");for(let Q=0;Q<$.children.length;Q++){let X=$.children[Q];if(j.push(""),j.push(`${Q+1}. ${X.agent} — ${X.status}`),X.intercomTarget)j.push(`${$.source==="async"?"Previous intercom target":"Run intercom target"}: ${X.intercomTarget}`);if(X.artifactPath)j.push(`Output artifact: ${X.artifactPath}`);if(X.sessionPath)j.push(`Session: ${X.sessionPath}`);j.push(...l$(X.children)),j.push("Summary:"),j.push(X.summary)}return j.join(`
2
+ `)}function U$($){let J=$.children.map((B)=>({...B,summary:B.summary.trim()||"(no output)",children:E(B.children)})),j=r$(J),Z=H$(u(J)),Q=J[0],X={to:$.to,runId:$.runId,mode:$.mode,status:j,summary:Z,source:$.source,children:J,...$.asyncId?{asyncId:$.asyncId}:{},...$.asyncDir?{asyncDir:$.asyncDir}:{},...typeof $.chainSteps==="number"?{chainSteps:$.chainSteps}:{},...Q?.agent?{agent:Q.agent}:{},...Q?.index!==void 0?{index:Q.index}:{},...Q?.artifactPath?{artifactPath:Q.artifactPath}:{},...Q?.sessionPath?{sessionPath:Q.sessionPath}:{},message:""};return X.message=s$(X),X}async function M$($,J,j=500){return a$($,J.to,J.message,j,J)}async function a$($,J,j,Z=500,Q={}){if(typeof $.on!=="function"||typeof $.emit!=="function")return!1;let X=typeof Q.requestId==="string"?Q.requestId:u$();return new Promise((B)=>{let f=!1,O,L,M=(G)=>{if(f)return;if(f=!0,L)clearTimeout(L);O?.(),B(G)};O=$.on(K$,(G)=>{if(!G||typeof G!=="object")return;let b=G;if(b.requestId!==X)return;M(b.delivered===!0)}),L=setTimeout(()=>M(!1),Z);try{$.emit(Y$,{...Q,to:J,message:j,requestId:X})}catch{M(!1)}})}import*as F from"node:fs";import*as U from"node:path";import*as F$ from"node:path";var t$=128,e$=4;function r($){return typeof $==="string"&&$.length>0&&$.length<=t$&&!F$.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function V$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function L$($,J){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function T$($){if(!Array.isArray($))return[];return $.map((J)=>{if(!J||typeof J!=="object")return;let j=J;if(!r(j.runId))return;return{runId:j.runId,...V$(j.stepIndex)!==void 0?{stepIndex:V$(j.stepIndex)}:{},...L$(j.agent,128)?{agent:L$(j.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,e$)}import*as D from"node:fs";import*as z from"node:path";import{fileURLToPath as Zj}from"node:url";import*as A from"node:os";import*as T from"node:path";var X0=T.join(A.homedir(),".config","mcp","mcp.json"),B0={cursor:[T.join(A.homedir(),".cursor","mcp.json")],"claude-code":[T.join(A.homedir(),".claude","mcp.json"),T.join(A.homedir(),".claude.json"),T.join(A.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[T.join(A.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[T.join(A.homedir(),".codex","config.json")],windsurf:[T.join(A.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Y0}from"typebox/compile";function z$($,J){let j=Zj($),Z=z.extname(j),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts",X=z.dirname(j);while(!D.existsSync(z.join(X,"package.json"))){let B=z.dirname(X);if(B===X)throw Error(`Unable to resolve dm-subagents package root from ${j}`);X=B}return z.join(X,`${J}${Q}`)}var S0=z$(import.meta.url,z.join("src","runs","shared","subagent-prompt-runtime")),C0=z$(import.meta.url,z.join("src","extension","fanout-child"));import*as Qj from"node:fs";import*as y from"node:path";var Xj=[10,25,50,100,200,500,1000,2000,4000],Bj=new Set(["EACCES","EBUSY","EPERM"]),A$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,_$=A$?new Int32Array(A$):void 0;function Wj($){if($<=0)return;if(_$)try{Atomics.wait(_$,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function fj($){let J=$?.code;return typeof J==="string"&&Bj.has(J)}function Yj($,J,j,Z,Q){for(let X=0;;X++)try{$.renameSync(J,j);return}catch(B){let f=Z[X];if(f===void 0||!fj(B))throw B;Q(f)}}function Kj($={}){let J=$.fs??Qj,j=$.now??Date.now,Z=$.pid??process.pid,Q=$.random??Math.random,B=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??Xj:[],f=$.wait??Wj;return(O,L)=>{J.mkdirSync(y.dirname(O),{recursive:!0});let M=y.join(y.dirname(O),`.${y.basename(O)}.${Z}.${j()}.${Q().toString(36).slice(2)}.tmp`);try{J.writeFileSync(M,JSON.stringify(L,null,2),"utf-8"),Yj(J,M,O,B,f)}finally{J.rmSync(M,{force:!0})}}}var S$=Kj();var g=U.join(C,"nested-subagent-events"),Oj="route.json",qj="registry.json",b$=65536,C$=12,v=16,l=3;function m($){return r($)}function Hj($,J){if(!m(J))throw Error(`${$} must be a non-empty safe id token.`)}function i($,J){Hj($,J)}function s($,J){let j=U.resolve($),Z=U.resolve(J);return Z===j||Z.startsWith(`${j}${U.sep}`)}function R$($){return U.dirname(U.resolve($.eventSink))}function a($){if(i("rootRunId",$.rootRunId),i("capabilityToken",$.capabilityToken),!s(g,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!s(g,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(R$($)!==U.dirname(U.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function W($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function K($,J=512){return typeof $==="string"&&$.length>0?$.slice(0,J):void 0}function Gj($){if(!$||typeof $!=="object")return;let J=$,j=W(J.input),Z=W(J.output),Q=W(J.total);return j!==void 0&&Z!==void 0&&Q!==void 0?{input:j,output:Z,total:Q}:void 0}function Uj($){if(!$||typeof $!=="object")return;let J=$,j=W(J.inputTokens),Z=W(J.outputTokens),Q=W(J.costUsd);return j!==void 0&&Z!==void 0&&Q!==void 0?{inputTokens:j,outputTokens:Z,costUsd:Q}:void 0}function c($){if(!$||typeof $!=="object")return;let J=$,j=W(J.maxTurns),Z=W(J.graceTurns),Q=W(J.turnCount),X=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if(j===void 0||Z===void 0||Q===void 0||!X)return;return{maxTurns:j,graceTurns:Z,turnCount:Q,outcome:X,...W(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:W(J.wrapUpRequestedAtTurn)}:{},...W(J.exceededAtTurn)!==void 0?{exceededAtTurn:W(J.exceededAtTurn)}:{}}}function Mj($,J){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:J}function Vj($,J){if(!$||typeof $!=="object")return;let j=$,Z=K(j.agent,128);if(!Z)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:Z,status:Q,...K(j.sessionFile,2048)?{sessionFile:K(j.sessionFile,2048)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...W(j.lastActivityAt)!==void 0?{lastActivityAt:W(j.lastActivityAt)}:{},...K(j.currentTool,128)?{currentTool:K(j.currentTool,128)}:{},...W(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:W(j.currentToolStartedAt)}:{},...K(j.currentPath,2048)?{currentPath:K(j.currentPath,2048)}:{},...W(j.turnCount)!==void 0?{turnCount:W(j.turnCount)}:{},...W(j.toolCount)!==void 0?{toolCount:W(j.toolCount)}:{},...W(j.startedAt)!==void 0?{startedAt:W(j.startedAt)}:{},...W(j.endedAt)!==void 0?{endedAt:W(j.endedAt)}:{},...K(j.error,1024)?{error:K(j.error,1024)}:{},...j.timedOut===!0?{timedOut:!0}:{},...c(j.turnBudget)?{turnBudget:c(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<l&&Array.isArray(j.children)?{children:j.children.map((X)=>N(X,J+1)).filter((X)=>Boolean(X)).slice(0,v)}:{}}}function N($,J=0){if(!$||typeof $!=="object")return;let j=$;if(!m(j.id)||!m(j.parentRunId))return;let Z=T$(j.path),Q=Array.isArray(j.steps)?j.steps.map((f)=>Vj(f,J+1)).filter((f)=>Boolean(f)).slice(0,C$):void 0,X=Gj(j.totalTokens),B=Uj(j.totalCost);return{id:j.id,parentRunId:j.parentRunId,...W(j.parentStepIndex)!==void 0?{parentStepIndex:W(j.parentStepIndex)}:{},...K(j.parentAgent,128)?{parentAgent:K(j.parentAgent,128)}:{},depth:Math.min(Math.max(0,W(j.depth)??0),l),path:Z,state:Mj(j.state,"running"),...K(j.asyncDir,2048)?{asyncDir:K(j.asyncDir,2048)}:{},...W(j.pid)!==void 0&&W(j.pid)>0&&Number.isInteger(W(j.pid))?{pid:W(j.pid)}:{},...K(j.sessionId,256)?{sessionId:K(j.sessionId,256)}:{},...K(j.sessionFile,2048)?{sessionFile:K(j.sessionFile,2048)}:{},...K(j.intercomTarget,256)?{intercomTarget:K(j.intercomTarget,256)}:{},...K(j.ownerIntercomTarget,256)?{ownerIntercomTarget:K(j.ownerIntercomTarget,256)}:{},...K(j.leafIntercomTarget,256)?{leafIntercomTarget:K(j.leafIntercomTarget,256)}:{},...j.ownerState==="live"||j.ownerState==="gone"||j.ownerState==="unknown"?{ownerState:j.ownerState}:{},...K(j.controlInbox,2048)?{controlInbox:K(j.controlInbox,2048)}:{},...K(j.capabilityToken,128)?{capabilityToken:K(j.capabilityToken,128)}:{},...j.mode==="single"||j.mode==="parallel"||j.mode==="chain"?{mode:j.mode}:{},...K(j.agent,128)?{agent:K(j.agent,128)}:{},...Array.isArray(j.agents)?{agents:j.agents.map((f)=>K(f,128)).filter((f)=>Boolean(f)).slice(0,C$)}:{},...W(j.currentStep)!==void 0?{currentStep:W(j.currentStep)}:{},...W(j.chainStepCount)!==void 0?{chainStepCount:W(j.chainStepCount)}:{},...j.activityState==="active_long_running"||j.activityState==="needs_attention"?{activityState:j.activityState}:{},...W(j.lastActivityAt)!==void 0?{lastActivityAt:W(j.lastActivityAt)}:{},...K(j.currentTool,128)?{currentTool:K(j.currentTool,128)}:{},...W(j.currentToolStartedAt)!==void 0?{currentToolStartedAt:W(j.currentToolStartedAt)}:{},...K(j.currentPath,2048)?{currentPath:K(j.currentPath,2048)}:{},...W(j.turnCount)!==void 0?{turnCount:W(j.turnCount)}:{},...W(j.toolCount)!==void 0?{toolCount:W(j.toolCount)}:{},...X?{totalTokens:X}:{},...B?{totalCost:B}:{},...W(j.startedAt)!==void 0?{startedAt:W(j.startedAt)}:{},...W(j.endedAt)!==void 0?{endedAt:W(j.endedAt)}:{},...W(j.lastUpdate)!==void 0?{lastUpdate:W(j.lastUpdate)}:{},...W(j.timeoutMs)!==void 0?{timeoutMs:W(j.timeoutMs)}:{},...W(j.deadlineAt)!==void 0?{deadlineAt:W(j.deadlineAt)}:{},...j.timedOut===!0?{timedOut:!0}:{},...c(j.turnBudget)?{turnBudget:c(j.turnBudget)}:{},...j.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...j.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...K(j.error,1024)?{error:K(j.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...J<l&&Array.isArray(j.children)?{children:j.children.map((f)=>N(f,J+1)).filter((f)=>Boolean(f)).slice(0,v)}:{}}}function E$($,J){if(Buffer.byteLength($,"utf-8")>b$)return;let j;try{j=JSON.parse($)}catch{return}if(!j||typeof j!=="object")return;let Z=j;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==J.rootRunId||Z.capabilityToken!==J.capabilityToken)return;if(!m(Z.parentRunId))return;let Q=W(Z.ts);if(Q===void 0)return;let X=N(Z.child);if(!X||X.id===J.rootRunId)return;let B={...X,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:X.ownerState??"unknown"};return{type:Z.type,ts:Q,rootRunId:J.rootRunId,parentRunId:Z.parentRunId,...W(Z.parentStepIndex)!==void 0?{parentStepIndex:W(Z.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:B}}function Lj($,J){if(!$.includes(`
3
+ `)){let j=E$($.trim(),J);return j?[j]:[]}return $.split(`
4
4
  `).slice(0,$.endsWith(`
5
- `)?void 0:-1).map((j)=>j.trim()?C$(j,J):void 0).filter((j)=>Boolean(j))}function P($){return $==="complete"||$==="failed"||$==="paused"}function E$($,J){let j=J.type==="subagent.nested.completed"&&J.child.state==="running"?"complete":J.child.state,Q={...J.child,state:j,lastUpdate:J.child.lastUpdate??J.ts};if(!$)return Q;let Z=$.lastUpdate??0,f=Q.lastUpdate??J.ts;if(f<Z)return $;if(P($.state)&&!P(Q.state))return $;if(P($.state)&&P(Q.state)&&f===Z)return $;return{...$,...Q,state:Q.state,lastUpdate:Math.max(Z,f)}}function Vj($,J){let j=!1,Q=(W)=>W.map((O)=>{if(O.id===J.parentRunId){let M=O.children??[],U=M.findIndex((V)=>V.id===J.child.id),y=E$(U>=0?M[U]:void 0,J),q=U>=0?M.map((V,Y)=>Y===U?y:V):[...M,y];return j=!0,{...O,children:q.slice(0,g),lastUpdate:Math.max(O.lastUpdate??0,J.ts)}}if(!O.children?.length)return O;let L=Q(O.children);return L===O.children?O:{...O,children:L}}),Z=Q($);if(j)return Z;let f=Z.findIndex((W)=>W.id===J.child.id),B=E$(f>=0?Z[f]:void 0,J);return f>=0?Z.map((W,O)=>O===f?B:W):[...Z,B].slice(0,g)}function Lj($,J){return{...$,updatedAt:Math.max($.updatedAt,J.ts),children:Vj($.children,J)}}function R$($){return G.join(b$($),Kj)}function Fj($){l("rootRunId",$);let J;try{J=F.readdirSync(k)}catch(j){if(j.code==="ENOENT")return;throw j}for(let j of J){if(!j.startsWith(`${$}-`))continue;let Q=G.join(k,j);try{let Z=JSON.parse(F.readFileSync(G.join(Q,Yj),"utf-8"));if(Z.rootRunId!==$||typeof Z.capabilityToken!=="string")continue;let f={rootRunId:$,eventSink:G.join(Q,"events"),controlInbox:G.join(Q,"controls"),capabilityToken:Z.capabilityToken};return s(f),f}catch{continue}}return}function I$($){let J=Fj($);return J?zj(J):void 0}function Tj($){s($);try{let J=JSON.parse(F.readFileSync(R$($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof J.updatedAt==="number"?J.updatedAt:0,children:Array.isArray(J.children)?J.children.map((j)=>D(j)).filter((j)=>Boolean(j)):[],processedEvents:Array.isArray(J.processedEvents)?J.processedEvents.filter((j)=>typeof j==="string"):[]}}catch(J){if(J.code!=="ENOENT")throw J;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function zj($){s($);let J=Tj($),j=new Set(J.processedEvents),Q=!1,Z=[];try{Z=F.readdirSync($.eventSink).filter((f)=>f.endsWith(".json")||f.endsWith(".jsonl")).sort()}catch(f){if(f.code!=="ENOENT")throw f}for(let f of Z){if(j.has(f))continue;let B=G.join($.eventSink,f);if(!i($.eventSink,B))continue;let W;try{let O=F.statSync(B);if(!O.isFile()||O.size>y$)continue;W=F.readFileSync(B,"utf-8")}catch{continue}for(let O of Mj(W,$))J=Lj(J,O),Q=!0;j.add(f),Q=!0}if(Q)J={...J,processedEvents:[...j].slice(-1000)},_$(R$($),J);return J}var _j=3000,Sj=3000;function D$($,J,j){if($===void 0)return;if(!Array.isArray($)){console.error(`Ignoring invalid nested children in subagent result file '${J}' at ${j}: expected an array.`);return}let Q=$.map((Z)=>D(Z)).filter((Z)=>Boolean(Z));if(Q.length!==$.length)console.error(`Ignoring ${$.length-Q.length} invalid nested child record(s) in subagent result file '${J}' at ${j}.`);return Q.length?Q:void 0}function e($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function N$($){return e($)==="ENOENT"}function a($){let J=e($);return J==="EMFILE"||J==="ENOSPC"}function Cj($,J){try{return $.realpathSync.native(J)}catch{return J}}function d0($,J,j,Q,Z={}){let f=Z.fs??Aj,B=Z.timers??{setTimeout,clearTimeout,setInterval,clearInterval},W=async(q)=>{let V=x$.join(j,q);if(!f.existsSync(V))return;try{let Y=JSON.parse(f.readFileSync(V,"utf-8"));if(typeof Y.sessionId!=="string"||Y.sessionId!==J.currentSessionId)return;let A=Y.runId??Y.id??q.replace(/\.json$/i,""),w$=Y.nestedChildren!==void 0,N=C(D$(Y.nestedChildren,V,"nestedChildren"));if(!N?.length&&!w$)try{N=C(I$(A)?.children)}catch(H){console.error(`Failed to enrich subagent result file '${V}' with nested registry children; will retry later:`,H);return}let P$=Date.now(),k$=Q$(Y,`result:${q}`);if(f$(J.completionSeen,k$,P$,Q)){f.unlinkSync(V);return}let t=Array.isArray(Y.results)&&Y.results.length>0,c=t?Y.results:[{agent:Y.agent,output:Y.summary,success:Y.success}],$$=H$(A,c.map((H={},_)=>{let x=H.output??Y.summary,J$=typeof x==="string"&&x.trim().length>0,g$=J$?x:"(no output)",v$=H.success===!1&&H.error?`${H.error}${J$?`
5
+ `)?void 0:-1).map((j)=>j.trim()?E$(j,J):void 0).filter((j)=>Boolean(j))}function k($){return $==="complete"||$==="failed"||$==="paused"}function y$($,J){let j=J.type==="subagent.nested.completed"&&J.child.state==="running"?"complete":J.child.state,Z={...J.child,state:j,lastUpdate:J.child.lastUpdate??J.ts};if(!$)return Z;let Q=$.lastUpdate??0,X=Z.lastUpdate??J.ts;if(X<Q)return $;if(k($.state)&&!k(Z.state))return $;if(k($.state)&&k(Z.state)&&X===Q)return $;return{...$,...Z,state:Z.state,lastUpdate:Math.max(Q,X)}}function Fj($,J){let j=!1,Z=(f)=>f.map((O)=>{if(O.id===J.parentRunId){let M=O.children??[],G=M.findIndex((V)=>V.id===J.child.id),b=y$(G>=0?M[G]:void 0,J),q=G>=0?M.map((V,Y)=>Y===G?b:V):[...M,b];return j=!0,{...O,children:q.slice(0,v),lastUpdate:Math.max(O.lastUpdate??0,J.ts)}}if(!O.children?.length)return O;let L=Z(O.children);return L===O.children?O:{...O,children:L}}),Q=Z($);if(j)return Q;let X=Q.findIndex((f)=>f.id===J.child.id),B=y$(X>=0?Q[X]:void 0,J);return X>=0?Q.map((f,O)=>O===X?B:f):[...Q,B].slice(0,v)}function Tj($,J){return{...$,updatedAt:Math.max($.updatedAt,J.ts),children:Fj($.children,J)}}function I$($){return U.join(R$($),qj)}function zj($){i("rootRunId",$);let J;try{J=F.readdirSync(g)}catch(j){if(j.code==="ENOENT")return;throw j}for(let j of J){if(!j.startsWith(`${$}-`))continue;let Z=U.join(g,j);try{let Q=JSON.parse(F.readFileSync(U.join(Z,Oj),"utf-8"));if(Q.rootRunId!==$||typeof Q.capabilityToken!=="string")continue;let X={rootRunId:$,eventSink:U.join(Z,"events"),controlInbox:U.join(Z,"controls"),capabilityToken:Q.capabilityToken};return a(X),X}catch{continue}}return}function D$($){let J=zj($);return J?_j(J):void 0}function Aj($){a($);try{let J=JSON.parse(F.readFileSync(I$($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof J.updatedAt==="number"?J.updatedAt:0,children:Array.isArray(J.children)?J.children.map((j)=>N(j)).filter((j)=>Boolean(j)):[],processedEvents:Array.isArray(J.processedEvents)?J.processedEvents.filter((j)=>typeof j==="string"):[]}}catch(J){if(J.code!=="ENOENT")throw J;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function _j($){a($);let J=Aj($),j=new Set(J.processedEvents),Z=!1,Q=[];try{Q=F.readdirSync($.eventSink).filter((X)=>X.endsWith(".json")||X.endsWith(".jsonl")).sort()}catch(X){if(X.code!=="ENOENT")throw X}for(let X of Q){if(j.has(X))continue;let B=U.join($.eventSink,X);if(!s($.eventSink,B))continue;let f;try{let O=F.statSync(B);if(!O.isFile()||O.size>b$)continue;f=F.readFileSync(B,"utf-8")}catch{continue}for(let O of Lj(f,$))J=Tj(J,O),Z=!0;j.add(X),Z=!0}if(Z)J={...J,processedEvents:[...j].slice(-1000)},S$(I$($),J);return J}var Cj=3000,Ej=3000;function N$($,J,j){if($===void 0)return;if(!Array.isArray($)){console.error(`Ignoring invalid nested children in subagent result file '${J}' at ${j}: expected an array.`);return}let Z=$.map((Q)=>N(Q)).filter((Q)=>Boolean(Q));if(Z.length!==$.length)console.error(`Ignoring ${$.length-Z.length} invalid nested child record(s) in subagent result file '${J}' at ${j}.`);return Z.length?Z:void 0}function e($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function x$($){return e($)==="ENOENT"}function t($){let J=e($);return J==="EMFILE"||J==="ENOSPC"}function yj($,J){try{return $.realpathSync.native(J)}catch{return J}}function u0($,J,j,Z,Q={}){let X=Q.fs??Sj,B=Q.timers??{setTimeout,clearTimeout,setInterval,clearInterval},f=async(q)=>{let V=w$.join(j,q);if(!X.existsSync(V))return;try{let Y=JSON.parse(X.readFileSync(V,"utf-8"));if(typeof Y.sessionId!=="string"||Y.sessionId!==J.currentSessionId)return;let _=Y.runId??Y.id??q.replace(/\.json$/i,""),P$=Y.nestedChildren!==void 0,x=E(N$(Y.nestedChildren,V,"nestedChildren"));if(!x?.length&&!P$)try{x=E(D$(_)?.children)}catch(H){console.error(`Failed to enrich subagent result file '${V}' with nested registry children; will retry later:`,H);return}let k$=Date.now(),g$=X$(Y,`result:${q}`);if(B$(J.completionSeen,g$,k$,Z)){X.unlinkSync(V);return}let $$=Array.isArray(Y.results)&&Y.results.length>0,h=$$?Y.results:[{agent:Y.agent,output:Y.summary,success:Y.success}],j$=G$(_,h.map((H={},S)=>{let w=H.output??Y.summary,Z$=typeof w==="string"&&w.trim().length>0,v$=Z$?w:"(no output)",m$=H.success===!1&&H.error?`${H.error}${Z$?`
6
6
 
7
7
  Output:
8
- ${x}`:""}`:g$,h=H.sessionFile??(c.length===1?Y.sessionFile:void 0),Z$=D$(H.children,V,`results[${_}].children`);return{agent:H.agent??Y.agent??`step-${_+1}`,status:O$({success:H.success,state:Y.state==="paused"||typeof H.success!=="boolean"?Y.state:void 0}),summary:v$,index:_,artifactPath:H.artifactPaths?.outputPath,...typeof h==="string"&&f.existsSync(h)?{sessionPath:h}:{},...H.intercomTarget?{intercomTarget:H.intercomTarget}:{},...Z$?{children:Z$}:{}}}),N),j$=Y.intercomTarget?.trim();if(j$){let H=Y.mode==="single"||Y.mode==="parallel"||Y.mode==="chain"?Y.mode:c.length>1?"chain":"single",_=U$({to:j$,runId:A,mode:H,source:"async",children:$$,asyncId:Y.id,asyncDir:Y.asyncDir});if(!await G$($.events,_))console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${V}'.`)}$.events.emit(B$,{...Y,runId:A,...N?.length?{nestedChildren:N}:{},...Array.isArray(Y.results)?{results:t?$$.map((H,_)=>({...Y.results[_],agent:H.agent,status:H.status,summary:H.summary,index:H.index,artifactPath:H.artifactPath,sessionPath:H.sessionPath,children:H.children})):[]}:{}}),f.unlinkSync(V)}catch(Y){if(N$(Y))return;console.error(`Failed to process subagent result file '${V}':`,Y)}};J.resultFileCoalescer=X$((q)=>{W(q)},50);let O=()=>{try{f.readdirSync(j).filter((q)=>q.endsWith(".json")).forEach((q)=>J.resultFileCoalescer.schedule(q,0))}catch(q){if(N$(q))return;console.error(`Failed to scan subagent result directory '${j}':`,q)}},L=(q)=>{if(J.watcher?.close(),J.watcher=null,J.watcherRestartTimer)return;console.error(`Subagent result watcher for '${j}' fell back to polling because native fs.watch is unavailable (${e(q)??"unknown error"}).`),O(),J.watcherRestartTimer=B.setInterval(O,Sj),J.watcherRestartTimer.unref?.()},M=()=>{if(J.watcherRestartTimer)return;J.watcherRestartTimer=B.setTimeout(()=>{J.watcherRestartTimer=null;try{f.mkdirSync(j,{recursive:!0}),U()}catch(q){if(a(q)){L(q);return}console.error(`Failed to restart subagent result watcher for '${j}':`,q),M()}},_j),J.watcherRestartTimer.unref?.()},U=()=>{if(J.watcher)return;if(J.watcherRestartTimer)B.clearTimeout(J.watcherRestartTimer),B.clearInterval(J.watcherRestartTimer),J.watcherRestartTimer=null;try{let q=Cj(f,j);J.watcher=f.watch(q,(V,Y)=>{if(V!=="rename"||!Y)return;let A=Y.toString();if(!A.endsWith(".json"))return;J.resultFileCoalescer.schedule(A)}),J.watcher.on("error",(V)=>{if(a(V)){L(V);return}console.error(`Subagent result watcher failed for '${j}':`,V),J.watcher?.close(),J.watcher=null,M()}),J.watcher.unref?.()}catch(q){if(a(q)){L(q);return}console.error(`Failed to start subagent result watcher for '${j}':`,q),J.watcher=null,M()}};return{startResultWatcher:U,primeExistingResults:O,stopResultWatcher:()=>{if(J.watcher?.close(),J.watcher=null,J.watcherRestartTimer)B.clearTimeout(J.watcherRestartTimer),B.clearInterval(J.watcherRestartTimer);J.watcherRestartTimer=null,J.resultFileCoalescer.clear()}}}export{d0 as createResultWatcher};
8
+ ${w}`:""}`:v$,o=H.sessionFile??(h.length===1?Y.sessionFile:void 0),Q$=N$(H.children,V,`results[${S}].children`);return{agent:H.agent??Y.agent??`step-${S+1}`,status:q$({success:H.success,state:Y.state==="paused"||typeof H.success!=="boolean"?Y.state:void 0}),summary:m$,index:S,artifactPath:H.artifactPaths?.outputPath,...typeof o==="string"&&X.existsSync(o)?{sessionPath:o}:{},...H.intercomTarget?{intercomTarget:H.intercomTarget}:{},...Q$?{children:Q$}:{}}}),x),J$=Y.intercomTarget?.trim();if(J$){let H=Y.mode==="single"||Y.mode==="parallel"||Y.mode==="chain"?Y.mode:h.length>1?"chain":"single",S=U$({to:J$,runId:_,mode:H,source:"async",children:j$,asyncId:Y.id,asyncDir:Y.asyncDir});if(!await M$($.events,S))console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${V}'.`)}$.events.emit(f$,{...Y,runId:_,...x?.length?{nestedChildren:x}:{},...Array.isArray(Y.results)?{results:$$?j$.map((H,S)=>({...Y.results[S],agent:H.agent,status:H.status,summary:H.summary,index:H.index,artifactPath:H.artifactPath,sessionPath:H.sessionPath,children:H.children})):[]}:{}}),X.unlinkSync(V)}catch(Y){if(x$(Y))return;console.error(`Failed to process subagent result file '${V}':`,Y)}};J.resultFileCoalescer=W$((q)=>{f(q)},50);let O=()=>{try{X.readdirSync(j).filter((q)=>q.endsWith(".json")).forEach((q)=>J.resultFileCoalescer.schedule(q,0))}catch(q){if(x$(q))return;console.error(`Failed to scan subagent result directory '${j}':`,q)}},L=(q)=>{if(J.watcher?.close(),J.watcher=null,J.watcherRestartTimer)return;console.error(`Subagent result watcher for '${j}' fell back to polling because native fs.watch is unavailable (${e(q)??"unknown error"}).`),O(),J.watcherRestartTimer=B.setInterval(O,Ej),J.watcherRestartTimer.unref?.()},M=()=>{if(J.watcherRestartTimer)return;J.watcherRestartTimer=B.setTimeout(()=>{J.watcherRestartTimer=null;try{X.mkdirSync(j,{recursive:!0}),G()}catch(q){if(t(q)){L(q);return}console.error(`Failed to restart subagent result watcher for '${j}':`,q),M()}},Cj),J.watcherRestartTimer.unref?.()},G=()=>{if(J.watcher)return;if(J.watcherRestartTimer)B.clearTimeout(J.watcherRestartTimer),B.clearInterval(J.watcherRestartTimer),J.watcherRestartTimer=null;try{let q=yj(X,j);J.watcher=X.watch(q,(V,Y)=>{if(V!=="rename"||!Y)return;let _=Y.toString();if(!_.endsWith(".json"))return;J.resultFileCoalescer.schedule(_)}),J.watcher.on("error",(V)=>{if(t(V)){L(V);return}console.error(`Subagent result watcher failed for '${j}':`,V),J.watcher?.close(),J.watcher=null,M()}),J.watcher.unref?.()}catch(q){if(t(q)){L(q);return}console.error(`Failed to start subagent result watcher for '${j}':`,q),J.watcher=null,M()}};return{startResultWatcher:G,primeExistingResults:O,stopResultWatcher:()=>{if(J.watcher?.close(),J.watcher=null,J.watcherRestartTimer)B.clearTimeout(J.watcherRestartTimer),B.clearInterval(J.watcherRestartTimer);J.watcherRestartTimer=null,J.resultFileCoalescer.clear()}}}export{u0 as createResultWatcher};
@@ -1,4 +1,4 @@
1
- import*as S from"node:fs";import*as u from"node:path";import*as q from"node:os";import*as _ from"node:path";function b(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function V$(j){let J=j?.env??process.env,$=j&&Object.hasOwn(j,"getuid")?j.getuid:process.getuid?.bind(process);if(typeof $==="function")return`uid-${$()}`;for(let H of["USERNAME","USER","LOGNAME"]){let Y=J[H];if(Y)return`user-${b(Y)}`}let Z=j&&Object.hasOwn(j,"userInfo")?j.userInfo:q.userInfo;try{let H=Z?.().username;if(H)return`user-${b(H)}`}catch{}let Q=J.USERPROFILE??J.HOME;if(Q)return`home-${b(Q)}`;let W=j&&Object.hasOwn(j,"homedir")?j.homedir:q.homedir;try{let H=W?.();if(H)return`home-${b(H)}`}catch{}return"shared"}var z=_.join(q.tmpdir(),`dm-subagents-${V$()}`),E=_.join(z,"async-subagent-results"),N=_.join(z,"async-subagent-runs"),L$=_.join(z,"chain-runs"),n$=_.join(z,"artifacts");import*as C from"node:fs";import*as O from"node:path";import*as M$ from"node:fs";import*as A from"node:path";var z$=[10,25,50,100,200,500,1000,2000,4000],A$=new Set(["EACCES","EBUSY","EPERM"]),i=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,s=i?new Int32Array(i):void 0;function C$(j){if(j<=0)return;if(s)try{Atomics.wait(s,0,0,j);return}catch{}let J=Date.now()+j;while(Date.now()<J);}function F$(j){let J=j?.code;return typeof J==="string"&&A$.has(J)}function q$(j,J,$,Z,Q){for(let W=0;;W++)try{j.renameSync(J,$);return}catch(H){let Y=Z[W];if(Y===void 0||!F$(H))throw H;Q(Y)}}function _$(j={}){let J=j.fs??M$,$=j.now??Date.now,Z=j.pid??process.pid,Q=j.random??Math.random,H=j.retryRenameErrors??process.platform==="win32"?j.retryDelaysMs??z$:[],Y=j.wait??C$;return(B,M)=>{J.mkdirSync(A.dirname(B),{recursive:!0});let G=A.join(A.dirname(B),`.${A.basename(B)}.${Z}.${$()}.${Q().toString(36).slice(2)}.tmp`);try{J.writeFileSync(G,JSON.stringify(M,null,2),"utf-8"),q$(J,G,B,H,Y)}finally{J.rmSync(G,{force:!0})}}}var y=_$();var Cj=process.platform==="win32"?"SIGBREAK":"SIGUSR2";import*as V from"node:fs";import*as U from"node:path";import*as e from"node:path";var T$=128,E$=4;function g(j){return typeof j==="string"&&j.length>0&&j.length<=T$&&!e.isAbsolute(j)&&!j.includes("/")&&!j.includes("\\")&&!j.includes("..")}function a(j){return typeof j==="number"&&Number.isFinite(j)?j:void 0}function t(j,J){return typeof j==="string"&&j.length>0?j.slice(0,J):void 0}function $$(j){if(!Array.isArray(j))return[];return j.map((J)=>{if(!J||typeof J!=="object")return;let $=J;if(!g($.runId))return;return{runId:$.runId,...a($.stepIndex)!==void 0?{stepIndex:a($.stepIndex)}:{},...t($.agent,128)?{agent:t($.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,E$)}import*as T from"node:path";import{fileURLToPath as j$}from"node:url";import*as f from"node:os";import*as L from"node:path";var Ej=L.join(f.homedir(),".config","mcp","mcp.json"),Sj={cursor:[L.join(f.homedir(),".cursor","mcp.json")],"claude-code":[L.join(f.homedir(),".claude","mcp.json"),L.join(f.homedir(),".claude.json"),L.join(f.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[L.join(f.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[L.join(f.homedir(),".codex","config.json")],windsurf:[L.join(f.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as yj}from"typebox/compile";var nj=T.join(T.dirname(j$(import.meta.url)),"subagent-prompt-runtime.ts"),pj=T.join(T.dirname(j$(import.meta.url)),"..","..","extension","fanout-child.ts");var x=U.join(z,"nested-subagent-events"),b$="route.json",N$="registry.json",W$=65536,J$=12,D=16,m=3;function k(j){return g(j)}function o(j,J){if(!k(J))throw Error(`${j} must be a non-empty safe id token.`)}function h(j,J){o(j,J)}function c(j,J){let $=U.resolve(j),Z=U.resolve(J);return Z===$||Z.startsWith(`${$}${U.sep}`)}function X$(j){return U.dirname(U.resolve(j.eventSink))}function n(j){if(h("rootRunId",j.rootRunId),h("capabilityToken",j.capabilityToken),!c(x,j.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!c(x,j.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(X$(j)!==U.dirname(U.resolve(j.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function X(j){return typeof j==="number"&&Number.isFinite(j)?j:void 0}function K(j,J=512){return typeof j==="string"&&j.length>0?j.slice(0,J):void 0}function y$(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.input),Z=X(J.output),Q=X(J.total);return $!==void 0&&Z!==void 0&&Q!==void 0?{input:$,output:Z,total:Q}:void 0}function R$(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.inputTokens),Z=X(J.outputTokens),Q=X(J.costUsd);return $!==void 0&&Z!==void 0&&Q!==void 0?{inputTokens:$,outputTokens:Z,costUsd:Q}:void 0}function I(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.maxTurns),Z=X(J.graceTurns),Q=X(J.turnCount),W=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if($===void 0||Z===void 0||Q===void 0||!W)return;return{maxTurns:$,graceTurns:Z,turnCount:Q,outcome:W,...X(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:X(J.wrapUpRequestedAtTurn)}:{},...X(J.exceededAtTurn)!==void 0?{exceededAtTurn:X(J.exceededAtTurn)}:{}}}function x$(j,J){return j==="queued"||j==="running"||j==="complete"||j==="failed"||j==="paused"?j:J}function D$(j,J){if(!j||typeof j!=="object")return;let $=j,Z=K($.agent,128);if(!Z)return;let Q=$.status==="pending"||$.status==="running"||$.status==="complete"||$.status==="completed"||$.status==="failed"||$.status==="paused"?$.status:"pending";return{agent:Z,status:Q,...K($.sessionFile,2048)?{sessionFile:K($.sessionFile,2048)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...X($.lastActivityAt)!==void 0?{lastActivityAt:X($.lastActivityAt)}:{},...K($.currentTool,128)?{currentTool:K($.currentTool,128)}:{},...X($.currentToolStartedAt)!==void 0?{currentToolStartedAt:X($.currentToolStartedAt)}:{},...K($.currentPath,2048)?{currentPath:K($.currentPath,2048)}:{},...X($.turnCount)!==void 0?{turnCount:X($.turnCount)}:{},...X($.toolCount)!==void 0?{toolCount:X($.toolCount)}:{},...X($.startedAt)!==void 0?{startedAt:X($.startedAt)}:{},...X($.endedAt)!==void 0?{endedAt:X($.endedAt)}:{},...K($.error,1024)?{error:K($.error,1024)}:{},...$.timedOut===!0?{timedOut:!0}:{},...I($.turnBudget)?{turnBudget:I($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<m&&Array.isArray($.children)?{children:$.children.map((W)=>P(W,J+1)).filter((W)=>Boolean(W)).slice(0,D)}:{}}}function P(j,J=0){if(!j||typeof j!=="object")return;let $=j;if(!k($.id)||!k($.parentRunId))return;let Z=$$($.path),Q=Array.isArray($.steps)?$.steps.map((Y)=>D$(Y,J+1)).filter((Y)=>Boolean(Y)).slice(0,J$):void 0,W=y$($.totalTokens),H=R$($.totalCost);return{id:$.id,parentRunId:$.parentRunId,...X($.parentStepIndex)!==void 0?{parentStepIndex:X($.parentStepIndex)}:{},...K($.parentAgent,128)?{parentAgent:K($.parentAgent,128)}:{},depth:Math.min(Math.max(0,X($.depth)??0),m),path:Z,state:x$($.state,"running"),...K($.asyncDir,2048)?{asyncDir:K($.asyncDir,2048)}:{},...X($.pid)!==void 0&&X($.pid)>0&&Number.isInteger(X($.pid))?{pid:X($.pid)}:{},...K($.sessionId,256)?{sessionId:K($.sessionId,256)}:{},...K($.sessionFile,2048)?{sessionFile:K($.sessionFile,2048)}:{},...K($.intercomTarget,256)?{intercomTarget:K($.intercomTarget,256)}:{},...K($.ownerIntercomTarget,256)?{ownerIntercomTarget:K($.ownerIntercomTarget,256)}:{},...K($.leafIntercomTarget,256)?{leafIntercomTarget:K($.leafIntercomTarget,256)}:{},...$.ownerState==="live"||$.ownerState==="gone"||$.ownerState==="unknown"?{ownerState:$.ownerState}:{},...K($.controlInbox,2048)?{controlInbox:K($.controlInbox,2048)}:{},...K($.capabilityToken,128)?{capabilityToken:K($.capabilityToken,128)}:{},...$.mode==="single"||$.mode==="parallel"||$.mode==="chain"?{mode:$.mode}:{},...K($.agent,128)?{agent:K($.agent,128)}:{},...Array.isArray($.agents)?{agents:$.agents.map((Y)=>K(Y,128)).filter((Y)=>Boolean(Y)).slice(0,J$)}:{},...X($.currentStep)!==void 0?{currentStep:X($.currentStep)}:{},...X($.chainStepCount)!==void 0?{chainStepCount:X($.chainStepCount)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...X($.lastActivityAt)!==void 0?{lastActivityAt:X($.lastActivityAt)}:{},...K($.currentTool,128)?{currentTool:K($.currentTool,128)}:{},...X($.currentToolStartedAt)!==void 0?{currentToolStartedAt:X($.currentToolStartedAt)}:{},...K($.currentPath,2048)?{currentPath:K($.currentPath,2048)}:{},...X($.turnCount)!==void 0?{turnCount:X($.turnCount)}:{},...X($.toolCount)!==void 0?{toolCount:X($.toolCount)}:{},...W?{totalTokens:W}:{},...H?{totalCost:H}:{},...X($.startedAt)!==void 0?{startedAt:X($.startedAt)}:{},...X($.endedAt)!==void 0?{endedAt:X($.endedAt)}:{},...X($.lastUpdate)!==void 0?{lastUpdate:X($.lastUpdate)}:{},...X($.timeoutMs)!==void 0?{timeoutMs:X($.timeoutMs)}:{},...X($.deadlineAt)!==void 0?{deadlineAt:X($.deadlineAt)}:{},...$.timedOut===!0?{timedOut:!0}:{},...I($.turnBudget)?{turnBudget:I($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...K($.error,1024)?{error:K($.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...J<m&&Array.isArray($.children)?{children:$.children.map((Y)=>P(Y,J+1)).filter((Y)=>Boolean(Y)).slice(0,D)}:{}}}function Z$(j,J){if(Buffer.byteLength(j,"utf-8")>W$)return;let $;try{$=JSON.parse(j)}catch{return}if(!$||typeof $!=="object")return;let Z=$;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==J.rootRunId||Z.capabilityToken!==J.capabilityToken)return;if(!k(Z.parentRunId))return;let Q=X(Z.ts);if(Q===void 0)return;let W=P(Z.child);if(!W||W.id===J.rootRunId)return;let H={...W,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:W.ownerState??"unknown"};return{type:Z.type,ts:Q,rootRunId:J.rootRunId,parentRunId:Z.parentRunId,...X(Z.parentStepIndex)!==void 0?{parentStepIndex:X(Z.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:H}}function k$(j,J){if(!j.includes(`
2
- `)){let $=Z$(j.trim(),J);return $?[$]:[]}return j.split(`
1
+ import*as S from"node:fs";import*as l from"node:path";import*as _ from"node:os";import*as T from"node:path";function N(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function L$(j){let J=j?.env??process.env,$=j&&Object.hasOwn(j,"getuid")?j.getuid:process.getuid?.bind(process);if(typeof $==="function")return`uid-${$()}`;for(let H of["USERNAME","USER","LOGNAME"]){let Y=J[H];if(Y)return`user-${N(Y)}`}let Z=j&&Object.hasOwn(j,"userInfo")?j.userInfo:_.userInfo;try{let H=Z?.().username;if(H)return`user-${N(H)}`}catch{}let Q=J.USERPROFILE??J.HOME;if(Q)return`home-${N(Q)}`;let W=j&&Object.hasOwn(j,"homedir")?j.homedir:_.homedir;try{let H=W?.();if(H)return`home-${N(H)}`}catch{}return"shared"}var A=T.join(_.tmpdir(),`dm-subagents-${L$()}`),b=T.join(A,"async-subagent-results"),y=T.join(A,"async-subagent-runs"),M$=T.join(A,"chain-runs"),u$=T.join(A,"artifacts");import*as F from"node:fs";import*as U from"node:path";import*as f$ from"node:fs";import*as C from"node:path";var A$=[10,25,50,100,200,500,1000,2000,4000],C$=new Set(["EACCES","EBUSY","EPERM"]),s=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,a=s?new Int32Array(s):void 0;function F$(j){if(j<=0)return;if(a)try{Atomics.wait(a,0,0,j);return}catch{}let J=Date.now()+j;while(Date.now()<J);}function q$(j){let J=j?.code;return typeof J==="string"&&C$.has(J)}function _$(j,J,$,Z,Q){for(let W=0;;W++)try{j.renameSync(J,$);return}catch(H){let Y=Z[W];if(Y===void 0||!q$(H))throw H;Q(Y)}}function T$(j={}){let J=j.fs??f$,$=j.now??Date.now,Z=j.pid??process.pid,Q=j.random??Math.random,H=j.retryRenameErrors??process.platform==="win32"?j.retryDelaysMs??A$:[],Y=j.wait??F$;return(B,f)=>{J.mkdirSync(C.dirname(B),{recursive:!0});let G=C.join(C.dirname(B),`.${C.basename(B)}.${Z}.${$()}.${Q().toString(36).slice(2)}.tmp`);try{J.writeFileSync(G,JSON.stringify(f,null,2),"utf-8"),_$(J,G,B,H,Y)}finally{J.rmSync(G,{force:!0})}}}var R=T$();var qj=process.platform==="win32"?"SIGBREAK":"SIGUSR2";import*as V from"node:fs";import*as O from"node:path";import*as $$ from"node:path";var E$=128,b$=4;function m(j){return typeof j==="string"&&j.length>0&&j.length<=E$&&!$$.isAbsolute(j)&&!j.includes("/")&&!j.includes("\\")&&!j.includes("..")}function t(j){return typeof j==="number"&&Number.isFinite(j)?j:void 0}function e(j,J){return typeof j==="string"&&j.length>0?j.slice(0,J):void 0}function j$(j){if(!Array.isArray(j))return[];return j.map((J)=>{if(!J||typeof J!=="object")return;let $=J;if(!m($.runId))return;return{runId:$.runId,...t($.stepIndex)!==void 0?{stepIndex:t($.stepIndex)}:{},...e($.agent,128)?{agent:e($.agent,128)}:{}}}).filter((J)=>Boolean(J)).slice(0,b$)}import*as E from"node:fs";import*as M from"node:path";import{fileURLToPath as N$}from"node:url";import*as z from"node:os";import*as L from"node:path";var Sj=L.join(z.homedir(),".config","mcp","mcp.json"),Nj={cursor:[L.join(z.homedir(),".cursor","mcp.json")],"claude-code":[L.join(z.homedir(),".claude","mcp.json"),L.join(z.homedir(),".claude.json"),L.join(z.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[L.join(z.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[L.join(z.homedir(),".codex","config.json")],windsurf:[L.join(z.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as xj}from"typebox/compile";function J$(j,J){let $=N$(j),Z=M.extname($),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts",W=M.dirname($);while(!E.existsSync(M.join(W,"package.json"))){let H=M.dirname(W);if(H===W)throw Error(`Unable to resolve dm-subagents package root from ${$}`);W=H}return M.join(W,`${J}${Q}`)}var uj=J$(import.meta.url,M.join("src","runs","shared","subagent-prompt-runtime")),lj=J$(import.meta.url,M.join("src","extension","fanout-child"));var D=O.join(A,"nested-subagent-events"),y$="route.json",R$="registry.json",X$=65536,Z$=12,k=16,h=3;function I(j){return m(j)}function o(j,J){if(!I(J))throw Error(`${j} must be a non-empty safe id token.`)}function c(j,J){o(j,J)}function d(j,J){let $=O.resolve(j),Z=O.resolve(J);return Z===$||Z.startsWith(`${$}${O.sep}`)}function Y$(j){return O.dirname(O.resolve(j.eventSink))}function p(j){if(c("rootRunId",j.rootRunId),c("capabilityToken",j.capabilityToken),!d(D,j.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!d(D,j.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(Y$(j)!==O.dirname(O.resolve(j.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function X(j){return typeof j==="number"&&Number.isFinite(j)?j:void 0}function K(j,J=512){return typeof j==="string"&&j.length>0?j.slice(0,J):void 0}function x$(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.input),Z=X(J.output),Q=X(J.total);return $!==void 0&&Z!==void 0&&Q!==void 0?{input:$,output:Z,total:Q}:void 0}function D$(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.inputTokens),Z=X(J.outputTokens),Q=X(J.costUsd);return $!==void 0&&Z!==void 0&&Q!==void 0?{inputTokens:$,outputTokens:Z,costUsd:Q}:void 0}function w(j){if(!j||typeof j!=="object")return;let J=j,$=X(J.maxTurns),Z=X(J.graceTurns),Q=X(J.turnCount),W=J.outcome==="within-budget"||J.outcome==="wrap-up-requested"||J.outcome==="exceeded"?J.outcome:void 0;if($===void 0||Z===void 0||Q===void 0||!W)return;return{maxTurns:$,graceTurns:Z,turnCount:Q,outcome:W,...X(J.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:X(J.wrapUpRequestedAtTurn)}:{},...X(J.exceededAtTurn)!==void 0?{exceededAtTurn:X(J.exceededAtTurn)}:{}}}function k$(j,J){return j==="queued"||j==="running"||j==="complete"||j==="failed"||j==="paused"?j:J}function I$(j,J){if(!j||typeof j!=="object")return;let $=j,Z=K($.agent,128);if(!Z)return;let Q=$.status==="pending"||$.status==="running"||$.status==="complete"||$.status==="completed"||$.status==="failed"||$.status==="paused"?$.status:"pending";return{agent:Z,status:Q,...K($.sessionFile,2048)?{sessionFile:K($.sessionFile,2048)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...X($.lastActivityAt)!==void 0?{lastActivityAt:X($.lastActivityAt)}:{},...K($.currentTool,128)?{currentTool:K($.currentTool,128)}:{},...X($.currentToolStartedAt)!==void 0?{currentToolStartedAt:X($.currentToolStartedAt)}:{},...K($.currentPath,2048)?{currentPath:K($.currentPath,2048)}:{},...X($.turnCount)!==void 0?{turnCount:X($.turnCount)}:{},...X($.toolCount)!==void 0?{toolCount:X($.toolCount)}:{},...X($.startedAt)!==void 0?{startedAt:X($.startedAt)}:{},...X($.endedAt)!==void 0?{endedAt:X($.endedAt)}:{},...K($.error,1024)?{error:K($.error,1024)}:{},...$.timedOut===!0?{timedOut:!0}:{},...w($.turnBudget)?{turnBudget:w($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...J<h&&Array.isArray($.children)?{children:$.children.map((W)=>v(W,J+1)).filter((W)=>Boolean(W)).slice(0,k)}:{}}}function v(j,J=0){if(!j||typeof j!=="object")return;let $=j;if(!I($.id)||!I($.parentRunId))return;let Z=j$($.path),Q=Array.isArray($.steps)?$.steps.map((Y)=>I$(Y,J+1)).filter((Y)=>Boolean(Y)).slice(0,Z$):void 0,W=x$($.totalTokens),H=D$($.totalCost);return{id:$.id,parentRunId:$.parentRunId,...X($.parentStepIndex)!==void 0?{parentStepIndex:X($.parentStepIndex)}:{},...K($.parentAgent,128)?{parentAgent:K($.parentAgent,128)}:{},depth:Math.min(Math.max(0,X($.depth)??0),h),path:Z,state:k$($.state,"running"),...K($.asyncDir,2048)?{asyncDir:K($.asyncDir,2048)}:{},...X($.pid)!==void 0&&X($.pid)>0&&Number.isInteger(X($.pid))?{pid:X($.pid)}:{},...K($.sessionId,256)?{sessionId:K($.sessionId,256)}:{},...K($.sessionFile,2048)?{sessionFile:K($.sessionFile,2048)}:{},...K($.intercomTarget,256)?{intercomTarget:K($.intercomTarget,256)}:{},...K($.ownerIntercomTarget,256)?{ownerIntercomTarget:K($.ownerIntercomTarget,256)}:{},...K($.leafIntercomTarget,256)?{leafIntercomTarget:K($.leafIntercomTarget,256)}:{},...$.ownerState==="live"||$.ownerState==="gone"||$.ownerState==="unknown"?{ownerState:$.ownerState}:{},...K($.controlInbox,2048)?{controlInbox:K($.controlInbox,2048)}:{},...K($.capabilityToken,128)?{capabilityToken:K($.capabilityToken,128)}:{},...$.mode==="single"||$.mode==="parallel"||$.mode==="chain"?{mode:$.mode}:{},...K($.agent,128)?{agent:K($.agent,128)}:{},...Array.isArray($.agents)?{agents:$.agents.map((Y)=>K(Y,128)).filter((Y)=>Boolean(Y)).slice(0,Z$)}:{},...X($.currentStep)!==void 0?{currentStep:X($.currentStep)}:{},...X($.chainStepCount)!==void 0?{chainStepCount:X($.chainStepCount)}:{},...$.activityState==="active_long_running"||$.activityState==="needs_attention"?{activityState:$.activityState}:{},...X($.lastActivityAt)!==void 0?{lastActivityAt:X($.lastActivityAt)}:{},...K($.currentTool,128)?{currentTool:K($.currentTool,128)}:{},...X($.currentToolStartedAt)!==void 0?{currentToolStartedAt:X($.currentToolStartedAt)}:{},...K($.currentPath,2048)?{currentPath:K($.currentPath,2048)}:{},...X($.turnCount)!==void 0?{turnCount:X($.turnCount)}:{},...X($.toolCount)!==void 0?{toolCount:X($.toolCount)}:{},...W?{totalTokens:W}:{},...H?{totalCost:H}:{},...X($.startedAt)!==void 0?{startedAt:X($.startedAt)}:{},...X($.endedAt)!==void 0?{endedAt:X($.endedAt)}:{},...X($.lastUpdate)!==void 0?{lastUpdate:X($.lastUpdate)}:{},...X($.timeoutMs)!==void 0?{timeoutMs:X($.timeoutMs)}:{},...X($.deadlineAt)!==void 0?{deadlineAt:X($.deadlineAt)}:{},...$.timedOut===!0?{timedOut:!0}:{},...w($.turnBudget)?{turnBudget:w($.turnBudget)}:{},...$.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...$.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...K($.error,1024)?{error:K($.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...J<h&&Array.isArray($.children)?{children:$.children.map((Y)=>v(Y,J+1)).filter((Y)=>Boolean(Y)).slice(0,k)}:{}}}function Q$(j,J){if(Buffer.byteLength(j,"utf-8")>X$)return;let $;try{$=JSON.parse(j)}catch{return}if(!$||typeof $!=="object")return;let Z=$;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==J.rootRunId||Z.capabilityToken!==J.capabilityToken)return;if(!I(Z.parentRunId))return;let Q=X(Z.ts);if(Q===void 0)return;let W=v(Z.child);if(!W||W.id===J.rootRunId)return;let H={...W,controlInbox:J.controlInbox,capabilityToken:J.capabilityToken,ownerState:W.ownerState??"unknown"};return{type:Z.type,ts:Q,rootRunId:J.rootRunId,parentRunId:Z.parentRunId,...X(Z.parentStepIndex)!==void 0?{parentStepIndex:X(Z.parentStepIndex)}:{},capabilityToken:J.capabilityToken,child:H}}function w$(j,J){if(!j.includes(`
2
+ `)){let $=Q$(j.trim(),J);return $?[$]:[]}return j.split(`
3
3
  `).slice(0,j.endsWith(`
4
- `)?void 0:-1).map(($)=>$.trim()?Z$($,J):void 0).filter(($)=>Boolean($))}function R(j){return j==="complete"||j==="failed"||j==="paused"}function Q$(j,J){let $=J.type==="subagent.nested.completed"&&J.child.state==="running"?"complete":J.child.state,Z={...J.child,state:$,lastUpdate:J.child.lastUpdate??J.ts};if(!j)return Z;let Q=j.lastUpdate??0,W=Z.lastUpdate??J.ts;if(W<Q)return j;if(R(j.state)&&!R(Z.state))return j;if(R(j.state)&&R(Z.state)&&W===Q)return j;return{...j,...Z,state:Z.state,lastUpdate:Math.max(Q,W)}}function I$(j,J){let $=!1,Z=(Y)=>Y.map((B)=>{if(B.id===J.parentRunId){let G=B.children??[],F=G.findIndex((v)=>v.id===J.child.id),l=Q$(F>=0?G[F]:void 0,J),U$=F>=0?G.map((v,O$)=>O$===F?l:v):[...G,l];return $=!0,{...B,children:U$.slice(0,D),lastUpdate:Math.max(B.lastUpdate??0,J.ts)}}if(!B.children?.length)return B;let M=Z(B.children);return M===B.children?B:{...B,children:M}}),Q=Z(j);if($)return Q;let W=Q.findIndex((Y)=>Y.id===J.child.id),H=Q$(W>=0?Q[W]:void 0,J);return W>=0?Q.map((Y,B)=>B===W?H:Y):[...Q,H].slice(0,D)}function w$(j,J){return{...j,updatedAt:Math.max(j.updatedAt,J.ts),children:I$(j.children,J)}}function Y$(j){return U.join(X$(j),N$)}function w(j,J=[]){for(let $ of j??[])J.push($),w($.children,J),w($.steps?.flatMap((Z)=>Z.children??[]),J);return J}function d(j,J,$=[]){if(!J)return w(j,$);for(let Z of j??[]){if(Z.parentRunId===J.parentRunId&&(J.parentStepIndex===void 0||Z.parentStepIndex===J.parentStepIndex)){w([Z],$);continue}d(Z.children,J,$),d(Z.steps?.flatMap((Q)=>Q.children??[]),J,$)}return $}function P$(){let j;try{j=V.readdirSync(x)}catch($){if($.code==="ENOENT")return[];throw $}let J=[];for(let $ of j){let Z=U.join(x,$);try{let Q=JSON.parse(V.readFileSync(U.join(Z,b$),"utf-8"));if(typeof Q.rootRunId!=="string"||typeof Q.capabilityToken!=="string")continue;let W={rootRunId:Q.rootRunId,eventSink:U.join(Z,"events"),controlInbox:U.join(Z,"controls"),capabilityToken:Q.capabilityToken};n(W),J.push(W)}catch{continue}}return J}function p(j,J={}){h("id",j);let $=[];for(let Z of J.scope?.routes??P$())try{let Q=K$(Z);for(let W of d(Q.children,J.scope?.descendantOf))if(J.prefix?W.id.startsWith(j):W.id===j)$.push({rootRunId:Z.rootRunId,route:Z,run:W})}catch{continue}return $}function v$(j){n(j);try{let J=JSON.parse(V.readFileSync(Y$(j),"utf-8"));return{rootRunId:j.rootRunId,updatedAt:typeof J.updatedAt==="number"?J.updatedAt:0,children:Array.isArray(J.children)?J.children.map(($)=>P($)).filter(($)=>Boolean($)):[],processedEvents:Array.isArray(J.processedEvents)?J.processedEvents.filter(($)=>typeof $==="string"):[]}}catch(J){if(J.code!=="ENOENT")throw J;return{rootRunId:j.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function K$(j){n(j);let J=v$(j),$=new Set(J.processedEvents),Z=!1,Q=[];try{Q=V.readdirSync(j.eventSink).filter((W)=>W.endsWith(".json")||W.endsWith(".jsonl")).sort()}catch(W){if(W.code!=="ENOENT")throw W}for(let W of Q){if($.has(W))continue;let H=U.join(j.eventSink,W);if(!c(j.eventSink,H))continue;let Y;try{let B=V.statSync(H);if(!B.isFile()||B.size>W$)continue;Y=V.readFileSync(H,"utf-8")}catch{continue}for(let B of k$(Y,j))J=w$(J,B),Z=!0;$.add(W),Z=!0}if(Z)J={...J,processedEvents:[...$].slice(-1000)},y(Y$(j),J);return J}var q0=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function g$(j,J){if(j===void 0)return;if(j.trim()==="")throw Error(`${J} must not be empty.`);if(O.isAbsolute(j)||/[\\/]/.test(j)||j.includes(".."))throw Error(`${J} must be an async run id or prefix, not a path.`);return j}function B$(j,J,$){let Z=O.resolve(j),Q=O.resolve(J),W=O.relative(Z,Q);if(W===""||!W.startsWith("..")&&!O.isAbsolute(W))return;throw Error(`${$} must be inside ${Z}.`)}function H$(j,J,$=""){if(!C.existsSync(j))return[];return C.readdirSync(j).filter((Z)=>Z.startsWith(J)&&(!$||Z.endsWith($))).map((Z)=>$?Z.slice(0,-$.length):Z).sort()}function m$(j,J){let $=O.join(j,`${J}.json`);return B$(j,$,"Async result file"),C.existsSync($)?$:null}function G$(j,J,$){let Z=g$(j,"id");if(!Z)return[];let Q=O.resolve(J),W=O.resolve($);return[...new Set([...H$(Q,Z),...H$(W,Z,".json")])].sort().map((Y)=>{let B=O.join(Q,Y);return B$(Q,B,"Async run directory"),{id:Y,location:{asyncDir:C.existsSync(B)?B:null,resultPath:m$(W,Y),resolvedId:Y}}})}function h$(j,J,$){let Z=u.join(J,j),Q=u.join($,`${j}.json`);if(!S.existsSync(Z)&&!S.existsSync(Q))return;return{asyncDir:S.existsSync(Z)?Z:null,resultPath:S.existsSync(Q)?Q:null,resolvedId:j}}function c$(j){if(!j)return[];return[...new Set([...j.foregroundControls.keys(),...j.foregroundRuns?.keys()??[]])]}function d$(j){if(!j)return;let J=[],$=new Set,Z=(Q)=>{if(!Q)return;let W=`${Q.rootRunId}:${Q.eventSink}:${Q.controlInbox}`;if($.has(W))return;$.add(W),J.push(Q)};for(let Q of j.foregroundControls.values())Z(Q.nestedRoute);for(let Q of j.asyncJobs.values())Z(Q.nestedRoute);return{routes:J}}function o$(j,J,$){return G$(j,J,$)}function b0(j,J={}){o("id",j);let $=J.asyncDirRoot??N,Z=J.resultsDir??E,Q=J.nested??d$(J.state);if(J.state?.foregroundControls.has(j)||J.state?.foregroundRuns?.has(j))return{kind:"foreground",id:j};let W=h$(j,$,Z);if(W)return{kind:"async",id:j,location:W};let H=p(j,Q?{scope:Q}:{});if(H.length>1)throw Error(`Nested run id '${j}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);if(H[0])return{kind:"nested",id:j,match:H[0]};let Y=[];for(let G of c$(J.state).filter((F)=>F.startsWith(j)))Y.push({kind:"foreground",id:G});for(let G of o$(j,$,Z))Y.push({kind:"async",id:G.id,location:G.location});for(let G of p(j,Q?{prefix:!0,scope:Q}:{prefix:!0}))Y.push({kind:"nested",id:G.run.id,match:G});let M=[...new Map(Y.map((G)=>[`${G.kind}:${G.id}`,G])).values()];if(M.length>1)throw Error(`Ambiguous subagent run id prefix '${j}' matched: ${M.map((G)=>`${G.kind}:${G.id}`).join(", ")}. Provide a longer id.`);return M[0]}export{b0 as resolveSubagentRunId};
4
+ `)?void 0:-1).map(($)=>$.trim()?Q$($,J):void 0).filter(($)=>Boolean($))}function x(j){return j==="complete"||j==="failed"||j==="paused"}function W$(j,J){let $=J.type==="subagent.nested.completed"&&J.child.state==="running"?"complete":J.child.state,Z={...J.child,state:$,lastUpdate:J.child.lastUpdate??J.ts};if(!j)return Z;let Q=j.lastUpdate??0,W=Z.lastUpdate??J.ts;if(W<Q)return j;if(x(j.state)&&!x(Z.state))return j;if(x(j.state)&&x(Z.state)&&W===Q)return j;return{...j,...Z,state:Z.state,lastUpdate:Math.max(Q,W)}}function P$(j,J){let $=!1,Z=(Y)=>Y.map((B)=>{if(B.id===J.parentRunId){let G=B.children??[],q=G.findIndex((g)=>g.id===J.child.id),r=W$(q>=0?G[q]:void 0,J),U$=q>=0?G.map((g,V$)=>V$===q?r:g):[...G,r];return $=!0,{...B,children:U$.slice(0,k),lastUpdate:Math.max(B.lastUpdate??0,J.ts)}}if(!B.children?.length)return B;let f=Z(B.children);return f===B.children?B:{...B,children:f}}),Q=Z(j);if($)return Q;let W=Q.findIndex((Y)=>Y.id===J.child.id),H=W$(W>=0?Q[W]:void 0,J);return W>=0?Q.map((Y,B)=>B===W?H:Y):[...Q,H].slice(0,k)}function v$(j,J){return{...j,updatedAt:Math.max(j.updatedAt,J.ts),children:P$(j.children,J)}}function K$(j){return O.join(Y$(j),R$)}function P(j,J=[]){for(let $ of j??[])J.push($),P($.children,J),P($.steps?.flatMap((Z)=>Z.children??[]),J);return J}function n(j,J,$=[]){if(!J)return P(j,$);for(let Z of j??[]){if(Z.parentRunId===J.parentRunId&&(J.parentStepIndex===void 0||Z.parentStepIndex===J.parentStepIndex)){P([Z],$);continue}n(Z.children,J,$),n(Z.steps?.flatMap((Q)=>Q.children??[]),J,$)}return $}function g$(){let j;try{j=V.readdirSync(D)}catch($){if($.code==="ENOENT")return[];throw $}let J=[];for(let $ of j){let Z=O.join(D,$);try{let Q=JSON.parse(V.readFileSync(O.join(Z,y$),"utf-8"));if(typeof Q.rootRunId!=="string"||typeof Q.capabilityToken!=="string")continue;let W={rootRunId:Q.rootRunId,eventSink:O.join(Z,"events"),controlInbox:O.join(Z,"controls"),capabilityToken:Q.capabilityToken};p(W),J.push(W)}catch{continue}}return J}function u(j,J={}){c("id",j);let $=[];for(let Z of J.scope?.routes??g$())try{let Q=H$(Z);for(let W of n(Q.children,J.scope?.descendantOf))if(J.prefix?W.id.startsWith(j):W.id===j)$.push({rootRunId:Z.rootRunId,route:Z,run:W})}catch{continue}return $}function m$(j){p(j);try{let J=JSON.parse(V.readFileSync(K$(j),"utf-8"));return{rootRunId:j.rootRunId,updatedAt:typeof J.updatedAt==="number"?J.updatedAt:0,children:Array.isArray(J.children)?J.children.map(($)=>v($)).filter(($)=>Boolean($)):[],processedEvents:Array.isArray(J.processedEvents)?J.processedEvents.filter(($)=>typeof $==="string"):[]}}catch(J){if(J.code!=="ENOENT")throw J;return{rootRunId:j.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function H$(j){p(j);let J=m$(j),$=new Set(J.processedEvents),Z=!1,Q=[];try{Q=V.readdirSync(j.eventSink).filter((W)=>W.endsWith(".json")||W.endsWith(".jsonl")).sort()}catch(W){if(W.code!=="ENOENT")throw W}for(let W of Q){if($.has(W))continue;let H=O.join(j.eventSink,W);if(!d(j.eventSink,H))continue;let Y;try{let B=V.statSync(H);if(!B.isFile()||B.size>X$)continue;Y=V.readFileSync(H,"utf-8")}catch{continue}for(let B of w$(Y,j))J=v$(J,B),Z=!0;$.add(W),Z=!0}if(Z)J={...J,processedEvents:[...$].slice(-1000)},R(K$(j),J);return J}var T0=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function h$(j,J){if(j===void 0)return;if(j.trim()==="")throw Error(`${J} must not be empty.`);if(U.isAbsolute(j)||/[\\/]/.test(j)||j.includes(".."))throw Error(`${J} must be an async run id or prefix, not a path.`);return j}function G$(j,J,$){let Z=U.resolve(j),Q=U.resolve(J),W=U.relative(Z,Q);if(W===""||!W.startsWith("..")&&!U.isAbsolute(W))return;throw Error(`${$} must be inside ${Z}.`)}function B$(j,J,$=""){if(!F.existsSync(j))return[];return F.readdirSync(j).filter((Z)=>Z.startsWith(J)&&(!$||Z.endsWith($))).map((Z)=>$?Z.slice(0,-$.length):Z).sort()}function c$(j,J){let $=U.join(j,`${J}.json`);return G$(j,$,"Async result file"),F.existsSync($)?$:null}function O$(j,J,$){let Z=h$(j,"id");if(!Z)return[];let Q=U.resolve(J),W=U.resolve($);return[...new Set([...B$(Q,Z),...B$(W,Z,".json")])].sort().map((Y)=>{let B=U.join(Q,Y);return G$(Q,B,"Async run directory"),{id:Y,location:{asyncDir:F.existsSync(B)?B:null,resultPath:c$(W,Y),resolvedId:Y}}})}function d$(j,J,$){let Z=l.join(J,j),Q=l.join($,`${j}.json`);if(!S.existsSync(Z)&&!S.existsSync(Q))return;return{asyncDir:S.existsSync(Z)?Z:null,resultPath:S.existsSync(Q)?Q:null,resolvedId:j}}function n$(j){if(!j)return[];return[...new Set([...j.foregroundControls.keys(),...j.foregroundRuns?.keys()??[]])]}function o$(j){if(!j)return;let J=[],$=new Set,Z=(Q)=>{if(!Q)return;let W=`${Q.rootRunId}:${Q.eventSink}:${Q.controlInbox}`;if($.has(W))return;$.add(W),J.push(Q)};for(let Q of j.foregroundControls.values())Z(Q.nestedRoute);for(let Q of j.asyncJobs.values())Z(Q.nestedRoute);return{routes:J}}function p$(j,J,$){return O$(j,J,$)}function y0(j,J={}){o("id",j);let $=J.asyncDirRoot??y,Z=J.resultsDir??b,Q=J.nested??o$(J.state);if(J.state?.foregroundControls.has(j)||J.state?.foregroundRuns?.has(j))return{kind:"foreground",id:j};let W=d$(j,$,Z);if(W)return{kind:"async",id:j,location:W};let H=u(j,Q?{scope:Q}:{});if(H.length>1)throw Error(`Nested run id '${j}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);if(H[0])return{kind:"nested",id:j,match:H[0]};let Y=[];for(let G of n$(J.state).filter((q)=>q.startsWith(j)))Y.push({kind:"foreground",id:G});for(let G of p$(j,$,Z))Y.push({kind:"async",id:G.id,location:G.location});for(let G of u(j,Q?{prefix:!0,scope:Q}:{prefix:!0}))Y.push({kind:"nested",id:G.run.id,match:G});let f=[...new Map(Y.map((G)=>[`${G.kind}:${G.id}`,G])).values()];if(f.length>1)throw Error(`Ambiguous subagent run id prefix '${j}' matched: ${f.map((G)=>`${G.kind}:${G.id}`).join(", ")}. Provide a longer id.`);return f[0]}export{y0 as resolveSubagentRunId};