{"version":3,"file":"subagent-executor.d.ts","sourceRoot":"","sources":["../../../../src/runs/foreground/subagent-executor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAIhF,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAoB,MAAM,wBAAwB,CAAC;AAc7F,OAAO,EAKN,2BAA2B,EAE3B,MAAM,mCAAmC,CAAC;AAc3C,OAAO,EAEN,KAAK,SAAS,EAcd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,aAAa,EAMlB,KAAK,aAAa,EAKlB,KAAK,OAAO,EAEZ,KAAK,eAAe,EAGpB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EAUpB,KAAK,YAAY,EAMjB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EAEtB,MAAM,uBAAuB,CAAC;AAU/B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AA2BrE,OAAO,EAKN,KAAK,iBAAiB,EACtB,MAAM,kCAAkC,CAAC;AAqB1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAqIjE,UAAU,SAAS;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC;IACpC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IACpC,YAAY,CAAC,EAAE,gBAAgB,CAAC;IAChC,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AAED,MAAM,WAAW,kBAAkB;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,CAAC;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,WAAW,CAAC;IAC5C,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,2EAA2E;IAC3E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6BAA6B,CAAC,EAAE,OAAO,CAAC;IACxC,yFAAyF;IACzF,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,0FAA0F;IAC1F,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IACpC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC;IACpC,YAAY,CAAC,EAAE,gBAAgB,CAAC;IAChC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAeD,UAAU,YAAY;IACrB,EAAE,EAAE,YAAY,CAAC;IACjB,KAAK,EAAE,aAAa,CAAC;IACrB,MAAM,EAAE,eAAe,CAAC;IACxB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,wBAAwB,CAAC,EAAE,CAAC,MAAM,EAAE,kBAAkB,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;IACpH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAC/B,gBAAgB,EAAE,MAAM,CAAC;IACzB,sBAAsB,EAAE,CAAC,iBAAiB,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;IACrE,WAAW,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,KAAK;QAAE,MAAM,EAAE,WAAW,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,gBAAgB,CAAA;KAAE,CAAC;IAC7G,8BAA8B,CAAC,EAAE,OAAO,CAAC;IACzC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,OAAO,GAAG,CAAC,KAAK,OAAO,CAAC;CAC7D;AAqtDD,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,YAAY,GAAG,UAAU,CAAC,OAAO,2BAA2B,CAAC,CAanH;AAED,wBAAgB,mCAAmC,CAAC,KAAK,EAAE;IAC1D,6BAA6B,CAAC,EAAE,OAAO,CAAC;IACxC,OAAO,EAAE,YAAY,EAAE,CAAC;CACxB,GAAG,OAAO,CAMV;AA6XD,eAAO,MAAM,6BAA6B,QAAiB,CAAC;AA8xE5D,wBAAgB,2BAA2B,CAC1C,gBAAgB,EAAE,kBAAkB,EACpC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,mBAAmB,EAAE,MAAM,EAC3B,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAC;IAAC,6BAA6B,CAAC,EAAE,OAAO,CAAA;CAAO,GAClF,kBAAkB,CAmCpB;AA2GD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,YAAY,GAAG;IAC3D,OAAO,EAAE,CACR,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC7D,GAAG,EAAE,gBAAgB,KACjB,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;IACvC,iHAAiH;IACjH,aAAa,EAAE,CACd,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC7D,GAAG,EAAE,gBAAgB,KACjB,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;IACvC;;;;OAIG;IACH,gBAAgB,EAAE,CACjB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,EAC7D,GAAG,EAAE,gBAAgB,KACjB,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;IACvC,gGAAgG;IAChG,gBAAgB,EAAE,CACjB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE,gBAAgB,KACjB,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;CACvC,CAskEA","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentToolResult } from \"@lpb-work/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"@lpb-work/pi-coding-agent\";\nimport { handleManagementAction } from \"../../agents/agent-management.ts\";\nimport { handleRefinementAction } from \"../../agents/agent-refinements.ts\";\nimport { resolveExecutionAgentScope } from \"../../agents/agent-scope.ts\";\nimport { type AgentConfig, type AgentScope, resolveAgentName } from \"../../agents/agents.ts\";\nimport { discoverAvailableSkills, normalizeSkillInput } from \"../../agents/skills.ts\";\nimport { buildDoctorReport } from \"../../extension/doctor.ts\";\nimport { normalizePublicSubagentExecution } from \"../../extension/public-execution.ts\";\nimport { HERDR_INSPECTOR_ACTIONS, handleHerdrInspectorAction } from \"../../inspectors/herdr/actions.ts\";\nimport { HERDR_PROJECT_PANE_ACTIONS, handleHerdrProjectPaneAction } from \"../../inspectors/herdr/project-panes.ts\";\nimport {\n\tapplyIntercomBridgeToAgent,\n\tINTERCOM_BRIDGE_MARKER,\n\ttype IntercomBridgeState,\n\tresolveIntercomBridge,\n\tresolveIntercomSessionTarget,\n\tresolveSubagentIntercomTarget,\n} from \"../../intercom/intercom-bridge.ts\";\nimport {\n\tattachNestedChildrenToResultChildren,\n\tbuildSubagentResultIntercomPayload,\n\tdeliverSubagentResultIntercomEvent,\n\tformatSubagentResultReceipt,\n\tresolveSubagentResultStatus,\n\tstripDetailsOutputsForIntercomReceipt,\n} from \"../../intercom/result-intercom.ts\";\nimport { handleMissionAction, MISSION_ACTIONS } from \"../../missions/actions.ts\";\nimport {\n\tattachMissionToLaunchResult,\n\ttype MissionLaunchBinding,\n\tprepareMissionLaunch,\n} from \"../../missions/lifecycle.ts\";\nimport { createMissionWorkflowState } from \"../../missions/workflow-state.ts\";\nimport { resolveAuthorityDecision } from \"../../policy/authority.ts\";\nimport { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning } from \"../../shared/artifacts.ts\";\nimport { writeAtomicJson } from \"../../shared/atomic-json.ts\";\nimport { createForkContextResolver, forkedChildRequiresThinkingOff } from \"../../shared/fork-context.ts\";\nimport { type ModelInfo, resolveEffectiveThinking, toModelInfo } from \"../../shared/model-info.ts\";\nimport { resolveCurrentSessionId } from \"../../shared/session-identity.ts\";\nimport {\n\tbuildChainInstructions,\n\ttype ChainStep,\n\ttype DynamicParallelStep,\n\tgetStepAgents,\n\tisDynamicParallelStep,\n\tisParallelStep,\n\ttype ParallelStep,\n\ttype ParallelTaskItem,\n\ttype ResolvedStepBehavior,\n\tresolveStepBehavior,\n\ttype SequentialStep,\n\ttype StepOverrides,\n\tsuppressProgressForReadOnlyTask,\n\ttaskDisallowsFileUpdates,\n\twriteInitialProgressFile,\n} from \"../../shared/settings.ts\";\nimport {\n\ttype AcceptanceInput,\n\ttype AgentContract,\n\ttype AgentProgress,\n\ttype ArtifactConfig,\n\ttype ArtifactPaths,\n\ttype AsyncJobState,\n\ttype AsyncStatus,\n\ttype ControlConfig,\n\ttype ControlEvent,\n\tcheckSubagentDepth,\n\tDEFAULT_ARTIFACT_CONFIG,\n\tDEFAULT_FORK_PREAMBLE,\n\ttype Details,\n\tDIRS,\n\ttype ExtensionConfig,\n\ttype ForegroundRunControl,\n\ttype IntercomEventBus,\n\ttype JsonSchemaObject,\n\ttype MaxOutputConfig,\n\ttype NestedRouteInfo,\n\ttype NestedRunSummary,\n\ttype ResolvedControlConfig,\n\ttype ResolvedToolBudget,\n\ttype ResolvedTurnBudget,\n\tresolveChildMaxSubagentDepth,\n\tresolveCurrentMaxSubagentDepth,\n\tresolveTopLevelParallelConcurrency,\n\tresolveTopLevelParallelMaxTasks,\n\ttype SingleResult,\n\tSUBAGENT_ACTIONS,\n\tSUBAGENT_CONTROL_EVENT,\n\tSUBAGENT_CONTROL_INTERCOM_EVENT,\n\tSUBAGENT_FOREGROUND_COMPLETE_EVENT,\n\ttype SubagentRunMode,\n\ttype SubagentState,\n\ttype ToolBudgetConfig,\n\ttype TurnBudgetConfig,\n\ttype UsageBudgetConfig,\n\twrapForkTask,\n} from \"../../shared/types.ts\";\nimport {\n\tcompactForegroundDetails,\n\tgetSingleResultOutput,\n\tmapConcurrent,\n\treadStatus,\n\tresolveChildCwd,\n\tsumResultsCost,\n\tsumResultsUsage,\n} from \"../../shared/utils.ts\";\nimport type { MainWatchdogRuntime } from \"../../watchdog/runtime.ts\";\nimport { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from \"../../watchdog/tool-actions.ts\";\nimport { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from \"../../workflows/chat-progress.ts\";\nimport {\n\trunWorkflowScript,\n\ttype WorkflowScriptChildResult,\n\tWorkflowScriptError,\n} from \"../../workflows/scripted-workflow.ts\";\nimport {\n\tbuildAsyncRunnerSteps,\n\texecuteAsyncChain,\n\texecuteAsyncSingle,\n\tformatAsyncStartedMessage,\n\tisAsyncAvailable,\n} from \"../background/async-execution.ts\";\nimport {\n\tapplySteeringRecoveryAgentConfig,\n\tbuildRevivedAsyncTask,\n\tresolveAsyncResumeTarget,\n\tresolveAsyncRunLocation,\n} from \"../background/async-resume.ts\";\nimport {\n\tenqueueChainAppendRequest,\n\treadPendingChainAppendRequests,\n\trunnerStepOutputNames,\n} from \"../background/chain-append.ts\";\nimport { resolveAsyncRootResultPath } from \"../background/chain-root-attachment.ts\";\nimport {\n\tdeliverCheckpointDecisionRequest,\n\tdeliverInterruptRequest,\n\treadRevivalBriefs,\n\trequestAsyncSteer,\n\ttype SteerDeliveryMode,\n} from \"../background/control-channel.ts\";\nimport { formatRetainedChildren, listRetainedChildren } from \"../background/retained-children.ts\";\nimport { type ResolvedSubagentRunId, resolveSubagentRunId } from \"../background/run-id-resolver.ts\";\nimport { inspectSubagentStatus } from \"../background/run-status.ts\";\nimport { reconcileAsyncRun } from \"../background/stale-run-reconciler.ts\";\nimport { updateSteeringTarget, waitForSteeringAction } from \"../background/steering.ts\";\nimport { applyForceTopLevelAsyncOverride } from \"../background/top-level-async.ts\";\nimport { normalizeGateAcceptance, validateExecutionAcceptance } from \"../shared/acceptance.ts\";\nimport {\n\tintersectSubagentCapabilityCeilings,\n\ttype ResolvedSubagentCapabilityCeiling,\n\tresolveCurrentSubagentCapabilityCeiling,\n} from \"../shared/capability-ceiling.ts\";\nimport { ChainOutputValidationError, validateChainOutputBindingsWithContext } from \"../shared/chain-outputs.ts\";\nimport { type ContextMode, type ContextSummary, summarizeContextModes } from \"../shared/context-mode.ts\";\nimport {\n\tbuildModelCandidates,\n\tnormalizeParentModel,\n\ttype ParentModel,\n\tresolveEffectiveSubagentModel,\n} from \"../shared/model-fallback.ts\";\nimport type { ModelScopeConfig } from \"../shared/model-scope.ts\";\nimport {\n\tattachRootChildrenToSteps,\n\tcreateNestedRoute,\n\tfindNestedControlResult,\n\ttype NestedRunResolutionScope,\n\tresolveInheritedNestedRouteFromEnv,\n\tresolveNestedAsyncDir,\n\tresolveNestedParentAddressFromEnv,\n\tsnapshotNestedEventFiles,\n\tupdateForegroundNestedProjection,\n\twriteNestedControlRequest,\n\twriteNestedEvent,\n} from \"../shared/nested-events.ts\";\nimport { formatNestedRunStatusLines } from \"../shared/nested-render.ts\";\nimport {\n\tdiscardPreservedWorktrees,\n\tformatParallelHandoffError,\n\tformatParallelHandoffReference,\n\tparallelHandoffPath,\n\twriteParallelHandoffGroup,\n\twritePendingParallelHandoff,\n} from \"../shared/parallel-handoff.ts\";\nimport { aggregateParallelOutputs, DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from \"../shared/parallel-utils.ts\";\nimport { recordRun } from \"../shared/run-history.ts\";\nimport {\n\tfinalizeSingleOutput,\n\tinjectSingleOutputInstruction,\n\tnormalizeSingleOutputOverride,\n\tresolveSingleOutputPath,\n\tvalidateFileOnlyOutputMode,\n} from \"../shared/single-output.ts\";\nimport {\n\tformatSpawnBudget,\n\tgetSpawnBudgetSnapshot,\n\tgrantSpawnBudget,\n\tpreflightSpawnBudget,\n\tpreflightSpawnBudgetGrant,\n\treserveSpawnBudget,\n} from \"../shared/spawn-budget.ts\";\nimport { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from \"../shared/structured-output.ts\";\nimport {\n\tformatControlIntercomMessage,\n\tformatControlNoticeMessage,\n\tresolveControlConfig,\n\tshouldNotifyControlEvent,\n} from \"../shared/subagent-control.ts\";\nimport { validateToolBudgetConfig } from \"../shared/tool-budget.ts\";\nimport { resolveTurnBudgetConfig } from \"../shared/turn-budget.ts\";\nimport { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from \"../shared/usage-budget.ts\";\nimport {\n\tcleanupWorktrees,\n\tcreateWorktrees,\n\tdiffWorktrees,\n\tfindWorktreeTaskCwdConflict,\n\tformatWorktreeDiffSummary,\n\tformatWorktreeTaskCwdConflict,\n\ttype WorktreeSetup,\n} from \"../shared/worktree.ts\";\nimport { steerAsyncRun } from \"./async-steering-action.ts\";\nimport { stopAsyncRun } from \"./async-stop-action.ts\";\nimport { ChainClarifyComponent, type ChainClarifyResult } from \"./chain-clarify.ts\";\nimport { executeChain } from \"./chain-execution.ts\";\nimport { runSync } from \"./execution.ts\";\nimport {\n\tbeginForegroundChild,\n\tfinishForegroundChild,\n\tforegroundSchedulingSettled,\n\tretainForegroundSchedulingOwner,\n\tsettleForegroundSchedulingOwner,\n\tupdateForegroundChild,\n} from \"./foreground-control.ts\";\n\nconst MUTATING_MANAGEMENT_ACTIONS = new Set([\n\t\"create\",\n\t\"update\",\n\t\"delete\",\n\t\"eject\",\n\t\"disable\",\n\t\"enable\",\n\t\"reset\",\n\t\"grant-spawn-budget\",\n\t\"watchdog.configure\",\n\t\"mission.create\",\n\t\"mission.update\",\n\t\"mission.attach-run\",\n\t\"mission.close\",\n\t\"inspector.open\",\n\t\"inspector.close\",\n\t\"project.open\",\n\t\"project.close\",\n\t\"worktree.discard\",\n\t\"refine\",\n\t\"refine.rollback\",\n\t\"schedule.create\",\n\t\"schedule.pause\",\n\t\"schedule.resume\",\n\t\"schedule.run\",\n\t\"schedule.run-due\",\n\t\"schedule.delete\",\n]);\n\ntype UndefinedOmitted<T extends object> = {\n\t[K in keyof T as undefined extends T[K] ? never : K]: T[K];\n} & {\n\t[K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;\n};\n\n// These helpers mutate their argument, so keep calls scoped to fresh object literals or shallow copies.\nfunction omitUndefinedProperties<T extends object>(value: T): UndefinedOmitted<T> {\n\tfor (const key of Object.keys(value) as Array<keyof T>) {\n\t\tif (value[key] === undefined) delete value[key];\n\t}\n\treturn value as UndefinedOmitted<T>;\n}\n\ntype WithUndefinedOptionals<T extends object> = {\n\t[K in keyof T]: {} extends Pick<T, K> ? T[K] | undefined : T[K];\n};\n\ntype RequiredKeysAllowingUndefined<T extends object> = {\n\t[K in keyof T]-?: {} extends Pick<T, K> ? never : undefined extends T[K] ? K : never;\n}[keyof T];\n\nfunction compactOptional<T extends object>(\n\tvalue: WithUndefinedOptionals<T> & (RequiredKeysAllowingUndefined<T> extends never ? unknown : never),\n): T {\n\tfor (const key of Object.keys(value) as Array<keyof T>) {\n\t\tif (value[key] === undefined) delete value[key];\n\t}\n\treturn value as T;\n}\n\ninterface TaskParam {\n\tagent: string;\n\ttask: string;\n\tcwd?: string;\n\tcount?: number;\n\toutput?: string | boolean;\n\toutputMode?: \"inline\" | \"file-only\";\n\treads?: string[] | boolean;\n\tprogress?: boolean;\n\tmodel?: string;\n\tskill?: string | string[] | boolean;\n\toutputSchema?: JsonSchemaObject;\n\tacceptance?: AcceptanceInput;\n\tagentContract?: AgentContract;\n\ttoolBudget?: ToolBudgetConfig;\n}\n\nexport interface SubagentParamsLike {\n\taction?: string;\n\tid?: string;\n\trunId?: string;\n\tdir?: string;\n\thandoffPath?: string;\n\tindex?: number;\n\tview?: \"fleet\" | \"transcript\";\n\tlines?: number;\n\tchainName?: string;\n\tconfig?: unknown;\n\tname?: string;\n\ttype?: string;\n\tagent?: string;\n\ttask?: string;\n\t/** Retained async child run id. Valid only on workflow runs.run items. */\n\tresume?: string;\n\tmessage?: string;\n\tsteeringRecovery?: boolean;\n\tmode?: SteerDeliveryMode;\n\tworkflowScript?: string;\n\tchatProgress?: \"auto\" | \"off\" | \"live-card\";\n\tstep?: ChainStep;\n\t/** Internal workflow ownership metadata; not part of the public schema. */\n\tworkflowParentRunId?: string;\n\tworkflowKey?: string;\n\tsuppressRoutineResultIntercom?: boolean;\n\t/** Internal durable-run compatibility fields. Public callers must use workflowScript. */\n\tchain?: ChainStep[];\n\ttasks?: TaskParam[];\n\tconcurrency?: number;\n\tworktree?: boolean;\n\tcontext?: \"fresh\" | \"fork\";\n\tasync?: boolean;\n\tforegroundOnly?: boolean;\n\ttimeoutMs?: number;\n\tmaxRuntimeMs?: number;\n\tturnBudget?: TurnBudgetConfig;\n\t/** Internal-only strict turn-boundary enforcement for versioned foreground delegation. */\n\tenforceHardTurnLimit?: boolean;\n\ttoolBudget?: ToolBudgetConfig;\n\tusageBudget?: UsageBudgetConfig;\n\tclarify?: boolean;\n\tshare?: boolean;\n\tcontrol?: ControlConfig;\n\tsessionDir?: string;\n\tcwd?: string;\n\tmaxOutput?: MaxOutputConfig;\n\tartifacts?: boolean;\n\tincludeProgress?: boolean;\n\tmodel?: string;\n\tthinking?: string | false;\n\tscope?: string;\n\ttarget?: string;\n\tfocus?: boolean;\n\tskill?: string | string[] | boolean;\n\toutput?: string | boolean;\n\toutputMode?: \"inline\" | \"file-only\";\n\toutputSchema?: JsonSchemaObject;\n\tagentScope?: unknown;\n\tchainDir?: string;\n\tacceptance?: AcceptanceInput;\n\tgate?: string;\n\tagentContract?: AgentContract;\n\tschedule?: string;\n\tscheduleName?: string;\n\tat?: string;\n\tevery?: string;\n\ton?: string | number;\n\ttimezone?: string;\n\toverlap?: \"skip\";\n\tcatchUp?: \"none\" | \"latest\";\n\tadditional?: number;\n\tmissionId?: string;\n\tmission?: unknown;\n\tmissionUpdate?: unknown;\n\tmissionStatus?: string;\n\tmissionScope?: string;\n\trunMode?: string;\n\trunStatus?: string;\n\tsummary?: string;\n}\n\nfunction rememberParentModel(\n\tstate: { currentSessionId?: string | null; lastParentModel?: ParentModel },\n\tsessionId: string | null,\n\tmodel: unknown,\n): ParentModel | undefined {\n\tif (state.currentSessionId !== sessionId) delete state.lastParentModel;\n\tstate.currentSessionId = sessionId;\n\tconst parentModel = normalizeParentModel(model);\n\tif (!sessionId) return parentModel;\n\tif (parentModel) state.lastParentModel = parentModel;\n\treturn parentModel ?? state.lastParentModel;\n}\n\ninterface ExecutorDeps {\n\tpi: ExtensionAPI;\n\tstate: SubagentState;\n\tconfig: ExtensionConfig;\n\tasyncByDefault: boolean;\n\twaitToolEnabled?: boolean;\n\thandleScheduledRunAction?: (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;\n\twatchdog?: MainWatchdogRuntime;\n\ttempArtifactsDir: string;\n\tgetSubagentSessionRoot: (parentSessionFile: string | null) => string;\n\texpandTilde: (p: string) => string;\n\tdiscoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; modelScope?: ModelScopeConfig };\n\tallowMutatingManagementActions?: boolean;\n\tkill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;\n}\n\ntype ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string) => string | undefined;\ntype ForkThinkingOverrideForTask = (\n\tagentName: string,\n\tidx?: number,\n\tmodelOverride?: string,\n) => AgentConfig[\"thinking\"] | undefined;\n\ninterface ExecutionContextData {\n\tparams: SubagentParamsLike;\n\teffectiveCwd: string;\n\tctx: ExtensionContext;\n\tsignal: AbortSignal;\n\tonUpdate?: (r: AgentToolResult<Details>) => void;\n\tagents: AgentConfig[];\n\trunId: string;\n\tshareEnabled: boolean;\n\tsessionRoot: string;\n\tsessionDirForIndex: (idx?: number) => string;\n\tsessionFileForIndex: (idx?: number) => string | undefined;\n\tsessionFileForTask: ForkSessionFileForTask;\n\tthinkingOverrideForTask: ForkThinkingOverrideForTask;\n\tartifactConfig: ArtifactConfig;\n\tartifactsDir: string;\n\tbackgroundRequestedWhileClarifying: boolean;\n\teffectiveAsync: boolean;\n\tcontrolConfig: ResolvedControlConfig;\n\tintercomBridge: IntercomBridgeState;\n\tnestedRoute?: NestedRouteInfo;\n\ttimeoutMs?: number;\n\tdeadlineAt?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tusageBudget?: UsageBudgetConfig;\n\tallowZeroToolBudget?: boolean;\n\tconfigToolBudget?: ResolvedToolBudget;\n\tcontextPolicy: AgentDefaultContextPolicy;\n\tmodelScope?: ModelScopeConfig;\n\tparentModel?: ParentModel;\n\tparentSessionId: string | null;\n\tparentPiSessionId?: string;\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n}\n\nfunction resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {\n\treturn requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;\n}\n\nfunction removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {\n\tconst control = state.foregroundControls.get(runId);\n\tif (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;\n\tstate.foregroundControls.delete(runId);\n\tif (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;\n\treturn true;\n}\n\nfunction getForegroundControl(state: SubagentState, runId: string | undefined) {\n\tif (runId) return state.foregroundControls.get(runId);\n\tif (state.lastForegroundControlId) {\n\t\tconst latest = state.foregroundControls.get(state.lastForegroundControlId);\n\t\tif (latest) return latest;\n\t}\n\tlet newest: (SubagentState[\"foregroundControls\"] extends Map<string, infer T> ? T : never) | undefined;\n\tfor (const control of state.foregroundControls.values()) {\n\t\tif (!newest || control.updatedAt > newest.updatedAt) newest = control;\n\t}\n\treturn newest;\n}\n\nfunction formatForegroundActivity(\n\tcontrol: SubagentState[\"foregroundControls\"] extends Map<string, infer T> ? T : never,\n): string | undefined {\n\tconst facts: string[] = [];\n\tif (control.currentTool && control.currentToolStartedAt)\n\t\tfacts.push(\n\t\t\t`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1000)}s`,\n\t\t);\n\telse if (control.currentTool) facts.push(`tool ${control.currentTool}`);\n\tif (control.currentPath) facts.push(`path ${control.currentPath}`);\n\tif (control.turnCount !== undefined) facts.push(`${control.turnCount} turns`);\n\tif (control.tokens !== undefined) facts.push(`${control.tokens} tokens`);\n\tif (control.toolCount !== undefined) facts.push(`${control.toolCount} tools`);\n\tif (!control.lastActivityAt) {\n\t\tif (control.currentActivityState === \"needs_attention\") return [\"needs attention\", ...facts].join(\" | \");\n\t\tif (control.currentActivityState === \"active_long_running\")\n\t\t\treturn [\"active but long-running\", ...facts].join(\" | \");\n\t\treturn facts.length ? facts.join(\" | \") : undefined;\n\t}\n\tconst seconds = Math.floor(Math.max(0, Date.now() - control.lastActivityAt) / 1000);\n\tif (control.currentActivityState === \"needs_attention\") return [`no activity for ${seconds}s`, ...facts].join(\" | \");\n\tif (control.currentActivityState === \"active_long_running\")\n\t\treturn [`active but long-running; last activity ${seconds}s ago`, ...facts].join(\" | \");\n\treturn [`active ${seconds}s ago`, ...facts].join(\" | \");\n}\n\nfunction nestedResolutionScopeForExecutor(deps: ExecutorDeps): NestedRunResolutionScope | undefined {\n\tif (deps.allowMutatingManagementActions !== false) return undefined;\n\tconst route = resolveInheritedNestedRouteFromEnv();\n\tconst address = route ? resolveNestedParentAddressFromEnv() : undefined;\n\treturn {\n\t\troutes: route ? [route] : [],\n\t\t...(address\n\t\t\t? {\n\t\t\t\t\tdescendantOf: {\n\t\t\t\t\t\tparentRunId: address.parentRunId,\n\t\t\t\t\t\t...(address.parentStepIndex !== undefined ? { parentStepIndex: address.parentStepIndex } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nfunction trustedSessionRootsForStatus(ctx: ExtensionContext, deps: ExecutorDeps): string[] {\n\tconst roots = deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : [];\n\tconst parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;\n\tif (parentSessionFile) roots.push(deps.getSubagentSessionRoot(parentSessionFile));\n\treturn [...new Set(roots)];\n}\n\nfunction spawnBudgetErrorResult(message: string, mode: \"single\" | \"parallel\" | \"chain\"): AgentToolResult<Details> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tisError: true,\n\t\tdetails: { mode, results: [] },\n\t};\n}\n\nfunction withSpawnBudgetStatus(\n\tresult: AgentToolResult<Details>,\n\tstate: SubagentState,\n\tconfig: ExtensionConfig,\n\tsessionId: string | null,\n): AgentToolResult<Details> {\n\tconst spawnBudget = getSpawnBudgetSnapshot(state, config, sessionId);\n\treturn {\n\t\t...result,\n\t\tcontent: result.content.map((item, index) =>\n\t\t\tindex === 0 && item.type === \"text\"\n\t\t\t\t? { ...item, text: `${formatSpawnBudget(spawnBudget)}\\n${item.text}` }\n\t\t\t\t: item,\n\t\t),\n\t\tdetails: { ...result.details, spawnBudget },\n\t};\n}\n\nfunction hasActiveSubagentChildren(state: SubagentState): boolean {\n\tif (state.subagentInProgress || state.foregroundControls.size > 0) return true;\n\tconst isActive = (status: string) => status === \"queued\" || status === \"running\";\n\treturn [...state.asyncJobs.values(), ...(state.fleetJobs?.values() ?? [])].some((job) => isActive(job.status));\n}\n\nfunction countRequestedSubagentSpawns(params: SubagentParamsLike, config: ExtensionConfig): number {\n\tif (params.tasks) return params.tasks.length;\n\tif (params.chain) {\n\t\treturn params.chain.reduce((total, step) => {\n\t\t\tif (isDynamicParallelStep(step))\n\t\t\t\treturn total + (step.expand.maxItems ?? config.chain?.dynamicFanout?.maxItems ?? 0);\n\t\t\treturn total + getStepAgents(step).length;\n\t\t}, 0);\n\t}\n\treturn params.agent ? 1 : 0;\n}\n\nfunction foregroundStatusResult(\n\tcontrol: SubagentState[\"foregroundControls\"] extends Map<string, infer T> ? T : never,\n): AgentToolResult<Details> {\n\tlet nestedWarning: string | undefined;\n\ttry {\n\t\tupdateForegroundNestedProjection(control);\n\t} catch (error) {\n\t\tnestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;\n\t}\n\tconst activity = formatForegroundActivity(control);\n\tconst lines = [\n\t\t`Run: ${control.runId}`,\n\t\t\"State: running\",\n\t\t`Mode: ${control.mode}`,\n\t\tcontrol.currentAgent\n\t\t\t? `Current: ${control.currentAgent}${control.currentIndex !== undefined ? ` step ${control.currentIndex + 1}` : \"\"}`\n\t\t\t: undefined,\n\t\tactivity ? `Activity: ${activity}` : undefined,\n\t].filter((line): line is string => Boolean(line));\n\tlines.push(...formatNestedRunStatusLines(control.nestedChildren, { indent: \"\", commandHints: true, maxLines: 20 }));\n\tif (nestedWarning) lines.push(`Warning: ${nestedWarning}`);\n\treturn { content: [{ type: \"text\", text: lines.join(\"\\n\") }], details: { mode: \"management\", results: [] } };\n}\n\nfunction trimRememberedForegroundRuns(state: SubagentState): void {\n\tif (!state.foregroundRuns) return;\n\twhile (state.foregroundRuns.size > 50) {\n\t\tconst oldestTerminal = [...state.foregroundRuns.values()]\n\t\t\t.filter((run) => !run.children.some((child) => child.status === \"detached\"))\n\t\t\t.sort((left, right) => left.updatedAt - right.updatedAt)[0];\n\t\tif (!oldestTerminal) break;\n\t\tstate.foregroundRuns.delete(oldestTerminal.runId);\n\t}\n}\n\nfunction foregroundChildActivityFromProgress(progress: SingleResult[\"progress\"] | undefined) {\n\treturn {\n\t\t...(progress?.activityState ? { activityState: progress.activityState } : {}),\n\t\t...(progress?.lastActivityAt !== undefined ? { lastActivityAt: progress.lastActivityAt } : {}),\n\t\t...(progress?.currentTool ? { currentTool: progress.currentTool } : {}),\n\t\t...(progress?.currentToolStartedAt !== undefined ? { currentToolStartedAt: progress.currentToolStartedAt } : {}),\n\t\t...(progress?.currentPath ? { currentPath: progress.currentPath } : {}),\n\t\t...(progress?.turnCount !== undefined ? { turnCount: progress.turnCount } : {}),\n\t\t...(progress?.tokens !== undefined ? { tokens: progress.tokens } : {}),\n\t\t...(progress?.toolCount !== undefined ? { toolCount: progress.toolCount } : {}),\n\t};\n}\n\nfunction rememberForegroundRun(\n\tstate: SubagentState,\n\tinput: {\n\t\trunId: string;\n\t\tmode: \"single\" | \"parallel\" | \"chain\";\n\t\tcwd: string;\n\t\tsessionId: string | null;\n\t\tresults: SingleResult[];\n\t\tcheckpoint?: Details[\"checkpoint\"];\n\t},\n): void {\n\tstate.foregroundRuns ??= new Map();\n\tconst previous = state.foregroundRuns.get(input.runId);\n\tconst updatedAt = Date.now();\n\tstate.foregroundRuns.set(input.runId, {\n\t\trunId: input.runId,\n\t\tmode: input.mode,\n\t\tcwd: input.cwd,\n\t\t...(input.sessionId ? { sessionId: input.sessionId } : {}),\n\t\tupdatedAt,\n\t\t...(input.checkpoint ? { checkpoint: input.checkpoint } : {}),\n\t\tchildren: input.results.map((result, index) => {\n\t\t\tconst child = {\n\t\t\t\tagent: result.agent,\n\t\t\t\tindex,\n\t\t\t\t...(result.context ? { context: result.context } : {}),\n\t\t\t\tstatus: resolveSubagentResultStatus(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\texitCode: result.exitCode,\n\t\t\t\t\t\tinterrupted: result.interrupted,\n\t\t\t\t\t\tdetached: result.detached,\n\t\t\t\t\t\tprocessSignal: result.processSignal,\n\t\t\t\t\t\ttimedOut: result.timedOut,\n\t\t\t\t\t\tstopped: result.stopped,\n\t\t\t\t\t\tturnBudgetExceeded: result.turnBudgetExceeded,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\t...foregroundChildActivityFromProgress(result.progress),\n\t\t\t\tupdatedAt,\n\t\t\t\t...(result.exitCode !== undefined ? { exitCode: result.exitCode } : {}),\n\t\t\t\t...(result.error ? { error: result.error } : {}),\n\t\t\t\t...(result.finalOutput ? { finalOutput: result.finalOutput } : {}),\n\t\t\t\t...(result.outputState ? { outputState: result.outputState } : {}),\n\t\t\t\t...(result.outputMode ? { outputMode: result.outputMode } : {}),\n\t\t\t\t...(result.savedOutputPath ? { savedOutputPath: result.savedOutputPath } : {}),\n\t\t\t\t...(result.outputSaveError ? { outputSaveError: result.outputSaveError } : {}),\n\t\t\t\t...(result.sessionFile ? { sessionFile: result.sessionFile } : {}),\n\t\t\t\t...(result.model ? { model: result.model } : {}),\n\t\t\t\t...(result.thinking ? { thinking: result.thinking } : {}),\n\t\t\t\t...(result.artifactPaths ? { artifactPaths: result.artifactPaths } : {}),\n\t\t\t\t...(result.transcriptPath ? { transcriptPath: result.transcriptPath } : {}),\n\t\t\t\t...(result.transcriptError ? { transcriptError: result.transcriptError } : {}),\n\t\t\t\t...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),\n\t\t\t\t...(result.acceptance ? { acceptance: result.acceptance } : {}),\n\t\t\t\t...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),\n\t\t\t\t...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),\n\t\t\t\t...(result.runtimeAcknowledgedExtensions\n\t\t\t\t\t? { runtimeAcknowledgedExtensions: result.runtimeAcknowledgedExtensions }\n\t\t\t\t\t: {}),\n\t\t\t\t...(result.capabilityCeiling ? { capabilityCeiling: result.capabilityCeiling } : {}),\n\t\t\t\t...(result.capabilityAudit ? { capabilityAudit: result.capabilityAudit } : {}),\n\t\t\t};\n\t\t\tconst recovered = previous?.children[index];\n\t\t\treturn child.status === \"detached\" && recovered && recovered.status !== \"detached\" ? recovered : child;\n\t\t}),\n\t});\n\ttrimRememberedForegroundRuns(state);\n}\n\nfunction applyControlEventToRememberedForegroundRun(state: SubagentState, event: ControlEvent): void {\n\tconst run = state.foregroundRuns?.get(event.runId);\n\tif (!run) return;\n\tconst index = event.index ?? (run.children.length === 1 ? run.children[0]?.index : undefined);\n\tif (index === undefined) return;\n\tconst child = run.children[index];\n\tif (!child || child.status !== \"detached\") return;\n\tconst updatedAt = event.ts;\n\trun.updatedAt = updatedAt;\n\trun.children[index] = {\n\t\t...child,\n\t\tactivityState: event.to,\n\t\tupdatedAt,\n\t\t...(event.elapsedMs !== undefined ? { lastActivityAt: event.ts - event.elapsedMs } : {}),\n\t\t...(event.currentTool ? { currentTool: event.currentTool } : {}),\n\t\t...(event.currentToolDurationMs !== undefined\n\t\t\t? { currentToolStartedAt: event.ts - event.currentToolDurationMs }\n\t\t\t: {}),\n\t\t...(event.currentPath ? { currentPath: event.currentPath } : {}),\n\t\t...(event.turns !== undefined ? { turnCount: event.turns } : {}),\n\t\t...(event.tokens !== undefined ? { tokens: event.tokens } : {}),\n\t\t...(event.toolCount !== undefined ? { toolCount: event.toolCount } : {}),\n\t};\n}\n\nfunction updateRememberedForegroundChild(\n\tstate: SubagentState,\n\tinput: {\n\t\trunId: string;\n\t\tmode: \"single\" | \"parallel\" | \"chain\";\n\t\tcwd: string;\n\t\tsessionId: string | null;\n\t\tindex: number;\n\t\tresult: SingleResult;\n\t\tevents: IntercomEventBus;\n\t\tnotify?: boolean;\n\t},\n): void {\n\tstate.foregroundRuns ??= new Map();\n\tconst updatedAt = Date.now();\n\tlet run = state.foregroundRuns.get(input.runId);\n\tif (!run) {\n\t\trun = {\n\t\t\trunId: input.runId,\n\t\t\tmode: input.mode,\n\t\t\tcwd: input.cwd,\n\t\t\t...(input.sessionId ? { sessionId: input.sessionId } : {}),\n\t\t\tupdatedAt,\n\t\t\tchildren: [],\n\t\t};\n\t\tstate.foregroundRuns.set(input.runId, run);\n\t}\n\trun.updatedAt = updatedAt;\n\tconst terminalStatus = resolveSubagentResultStatus(\n\t\tomitUndefinedProperties({\n\t\t\texitCode: input.result.exitCode,\n\t\t\t...(input.result.acceptance?.status === \"rejected\" ? { success: false } : {}),\n\t\t\tinterrupted: input.result.interrupted,\n\t\t\tdetached: false,\n\t\t\tprocessSignal: input.result.processSignal,\n\t\t\ttimedOut: input.result.timedOut,\n\t\t\tstopped: input.result.stopped,\n\t\t\tturnBudgetExceeded: input.result.turnBudgetExceeded,\n\t\t}),\n\t);\n\tconst child = run.children[input.index] ?? {\n\t\tagent: input.result.agent,\n\t\tindex: input.index,\n\t\tstatus: \"detached\" as const,\n\t};\n\trun.children[input.index] = omitUndefinedProperties({\n\t\t...child,\n\t\tagent: input.result.agent,\n\t\tindex: input.index,\n\t\t...(input.result.context ? { context: input.result.context } : {}),\n\t\tstatus: terminalStatus,\n\t\t...foregroundChildActivityFromProgress(input.result.progress),\n\t\tupdatedAt,\n\t\t...(input.result.exitCode !== undefined ? { exitCode: input.result.exitCode } : {}),\n\t\t...(input.result.error ? { error: input.result.error } : {}),\n\t\t...(input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {}),\n\t\toutputState: input.result.outputState,\n\t\toutputMode: input.result.outputMode,\n\t\tsavedOutputPath: input.result.savedOutputPath,\n\t\toutputSaveError: input.result.outputSaveError,\n\t\t...(input.result.sessionFile ? { sessionFile: input.result.sessionFile } : {}),\n\t\t...(input.result.model ? { model: input.result.model } : {}),\n\t\t...(input.result.thinking ? { thinking: input.result.thinking } : {}),\n\t\t...(input.result.artifactPaths ? { artifactPaths: input.result.artifactPaths } : {}),\n\t\t...(input.result.transcriptPath ? { transcriptPath: input.result.transcriptPath } : {}),\n\t\t...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),\n\t\t...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),\n\t\t...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),\n\t\t...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),\n\t\t...(input.result.launchResolvedExtensions\n\t\t\t? { launchResolvedExtensions: input.result.launchResolvedExtensions }\n\t\t\t: {}),\n\t\t...(input.result.runtimeAcknowledgedExtensions\n\t\t\t? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions }\n\t\t\t: {}),\n\t\t...(input.result.capabilityCeiling ? { capabilityCeiling: input.result.capabilityCeiling } : {}),\n\t\t...(input.result.capabilityAudit ? { capabilityAudit: input.result.capabilityAudit } : {}),\n\t});\n\ttrimRememberedForegroundRuns(state);\n\tconst output = getSingleResultOutput(input.result).trim();\n\tconst success = terminalStatus === \"completed\";\n\tconst summary =\n\t\t!success && input.result.error\n\t\t\t? `${input.result.error}${output ? `\\n\\nOutput:\\n${output}` : \"\"}`\n\t\t\t: output || input.result.error || \"Detached child exited without final output.\";\n\t// A detached callback may outlive its extension runtime. Stale sessions are\n\t// intentionally dropped rather than routed through a replacement runtime.\n\tif (input.notify === false || !input.sessionId || input.sessionId !== state.currentSessionId) return;\n\tinput.events.emit(SUBAGENT_FOREGROUND_COMPLETE_EVENT, {\n\t\tid: `${input.runId}:${input.index}`,\n\t\trunId: input.runId,\n\t\tsource: \"foreground\",\n\t\tmode: input.mode,\n\t\tagent: input.result.agent,\n\t\tsuccess,\n\t\tsummary,\n\t\texitCode: input.result.exitCode,\n\t\tstate: terminalStatus === \"completed\" ? \"complete\" : terminalStatus,\n\t\t...(input.result.interrupted !== undefined ? { interrupted: input.result.interrupted } : {}),\n\t\t...(input.result.stopped !== undefined ? { stopped: input.result.stopped } : {}),\n\t\t...(input.result.processSignal !== undefined ? { processSignal: input.result.processSignal } : {}),\n\t\t...(input.result.timedOut !== undefined ? { timedOut: input.result.timedOut } : {}),\n\t\t...(input.result.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: input.result.turnBudgetExceeded } : {}),\n\t\ttimestamp: updatedAt,\n\t\tcwd: input.cwd,\n\t\tsessionFile: input.result.sessionFile,\n\t\tsessionId: input.sessionId,\n\t\ttaskIndex: input.index,\n\t});\n}\n\nfunction resolveForegroundResumeTarget(\n\tparams: SubagentParamsLike,\n\tstate: SubagentState,\n):\n\t| {\n\t\t\trunId: string;\n\t\t\tmode: SubagentRunMode;\n\t\t\tstate: \"complete\";\n\t\t\tagent: string;\n\t\t\tindex: number;\n\t\t\tcwd: string;\n\t\t\tsessionFile: string;\n\t\t\tmodel?: string;\n\t\t\tthinking?: string;\n\t\t\tlaunchContractDigest?: string;\n\t\t\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n\t  }\n\t| undefined {\n\tconst requested = (params.id ?? params.runId)?.trim();\n\tif (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;\n\tconst sessionRuns = [...state.foregroundRuns.values()].filter((run) => run.sessionId === state.currentSessionId);\n\tconst direct = sessionRuns.find((run) => run.runId === requested);\n\tconst matches = direct ? [direct] : sessionRuns.filter((run) => run.runId.startsWith(requested));\n\tif (matches.length === 0) return undefined;\n\tif (matches.length > 1)\n\t\tthrow new Error(\n\t\t\t`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(\", \")}. Provide a longer id.`,\n\t\t);\n\tconst run = matches[0]!;\n\tif (run.children.some((child) => child.status === \"detached\"))\n\t\tthrow new Error(\n\t\t\t`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with subagent_wait({ id: \"${run.runId}\" }); use status to recover the result and do not launch a replacement while it remains detached.`,\n\t\t);\n\tif (run.children.length > 1 && params.index === undefined)\n\t\tthrow new Error(\n\t\t\t`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`,\n\t\t);\n\tconst index = params.index ?? 0;\n\tif (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);\n\tif (index < 0 || index >= run.children.length)\n\t\tthrow new Error(\n\t\t\t`Foreground run '${run.runId}' has ${run.children.length} children. Index ${index} is out of range.`,\n\t\t);\n\tconst child = run.children[index]!;\n\tif (!child.sessionFile)\n\t\tthrow new Error(\n\t\t\t`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`,\n\t\t);\n\tif (path.extname(child.sessionFile) !== \".jsonl\")\n\t\tthrow new Error(\n\t\t\t`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`,\n\t\t);\n\tconst sessionFile = path.resolve(child.sessionFile);\n\tif (!fs.existsSync(sessionFile))\n\t\tthrow new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);\n\treturn {\n\t\trunId: run.runId,\n\t\tmode: run.mode,\n\t\tstate: \"complete\",\n\t\tagent: child.agent,\n\t\tindex,\n\t\tcwd: run.cwd,\n\t\tsessionFile,\n\t\t...(child.model ? { model: child.model } : {}),\n\t\t...(child.thinking ? { thinking: child.thinking } : {}),\n\t\t...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),\n\t\t...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),\n\t};\n}\n\ntype AsyncResumeSourceTarget = ReturnType<typeof resolveAsyncResumeTarget> & { source: \"async\" };\ntype ForegroundResumeSourceTarget = NonNullable<ReturnType<typeof resolveForegroundResumeTarget>> & {\n\tkind: \"revive\";\n\tsource: \"foreground\";\n};\ntype NestedResumeSourceTarget = {\n\tkind: \"revive\";\n\tsource: \"nested\";\n\trunId: string;\n\tstate: \"complete\" | \"failed\" | \"paused\";\n\tagent: string;\n\tindex: number;\n\tcwd?: string;\n\tsessionFile: string;\n\tmodel?: string;\n\tthinking?: AgentConfig[\"thinking\"];\n\tlaunchContractDigest?: string;\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n};\ntype ResumeSourceTarget = AsyncResumeSourceTarget | ForegroundResumeSourceTarget | NestedResumeSourceTarget;\n\nfunction isAsyncRunNotFound(error: unknown): boolean {\n\treturn error instanceof Error && error.message.startsWith(\"Async run not found.\");\n}\n\nfunction isResumeAmbiguity(error: unknown): boolean {\n\treturn error instanceof Error && /Ambiguous .*run id prefix/.test(error.message);\n}\n\nfunction resumeTargetExact(target: { runId: string } | undefined, requested: string): boolean {\n\treturn target?.runId === requested;\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction isExactResumeError(error: unknown, source: \"async\" | \"foreground\", requested: string): boolean {\n\tif (!(error instanceof Error) || !requested) return false;\n\treturn new RegExp(`\\\\b${source} run '${escapeRegExp(requested)}'`, \"i\").test(error.message);\n}\n\nfunction resolveResumeTarget(\n\tparams: SubagentParamsLike,\n\tstate: SubagentState,\n\toptions: { asyncRequireSessionFile?: boolean } = {},\n): ResumeSourceTarget {\n\tconst requested = (params.id ?? params.runId)?.trim() ?? \"\";\n\tlet foregroundTarget: ForegroundResumeSourceTarget | undefined;\n\tlet foregroundError: unknown;\n\tlet asyncTarget: AsyncResumeSourceTarget | undefined;\n\tlet asyncError: unknown;\n\n\ttry {\n\t\tconst target = resolveForegroundResumeTarget(params, state);\n\t\tif (target) foregroundTarget = { kind: \"revive\", source: \"foreground\", ...target };\n\t} catch (error) {\n\t\tforegroundError = error;\n\t}\n\ttry {\n\t\tasyncTarget = {\n\t\t\tsource: \"async\",\n\t\t\t...resolveAsyncResumeTarget(\n\t\t\t\tparams,\n\t\t\t\t{},\n\t\t\t\tcompactOptional<NonNullable<Parameters<typeof resolveAsyncResumeTarget>[2]>>({\n\t\t\t\t\trequireSessionFile: options.asyncRequireSessionFile,\n\t\t\t\t\tsessionId: state.currentSessionId ?? undefined,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t} catch (error) {\n\t\tasyncError = error;\n\t}\n\n\tif (foregroundTarget && asyncTarget) {\n\t\tconst foregroundExact = resumeTargetExact(foregroundTarget, requested);\n\t\tconst asyncExact = resumeTargetExact(asyncTarget, requested);\n\t\tif (foregroundExact && !asyncExact) return foregroundTarget;\n\t\tif (asyncExact && !foregroundExact) return asyncTarget;\n\t\tthrow new Error(\n\t\t\t`Resume id '${requested}' is ambiguous between foreground run '${foregroundTarget.runId}' and async run '${asyncTarget.runId}'. Provide a full run id.`,\n\t\t);\n\t}\n\tif (foregroundTarget) {\n\t\tif (isExactResumeError(asyncError, \"async\", requested)) throw asyncError;\n\t\tif (isResumeAmbiguity(asyncError) && !resumeTargetExact(foregroundTarget, requested)) throw asyncError;\n\t\treturn foregroundTarget;\n\t}\n\tif (asyncTarget) {\n\t\tif (isExactResumeError(foregroundError, \"foreground\", requested)) throw foregroundError;\n\t\tif (isResumeAmbiguity(foregroundError) && !resumeTargetExact(asyncTarget, requested)) throw foregroundError;\n\t\treturn asyncTarget;\n\t}\n\tif (foregroundError && !isAsyncRunNotFound(asyncError)) throw foregroundError;\n\tif (foregroundError) throw foregroundError;\n\tif (asyncError) throw asyncError;\n\tthrow new Error(\"Run not found. Provide id or runId.\");\n}\n\nfunction getAsyncInterruptTarget(\n\tstate: SubagentState,\n\trunId: string | undefined,\n\tlocation?: { asyncDir: string | null; resolvedId?: string },\n\toptions: { fallbackToNewest?: boolean } = {},\n): { asyncId: string; asyncDir: string } | undefined {\n\tif (location?.asyncDir) {\n\t\treturn {\n\t\t\tasyncId: location.resolvedId ?? runId ?? path.basename(location.asyncDir),\n\t\t\tasyncDir: location.asyncDir,\n\t\t};\n\t}\n\tif (runId) {\n\t\tconst direct = state.asyncJobs.get(runId);\n\t\tif (direct) return { asyncId: direct.asyncId, asyncDir: direct.asyncDir };\n\t\tif (options.fallbackToNewest === false) return undefined;\n\t}\n\tlet newest: { asyncId: string; asyncDir: string; updatedAt: number } | undefined;\n\tfor (const job of state.asyncJobs.values()) {\n\t\tif (job.status !== \"running\") continue;\n\t\tif (!newest || (job.updatedAt ?? 0) > newest.updatedAt) {\n\t\t\tnewest = { asyncId: job.asyncId, asyncDir: job.asyncDir, updatedAt: job.updatedAt ?? 0 };\n\t\t}\n\t}\n\treturn newest ? { asyncId: newest.asyncId, asyncDir: newest.asyncDir } : undefined;\n}\n\nfunction emitControlNotification(input: {\n\tpi: ExtensionAPI;\n\tcontrolConfig: ResolvedControlConfig;\n\tintercomBridge: IntercomBridgeState;\n\tevent: ControlEvent;\n}): void {\n\tif (!shouldNotifyControlEvent(input.controlConfig, input.event)) return;\n\tconst childIntercomTarget = input.intercomBridge.active\n\t\t? resolveSubagentIntercomTarget(input.event.runId, input.event.agent, input.event.index)\n\t\t: undefined;\n\tconst payload = {\n\t\tevent: input.event,\n\t\tsource: \"foreground\" as const,\n\t\tchildIntercomTarget,\n\t\tnoticeText: formatControlNoticeMessage(input.event, childIntercomTarget),\n\t};\n\tif (input.controlConfig.notifyChannels.includes(\"event\")) {\n\t\tinput.pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);\n\t}\n\tif (\n\t\tinput.event.type !== \"active_long_running\" &&\n\t\tinput.controlConfig.notifyChannels.includes(\"intercom\") &&\n\t\tinput.intercomBridge.active &&\n\t\tinput.intercomBridge.orchestratorTarget\n\t) {\n\t\tinput.pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {\n\t\t\t...payload,\n\t\t\tto: input.intercomBridge.orchestratorTarget,\n\t\t\tmessage: formatControlIntercomMessage(input.event, childIntercomTarget),\n\t\t});\n\t}\n}\n\nfunction interruptAsyncRun(\n\tstate: SubagentState,\n\trunId: string | undefined,\n\tkill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,\n\tlocation?: { asyncDir: string | null; resolvedId?: string },\n): AgentToolResult<Details> | null {\n\tconst target = getAsyncInterruptTarget(state, runId, location);\n\tif (!target) return null;\n\tconst status = reconcileAsyncRun(target.asyncDir, omitUndefinedProperties({ kill })).status;\n\tif (!status || status.state !== \"running\" || typeof status.pid !== \"number\") {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `No running async run with an interrupt-capable pid was found for '${runId ?? \"current\"}'.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst activeSteps = status.steps?.filter((step) => step.status === \"running\") ?? [];\n\tif (activeSteps.length > 0 && activeSteps.every((step) => step.runner?.type === \"external-cli\")) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Interrupt is unsupported for one-shot external CLI async run ${target.asyncId}; use stop instead.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\ttry {\n\t\tdeliverInterruptRequest(\n\t\t\tomitUndefinedProperties({ asyncDir: target.asyncDir, pid: status.pid, kill, source: \"interrupt-action\" }),\n\t\t);\n\t\tconst tracked = state.asyncJobs.get(target.asyncId);\n\t\tif (tracked) {\n\t\t\tdelete tracked.activityState;\n\t\t\ttracked.updatedAt = Date.now();\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Interrupt requested for async run ${target.asyncId}.` }],\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to interrupt async run ${target.asyncId}: ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n}\n\nfunction duplicateNames(names: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst duplicates = new Set<string>();\n\tfor (const name of names) {\n\t\tif (seen.has(name)) duplicates.add(name);\n\t\telse seen.add(name);\n\t}\n\treturn [...duplicates];\n}\n\nfunction appendStepToAsyncChain(input: {\n\tparams: SubagentParamsLike;\n\trequestCwd: string;\n\tctx: ExtensionContext;\n\tdeps: ExecutorDeps;\n\tparentModel?: ParentModel;\n}): AgentToolResult<Details> {\n\tconst targetRunId = input.params.id ?? input.params.runId;\n\tif (!targetRunId) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"action='append-step' requires id.\" }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (!input.params.step) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"action='append-step' requires step.\" }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst chain = [input.params.step];\n\tconst acceptanceErrors = validateExecutionAcceptance({ ...input.params, chain } as Parameters<\n\t\ttypeof validateExecutionAcceptance\n\t>[0]);\n\tif (acceptanceErrors.length > 0) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Cannot append step: ${acceptanceErrors.join(\" \")}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tlet resolved: ResolvedSubagentRunId | undefined;\n\ttry {\n\t\tresolved = resolveSubagentRunId(\n\t\t\ttargetRunId,\n\t\t\tomitUndefinedProperties({ state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) }),\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (!resolved) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `No async chain run found for '${targetRunId}'.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (resolved.kind !== \"async\" || !resolved.location.asyncDir) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Run '${resolved.id}' is not an append-capable async chain run.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tconst status = readStatus(resolved.location.asyncDir);\n\tif (!status) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `No async run status found for '${resolved.id}'.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (status.mode !== \"chain\") {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Run '${resolved.id}' is ${status.mode}; only active chain runs accept appended steps.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (status.state !== \"running\") {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Run '${resolved.id}' is ${status.state}; only running chain runs accept appended steps.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst stillInProgress =\n\t\t(status.steps ?? []).some((step) => step.status === \"running\" || step.status === \"pending\") ||\n\t\t(status.pendingAppends ?? 0) > 0;\n\tif (!stillInProgress) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Run '${resolved.id}' has no running or pending chain steps left; append-step must target an in-progress chain.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tconst pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir);\n\tconst reservedOutputNames = new Set<string>([\n\t\t...Object.keys(status.outputs ?? {}),\n\t\t...(status.steps ?? []).map((step) => step.outputName).filter((name): name is string => Boolean(name)),\n\t\t...pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps)),\n\t]);\n\ttry {\n\t\tvalidateChainOutputBindingsWithContext(\n\t\t\tchain,\n\t\t\tomitUndefinedProperties({ maxItems: input.deps.config.chain?.dynamicFanout?.maxItems }),\n\t\t\t{\n\t\t\t\tpriorOutputNames: reservedOutputNames,\n\t\t\t\tstartStepIndex: status.chainStepCount ?? status.steps?.length ?? 0,\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tif (!(error instanceof ChainOutputValidationError)) throw error;\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Cannot append step to run '${resolved.id}': ${error.message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tconst scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);\n\tconst discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope);\n\tconst agents = discoveredForAppend.agents;\n\tconst contextPolicy = resolveExplicitContextPolicy(input.params);\n\tconst chainSkillInput = normalizeSkillInput(input.params.skill);\n\tconst chainSkills = chainSkillInput === false ? [] : (chainSkillInput ?? []);\n\tconst parentModel = input.parentModel;\n\tconst asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\tpi: input.deps.pi,\n\t\tcwd: input.ctx.cwd,\n\t\tcurrentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),\n\t\tparentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,\n\t\tcurrentModelProvider: parentModel?.provider,\n\t\tcurrentModel: parentModel,\n\t\tmodelScope: discoveredForAppend.modelScope,\n\t\tinteractive: input.ctx.hasUI,\n\t\tpermissions: input.deps.config.permissions,\n\t});\n\tconst built = buildAsyncRunnerSteps(\n\t\tresolved.id,\n\t\tcompactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({\n\t\t\tchain: wrapChainTasksForFork(chain, contextPolicy),\n\t\t\ttask: input.params.task,\n\t\t\tresultMode: \"chain\",\n\t\t\tagents,\n\t\t\tctx: asyncCtx,\n\t\t\tavailableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),\n\t\t\tcwd: status.cwd ?? input.requestCwd,\n\t\t\tchainSkills,\n\t\t\tdynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\tmaxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),\n\t\t\twaitToolEnabled: input.deps.waitToolEnabled,\n\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\tasyncDir: resolved.location.asyncDir,\n\t\t\tvalidateOutputBindings: false,\n\t\t\tcapabilityCeiling: intersectSubagentCapabilityCeilings(\n\t\t\t\tstatus.capabilityCeiling,\n\t\t\t\tresolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId),\n\t\t\t),\n\t\t}),\n\t);\n\tif (\"error\" in built) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: built.error }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst appendedOutputNames = runnerStepOutputNames(built.steps);\n\tconst duplicateAppendedOutputs = duplicateNames(appendedOutputNames);\n\tif (duplicateAppendedOutputs.length > 0) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Cannot append step to run '${resolved.id}': duplicate output name in appended step: ${duplicateAppendedOutputs.join(\", \")}.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst pendingOutputNames = new Set(pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps)));\n\tconst pendingDuplicateOutputs = appendedOutputNames.filter((name) => pendingOutputNames.has(name));\n\tif (pendingDuplicateOutputs.length > 0) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Cannot append step to run '${resolved.id}': output name already belongs to a pending append: ${pendingDuplicateOutputs.join(\", \")}.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\ttry {\n\t\tconst result = enqueueChainAppendRequest({\n\t\t\tasyncDir: resolved.location.asyncDir,\n\t\t\trunId: resolved.id,\n\t\t\tsteps: built.steps,\n\t\t});\n\t\tconst stepText = built.steps.length === 1 ? \"step\" : \"steps\";\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result.pendingCount}.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tdetails: { mode: \"management\", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir },\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to append step to chain run ${resolved.id}: ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n}\n\nfunction nestedRunSessionFile(run: NestedRunSummary): string | undefined {\n\treturn run.sessionFile ?? (run.steps?.length === 1 ? run.steps[0]?.sessionFile : undefined);\n}\n\nfunction nestedRunAgent(run: NestedRunSummary): string | undefined {\n\treturn run.agent ?? run.agents?.[0] ?? (run.steps?.length === 1 ? run.steps[0]?.agent : undefined);\n}\n\nfunction pathWithin(base: string, candidate: string): boolean {\n\tconst resolvedBase = path.resolve(base);\n\tconst resolvedCandidate = path.resolve(candidate);\n\treturn resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);\n}\n\nfunction validateNestedSessionFile(run: NestedRunSummary, trustedSessionRoots: string[]): string {\n\tconst sessionFile = nestedRunSessionFile(run);\n\tif (!sessionFile) throw new Error(`Nested run '${run.id}' does not have a persisted session file to resume from.`);\n\tif (path.extname(sessionFile) !== \".jsonl\")\n\t\tthrow new Error(`Nested run '${run.id}' session file must be a .jsonl file: ${sessionFile}`);\n\tconst resolved = path.resolve(sessionFile);\n\tif (!path.isAbsolute(sessionFile))\n\t\tthrow new Error(`Nested run '${run.id}' session file must be absolute: ${sessionFile}`);\n\tif (!fs.existsSync(resolved)) throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}`);\n\tconst stat = fs.lstatSync(resolved);\n\tif (!stat.isFile() || stat.isSymbolicLink())\n\t\tthrow new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);\n\tconst realSessionFile = fs.realpathSync(resolved);\n\tconst trustedRoots = trustedSessionRoots.filter((root) => fs.existsSync(root)).map((root) => fs.realpathSync(root));\n\tif (!trustedRoots.some((root) => pathWithin(root, realSessionFile))) {\n\t\tthrow new Error(`Nested run '${run.id}' session file is outside trusted nested session roots: ${sessionFile}`);\n\t}\n\tif (!realSessionFile.split(path.sep).includes(run.id)) {\n\t\tthrow new Error(\n\t\t\t`Nested run '${run.id}' session file is not under that nested run's session directory: ${sessionFile}`,\n\t\t);\n\t}\n\treturn realSessionFile;\n}\n\nfunction resolveNestedResumeTarget(\n\tmatch: ResolvedSubagentRunId & { kind: \"nested\" },\n\ttrustedSessionRoots: string[],\n): NestedResumeSourceTarget {\n\tconst run = match.match.run;\n\tif (run.state === \"running\" || run.state === \"queued\")\n\t\tthrow new Error(`Nested run '${run.id}' is live; route the follow-up to the owner process instead.`);\n\tif (run.state === \"stopped\")\n\t\tthrow new Error(`Nested run '${run.id}' was stopped and cannot be resumed. Start a new run instead.`);\n\tconst agent = nestedRunAgent(run);\n\tif (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);\n\tconst state = run.state === \"complete\" || run.state === \"failed\" || run.state === \"paused\" ? run.state : \"failed\";\n\tconst asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);\n\treturn compactOptional<NestedResumeSourceTarget>({\n\t\tkind: \"revive\",\n\t\tsource: \"nested\",\n\t\trunId: run.id,\n\t\tstate,\n\t\tagent,\n\t\tindex: 0,\n\t\tcwd: asyncDir ? path.dirname(asyncDir) : undefined,\n\t\tsessionFile: validateNestedSessionFile(run, trustedSessionRoots),\n\t\t...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),\n\t});\n}\n\nasync function waitForNestedControlResult(\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" },\n\trequestId: string,\n\tignoredFiles: ReadonlySet<string>,\n\ttimeoutMs = 1_000,\n) {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() < deadline) {\n\t\tconst result = findNestedControlResult(target.match.route, requestId, target.match.run.id, ignoredFiles);\n\t\tif (result) return result;\n\t\tawait new Promise((resolve) => setTimeout(resolve, 50));\n\t}\n\treturn undefined;\n}\n\nasync function sendNestedControlRequest(\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" },\n\taction: \"interrupt\" | \"resume\",\n\tmessage?: string,\n) {\n\tconst requestId = randomUUID();\n\tconst ignoredFiles = snapshotNestedEventFiles(target.match.route);\n\tconst requestedAt = Date.now();\n\twriteNestedControlRequest(target.match.route, {\n\t\tts: requestedAt,\n\t\trequestId,\n\t\ttargetRunId: target.match.run.id,\n\t\taction,\n\t\t...(message ? { message } : {}),\n\t});\n\treturn waitForNestedControlResult(target, requestId, ignoredFiles);\n}\n\nfunction directNestedAsyncInterrupt(\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" },\n): AgentToolResult<Details> | undefined {\n\tconst run = target.match.run;\n\tconst asyncDir = resolveNestedAsyncDir(target.match.rootRunId, run);\n\tif (!asyncDir) return undefined;\n\tconst status = reconcileAsyncRun(asyncDir, {\n\t\tresultsDir: path.join(DIRS.results, \"nested\", target.match.rootRunId),\n\t}).status;\n\tconst pid = typeof status?.pid === \"number\" && status.pid > 0 ? status.pid : run.pid;\n\tif (!status || status.state !== \"running\" || typeof pid !== \"number\" || pid <= 0) return undefined;\n\ttry {\n\t\tdeliverInterruptRequest({ asyncDir, pid, source: \"nested-interrupt\" });\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Interrupt requested for nested async run ${run.id}.` }],\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to interrupt nested async run ${run.id}: ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n}\n\nasync function directNestedAsyncSteer(input: {\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" };\n\tmessage: string;\n\tmode?: SteerDeliveryMode;\n\tindex?: number;\n\tsignal?: AbortSignal;\n}): Promise<AgentToolResult<Details> | undefined> {\n\tconst run = input.target.match.run;\n\tconst asyncDir = resolveNestedAsyncDir(input.target.match.rootRunId, run);\n\tif (!asyncDir) return undefined;\n\tconst status = reconcileAsyncRun(asyncDir, {\n\t\tresultsDir: path.join(DIRS.results, \"nested\", input.target.match.rootRunId),\n\t}).status;\n\tif (!status || (status.state !== \"running\" && status.state !== \"queued\")) return undefined;\n\tconst steps = status.steps ?? [];\n\tif (input.index !== undefined) {\n\t\tif (input.index < 0 || input.index >= steps.length)\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Nested async run ${run.id} has ${steps.length} children. Index ${input.index} is out of range.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t};\n\t\tconst step = steps[input.index];\n\t\tif (step && step.status !== \"running\" && step.status !== \"pending\")\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Nested async run ${run.id} child ${input.index} is ${step.status} and cannot be steered.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t};\n\t}\n\tconst runningIndexes = steps\n\t\t.map((step, index) => (step.status === \"running\" ? index : undefined))\n\t\t.filter((index): index is number => index !== undefined);\n\tconst effectiveTargetIndex =\n\t\tinput.index ??\n\t\t(status.mode === \"single\" && runningIndexes.length === 0 && steps[0]?.status === \"pending\" ? 0 : undefined);\n\tconst targetIndexes = effectiveTargetIndex !== undefined ? [effectiveTargetIndex] : runningIndexes;\n\tif (targetIndexes.length === 0)\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Nested async run ${run.id} has no running child to steer.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tconst requestId = randomUUID();\n\ttry {\n\t\trequestAsyncSteer(asyncDir, {\n\t\t\tmessage: input.message,\n\t\t\tmode: input.mode,\n\t\t\t...(effectiveTargetIndex !== undefined ? { targetIndex: effectiveTargetIndex } : { targetIndexes }),\n\t\t\tsource: \"nested-steer\",\n\t\t\tid: requestId,\n\t\t});\n\t} catch (error) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Failed to queue steering for nested async run ${run.id}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst targets = targetIndexes.map((index) => ({\n\t\tindex,\n\t\tstate: steps[index]?.status === \"pending\" ? (\"scheduled\" as const) : (\"pending\" as const),\n\t}));\n\tif (targets.every((target) => target.state === \"scheduled\")) {\n\t\tconst scheduled = {\n\t\t\trequestId,\n\t\t\tstate: \"scheduled\" as const,\n\t\t\tdeliveryStatus: \"queued\" as const,\n\t\t\tsourceRunId: run.id,\n\t\t\ttargets,\n\t\t};\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Steering scheduled for nested async run ${run.id} (request ${requestId}).` }],\n\t\t\tdetails: { mode: \"management\", results: [], steering: scheduled },\n\t\t};\n\t}\n\tconst waited = await waitForSteeringAction(\n\t\tomitUndefinedProperties({ asyncDir, sourceRunId: run.id, requestId, timeoutMs: 3_000, signal: input.signal }),\n\t);\n\tconst result = waited ?? {\n\t\trequestId,\n\t\tstate: \"pending\" as const,\n\t\tdeliveryStatus: \"queued\" as const,\n\t\tsourceRunId: run.id,\n\t\ttargets,\n\t};\n\tconst stateText =\n\t\tresult.state === \"failed\"\n\t\t\t? \"failed\"\n\t\t\t: result.state === \"partial\"\n\t\t\t\t? \"partial\"\n\t\t\t\t: result.deliveryStatus === \"queued\"\n\t\t\t\t\t? \"queued\"\n\t\t\t\t\t: result.state === \"delivered\"\n\t\t\t\t\t\t? \"delivered\"\n\t\t\t\t\t\t: \"pending\";\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Steering ${stateText} for nested async run ${run.id} (request ${requestId}).` }],\n\t\t...(result.state === \"failed\" || result.state === \"partial\" ? { isError: true } : {}),\n\t\tdetails: { mode: \"management\", results: [], steering: result },\n\t};\n}\n\nasync function interruptNestedRun(\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" },\n): Promise<AgentToolResult<Details>> {\n\tconst run = target.match.run;\n\tif (run.state === \"complete\")\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Nested run ${run.id} is already complete and cannot be interrupted.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tif (run.state === \"failed\")\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Nested run ${run.id} has failed and cannot be interrupted.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tif (run.state === \"paused\")\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Nested run ${run.id} is already paused.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tconst result = await sendNestedControlRequest(target, \"interrupt\");\n\tif (result)\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.message }],\n\t\t\t...(result.ok ? {} : { isError: true }),\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tconst direct = directNestedAsyncInterrupt(target);\n\tif (direct) return direct;\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Nested run ${run.id} owner is not reachable and no safe direct async interrupt fallback is available.`,\n\t\t\t},\n\t\t],\n\t\tisError: true,\n\t\tdetails: { mode: \"management\", results: [] },\n\t};\n}\n\nasync function resumeLiveNestedRun(input: {\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" };\n\tmessage: string;\n}): Promise<AgentToolResult<Details>> {\n\tconst run = input.target.match.run;\n\tconst result = await sendNestedControlRequest(input.target, \"resume\", input.message);\n\tif (result)\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: result.message }],\n\t\t\t...(result.ok ? {} : { isError: true }),\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Nested run ${run.id} appears live but its owner route is not reachable. Wait for completion, then retry action='resume'.`,\n\t\t\t},\n\t\t],\n\t\tisError: true,\n\t\tdetails: { mode: \"management\", results: [] },\n\t};\n}\n\nasync function steerNestedRun(input: {\n\ttarget: ResolvedSubagentRunId & { kind: \"nested\" };\n\tmessage: string;\n\tmode?: SteerDeliveryMode;\n\tindex?: number;\n\tsignal?: AbortSignal;\n}): Promise<AgentToolResult<Details>> {\n\tconst run = input.target.match.run;\n\tif (run.state !== \"running\" && run.state !== \"queued\")\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Nested run ${run.id} is ${run.state} and cannot be steered.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\tconst direct = await directNestedAsyncSteer(input);\n\tif (direct) return direct;\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Nested run ${run.id} is not a live async Pi child session with a steering inbox. action='steer' cannot target foreground nested runs.`,\n\t\t\t},\n\t\t],\n\t\tisError: true,\n\t\tdetails: { mode: \"management\", results: [] },\n\t};\n}\n\nfunction externalRunnerControlError(\n\tasyncDir: string,\n\taction: \"steer\" | \"resume\",\n): AgentToolResult<Details> | undefined {\n\tconst status = readStatus(asyncDir);\n\tif (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === \"external-cli\")) return undefined;\n\tconst message =\n\t\taction === \"steer\"\n\t\t\t? \"One-shot external CLI runners do not accept live steer messages.\"\n\t\t\t: \"One-shot external CLI runners do not persist sessions and cannot be resumed.\";\n\treturn { content: [{ type: \"text\", text: message }], isError: true, details: { mode: \"management\", results: [] } };\n}\n\nasync function resumeAsyncRun(input: {\n\tparams: SubagentParamsLike;\n\trequestCwd: string;\n\tctx: ExtensionContext;\n\tdeps: ExecutorDeps;\n\tparentModel?: ParentModel;\n\tabsoluteDeadlineAt?: number;\n}): Promise<AgentToolResult<Details>> {\n\tconst followUp = (input.params.message ?? input.params.task ?? \"\").trim();\n\tconst attachChain = (input.params.chain?.length ?? 0) > 0 ? (input.params.chain as ChainStep[]) : undefined;\n\tif (!followUp && !attachChain) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"action='resume' requires message.\" }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tif (input.params.model !== undefined) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: \"action='resume' reuses the persisted child model and does not accept a model override.\",\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst acceptanceErrors = validateExecutionAcceptance(\n\t\tinput.params as Parameters<typeof validateExecutionAcceptance>[0],\n\t);\n\tif (acceptanceErrors.length > 0) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Cannot resume: ${acceptanceErrors.join(\" \")}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tinput.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);\n\n\tlet target: ResumeSourceTarget;\n\tconst parentSessionFile = input.ctx.sessionManager.getSessionFile() ?? null;\n\ttry {\n\t\tconst requestedId = input.params.id ?? input.params.runId;\n\t\tlet resolved: ResolvedSubagentRunId | undefined;\n\t\ttry {\n\t\t\tresolved = requestedId\n\t\t\t\t? resolveSubagentRunId(\n\t\t\t\t\t\trequestedId,\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tstate: input.deps.state,\n\t\t\t\t\t\t\tnested: nestedResolutionScopeForExecutor(input.deps),\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"\";\n\t\t\tconst asyncMatches = message.match(/async:/g)?.length ?? 0;\n\t\t\tif (!isResumeAmbiguity(error) || !message.includes(\"foreground:\") || asyncMatches !== 1) throw error;\n\t\t}\n\t\tif (resolved?.kind === \"nested\") {\n\t\t\tif (attachChain) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Attaching a running subagent as a chain root is currently available for top-level async runs only.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (resolved.match.run.state === \"running\" || resolved.match.run.state === \"queued\") {\n\t\t\t\treturn resumeLiveNestedRun({ target: resolved, message: followUp });\n\t\t\t}\n\t\t\tconst trustedSessionRoots = [\n\t\t\t\t...(input.deps.config.defaultSessionDir\n\t\t\t\t\t? [path.resolve(input.deps.expandTilde(input.deps.config.defaultSessionDir))]\n\t\t\t\t\t: []),\n\t\t\t\t...(parentSessionFile ? [input.deps.getSubagentSessionRoot(parentSessionFile)] : []),\n\t\t\t];\n\t\t\ttarget = resolveNestedResumeTarget(resolved, trustedSessionRoots);\n\t\t} else {\n\t\t\tif (resolved?.kind === \"async\" && resolved.location.asyncDir) {\n\t\t\t\tconst unsupported = externalRunnerControlError(resolved.location.asyncDir, \"resume\");\n\t\t\t\tif (unsupported) return unsupported;\n\t\t\t}\n\t\t\ttarget = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: !attachChain });\n\t\t}\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tif (target.kind === \"live\" && !attachChain) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: [\n\t\t\t\t\t\t`Async child '${target.runId}' index ${target.index} is still running. action='resume' only revives paused, completed, or failed children.`,\n\t\t\t\t\t\t`Send live input with subagent({ action: \"steer\", id: \"${target.runId}\", index: ${target.index}, message: \"...\" }).`,\n\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tconst { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);\n\tif (blocked) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tinput.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);\n\tconst effectiveCwd = target.cwd ?? input.requestCwd;\n\tconst scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);\n\tconst discovered = input.deps.discoverAgents(effectiveCwd, scope);\n\tconst discoveredAgents = discovered.agents;\n\tconst modelScope = discovered.modelScope;\n\tconst sessionName = resolveIntercomSessionTarget(\n\t\tinput.deps.pi.getSessionName(),\n\t\tinput.ctx.sessionManager.getSessionId(),\n\t);\n\tconst intercomBridge = resolveIntercomBridge({\n\t\tconfig: input.deps.config.intercomBridge,\n\t\tcontext: input.params.context,\n\t\torchestratorTarget: sessionName,\n\t});\n\tconst agents = intercomBridge.active\n\t\t? discoveredAgents.map((agent) => applyIntercomBridgeToAgent(agent, intercomBridge))\n\t\t: discoveredAgents;\n\tconst recoveryDescriptor = \"recoveryDescriptor\" in target ? target.recoveryDescriptor : undefined;\n\tconst discoveredAgentConfig = agents.find((agent) => agent.name === target.agent);\n\tconst agentConfig: AgentConfig | undefined =\n\t\tdiscoveredAgentConfig ??\n\t\t(recoveryDescriptor\n\t\t\t? {\n\t\t\t\t\tname: recoveryDescriptor.agent,\n\t\t\t\t\tdescription: \"Persisted async recovery contract\",\n\t\t\t\t\tsystemPrompt: \"\",\n\t\t\t\t\tsystemPromptMode: recoveryDescriptor.systemPromptMode,\n\t\t\t\t\tinheritProjectContext: recoveryDescriptor.inheritProjectContext,\n\t\t\t\t\tinheritSkills: recoveryDescriptor.inheritSkills,\n\t\t\t\t\tsource: \"project\",\n\t\t\t\t\tfilePath:\n\t\t\t\t\t\trecoveryDescriptor.agentFilePath ?? path.join(recoveryDescriptor.cwd, \".pi-subagents-recovery-agent\"),\n\t\t\t\t}\n\t\t\t: undefined);\n\tif (!agentConfig) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Unknown agent for resume: ${target.agent}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\n\tif (attachChain) {\n\t\tif (target.source !== \"async\") {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Attaching a running subagent as a chain root is currently available for async runs only.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t};\n\t\t}\n\t\tif (!isAsyncAvailable()) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\", results: [] },\n\t\t\t};\n\t\t}\n\t\tconst runId = randomUUID().slice(0, 8);\n\t\tconst artifactConfig: ArtifactConfig = omitUndefinedProperties({\n\t\t\t...DEFAULT_ARTIFACT_CONFIG,\n\t\t\tenabled: input.params.artifacts !== false,\n\t\t\tdir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,\n\t\t});\n\t\tconst availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);\n\t\tconst contextPolicy = resolveExplicitContextPolicy(input.params);\n\t\tconst workflowTask = (input.params.task ?? followUp) || undefined;\n\t\tconst goal = resolveAsyncEventGoal(workflowTask, attachChain);\n\t\tconst chain = wrapChainTasksForFork(attachChain, contextPolicy);\n\t\tconst normalized = normalizeSkillInput(input.params.skill);\n\t\tconst parentModel = input.parentModel;\n\t\tconst result = executeAsyncChain(\n\t\t\trunId,\n\t\t\tcompactOptional<Parameters<typeof executeAsyncChain>[1]>({\n\t\t\t\tchain,\n\t\t\t\ttask: workflowTask,\n\t\t\t\tgoal,\n\t\t\t\tattachRoot: {\n\t\t\t\t\trunId: target.runId,\n\t\t\t\t\tasyncDir: target.asyncDir ?? path.join(DIRS.async, target.runId),\n\t\t\t\t\tresultPath: resolveAsyncRootResultPath(DIRS.results, target.runId),\n\t\t\t\t\tindex: target.index,\n\t\t\t\t\tagent: target.agent,\n\t\t\t\t\tlabel: `Attached ${target.runId}`,\n\t\t\t\t},\n\t\t\t\tagents,\n\t\t\t\tctx: compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\t\t\t\tpi: input.deps.pi,\n\t\t\t\t\tcwd: input.requestCwd,\n\t\t\t\t\tcurrentSessionId: input.deps.state.currentSessionId,\n\t\t\t\t\tparentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,\n\t\t\t\t\tcurrentModelProvider: parentModel?.provider,\n\t\t\t\t\tcurrentModel: parentModel,\n\t\t\t\t\tmodelScope,\n\t\t\t\t\tinteractive: input.ctx.hasUI,\n\t\t\t\t\tpermissions: input.deps.config.permissions,\n\t\t\t\t}),\n\t\t\t\tavailableModels,\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tmaxOutput: input.params.maxOutput,\n\t\t\t\tartifactsDir: getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir),\n\t\t\t\tartifactConfig,\n\t\t\t\tshareEnabled: input.params.share === true,\n\t\t\t\tsessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),\n\t\t\t\tchainSkills: normalized === false ? [] : (normalized ?? []),\n\t\t\t\tagentContract: input.params.agentContract,\n\t\t\t\tdynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\tmaxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),\n\t\t\t\twaitToolEnabled: input.deps.waitToolEnabled,\n\t\t\t\tworktreeSetupHook: input.deps.config.worktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir: input.deps.config.worktreeBaseDir,\n\t\t\t\tcontrolConfig: resolveControlConfig(input.deps.config.control, input.params.control),\n\t\t\t\tcontrolIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,\n\t\t\t\tchildIntercomTarget: intercomBridge.active\n\t\t\t\t\t? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index)\n\t\t\t\t\t: undefined,\n\t\t\t\tglobalConcurrencyLimit: input.deps.config.globalConcurrencyLimit,\n\t\t\t\tcapabilityCeiling: intersectSubagentCapabilityCeilings(\n\t\t\t\t\t\"capabilityCeiling\" in target ? target.capabilityCeiling : undefined,\n\t\t\t\t\tresolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId),\n\t\t\t\t),\n\t\t\t}),\n\t\t);\n\t\tif (result.isError) return result;\n\t\tconst attachedId = result.details.asyncId ?? runId;\n\t\tconst lines = [\n\t\t\t`Attached async subagent ${target.runId} as the first step of a new chain.`,\n\t\t\t`Chain run: ${attachedId}`,\n\t\t\t`Root: ${target.agent} (step ${target.index + 1})`,\n\t\t\tresult.details.asyncDir ? `Async dir: ${result.details.asyncDir}` : undefined,\n\t\t\t`Status if needed: subagent({ action: \"status\", id: \"${attachedId}\" })`,\n\t\t].filter((line): line is string => Boolean(line));\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(lines.join(\"\\n\"), input.ctx.hasUI) }],\n\t\t\tdetails: result.details,\n\t\t};\n\t}\n\n\tconst sourceAsyncDir = target.source === \"async\" ? target.asyncDir : undefined;\n\tconst queuedBriefs = sourceAsyncDir ? readRevivalBriefs(sourceAsyncDir) : [];\n\tconst effectiveFollowUp = [...queuedBriefs.map(({ request }) => request.message), followUp]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\tconst revivalSessionFile = target.sessionFile;\n\tif (!revivalSessionFile) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Async child '${target.runId}' has no persisted session file to resume.` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t};\n\t}\n\tconst runId = randomUUID().slice(0, 8);\n\tconst recoveryAgentConfig = recoveryDescriptor\n\t\t? applySteeringRecoveryAgentConfig(agentConfig, recoveryDescriptor)\n\t\t: agentConfig;\n\tconst artifactConfig: ArtifactConfig =\n\t\trecoveryDescriptor?.artifactConfig ??\n\t\tomitUndefinedProperties({\n\t\t\t...DEFAULT_ARTIFACT_CONFIG,\n\t\t\tenabled: input.params.artifacts !== false,\n\t\t\tdir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,\n\t\t});\n\tconst artifactsDir =\n\t\trecoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);\n\tconst availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);\n\tconst parentModel = input.parentModel;\n\tconst result = executeAsyncSingle(\n\t\trunId,\n\t\tcompactOptional<Parameters<typeof executeAsyncSingle>[1]>({\n\t\t\tagent: target.agent,\n\t\t\ttask: buildRevivedAsyncTask(target as Parameters<typeof buildRevivedAsyncTask>[0], effectiveFollowUp),\n\t\t\tgoal: effectiveFollowUp,\n\t\t\tagentConfig: recoveryAgentConfig,\n\t\t\tctx: compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\t\t\tpi: input.deps.pi,\n\t\t\t\tcwd: input.requestCwd,\n\t\t\t\tcurrentSessionId: input.deps.state.currentSessionId,\n\t\t\t\tparentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,\n\t\t\t\tcurrentModelProvider: parentModel?.provider,\n\t\t\t\tcurrentModel: parentModel,\n\t\t\t\tmodelScope,\n\t\t\t\tinteractive: input.ctx.hasUI,\n\t\t\t\tpermissions: input.deps.config.permissions,\n\t\t\t}),\n\t\t\tcwd: effectiveCwd,\n\t\t\tmaxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,\n\t\t\tartifactsDir,\n\t\t\tartifactConfig,\n\t\t\tshareEnabled: recoveryDescriptor?.share ?? input.params.share === true,\n\t\t\tsessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile ?? revivalSessionFile),\n\t\t\t...(recoveryDescriptor?.sessionDir ? { sessionDir: recoveryDescriptor.sessionDir } : {}),\n\t\t\tsessionFile: revivalSessionFile,\n\t\t\trevivalLease: {\n\t\t\t\tsessionFile: revivalSessionFile,\n\t\t\t\trunId,\n\t\t\t\tsourceRunId: target.runId,\n\t\t\t\t...(input.deps.state.currentSessionId ? { parentSessionId: input.deps.state.currentSessionId } : {}),\n\t\t\t},\n\t\t\tmodelOverride: recoveryDescriptor?.model ?? target.model,\n\t\t\tthinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,\n\t\t\toutputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),\n\t\t\tmaxSubagentDepth:\n\t\t\t\trecoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),\n\t\t\twaitToolEnabled: input.deps.waitToolEnabled,\n\t\t\tworktreeSetupHook: input.deps.config.worktreeSetupHook,\n\t\t\tworktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,\n\t\t\tworktreeBaseDir: input.deps.config.worktreeBaseDir,\n\t\t\tcontrolConfig:\n\t\t\t\trecoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),\n\t\t\tcontrolIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,\n\t\t\tchildIntercomTarget: intercomBridge.active\n\t\t\t\t? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index)\n\t\t\t\t: undefined,\n\t\t\tavailableModels,\n\t\t\toutput: typeof input.params.output === \"string\" ? input.params.output : recoveryDescriptor?.outputPath,\n\t\t\toutputMode: input.params.outputMode ?? recoveryDescriptor?.outputMode,\n\t\t\t...(recoveryDescriptor?.agentContract ? { agentContract: recoveryDescriptor.agentContract } : {}),\n\t\t\t...(recoveryDescriptor?.structuredOutputSchema\n\t\t\t\t? { structuredOutputSchema: recoveryDescriptor.structuredOutputSchema }\n\t\t\t\t: {}),\n\t\t\t...(recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {}),\n\t\t\t...(recoveryDescriptor?.acceptance !== undefined && input.params.acceptance === undefined\n\t\t\t\t? { acceptance: recoveryDescriptor.acceptance }\n\t\t\t\t: {}),\n\t\t\t...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),\n\t\t\t...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),\n\t\t\t...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),\n\t\t\t...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),\n\t\t\tcapabilityCeiling: intersectSubagentCapabilityCeilings(\n\t\t\t\t\"capabilityCeiling\" in target ? target.capabilityCeiling : undefined,\n\t\t\t\trecoveryDescriptor?.capabilityCeiling,\n\t\t\t\tresolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId),\n\t\t\t),\n\t\t\tparentWorkflowRunId: input.params.workflowParentRunId,\n\t\t\tworkflowKey: input.params.workflowKey,\n\t\t}),\n\t);\n\tif (result.isError) return result;\n\tfor (const brief of queuedBriefs) fs.rmSync(brief.path, { force: true });\n\tif (queuedBriefs.length > 0 && sourceAsyncDir) {\n\t\tconst sourceStatus = readStatus(sourceAsyncDir);\n\t\tif (sourceStatus?.steering) {\n\t\t\tfor (const brief of queuedBriefs)\n\t\t\t\tupdateSteeringTarget(sourceStatus.steering, brief.request.id, target.index, \"delivered\", Date.now());\n\t\t\twriteAtomicJson(path.join(sourceAsyncDir, \"status.json\"), sourceStatus);\n\t\t}\n\t}\n\n\tconst revivedId = result.details.asyncId ?? runId;\n\tconst revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;\n\tconst sourceLabel = target.source;\n\tconst lines = [\n\t\t`Revived ${sourceLabel} subagent from ${target.runId}.`,\n\t\t`Revived run: ${revivedId}`,\n\t\t`Agent: ${target.agent}`,\n\t\t`Session: ${target.sessionFile}`,\n\t\tresult.details.asyncDir ? `Async dir: ${result.details.asyncDir}` : undefined,\n\t\trevivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : undefined,\n\t\t`Status if needed: subagent({ action: \"status\", id: \"${revivedId}\" })`,\n\t].filter((line): line is string => Boolean(line));\n\treturn {\n\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(lines.join(\"\\n\"), input.ctx.hasUI) }],\n\t\tdetails: {\n\t\t\t...result.details,\n\t\t\t...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),\n\t\t},\n\t};\n}\n\nfunction resultSummaryForIntercom(result: SingleResult): string {\n\tconst output = getSingleResultOutput(result);\n\tif (result.exitCode !== 0 && result.error) {\n\t\treturn output ? `${result.error}\\n\\nOutput:\\n${output}` : result.error;\n\t}\n\treturn output || result.error || \"(no output)\";\n}\n\nfunction formatFailedSingleRunOutput(result: SingleResult, displayOutput: string): string {\n\tconst error = result.error || \"Failed\";\n\tconst output = displayOutput.trim();\n\tconst lines = [error];\n\tif (output && output !== error.trim()) {\n\t\tlines.push(\"\", \"Output:\", output);\n\t}\n\tif (result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {\n\t\tlines.push(\"\", `Output artifact: ${result.artifactPaths.outputPath}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction createForegroundControlNotifier(\n\tdata: Pick<ExecutionContextData, \"controlConfig\" | \"intercomBridge\">,\n\tdeps: Pick<ExecutorDeps, \"pi\" | \"state\">,\n): (event: ControlEvent) => void {\n\treturn (event) => {\n\t\tapplyControlEventToRememberedForegroundRun(deps.state, event);\n\t\temitControlNotification({\n\t\t\tpi: deps.pi,\n\t\t\tcontrolConfig: data.controlConfig,\n\t\t\tintercomBridge: data.intercomBridge,\n\t\t\tevent,\n\t\t});\n\t};\n}\n\nexport function foregroundResultIntercomStatus(result: SingleResult): ReturnType<typeof resolveSubagentResultStatus> {\n\treturn resolveSubagentResultStatus(\n\t\tomitUndefinedProperties({\n\t\t\texitCode: result.exitCode,\n\t\t\t...(result.acceptance?.status === \"rejected\" ? { success: false } : {}),\n\t\t\tinterrupted: result.interrupted,\n\t\t\tdetached: result.detached,\n\t\t\tprocessSignal: result.processSignal,\n\t\t\ttimedOut: result.timedOut,\n\t\t\tstopped: result.stopped,\n\t\t\tturnBudgetExceeded: result.turnBudgetExceeded,\n\t\t}),\n\t);\n}\n\nexport function shouldSuppressRoutineResultIntercom(input: {\n\tsuppressRoutineResultIntercom?: boolean;\n\tresults: SingleResult[];\n}): boolean {\n\treturn (\n\t\tinput.suppressRoutineResultIntercom === true &&\n\t\tinput.results.length > 0 &&\n\t\tinput.results.every((result) => foregroundResultIntercomStatus(result) === \"completed\")\n\t);\n}\n\nasync function emitForegroundResultIntercom(input: {\n\tpi: ExtensionAPI;\n\tintercomBridge: IntercomBridgeState;\n\trunId: string;\n\tmode: SubagentRunMode;\n\tresults: SingleResult[];\n\tchainSteps?: number;\n\tnestedChildren?: NestedRunSummary[];\n\tparallelHandoff?: Details[\"parallelHandoff\"];\n}): Promise<ReturnType<typeof buildSubagentResultIntercomPayload> | null> {\n\tif (!input.intercomBridge.active || !input.intercomBridge.resultDelivery || !input.intercomBridge.orchestratorTarget)\n\t\treturn null;\n\tconst children = input.results.flatMap((result, index) =>\n\t\tresult.detached\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: result.agent,\n\t\t\t\t\t\tstatus: foregroundResultIntercomStatus(result),\n\t\t\t\t\t\toutputState: result.outputState ?? \"unknown\",\n\t\t\t\t\t\tsummary: resultSummaryForIntercom(result),\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\tartifactPath: result.artifactPaths?.outputPath,\n\t\t\t\t\t\tsessionPath: result.sessionFile,\n\t\t\t\t\t\tintercomTarget: resolveSubagentIntercomTarget(input.runId, result.agent, index),\n\t\t\t\t\t}),\n\t\t\t\t],\n\t);\n\tif (children.length === 0) return null;\n\tconst payload = buildSubagentResultIntercomPayload({\n\t\tto: input.intercomBridge.orchestratorTarget,\n\t\trunId: input.runId,\n\t\tmode: input.mode,\n\t\tsource: \"foreground\",\n\t\tchildren: attachNestedChildrenToResultChildren(input.runId, children, input.nestedChildren),\n\t\t...(typeof input.chainSteps === \"number\" ? { chainSteps: input.chainSteps } : {}),\n\t\t...(input.parallelHandoff ? { parallelHandoff: input.parallelHandoff } : {}),\n\t});\n\tconst delivered = await deliverSubagentResultIntercomEvent(input.pi.events, payload);\n\tif (!delivered) return null;\n\treturn payload;\n}\n\nasync function maybeBuildForegroundIntercomReceipt(input: {\n\tpi: ExtensionAPI;\n\tintercomBridge: IntercomBridgeState;\n\trunId: string;\n\tmode: SubagentRunMode;\n\tdetails: Details;\n\tnestedChildren?: NestedRunSummary[];\n\tpreserveDetailsOutputs?: boolean;\n}): Promise<{ text: string; details: Details } | null> {\n\tconst payload = await emitForegroundResultIntercom({\n\t\tpi: input.pi,\n\t\tintercomBridge: input.intercomBridge,\n\t\trunId: input.runId,\n\t\tmode: input.mode,\n\t\tresults: input.details.results,\n\t\t...(typeof input.details.totalSteps === \"number\" ? { chainSteps: input.details.totalSteps } : {}),\n\t\t...(input.nestedChildren?.length ? { nestedChildren: input.nestedChildren } : {}),\n\t\t...(input.details.parallelHandoff ? { parallelHandoff: input.details.parallelHandoff } : {}),\n\t});\n\tif (!payload) return null;\n\treturn {\n\t\ttext: formatSubagentResultReceipt({ mode: input.mode, runId: input.runId, payload }),\n\t\tdetails: input.preserveDetailsOutputs ? input.details : stripDetailsOutputsForIntercomReceipt(input.details),\n\t};\n}\n\nconst DEFAULT_DIRECT_AGENT = \"worker\";\n\nfunction applyDefaultDirectAgent(\n\tparams: SubagentParamsLike,\n\tagents: AgentConfig[],\n): { params?: SubagentParamsLike; error?: string } {\n\tif (params.agent !== undefined || params.task === undefined) return { params };\n\tif (agents.some((agent) => agent.name === DEFAULT_DIRECT_AGENT && agent.disabled !== true))\n\t\treturn { params: { ...params, agent: DEFAULT_DIRECT_AGENT } };\n\treturn {\n\t\terror: `The default direct agent '${DEFAULT_DIRECT_AGENT}' is unavailable or disabled. Pass an explicit agent or enable '${DEFAULT_DIRECT_AGENT}'.`,\n\t};\n}\n\nfunction canonicalizeAgentName(name: string, agents: AgentConfig[]): { name?: string; error?: string } {\n\tconst resolved = resolveAgentName(name, agents);\n\tif (resolved.error) return { error: resolved.error };\n\tif (!resolved.agent) return { error: `Unknown agent: ${name}` };\n\treturn { name: resolved.agent.name };\n}\n\nfunction canonicalizeExecutionParams(\n\tparams: SubagentParamsLike,\n\tagents: AgentConfig[],\n): { params?: SubagentParamsLike; error?: string } {\n\tconst resolve = (name: string, location?: string): { name?: string; error?: string } => {\n\t\tconst result = canonicalizeAgentName(name, agents);\n\t\treturn result.error && location ? { error: `${result.error} (${location})` } : result;\n\t};\n\tif (params.agent) {\n\t\tconst result = resolve(params.agent);\n\t\tif (result.error) return { error: result.error };\n\t\tparams = omitUndefinedProperties({ ...params, agent: result.name });\n\t}\n\tif (params.tasks) {\n\t\tconst tasks: TaskParam[] = [];\n\t\tfor (let index = 0; index < params.tasks.length; index++) {\n\t\t\tconst task = params.tasks[index]!;\n\t\t\tconst result = resolve(task.agent, `task ${index + 1}`);\n\t\t\tif (result.error) return { error: result.error };\n\t\t\ttasks.push({ ...task, agent: result.name! });\n\t\t}\n\t\tparams = { ...params, tasks };\n\t}\n\tif (params.chain) {\n\t\tconst chain: ChainStep[] = [];\n\t\tfor (let index = 0; index < params.chain.length; index++) {\n\t\t\tconst step = params.chain[index]!;\n\t\t\tif (isParallelStep(step)) {\n\t\t\t\tconst parallel: ParallelTaskItem[] = [];\n\t\t\t\tfor (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {\n\t\t\t\t\tconst task = step.parallel[taskIndex]!;\n\t\t\t\t\tconst result = resolve(task.agent, `step ${index + 1}, task ${taskIndex + 1}`);\n\t\t\t\t\tif (result.error) return { error: result.error };\n\t\t\t\t\tparallel.push({ ...task, agent: result.name! });\n\t\t\t\t}\n\t\t\t\tchain.push({ ...step, parallel });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isDynamicParallelStep(step)) {\n\t\t\t\tconst result = resolve(step.parallel.agent, `step ${index + 1}`);\n\t\t\t\tif (result.error) return { error: result.error };\n\t\t\t\tchain.push({ ...step, parallel: { ...step.parallel, agent: result.name! } });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\"agent\" in step && typeof step.agent === \"string\") {\n\t\t\t\tconst result = resolve(step.agent, `step ${index + 1}`);\n\t\t\t\tif (result.error) return { error: result.error };\n\t\t\t\tchain.push({ ...step, agent: result.name! });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchain.push(step);\n\t\t}\n\t\tparams = { ...params, chain };\n\t}\n\treturn { params };\n}\n\nfunction validateExecutionInput(\n\tparams: SubagentParamsLike,\n\tagents: AgentConfig[],\n\thasChain: boolean,\n\thasTasks: boolean,\n\thasSingle: boolean,\n\tallowClarifyTaskPrompt: boolean,\n): AgentToolResult<Details> | null {\n\tif (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Provide exactly one mode. Agents: ${agents.map((a) => a.name).join(\", \") || \"none\"}`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t};\n\t}\n\n\tconst acceptanceErrors = validateExecutionAcceptance(params as Parameters<typeof validateExecutionAcceptance>[0]);\n\tif (acceptanceErrors.length > 0) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: acceptanceErrors.join(\" \") }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: getRequestedModeLabel(params), results: [] },\n\t\t};\n\t}\n\n\tif (hasSingle && params.agent && !agents.find((agent) => agent.name === params.agent)) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${params.agent}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t};\n\t}\n\n\tif (hasTasks && params.tasks) {\n\t\tfor (let i = 0; i < params.tasks.length; i++) {\n\t\t\tconst task = params.tasks[i]!;\n\t\t\tif (!agents.find((agent) => agent.name === task.agent)) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${task.agent} (task ${i + 1})` }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"parallel\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (hasChain && params.chain) {\n\t\tif (params.chain.length === 0) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: \"Chain must have at least one step\" }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tconst firstStep = params.chain[0] as ChainStep;\n\t\tif (isParallelStep(firstStep)) {\n\t\t\tconst missingTaskIndex = firstStep.parallel.findIndex((t) => !t.task);\n\t\t\tif (missingTaskIndex !== -1) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `First parallel step: task ${missingTaskIndex + 1} must have a task (no previous output to reference)`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (isDynamicParallelStep(firstStep)) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"First step in chain cannot be dynamic fanout; expand.from requires a prior structured named output\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t} else if (!(firstStep as SequentialStep).task && !params.task && !allowClarifyTaskPrompt) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: \"First step in chain must have a task\" }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tfor (let i = 0; i < params.chain.length; i++) {\n\t\t\tconst step = params.chain[i] as ChainStep;\n\t\t\tconst stepAgents = getStepAgents(step);\n\t\t\tfor (const agentName of stepAgents) {\n\t\t\t\tif (!agents.find((a) => a.name === agentName)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${agentName} (step ${i + 1})` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isParallelStep(step) && step.parallel.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Parallel step ${i + 1} must have at least one task` }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction validateExecutionChainBindings(\n\tparams: SubagentParamsLike,\n\tdynamicFanoutMaxItems?: number,\n): AgentToolResult<Details> | null {\n\tif ((params.chain?.length ?? 0) === 0) return null;\n\ttry {\n\t\tvalidateChainOutputBindingsWithContext(\n\t\t\tparams.chain as ChainStep[],\n\t\t\tdynamicFanoutMaxItems === undefined ? {} : { maxItems: dynamicFanoutMaxItems },\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof ChainOutputValidationError) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: error.message }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n\treturn null;\n}\n\nfunction getRequestedModeLabel(params: SubagentParamsLike): Details[\"mode\"] {\n\tif (params.workflowScript !== undefined) return \"workflow\";\n\tif ((params.chain?.length ?? 0) > 0) return \"chain\";\n\tif ((params.tasks?.length ?? 0) > 0) return \"parallel\";\n\tif (params.agent) return \"single\";\n\treturn \"single\";\n}\n\ninterface AgentDefaultContextPolicy {\n\tparams: SubagentParamsLike;\n\tcontextForAgent(agentName: string): ContextMode;\n\tcontextSummary?: ContextSummary;\n\tusesFork: boolean;\n}\n\nfunction resolveAgentDefaultContextPolicy(\n\tparams: SubagentParamsLike,\n\tagents: AgentConfig[],\n): AgentDefaultContextPolicy {\n\tif (params.context !== undefined) {\n\t\treturn resolveExplicitContextPolicy(params);\n\t}\n\tconst byName = new Map(agents.map((agent) => [agent.name, agent]));\n\tconst contextForAgent = (agentName: string): ContextMode =>\n\t\tbyName.get(agentName)?.defaultContext === \"fork\" ? \"fork\" : \"fresh\";\n\tconst requestedAgentNames = collectRequestedAgentNames(params);\n\tconst contextSummary = summarizeContextModes(requestedAgentNames.map((name) => contextForAgent(name)));\n\tconst usesFork = contextSummary === \"fork\" || contextSummary === \"mixed\";\n\treturn omitUndefinedProperties({\n\t\tparams,\n\t\tcontextForAgent,\n\t\tcontextSummary,\n\t\tusesFork,\n\t});\n}\n\nfunction resolveExplicitContextPolicy(params: SubagentParamsLike): AgentDefaultContextPolicy {\n\tconst context = params.context === \"fork\" ? \"fork\" : \"fresh\";\n\treturn {\n\t\tparams,\n\t\tcontextForAgent: () => context,\n\t\tcontextSummary: context,\n\t\tusesFork: context === \"fork\",\n\t};\n}\n\nfunction collectRequestedAgentNames(params: SubagentParamsLike): string[] {\n\tconst names: string[] = [];\n\tif (params.agent) names.push(params.agent);\n\tfor (const task of params.tasks ?? []) names.push(task.agent);\n\tfor (const step of params.chain ?? []) names.push(...getStepAgents(step));\n\treturn names;\n}\n\nfunction shouldForkAgent(contextPolicy: AgentDefaultContextPolicy, agentName: string): boolean {\n\treturn contextPolicy.contextForAgent(agentName) === \"fork\";\n}\n\nfunction summarizeResultContext(details: Details, fallback: ContextSummary | undefined): ContextSummary | undefined {\n\treturn summarizeContextModes(details.results.map((result) => result.context)) ?? fallback;\n}\n\nfunction buildRequestedModeError(params: SubagentParamsLike, message: string): AgentToolResult<Details> {\n\treturn withResolvedContext(\n\t\t{\n\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: getRequestedModeLabel(params), results: [] },\n\t\t},\n\t\tparams.context,\n\t);\n}\n\nfunction applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: AgentConfig[]): SubagentParamsLike {\n\tif ((params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || !params.agent) return params;\n\tconst agent = agents.find((candidate) => candidate.name === params.agent);\n\tif (!agent) return params;\n\treturn {\n\t\t...params,\n\t\t...(params.async === undefined && agent.defaultAsync !== undefined ? { async: agent.defaultAsync } : {}),\n\t\t...(params.timeoutMs === undefined && params.maxRuntimeMs === undefined && agent.defaultTimeoutMs !== undefined\n\t\t\t? { timeoutMs: agent.defaultTimeoutMs }\n\t\t\t: {}),\n\t\t...(params.turnBudget === undefined && agent.defaultTurnBudget !== undefined\n\t\t\t? { turnBudget: agent.defaultTurnBudget }\n\t\t\t: {}),\n\t\t...(params.acceptance === undefined && agent.defaultAcceptance !== undefined\n\t\t\t? { acceptance: agent.defaultAcceptance }\n\t\t\t: {}),\n\t};\n}\n\nexport const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;\n\nfunction resolveForegroundTimeout(\n\tparams: SubagentParamsLike,\n\tdefaultTimeoutMs?: number,\n): { timeoutMs?: number; error?: string } {\n\tconst rawTimeout = params.timeoutMs;\n\tconst rawMaxRuntime = params.maxRuntimeMs;\n\tif (rawTimeout === undefined && rawMaxRuntime === undefined) {\n\t\treturn defaultTimeoutMs === undefined ? {} : { timeoutMs: defaultTimeoutMs };\n\t}\n\tfor (const [name, value] of [\n\t\t[\"timeoutMs\", rawTimeout],\n\t\t[\"maxRuntimeMs\", rawMaxRuntime],\n\t] as const) {\n\t\tif (value === undefined) continue;\n\t\tif (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n\t\t\treturn { error: `${name} must be a positive integer.` };\n\t\t}\n\t}\n\tif (rawTimeout !== undefined && rawMaxRuntime !== undefined && rawTimeout !== rawMaxRuntime) {\n\t\treturn {\n\t\t\terror: \"timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both.\",\n\t\t};\n\t}\n\tconst timeoutMs = rawTimeout ?? rawMaxRuntime;\n\treturn timeoutMs === undefined ? {} : { timeoutMs };\n}\n\nfunction resolveToolBudget(\n\traw: unknown,\n\tlabel = \"toolBudget\",\n\toptions?: { minimumHard?: 0 | 1 },\n): { toolBudget?: ResolvedToolBudget; error?: string } {\n\tconst resolved = validateToolBudgetConfig(raw, label, options);\n\treturn {\n\t\t...(resolved.budget === undefined ? {} : { toolBudget: resolved.budget }),\n\t\t...(resolved.error === undefined ? {} : { error: resolved.error }),\n\t};\n}\n\nfunction resolveEffectiveToolBudget(input: {\n\tstepBudget?: ToolBudgetConfig;\n\trunBudget?: ResolvedToolBudget;\n\tagentBudget?: ToolBudgetConfig;\n\tconfigBudget?: ToolBudgetConfig;\n}): { toolBudget?: ResolvedToolBudget; error?: string } {\n\tif (input.stepBudget !== undefined) return resolveToolBudget(input.stepBudget, \"toolBudget\");\n\tif (input.runBudget !== undefined) return { toolBudget: input.runBudget };\n\tif (input.agentBudget !== undefined) return resolveToolBudget(input.agentBudget, \"agent.toolBudget\");\n\treturn resolveToolBudget(input.configBudget, \"config.toolBudget\");\n}\n\nfunction expandTopLevelTaskCounts(tasks: TaskParam[]): { tasks?: TaskParam[]; error?: string } {\n\tconst expanded: TaskParam[] = [];\n\tfor (let taskIndex = 0; taskIndex < tasks.length; taskIndex++) {\n\t\tconst task = tasks[taskIndex]!;\n\t\tconst rawCount = (task as TaskParam & { count?: unknown }).count;\n\t\tif (rawCount !== undefined && (typeof rawCount !== \"number\" || !Number.isInteger(rawCount) || rawCount < 1)) {\n\t\t\treturn { error: `tasks[${taskIndex}].count must be an integer >= 1` };\n\t\t}\n\t\tconst { count, ...concreteTask } = task;\n\t\tfor (let repeat = 0; repeat < (rawCount ?? 1); repeat++) {\n\t\t\texpanded.push({ ...concreteTask });\n\t\t}\n\t}\n\treturn { tasks: expanded };\n}\n\nfunction expandChainParallelCounts(chain: ChainStep[]): { chain?: ChainStep[]; error?: string } {\n\tconst expandedChain: ChainStep[] = [];\n\tfor (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {\n\t\tconst step = chain[stepIndex]!;\n\t\tif (!isParallelStep(step)) {\n\t\t\texpandedChain.push(step);\n\t\t\tcontinue;\n\t\t}\n\t\tconst expandedParallel: ParallelTaskItem[] = [];\n\t\tfor (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {\n\t\t\tconst task = step.parallel[taskIndex]!;\n\t\t\tconst rawCount = (task as typeof task & { count?: unknown }).count;\n\t\t\tif (rawCount !== undefined && (typeof rawCount !== \"number\" || !Number.isInteger(rawCount) || rawCount < 1)) {\n\t\t\t\treturn { error: `chain[${stepIndex}].parallel[${taskIndex}].count must be an integer >= 1` };\n\t\t\t}\n\t\t\tconst { count, ...concreteTask } = task;\n\t\t\tfor (let repeat = 0; repeat < (rawCount ?? 1); repeat++) {\n\t\t\t\texpandedParallel.push({ ...concreteTask });\n\t\t\t}\n\t\t}\n\t\texpandedChain.push({ ...step, parallel: expandedParallel });\n\t}\n\treturn { chain: expandedChain };\n}\n\nfunction normalizeRepeatedParallelCounts(params: SubagentParamsLike): {\n\tparams?: SubagentParamsLike;\n\terror?: AgentToolResult<Details>;\n} {\n\tif (params.tasks) {\n\t\tconst expandedTasks = expandTopLevelTaskCounts(params.tasks);\n\t\tif (expandedTasks.error) {\n\t\t\treturn { error: buildRequestedModeError(params, expandedTasks.error) };\n\t\t}\n\t\treturn { params: { ...params, ...(expandedTasks.tasks === undefined ? {} : { tasks: expandedTasks.tasks }) } };\n\t}\n\tif (params.chain) {\n\t\tconst expandedChain = expandChainParallelCounts(params.chain);\n\t\tif (expandedChain.error) {\n\t\t\treturn { error: buildRequestedModeError(params, expandedChain.error) };\n\t\t}\n\t\treturn { params: { ...params, ...(expandedChain.chain === undefined ? {} : { chain: expandedChain.chain }) } };\n\t}\n\treturn { params };\n}\n\nfunction withResolvedContext(\n\tresult: AgentToolResult<Details>,\n\tfallback: ContextSummary | undefined,\n): AgentToolResult<Details> {\n\tif (!result.details) return result;\n\tconst context = summarizeResultContext(result.details, fallback);\n\tif (!context) return result;\n\treturn {\n\t\t...result,\n\t\tdetails: {\n\t\t\t...result.details,\n\t\t\tcontext,\n\t\t},\n\t};\n}\n\nfunction withForkThinkingNotes(\n\tresult: AgentToolResult<Details>,\n\tdowngrades: Map<number, string>,\n): AgentToolResult<Details> {\n\tif (downgrades.size === 0) return result;\n\tconst children = [...downgrades.entries()]\n\t\t.sort(([a], [b]) => a - b)\n\t\t.map(([index, agent]) => `${agent} (child ${index})`)\n\t\t.join(\", \");\n\tconst note = `Note: fork context forced thinking off for ${children}. The forked transcript contained signed Anthropic thinking blocks that were sanitized, and Anthropic children cannot resume such a transcript with thinking enabled. Use context: \"fresh\" when an Anthropic child needs thinking.`;\n\treturn { ...result, content: [...result.content, { type: \"text\", text: note }] };\n}\n\nfunction toExecutionErrorResult(\n\tparams: SubagentParamsLike,\n\terror: unknown,\n\tcontextSummary?: ContextSummary,\n): AgentToolResult<Details> {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn withResolvedContext(\n\t\t{\n\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: getRequestedModeLabel(params), results: [] },\n\t\t},\n\t\tcontextSummary,\n\t);\n}\n\nfunction collectChainSessionFiles(\n\tchain: ChainStep[],\n\tsessionFileForTask: ForkSessionFileForTask,\n\tdynamicFanoutMaxItems?: number,\n): (string | undefined)[] {\n\tconst sessionFiles: (string | undefined)[] = [];\n\tlet flatIndex = 0;\n\tfor (const step of chain) {\n\t\tif (isParallelStep(step)) {\n\t\t\tfor (const task of step.parallel) {\n\t\t\t\tsessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model));\n\t\t\t\tflatIndex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (isDynamicParallelStep(step)) {\n\t\t\tconst maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;\n\t\t\tfor (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {\n\t\t\t\tsessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model));\n\t\t\t\tflatIndex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst sequential = step as SequentialStep;\n\t\tsessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model));\n\t\tflatIndex++;\n\t}\n\treturn sessionFiles;\n}\n\nfunction collectChainThinkingOverrides(\n\tchain: ChainStep[],\n\tthinkingOverrideForTask: ForkThinkingOverrideForTask,\n\tdynamicFanoutMaxItems?: number,\n): (AgentConfig[\"thinking\"] | undefined)[] {\n\tconst thinkingOverrides: (AgentConfig[\"thinking\"] | undefined)[] = [];\n\tlet flatIndex = 0;\n\tfor (const step of chain) {\n\t\tif (isParallelStep(step)) {\n\t\t\tfor (const task of step.parallel) {\n\t\t\t\tthinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model));\n\t\t\t\tflatIndex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (isDynamicParallelStep(step)) {\n\t\t\tconst maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;\n\t\t\tfor (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {\n\t\t\t\tthinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model));\n\t\t\t\tflatIndex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst sequential = step as SequentialStep;\n\t\tthinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model));\n\t\tflatIndex++;\n\t}\n\treturn thinkingOverrides;\n}\n\ntype StaticLaunchSummary = { agent: string; model?: string; thinking?: string };\n\nfunction resolveStaticLaunchSummary(input: {\n\tagent: string;\n\tindex: number;\n\texplicitModel?: string;\n\tagents: AgentConfig[];\n\tparentModel?: ParentModel;\n\tavailableModels: ModelInfo[];\n\tcurrentProvider?: string;\n\tmodelScope?: ModelScopeConfig;\n\tthinkingOverrideForTask: ForkThinkingOverrideForTask;\n}): StaticLaunchSummary {\n\tconst agentConfig = input.agents.find((agent) => agent.name === input.agent);\n\tconst model = resolveEffectiveSubagentModel(\n\t\tinput.explicitModel,\n\t\tagentConfig?.model,\n\t\tinput.parentModel,\n\t\tinput.availableModels,\n\t\tinput.currentProvider,\n\t\tinput.modelScope === undefined ? {} : { scope: input.modelScope },\n\t);\n\tconst thinkingOverride = input.thinkingOverrideForTask(input.agent, input.index, model);\n\tconst thinking = resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);\n\treturn {\n\t\tagent: input.agent,\n\t\t...(model ? { model } : {}),\n\t\t...(thinking ? { thinking } : {}),\n\t};\n}\n\nfunction collectStaticLaunchSummaries(input: {\n\tparams: SubagentParamsLike;\n\tagents: AgentConfig[];\n\tparentModel?: ParentModel;\n\tavailableModels: ModelInfo[];\n\tcurrentProvider?: string;\n\tmodelScope?: ModelScopeConfig;\n\tthinkingOverrideForTask: ForkThinkingOverrideForTask;\n\tdynamicFanoutMaxItems?: number;\n}): StaticLaunchSummary[] {\n\tconst summary = (agent: string, index: number, explicitModel?: string) =>\n\t\tresolveStaticLaunchSummary({\n\t\t\tagent,\n\t\t\tindex,\n\t\t\texplicitModel,\n\t\t\tagents: input.agents,\n\t\t\tparentModel: input.parentModel,\n\t\t\tavailableModels: input.availableModels,\n\t\t\tcurrentProvider: input.currentProvider,\n\t\t\tmodelScope: input.modelScope,\n\t\t\tthinkingOverrideForTask: input.thinkingOverrideForTask,\n\t\t});\n\tif (input.params.tasks) return input.params.tasks.map((task, index) => summary(task.agent, index, task.model));\n\tif (input.params.chain?.length) {\n\t\tconst launches: StaticLaunchSummary[] = [];\n\t\tlet flatIndex = 0;\n\t\tfor (const step of input.params.chain) {\n\t\t\tif (isParallelStep(step)) {\n\t\t\t\tfor (const task of step.parallel) {\n\t\t\t\t\tlaunches.push(summary(task.agent, flatIndex, task.model));\n\t\t\t\t\tflatIndex++;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isDynamicParallelStep(step)) {\n\t\t\t\tconst maxItems = step.expand.maxItems ?? input.dynamicFanoutMaxItems ?? 0;\n\t\t\t\tfor (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {\n\t\t\t\t\tlaunches.push(summary(step.parallel.agent, flatIndex, step.parallel.model));\n\t\t\t\t\tflatIndex++;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst sequential = step as SequentialStep;\n\t\t\tlaunches.push(summary(sequential.agent, flatIndex, sequential.model));\n\t\t\tflatIndex++;\n\t\t}\n\t\treturn launches;\n\t}\n\treturn input.params.agent ? [summary(input.params.agent, 0, input.params.model as string | undefined)] : [];\n}\n\nfunction firstChainAgent(chain: ChainStep[]): string | undefined {\n\tconst first = chain[0];\n\tif (!first) return undefined;\n\tif (isParallelStep(first)) return first.parallel[0]?.agent;\n\tif (isDynamicParallelStep(first)) return first.parallel.agent;\n\treturn (first as SequentialStep).agent;\n}\n\nfunction firstRawChainTask(chain: ChainStep[]): string | undefined {\n\tconst first = chain[0];\n\tif (!first) return undefined;\n\tif (isParallelStep(first)) return first.parallel[0]?.task;\n\tif (isDynamicParallelStep(first)) return first.parallel.task;\n\treturn (first as SequentialStep).task;\n}\n\nfunction resolveAsyncEventGoal(\n\tworkflowTask: string | undefined,\n\trawChain: ChainStep[],\n\tunwrapForkFallback = false,\n): string {\n\tif (workflowTask?.trim()) return workflowTask;\n\tconst fallback = firstRawChainTask(rawChain) || \"\";\n\tif (!unwrapForkFallback) return fallback;\n\tconst forkPrefix = `${DEFAULT_FORK_PREAMBLE}\\n\\nTask:\\n`;\n\treturn fallback.startsWith(forkPrefix) ? fallback.slice(forkPrefix.length) : fallback;\n}\n\nfunction wrapChainTasksForFork(chain: ChainStep[], contextPolicy: AgentDefaultContextPolicy): ChainStep[] {\n\treturn chain.map((step, stepIndex) => {\n\t\tif (isParallelStep(step)) {\n\t\t\treturn compactOptional<ParallelStep>({\n\t\t\t\t...step,\n\t\t\t\tparallel: step.parallel.map((task) =>\n\t\t\t\t\tcompactOptional<ParallelTaskItem>({\n\t\t\t\t\t\t...task,\n\t\t\t\t\t\ttask: shouldForkAgent(contextPolicy, task.agent)\n\t\t\t\t\t\t\t? wrapForkTask(task.task ?? \"{previous}\")\n\t\t\t\t\t\t\t: task.task,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\t\tif (isDynamicParallelStep(step)) {\n\t\t\treturn compactOptional<DynamicParallelStep>({\n\t\t\t\t...step,\n\t\t\t\tparallel: compactOptional<DynamicParallelStep[\"parallel\"]>({\n\t\t\t\t\t...step.parallel,\n\t\t\t\t\ttask: shouldForkAgent(contextPolicy, step.parallel.agent)\n\t\t\t\t\t\t? wrapForkTask(step.parallel.task ?? \"{previous}\")\n\t\t\t\t\t\t: step.parallel.task,\n\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t\tconst sequential = step as SequentialStep;\n\t\treturn compactOptional<SequentialStep>({\n\t\t\t...sequential,\n\t\t\ttask: shouldForkAgent(contextPolicy, sequential.agent)\n\t\t\t\t? wrapForkTask(sequential.task ?? (stepIndex === 0 ? \"{task}\" : \"{previous}\"))\n\t\t\t\t: sequential.task,\n\t\t});\n\t});\n}\n\nfunction preflightForkSessionsForStaticTasks(\n\tparams: SubagentParamsLike,\n\tcontextPolicy: AgentDefaultContextPolicy,\n\tsessionFileForTask: ForkSessionFileForTask,\n\tdynamicFanoutMaxItems?: number,\n): void {\n\tif (!contextPolicy.usesFork) return;\n\tif (params.agent) {\n\t\tif (shouldForkAgent(contextPolicy, params.agent)) sessionFileForTask(params.agent, 0, params.model);\n\t\treturn;\n\t}\n\tif (params.tasks) {\n\t\tparams.tasks.forEach((task, index) => {\n\t\t\tif (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, index, task.model);\n\t\t});\n\t\treturn;\n\t}\n\tif (!params.chain?.length) return;\n\tlet flatIndex = 0;\n\tfor (const step of params.chain) {\n\t\tif (isParallelStep(step)) {\n\t\t\tfor (const task of step.parallel) {\n\t\t\t\tif (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, flatIndex, task.model);\n\t\t\t\tflatIndex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (isDynamicParallelStep(step)) {\n\t\t\tconst maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;\n\t\t\tif (shouldForkAgent(contextPolicy, step.parallel.agent)) {\n\t\t\t\tfor (let itemIndex = 0; itemIndex < maxItems; itemIndex++)\n\t\t\t\t\tsessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);\n\t\t\t}\n\t\t\tflatIndex += maxItems;\n\t\t\tcontinue;\n\t\t}\n\t\tconst sequential = step as SequentialStep;\n\t\tif (shouldForkAgent(contextPolicy, sequential.agent))\n\t\t\tsessionFileForTask(sequential.agent, flatIndex, sequential.model);\n\t\tflatIndex++;\n\t}\n}\n\nfunction runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentToolResult<Details> | null {\n\tconst {\n\t\tparams,\n\t\teffectiveCwd,\n\t\tagents,\n\t\tctx,\n\t\tshareEnabled,\n\t\tsessionRoot,\n\t\tsessionFileForIndex,\n\t\tsessionFileForTask,\n\t\tthinkingOverrideForTask,\n\t\tartifactConfig,\n\t\tartifactsDir,\n\t\teffectiveAsync,\n\t\tcontrolConfig,\n\t\tintercomBridge,\n\t\tnestedRoute,\n\t\tcontextPolicy,\n\t} = data;\n\tconst hasChain = (params.chain?.length ?? 0) > 0;\n\tconst hasTasks = (params.tasks?.length ?? 0) > 0;\n\tconst hasSingle = !hasChain && !hasTasks && Boolean(params.agent);\n\tif (!effectiveAsync) return null;\n\n\tif (hasChain && params.chain) {\n\t\tconst chainWorktreeTaskCwdError = buildChainWorktreeTaskCwdError(params.chain as ChainStep[], effectiveCwd);\n\t\tif (chainWorktreeTaskCwdError) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: chainWorktreeTaskCwdError }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t}\n\n\tif (hasTasks && params.tasks) {\n\t\tconst maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);\n\t\tif (params.tasks.length > maxParallelTasks) {\n\t\t\treturn buildParallelModeError(`Max ${maxParallelTasks} tasks`);\n\t\t}\n\t\tif (params.worktree) {\n\t\t\tconst worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(params.tasks, effectiveCwd);\n\t\t\tif (worktreeTaskCwdError) return buildParallelModeError(worktreeTaskCwdError);\n\t\t}\n\t}\n\n\tif (!isAsyncAvailable()) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: \"Async mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed.\",\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t};\n\t}\n\tconst id = randomUUID();\n\tconst parentModel = data.parentModel;\n\tconst asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\tpi: deps.pi,\n\t\tcwd: ctx.cwd,\n\t\tcurrentSessionId: data.parentSessionId!,\n\t\tparentSessionId: data.parentPiSessionId,\n\t\tcurrentModelProvider: parentModel?.provider,\n\t\tcurrentModel: parentModel,\n\t\tmodelScope: data.modelScope,\n\t\tinteractive: ctx.hasUI,\n\t\tpermissions: deps.config.permissions,\n\t});\n\tconst availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);\n\tconst currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);\n\tconst currentProvider = parentModel?.provider;\n\tconst controlIntercomTarget = intercomBridge.active ? intercomBridge.orchestratorTarget : undefined;\n\tconst childIntercomTarget = intercomBridge.active\n\t\t? (agent: string, index: number) => resolveSubagentIntercomTarget(id, agent, index)\n\t\t: undefined;\n\n\tif (hasTasks && params.tasks) {\n\t\tconst skillOverrides = params.tasks.map((task) => normalizeSkillInput(task.skill));\n\t\tconst parallelTasks = params.tasks.map((task, index) =>\n\t\t\tcompactOptional<ParallelTaskItem>({\n\t\t\t\tagent: task.agent,\n\t\t\t\ttask: shouldForkAgent(contextPolicy, task.agent) ? wrapForkTask(task.task) : task.task,\n\t\t\t\tcwd: task.cwd,\n\t\t\t\t...(task.model !== undefined ? { model: task.model } : {}),\n\t\t\t\t...(skillOverrides[index] !== undefined ? { skill: skillOverrides[index] } : {}),\n\t\t\t\t...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),\n\t\t\t\t...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),\n\t\t\t\t...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),\n\t\t\t\t...(task.progress !== undefined ? { progress: task.progress } : {}),\n\t\t\t\t...(task.toolBudget !== undefined ? { toolBudget: task.toolBudget } : {}),\n\t\t\t\t...(task.outputSchema !== undefined ? { outputSchema: task.outputSchema } : {}),\n\t\t\t\t...(task.agentContract !== undefined ? { agentContract: task.agentContract } : {}),\n\t\t\t\t...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),\n\t\t\t}),\n\t\t);\n\t\treturn executeAsyncChain(\n\t\t\tid,\n\t\t\tcompactOptional<Parameters<typeof executeAsyncChain>[1]>({\n\t\t\t\tchain: [\n\t\t\t\t\tcompactOptional<ParallelStep>({\n\t\t\t\t\t\tparallel: parallelTasks,\n\t\t\t\t\t\tconcurrency: resolveTopLevelParallelConcurrency(\n\t\t\t\t\t\t\tparams.concurrency,\n\t\t\t\t\t\t\tdeps.config.parallel?.concurrency,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tworktree: params.worktree,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t\tresultMode: \"parallel\",\n\t\t\t\tgoal: params.tasks[0]?.task ?? \"\",\n\t\t\t\tagents,\n\t\t\t\tctx: asyncCtx,\n\t\t\t\tavailableModels,\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshareEnabled,\n\t\t\t\tsessionRoot,\n\t\t\t\tchainSkills: [],\n\t\t\t\tsessionFilesByFlatIndex: params.tasks.map((task, index) =>\n\t\t\t\t\tsessionFileForTask(task.agent, index, task.model),\n\t\t\t\t),\n\t\t\t\tthinkingOverridesByFlatIndex: params.tasks.map((task, index) =>\n\t\t\t\t\tthinkingOverrideForTask(task.agent, index, task.model),\n\t\t\t\t),\n\t\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\t\tmaxSubagentDepth: currentMaxSubagentDepth,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTarget,\n\t\t\t\tnestedRoute,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\ttoolBudget: data.toolBudget,\n\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tglobalConcurrencyLimit: deps.config.globalConcurrencyLimit,\n\t\t\t\tparentWorkflowRunId: params.workflowParentRunId,\n\t\t\t\tworkflowKey: params.workflowKey,\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (hasChain && params.chain) {\n\t\tconst normalized = normalizeSkillInput(params.skill);\n\t\tconst chainSkills = normalized === false ? [] : (normalized ?? []);\n\t\tconst rawChain = params.chain as ChainStep[];\n\t\tconst chain = wrapChainTasksForFork(rawChain, contextPolicy);\n\t\treturn executeAsyncChain(\n\t\t\tid,\n\t\t\tcompactOptional<Parameters<typeof executeAsyncChain>[1]>({\n\t\t\t\tchain,\n\t\t\t\ttask: params.task,\n\t\t\t\tgoal: resolveAsyncEventGoal(params.task, rawChain),\n\t\t\t\tagents,\n\t\t\t\tctx: asyncCtx,\n\t\t\t\tavailableModels,\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshareEnabled,\n\t\t\t\tsessionRoot,\n\t\t\t\tchainSkills,\n\t\t\t\tsessionFilesByFlatIndex: collectChainSessionFiles(\n\t\t\t\t\tchain,\n\t\t\t\t\tsessionFileForTask,\n\t\t\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t),\n\t\t\t\tthinkingOverridesByFlatIndex: collectChainThinkingOverrides(\n\t\t\t\t\tchain,\n\t\t\t\t\tthinkingOverrideForTask,\n\t\t\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t),\n\t\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\t\tdynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\tmaxSubagentDepth: currentMaxSubagentDepth,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTarget,\n\t\t\t\tnestedRoute,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\ttoolBudget: data.toolBudget,\n\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tglobalConcurrencyLimit: deps.config.globalConcurrencyLimit,\n\t\t\t\tparentWorkflowRunId: params.workflowParentRunId,\n\t\t\t\tworkflowKey: params.workflowKey,\n\t\t\t}),\n\t\t);\n\t}\n\n\tif (hasSingle) {\n\t\tconst a = agents.find((x) => x.name === params.agent);\n\t\tif (!a) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${params.agent}` }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tconst rawOutput = params.output !== undefined ? params.output : a.output;\n\t\tconst effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);\n\t\tconst effectiveOutputMode = params.outputMode ?? \"inline\";\n\t\tconst normalizedSkills = normalizeSkillInput(params.skill);\n\t\tconst skills = normalizedSkills === false ? [] : normalizedSkills;\n\t\tconst maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth);\n\t\tconst modelOverride = resolveEffectiveSubagentModel(\n\t\t\tparams.model as string | undefined,\n\t\t\ta.model,\n\t\t\tparentModel,\n\t\t\tavailableModels,\n\t\t\tcurrentProvider,\n\t\t\tdata.modelScope === undefined ? {} : { scope: data.modelScope },\n\t\t);\n\t\treturn executeAsyncSingle(\n\t\t\tid,\n\t\t\tcompactOptional<Parameters<typeof executeAsyncSingle>[1]>({\n\t\t\t\tagent: params.agent!,\n\t\t\t\ttask: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? \"\") : (params.task ?? \"\"),\n\t\t\t\tgoal: params.task ?? \"\",\n\t\t\t\tagentConfig: a,\n\t\t\t\tctx: asyncCtx,\n\t\t\t\tavailableModels,\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshareEnabled,\n\t\t\t\tsessionRoot,\n\t\t\t\tsessionFile: sessionFileForTask(params.agent!, 0, modelOverride),\n\t\t\t\tcontext: contextPolicy.contextForAgent(params.agent!),\n\t\t\t\tskills,\n\t\t\t\toutput: effectiveOutput,\n\t\t\t\toutputMode: effectiveOutputMode,\n\t\t\t\toutputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),\n\t\t\t\tmodelOverride,\n\t\t\t\tthinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),\n\t\t\t\tmaxSubagentDepth,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : undefined,\n\t\t\t\tnestedRoute,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t\tstructuredOutputSchema: params.outputSchema,\n\t\t\t\tacceptance: params.acceptance,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\ttoolBudget: data.toolBudget,\n\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tparentWorkflowRunId: params.workflowParentRunId,\n\t\t\t\tworkflowKey: params.workflowKey,\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn null;\n}\n\nasync function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {\n\tconst {\n\t\tparams,\n\t\teffectiveCwd,\n\t\tagents,\n\t\tctx,\n\t\tsignal,\n\t\trunId,\n\t\tshareEnabled,\n\t\tsessionDirForIndex,\n\t\tsessionFileForIndex,\n\t\tsessionFileForTask,\n\t\tthinkingOverrideForTask,\n\t\tartifactsDir,\n\t\tartifactConfig,\n\t\tonUpdate,\n\t\tsessionRoot,\n\t\tcontrolConfig,\n\t\tcontextPolicy,\n\t} = data;\n\tconst onControlEvent = createForegroundControlNotifier(data, deps);\n\tconst childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;\n\tconst foregroundControl = deps.state.foregroundControls.get(runId);\n\tconst normalized = normalizeSkillInput(params.skill);\n\tconst chainSkills = normalized === false ? [] : (normalized ?? []);\n\tconst chain = wrapChainTasksForFork(params.chain as ChainStep[], contextPolicy);\n\tconst currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);\n\tconst chainCtx =\n\t\tnormalizeParentModel(ctx.model) || !data.parentModel\n\t\t\t? ctx\n\t\t\t: ({ ...ctx, model: data.parentModel } as ExtensionContext);\n\tconst chainResult = await executeChain(\n\t\tcompactOptional<Parameters<typeof executeChain>[0]>({\n\t\t\tchain,\n\t\t\ttask: params.task,\n\t\t\tagents,\n\t\t\tctx: chainCtx,\n\t\t\tmodelScope: data.modelScope,\n\t\t\tintercomEvents: deps.pi.events,\n\t\t\tsignal,\n\t\t\trunId,\n\t\t\tcwd: effectiveCwd,\n\t\t\tshareEnabled,\n\t\t\tsessionDirForIndex,\n\t\t\tsessionFileForIndex,\n\t\t\tsessionFileForTask,\n\t\t\tthinkingOverrideForTask,\n\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\tartifactsDir,\n\t\t\tartifactConfig,\n\t\t\tincludeProgress: params.includeProgress,\n\t\t\tclarify: params.clarify,\n\t\t\tonUpdate,\n\t\t\tonControlEvent,\n\t\t\tcontrolConfig,\n\t\t\tagentContract: params.agentContract,\n\t\t\tchildIntercomTarget: childIntercomTarget\n\t\t\t\t? (agent, index) => childIntercomTarget(runId, agent, index)\n\t\t\t\t: undefined,\n\t\t\torchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\tforegroundControl,\n\t\t\tnestedRoute: foregroundControl?.nestedRoute,\n\t\t\tchainSkills,\n\t\t\tchainDir: params.chainDir ?? getChainRunsDir(effectiveCwd, artifactConfig.dir),\n\t\t\tdynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\tmaxSubagentDepth: currentMaxSubagentDepth,\n\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\tdeadlineAt: data.deadlineAt,\n\t\t\tturnBudget: data.turnBudget,\n\t\t\tonDetachedExit: (index, result) => {\n\t\t\t\ttry {\n\t\t\t\t\tupdateRememberedForegroundChild(deps.state, {\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tmode: \"chain\",\n\t\t\t\t\t\tcwd: effectiveCwd,\n\t\t\t\t\t\tsessionId: data.parentSessionId,\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tevents: deps.pi.events,\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tremoveForegroundControlIfIdle(deps.state, runId);\n\t\t\t\t}\n\t\t\t},\n\t\t\tonForegroundChildSettled: () => {\n\t\t\t\tremoveForegroundControlIfIdle(deps.state, runId);\n\t\t\t},\n\t\t\ttoolBudget: data.toolBudget,\n\t\t\tusageBudget: data.usageBudget,\n\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\tpermissions: deps.config.permissions,\n\t\t\tglobalConcurrencyLimit: deps.config.globalConcurrencyLimit,\n\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t}),\n\t);\n\n\tif (chainResult.requestedAsync) {\n\t\tif (!isAsyncAvailable()) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"chain\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tconst id = randomUUID();\n\t\tconst parentModel = data.parentModel;\n\t\tconst asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\t\tpi: deps.pi,\n\t\t\tcwd: ctx.cwd,\n\t\t\tcurrentSessionId: data.parentSessionId!,\n\t\t\tparentSessionId: data.parentPiSessionId,\n\t\t\tcurrentModelProvider: parentModel?.provider,\n\t\t\tcurrentModel: parentModel,\n\t\t\tmodelScope: data.modelScope,\n\t\t\tinteractive: ctx.hasUI,\n\t\t\tpermissions: deps.config.permissions,\n\t\t});\n\t\tconst rawAsyncChain = chainResult.requestedAsync.chain;\n\t\tconst asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy);\n\t\tconst firstAgent = firstChainAgent(rawAsyncChain);\n\t\treturn executeAsyncChain(\n\t\t\tid,\n\t\t\tcompactOptional<Parameters<typeof executeAsyncChain>[1]>({\n\t\t\t\tchain: asyncChain,\n\t\t\t\ttask: params.task,\n\t\t\t\tgoal: resolveAsyncEventGoal(\n\t\t\t\t\tparams.task,\n\t\t\t\t\trawAsyncChain,\n\t\t\t\t\tfirstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false,\n\t\t\t\t),\n\t\t\t\tagents,\n\t\t\t\tctx: asyncCtx,\n\t\t\t\tavailableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshareEnabled,\n\t\t\t\tsessionRoot,\n\t\t\t\tchainSkills: chainResult.requestedAsync.chainSkills,\n\t\t\t\tsessionFilesByFlatIndex: collectChainSessionFiles(\n\t\t\t\t\tasyncChain,\n\t\t\t\t\tsessionFileForTask,\n\t\t\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t),\n\t\t\t\tthinkingOverridesByFlatIndex: collectChainThinkingOverrides(\n\t\t\t\t\tasyncChain,\n\t\t\t\t\tthinkingOverrideForTask,\n\t\t\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t),\n\t\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\t\tdynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\tmaxSubagentDepth: currentMaxSubagentDepth,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t\tcontrolIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\t\tchildIntercomTarget: data.intercomBridge.active\n\t\t\t\t\t? (agent, index) => resolveSubagentIntercomTarget(id, agent, index)\n\t\t\t\t\t: undefined,\n\t\t\t\tnestedRoute: data.nestedRoute,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\ttoolBudget: data.toolBudget,\n\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tglobalConcurrencyLimit: deps.config.globalConcurrencyLimit,\n\t\t\t}),\n\t\t);\n\t}\n\n\tconst rawChainDetails = chainResult.details\n\t\t? compactOptional<Details>({ ...chainResult.details, runId, timeoutMs: data.timeoutMs })\n\t\t: undefined;\n\tif (foregroundControl && rawChainDetails) {\n\t\tupdateForegroundNestedProjection(foregroundControl);\n\t\tattachRootChildrenToSteps(runId, rawChainDetails.results, foregroundControl.nestedChildren);\n\t\trawChainDetails.totalCost = sumResultsCost(rawChainDetails.results);\n\t\tconst usageBudget = usageBudgetState(data.usageBudget, rawChainDetails.totalCost);\n\t\tif (usageBudget === undefined) delete rawChainDetails.usageBudget;\n\t\telse rawChainDetails.usageBudget = usageBudget;\n\t}\n\tconst chainDetails = rawChainDetails ? compactForegroundDetails(rawChainDetails) : undefined;\n\tif (chainDetails)\n\t\trememberForegroundRun(deps.state, {\n\t\t\trunId,\n\t\t\tmode: \"chain\",\n\t\t\tcwd: effectiveCwd,\n\t\t\tsessionId: data.parentSessionId,\n\t\t\tresults: chainDetails.results,\n\t\t\tcheckpoint: chainDetails.checkpoint,\n\t\t});\n\tconst intercomReceipt =\n\t\tchainDetails && !chainDetails.results.some((result) => result.interrupted || result.detached)\n\t\t\t? await maybeBuildForegroundIntercomReceipt({\n\t\t\t\t\tpi: deps.pi,\n\t\t\t\t\tintercomBridge: data.intercomBridge,\n\t\t\t\t\trunId,\n\t\t\t\t\tmode: \"chain\",\n\t\t\t\t\tdetails: chainDetails,\n\t\t\t\t\t...(foregroundControl?.nestedChildren?.length\n\t\t\t\t\t\t? { nestedChildren: foregroundControl.nestedChildren }\n\t\t\t\t\t\t: {}),\n\t\t\t\t})\n\t\t\t: null;\n\tif (intercomReceipt) {\n\t\treturn {\n\t\t\t...chainResult,\n\t\t\tcontent: [{ type: \"text\", text: intercomReceipt.text }],\n\t\t\tdetails: intercomReceipt.details,\n\t\t};\n\t}\n\n\treturn chainDetails ? { ...chainResult, details: chainDetails } : chainResult;\n}\n\ninterface ForegroundParallelRunInput {\n\ttasks: TaskParam[];\n\ttaskTexts: string[];\n\ttaskDescriptions: string[];\n\tagents: AgentConfig[];\n\tctx: ExtensionContext;\n\tstate: SubagentState;\n\tintercomEvents: IntercomEventBus;\n\tparentSessionId: string | null;\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n\tsignal: AbortSignal;\n\trunId: string;\n\tsessionDirForIndex: (idx?: number) => string | undefined;\n\tsessionFileForIndex: (idx?: number) => string | undefined;\n\tsessionFileForTask: ForkSessionFileForTask;\n\tthinkingOverrideForTask: ForkThinkingOverrideForTask;\n\tshareEnabled: boolean;\n\tartifactConfig: ArtifactConfig;\n\tartifactsDir: string;\n\toutputBaseDir: string;\n\tmaxOutput?: MaxOutputConfig;\n\tparamsCwd: string;\n\tprogressDir: string;\n\tmaxSubagentDepths: number[];\n\twaitToolEnabled?: boolean;\n\tavailableModels: ModelInfo[];\n\tmodelScope?: ModelScopeConfig;\n\tparentModel?: ParentModel;\n\tmodelOverrides: (string | undefined)[];\n\tbehaviors: Array<ReturnType<typeof resolveStepBehavior>>;\n\tfirstProgressIndex: number;\n\tcontrolConfig: ResolvedControlConfig;\n\tcontextPolicy: AgentDefaultContextPolicy;\n\tonControlEvent?: (event: ControlEvent) => void;\n\tchildIntercomTarget?: (agent: string, index: number) => string | undefined;\n\torchestratorIntercomTarget?: string;\n\tforegroundControl?: SubagentState[\"foregroundControls\"] extends Map<string, infer T> ? T : never;\n\tconcurrencyLimit: number;\n\tglobalSemaphore?: Semaphore;\n\tliveResults: (SingleResult | undefined)[];\n\tliveProgress: (AgentProgress | undefined)[];\n\tonUpdate?: (r: AgentToolResult<Details>) => void;\n\tworktreeSetup?: WorktreeSetup;\n\ttimeoutMs?: number;\n\tdeadlineAt?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\tusageBudget?: UsageBudgetConfig;\n\ttoolBudgets: (ResolvedToolBudget | undefined)[];\n\tagentContract?: AgentContract;\n\tpermissions?: ExtensionConfig[\"permissions\"];\n}\nfunction buildParallelModeError(message: string): AgentToolResult<Details> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tisError: true,\n\t\tdetails: { mode: \"parallel\" as const, results: [] },\n\t};\n}\n\nfunction createParallelWorktreeSetup(\n\tenabled: boolean | undefined,\n\tcwd: string,\n\trunId: string,\n\ttasks: TaskParam[],\n\tsetupHook: ExtensionConfig[\"worktreeSetupHook\"],\n\tsetupHookTimeoutMs: ExtensionConfig[\"worktreeSetupHookTimeoutMs\"],\n\tbaseDir: ExtensionConfig[\"worktreeBaseDir\"],\n): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {\n\tif (!enabled) return {};\n\ttry {\n\t\treturn {\n\t\t\tsetup: createWorktrees(\n\t\t\t\tcwd,\n\t\t\t\trunId,\n\t\t\t\ttasks.length,\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagents: tasks.map((task) => task.agent),\n\t\t\t\t\tsetupHook: setupHook\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\thookPath: setupHook,\n\t\t\t\t\t\t\t\t...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tbaseDir,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn { errorResult: buildParallelModeError(message) };\n\t}\n}\n\nfunction buildParallelWorktreeTaskCwdError(\n\ttasks: ReadonlyArray<{ agent: string; cwd?: string }>,\n\tsharedCwd: string,\n): string | undefined {\n\tconst conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);\n\tif (!conflict) return undefined;\n\treturn formatWorktreeTaskCwdConflict(conflict, sharedCwd);\n}\n\nfunction resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {\n\treturn deps.config.singleRunOutputBaseDir\n\t\t? path.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir))\n\t\t: path.join(artifactsDir, \"outputs\", runId);\n}\n\nfunction buildChainWorktreeTaskCwdError(chain: ChainStep[], sharedCwd: string): string | undefined {\n\tfor (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {\n\t\tconst step = chain[stepIndex]!;\n\t\tif (!isParallelStep(step) || !step.worktree) continue;\n\t\tconst stepCwd = resolveChildCwd(sharedCwd, step.cwd);\n\t\tconst conflict = findWorktreeTaskCwdConflict(step.parallel, stepCwd);\n\t\tif (!conflict) continue;\n\t\tconst detail = formatWorktreeTaskCwdConflict(conflict, stepCwd);\n\t\treturn `parallel chain step ${stepIndex + 1}: ${detail}`;\n\t}\n\treturn undefined;\n}\n\nfunction resolveParallelTaskCwd(\n\ttask: TaskParam,\n\tparamsCwd: string,\n\tworktreeSetup: WorktreeSetup | undefined,\n\tindex: number,\n): string {\n\tif (worktreeSetup) return worktreeSetup.worktrees[index]!.agentCwd;\n\treturn resolveChildCwd(paramsCwd, task.cwd);\n}\n\nfunction finalizeParallelWorktreeHandoff(input: {\n\tworktreeSetup: WorktreeSetup;\n\tartifactsDir: string;\n\trunId: string;\n\tcwd: string;\n\ttasks: TaskParam[];\n\tresults: SingleResult[];\n}): { suffix: string; reference?: NonNullable<Details[\"parallelHandoff\"]> } {\n\tconst diffsDir = path.join(input.artifactsDir, \"worktree-diffs\", input.runId);\n\tconst diffs = diffWorktrees(\n\t\tinput.worktreeSetup,\n\t\tinput.tasks.map((task) => task.agent),\n\t\tdiffsDir,\n\t);\n\tconst diffSummary = formatWorktreeDiffSummary(diffs);\n\tconst manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);\n\tconst handoff = {\n\t\tmanifestPath,\n\t\trunId: input.runId,\n\t\tmode: \"parallel\" as const,\n\t\tsource: \"foreground\" as const,\n\t\tcwd: input.cwd,\n\t\tstepIndex: 0,\n\t\tflatStartIndex: 0,\n\t\tsetup: input.worktreeSetup,\n\t\tdiffs,\n\t\tresults: input.results.map((result) => ({\n\t\t\tagent: result.agent,\n\t\t\tstatus: resolveSubagentResultStatus(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\texitCode: result.exitCode,\n\t\t\t\t\tinterrupted: result.interrupted,\n\t\t\t\t\tdetached: result.detached,\n\t\t\t\t\tstate: result.stopped ? \"stopped\" : undefined,\n\t\t\t\t\tprocessSignal: result.processSignal,\n\t\t\t\t\ttimedOut: result.timedOut,\n\t\t\t\t\tstopped: result.stopped,\n\t\t\t\t\tturnBudgetExceeded: result.turnBudgetExceeded,\n\t\t\t\t}),\n\t\t\t),\n\t\t\tsummary: resultSummaryForIntercom(result),\n\t\t\t...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),\n\t\t\t...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),\n\t\t\t...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),\n\t\t\t...(result.sessionFile ? { sessionPath: result.sessionFile } : {}),\n\t\t})),\n\t};\n\ttry {\n\t\twriteParallelHandoffGroup(handoff);\n\t\tconst cleanup = cleanupWorktrees(input.worktreeSetup, {\n\t\t\tkind: \"preserve\",\n\t\t\tcapturedDiffs: diffs,\n\t\t\thandoffManifestPath: manifestPath,\n\t\t});\n\t\tconst reference = writeParallelHandoffGroup({ ...handoff, cleanup });\n\t\treturn {\n\t\t\tsuffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join(\"\\n\\n\"),\n\t\t\treference,\n\t\t};\n\t} catch (error) {\n\t\treturn { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join(\"\\n\\n\") };\n\t}\n}\n\nfunction findDuplicateParallelOutputPath(input: {\n\ttasks: TaskParam[];\n\tbehaviors: ResolvedStepBehavior[];\n\tparamsCwd: string;\n\tctxCwd: string;\n\toutputBaseDir: string;\n\tworktreeSetup?: WorktreeSetup;\n}): string | undefined {\n\tconst seen = new Map<string, { index: number; agent: string }>();\n\tfor (let index = 0; index < input.tasks.length; index++) {\n\t\tconst behavior = input.behaviors[index];\n\t\tif (!behavior?.output) continue;\n\t\tconst task = input.tasks[index]!;\n\t\tconst taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);\n\t\tconst outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);\n\t\tif (!outputPath) continue;\n\t\tconst previous = seen.get(outputPath);\n\t\tif (previous) {\n\t\t\treturn `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;\n\t\t}\n\t\tseen.set(outputPath, { index, agent: task.agent });\n\t}\n\treturn undefined;\n}\n\nasync function runForegroundParallelTasks(input: ForegroundParallelRunInput): Promise<SingleResult[]> {\n\t// Pre-warm fork session files sequentially before concurrent dispatch to avoid\n\t// races where multiple workers simultaneously try to branch the same parent session.\n\tfor (let i = 0; i < input.tasks.length; i++) {\n\t\tinput.sessionFileForTask(input.tasks[i]!.agent, i, input.modelOverrides[i]);\n\t}\n\tconst completedResults: SingleResult[] = [];\n\tif (input.foregroundControl) retainForegroundSchedulingOwner(input.foregroundControl);\n\treturn mapConcurrent(\n\t\tinput.tasks,\n\t\tinput.concurrencyLimit,\n\t\tasync (task, index) => {\n\t\t\tconst budgetState = usageBudgetState(input.usageBudget, sumResultsCost(completedResults));\n\t\t\tif (budgetState?.exhausted) {\n\t\t\t\treturn {\n\t\t\t\t\tindex,\n\t\t\t\t\tagent: task.agent,\n\t\t\t\t\ttask: input.taskTexts[index] ?? \"(skipped)\",\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\tmessages: [],\n\t\t\t\t\tusage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },\n\t\t\t\t\terror: usageBudgetExceededMessage(budgetState),\n\t\t\t\t\tskipped: true,\n\t\t\t\t} as SingleResult;\n\t\t\t}\n\t\t\tconst behavior = input.behaviors[index];\n\t\t\tconst effectiveSkills = behavior?.skills;\n\t\t\tconst taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);\n\t\t\tconst readInstructions = behavior\n\t\t\t\t? buildChainInstructions({ ...behavior, output: false, progress: false }, taskCwd, false)\n\t\t\t\t: { prefix: \"\", suffix: \"\" };\n\t\t\tconst progressInstructions = behavior\n\t\t\t\t? buildChainInstructions(\n\t\t\t\t\t\t{ ...behavior, output: false, reads: false },\n\t\t\t\t\t\tinput.progressDir,\n\t\t\t\t\t\tindex === input.firstProgressIndex,\n\t\t\t\t\t)\n\t\t\t\t: { prefix: \"\", suffix: \"\" };\n\t\t\tconst outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir);\n\t\t\tconst agentConfig = input.agents.find((agent) => agent.name === task.agent);\n\t\t\tconst taskText = injectSingleOutputInstruction(\n\t\t\t\t`${readInstructions.prefix}${input.taskTexts[index]!}${progressInstructions.suffix}`,\n\t\t\t\toutputPath,\n\t\t\t\tagentConfig,\n\t\t\t);\n\t\t\tconst interruptController = new AbortController();\n\t\t\tif (input.foregroundControl) {\n\t\t\t\tconst model = input.modelOverrides[index];\n\t\t\t\tconst thinking = resolveEffectiveThinking(model, input.thinkingOverrideForTask(task.agent, index, model));\n\t\t\t\tbeginForegroundChild(input.foregroundControl, {\n\t\t\t\t\tindex,\n\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t...(input.taskDescriptions[index] === undefined ? {} : { description: input.taskDescriptions[index] }),\n\t\t\t\t\t...(model ? { model } : {}),\n\t\t\t\t\t...(thinking ? { thinking } : {}),\n\t\t\t\t\tinterrupt: () => {\n\t\t\t\t\t\tif (interruptController.signal.aborted) return false;\n\t\t\t\t\t\tinterruptController.abort();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst structuredRuntime = task.outputSchema\n\t\t\t\t? createStructuredOutputRuntime(\n\t\t\t\t\t\ttask.outputSchema,\n\t\t\t\t\t\tpath.join(input.artifactsDir, \"structured-output\", input.runId),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tlet detachedReceipt = false;\n\t\t\tconst result = await runSync(\n\t\t\t\tinput.ctx.cwd,\n\t\t\t\tinput.agents,\n\t\t\t\ttask.agent,\n\t\t\t\ttaskText,\n\t\t\t\tcompactOptional<Parameters<typeof runSync>[4]>({\n\t\t\t\t\tpermissions: input.permissions,\n\t\t\t\t\tparentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,\n\t\t\t\t\tcontext: input.contextPolicy.contextForAgent(task.agent),\n\t\t\t\t\tcwd: taskCwd,\n\t\t\t\t\tsignal: input.signal,\n\t\t\t\t\tinterruptSignal: interruptController.signal,\n\t\t\t\t\tallowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,\n\t\t\t\t\tintercomEvents: input.intercomEvents,\n\t\t\t\t\trunId: input.runId,\n\t\t\t\t\tindex,\n\t\t\t\t\tsessionDir: input.sessionDirForIndex(index),\n\t\t\t\t\tsessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),\n\t\t\t\t\tshare: input.shareEnabled,\n\t\t\t\t\tartifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,\n\t\t\t\t\tartifactConfig: input.artifactConfig,\n\t\t\t\t\tmaxOutput: input.maxOutput,\n\t\t\t\t\toutputPath,\n\t\t\t\t\toutputMode: behavior?.outputMode,\n\t\t\t\t\tmaxSubagentDepth: input.maxSubagentDepths[index],\n\t\t\t\t\twaitToolEnabled: input.waitToolEnabled,\n\t\t\t\t\tcapabilityCeiling: input.capabilityCeiling,\n\t\t\t\t\tcontrolConfig: input.controlConfig,\n\t\t\t\t\tonControlEvent: input.onControlEvent,\n\t\t\t\t\tonDetachedExit: (result) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupdateRememberedForegroundChild(input.state, {\n\t\t\t\t\t\t\t\trunId: input.runId,\n\t\t\t\t\t\t\t\tmode: \"parallel\",\n\t\t\t\t\t\t\t\tcwd: taskCwd,\n\t\t\t\t\t\t\t\tsessionId: input.parentSessionId,\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\tevents: input.intercomEvents,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tif (input.foregroundControl) finishForegroundChild(input.foregroundControl, index);\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tremoveForegroundControlIfIdle(input.state, input.runId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tintercomSessionName: input.childIntercomTarget?.(task.agent, index),\n\t\t\t\t\torchestratorIntercomTarget: input.orchestratorIntercomTarget,\n\t\t\t\t\tnestedRoute: input.foregroundControl?.nestedRoute,\n\t\t\t\t\tmodelOverride: input.modelOverrides[index],\n\t\t\t\t\tthinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),\n\t\t\t\t\tavailableModels: input.availableModels,\n\t\t\t\t\tpreferredModelProvider: input.parentModel?.provider,\n\t\t\t\t\tmodelScope: input.modelScope,\n\t\t\t\t\tskills: effectiveSkills === false ? [] : effectiveSkills,\n\t\t\t\t\tstructuredOutput: structuredRuntime,\n\t\t\t\t\tagentContract: task.agentContract ?? input.agentContract,\n\t\t\t\t\tacceptance: task.acceptance,\n\t\t\t\t\tacceptanceContext: { mode: \"parallel\" },\n\t\t\t\t\ttimeoutMs: input.timeoutMs,\n\t\t\t\t\tdeadlineAt: input.deadlineAt,\n\t\t\t\t\tturnBudget: input.turnBudget,\n\t\t\t\t\ttoolBudget: input.toolBudgets[index],\n\t\t\t\t\tonUpdate: input.onUpdate\n\t\t\t\t\t\t? (progressUpdate) => {\n\t\t\t\t\t\t\t\tconst stepResults = progressUpdate.details?.results || [];\n\t\t\t\t\t\t\t\tconst stepProgress = progressUpdate.details?.progress || [];\n\t\t\t\t\t\t\t\tif (input.foregroundControl && stepProgress.length > 0) {\n\t\t\t\t\t\t\t\t\tupdateForegroundChild(input.foregroundControl, index, stepProgress[0]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (stepResults.length > 0) input.liveResults[index] = stepResults[0];\n\t\t\t\t\t\t\t\tif (stepProgress.length > 0) input.liveProgress[index] = stepProgress[0];\n\t\t\t\t\t\t\t\tconst mergedResults = input.liveResults.filter(\n\t\t\t\t\t\t\t\t\t(result): result is SingleResult => result !== undefined,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst mergedProgress = input.liveProgress.filter(\n\t\t\t\t\t\t\t\t\t(progress): progress is AgentProgress => progress !== undefined,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tinput.onUpdate?.({\n\t\t\t\t\t\t\t\t\tcontent: progressUpdate.content,\n\t\t\t\t\t\t\t\t\tdetails: compactOptional<Details>({\n\t\t\t\t\t\t\t\t\t\tmode: \"parallel\",\n\t\t\t\t\t\t\t\t\t\tresults: mergedResults,\n\t\t\t\t\t\t\t\t\t\tprogress: mergedProgress,\n\t\t\t\t\t\t\t\t\t\tcontrolEvents: progressUpdate.details?.controlEvents,\n\t\t\t\t\t\t\t\t\t\ttotalSteps: input.tasks.length,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tdetachedReceipt = result.detached === true;\n\t\t\t\t\treturn result;\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\t// mapConcurrent rejects before siblings settle, so every attached child\n\t\t\t\t\t// attempts idle removal after releasing its own control. Detached receipts\n\t\t\t\t\t// transfer both responsibilities to the authoritative exit callback.\n\t\t\t\t\tif (!detachedReceipt) {\n\t\t\t\t\t\tif (input.foregroundControl) finishForegroundChild(input.foregroundControl, index);\n\t\t\t\t\t\tremoveForegroundControlIfIdle(input.state, input.runId);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\tcompletedResults.push(result);\n\t\t\treturn result;\n\t\t},\n\t\tinput.globalSemaphore,\n\t\t() => {\n\t\t\tif (input.foregroundControl) settleForegroundSchedulingOwner(input.foregroundControl);\n\t\t\tremoveForegroundControlIfIdle(input.state, input.runId);\n\t\t},\n\t);\n}\n\nasync function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {\n\tconst {\n\t\tparams,\n\t\teffectiveCwd,\n\t\tagents,\n\t\tctx,\n\t\tsignal,\n\t\trunId,\n\t\tsessionDirForIndex,\n\t\tsessionFileForIndex,\n\t\tsessionFileForTask,\n\t\tthinkingOverrideForTask,\n\t\tshareEnabled,\n\t\tartifactConfig,\n\t\tartifactsDir,\n\t\tbackgroundRequestedWhileClarifying,\n\t\tonUpdate,\n\t\tsessionRoot,\n\t\tcontrolConfig,\n\t\tcontextPolicy,\n\t} = data;\n\tconst onControlEvent = createForegroundControlNotifier(data, deps);\n\tconst childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;\n\tconst allProgress: AgentProgress[] = [];\n\tconst allArtifactPaths: ArtifactPaths[] = [];\n\tconst tasks = params.tasks!;\n\tconst maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);\n\tconst parallelConcurrency = resolveTopLevelParallelConcurrency(\n\t\tparams.concurrency,\n\t\tdeps.config.parallel?.concurrency,\n\t);\n\n\tif (tasks.length > maxParallelTasks)\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Max ${maxParallelTasks} tasks` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"parallel\" as const, results: [] },\n\t\t};\n\n\tconst agentConfigs: AgentConfig[] = [];\n\tfor (const t of tasks) {\n\t\tconst config = agents.find((a) => a.name === t.agent);\n\t\tif (!config) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${t.agent}` }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"parallel\" as const, results: [] },\n\t\t\t};\n\t\t}\n\t\tagentConfigs.push(config);\n\t}\n\n\tconst currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);\n\tconst maxSubagentDepths = agentConfigs.map((config) =>\n\t\tresolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth),\n\t);\n\tconst toolBudgets: (ResolvedToolBudget | undefined)[] = [];\n\tfor (let index = 0; index < tasks.length; index++) {\n\t\tconst resolved = resolveEffectiveToolBudget(\n\t\t\tomitUndefinedProperties({\n\t\t\t\tstepBudget: tasks[index]?.toolBudget,\n\t\t\t\trunBudget: data.toolBudget,\n\t\t\t\tagentBudget: agentConfigs[index]?.toolBudget,\n\t\t\t\tconfigBudget: data.configToolBudget,\n\t\t\t}),\n\t\t);\n\t\tif (resolved.error) return buildParallelModeError(resolved.error);\n\t\ttoolBudgets.push(resolved.toolBudget);\n\t}\n\n\tif (params.worktree) {\n\t\tconst worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);\n\t\tif (worktreeTaskCwdError) return buildParallelModeError(worktreeTaskCwdError);\n\t}\n\n\tconst parentModel = data.parentModel;\n\tconst currentProvider = parentModel?.provider;\n\tconst availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);\n\tlet taskTexts = tasks.map((t) => t.task);\n\tconst skillOverrides: (string[] | false | undefined)[] = tasks.map((t) => normalizeSkillInput(t.skill));\n\tconst behaviorOverrides: StepOverrides[] = tasks.map((task, index) => ({\n\t\t...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),\n\t\t...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),\n\t\t...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),\n\t\t...(task.progress !== undefined ? { progress: task.progress } : {}),\n\t\t...(skillOverrides[index] !== undefined ? { skills: skillOverrides[index] } : {}),\n\t\t...(task.model !== undefined ? { model: task.model } : {}),\n\t}));\n\tconst modelOverrides: (string | undefined)[] = tasks.map((_, i) =>\n\t\tresolveEffectiveSubagentModel(\n\t\t\tbehaviorOverrides[i]?.model,\n\t\t\tagentConfigs[i]?.model,\n\t\t\tparentModel,\n\t\t\tavailableModels,\n\t\t\tcurrentProvider,\n\t\t\tdata.modelScope === undefined ? {} : { scope: data.modelScope },\n\t\t),\n\t);\n\n\tif (params.clarify === true && ctx.hasUI) {\n\t\tconst behaviors = agentConfigs.map((c, i) => resolveStepBehavior(c, behaviorOverrides[i]!));\n\t\tconst availableSkills = discoverAvailableSkills(effectiveCwd);\n\n\t\tconst result = await ctx.ui.custom<ChainClarifyResult>(\n\t\t\t(tui, theme, _kb, done) =>\n\t\t\t\tnew ChainClarifyComponent(\n\t\t\t\t\ttui,\n\t\t\t\t\ttheme,\n\t\t\t\t\tagentConfigs,\n\t\t\t\t\ttaskTexts,\n\t\t\t\t\t\"\",\n\t\t\t\t\tundefined,\n\t\t\t\t\tbehaviors,\n\t\t\t\t\tavailableModels,\n\t\t\t\t\tcurrentProvider,\n\t\t\t\t\tavailableSkills,\n\t\t\t\t\tdone,\n\t\t\t\t\t\"parallel\",\n\t\t\t\t),\n\t\t\t{ overlay: true, overlayOptions: { anchor: \"center\", width: 84, maxHeight: \"80%\" } },\n\t\t);\n\n\t\tif (!result || !result.confirmed) {\n\t\t\treturn { content: [{ type: \"text\", text: \"Cancelled\" }], details: { mode: \"parallel\", results: [] } };\n\t\t}\n\n\t\ttaskTexts = result.templates;\n\t\tfor (let i = 0; i < result.behaviorOverrides.length; i++) {\n\t\t\tconst override = result.behaviorOverrides[i];\n\t\t\tif (override?.model !== undefined) {\n\t\t\t\tmodelOverrides[i] = resolveEffectiveSubagentModel(\n\t\t\t\t\toverride.model,\n\t\t\t\t\tagentConfigs[i]?.model,\n\t\t\t\t\tparentModel,\n\t\t\t\t\tavailableModels,\n\t\t\t\t\tcurrentProvider,\n\t\t\t\t\tdata.modelScope === undefined ? {} : { scope: data.modelScope },\n\t\t\t\t);\n\t\t\t\tbehaviorOverrides[i]!.model = override.model;\n\t\t\t}\n\t\t\tif (override?.output !== undefined) behaviorOverrides[i]!.output = override.output;\n\t\t\tif (override?.reads !== undefined) behaviorOverrides[i]!.reads = override.reads;\n\t\t\tif (override?.progress !== undefined) behaviorOverrides[i]!.progress = override.progress;\n\t\t\tif (override?.skills !== undefined) {\n\t\t\t\tskillOverrides[i] = override.skills;\n\t\t\t\tbehaviorOverrides[i]!.skills = override.skills;\n\t\t\t}\n\t\t}\n\n\t\tif (result.runInBackground) {\n\t\t\tif (!isAsyncAvailable()) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"parallel\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst id = randomUUID();\n\t\t\tconst asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\t\t\tpi: deps.pi,\n\t\t\t\tcwd: ctx.cwd,\n\t\t\t\tcurrentSessionId: data.parentSessionId!,\n\t\t\t\tparentSessionId: data.parentPiSessionId,\n\t\t\t\tcurrentModelProvider: parentModel?.provider,\n\t\t\t\tcurrentModel: parentModel,\n\t\t\t\tmodelScope: data.modelScope,\n\t\t\t\tinteractive: ctx.hasUI,\n\t\t\t\tpermissions: deps.config.permissions,\n\t\t\t});\n\t\t\tconst parallelTasks = tasks.map((t, i) => {\n\t\t\t\tconst taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]!) : taskTexts[i]!;\n\t\t\t\tconst progress = taskDisallowsFileUpdates(taskText) ? false : behaviorOverrides[i]?.progress;\n\t\t\t\treturn compactOptional<ParallelTaskItem>({\n\t\t\t\t\tagent: t.agent,\n\t\t\t\t\ttask: taskText,\n\t\t\t\t\tcwd: t.cwd,\n\t\t\t\t\t...(behaviorOverrides[i]?.model !== undefined ? { model: behaviorOverrides[i]!.model } : {}),\n\t\t\t\t\t...(skillOverrides[i] !== undefined ? { skill: skillOverrides[i] } : {}),\n\t\t\t\t\t...(behaviorOverrides[i]?.output !== undefined ? { output: behaviorOverrides[i]!.output } : {}),\n\t\t\t\t\t...(behaviorOverrides[i]?.outputMode !== undefined\n\t\t\t\t\t\t? { outputMode: behaviorOverrides[i]!.outputMode }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(behaviorOverrides[i]?.reads !== undefined ? { reads: behaviorOverrides[i]!.reads } : {}),\n\t\t\t\t\t...(progress !== undefined ? { progress } : {}),\n\t\t\t\t\t...(t.toolBudget !== undefined ? { toolBudget: t.toolBudget } : {}),\n\t\t\t\t\t...(t.outputSchema !== undefined ? { outputSchema: t.outputSchema } : {}),\n\t\t\t\t\t...(t.acceptance !== undefined ? { acceptance: t.acceptance } : {}),\n\t\t\t\t\t...(t.agentContract !== undefined ? { agentContract: t.agentContract } : {}),\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn executeAsyncChain(\n\t\t\t\tid,\n\t\t\t\tcompactOptional<Parameters<typeof executeAsyncChain>[1]>({\n\t\t\t\t\tchain: [\n\t\t\t\t\t\tcompactOptional<ParallelStep>({\n\t\t\t\t\t\t\tparallel: parallelTasks,\n\t\t\t\t\t\t\tconcurrency: parallelConcurrency,\n\t\t\t\t\t\t\tworktree: params.worktree,\n\t\t\t\t\t\t}),\n\t\t\t\t\t],\n\t\t\t\t\tresultMode: \"parallel\",\n\t\t\t\t\tgoal: taskTexts[0] ?? \"\",\n\t\t\t\t\tagents,\n\t\t\t\t\tctx: asyncCtx,\n\t\t\t\t\tavailableModels,\n\t\t\t\t\tcwd: effectiveCwd,\n\t\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\t\tartifactConfig,\n\t\t\t\t\tshareEnabled,\n\t\t\t\t\tsessionRoot,\n\t\t\t\t\tchainSkills: [],\n\t\t\t\t\tsessionFilesByFlatIndex: tasks.map((task, index) =>\n\t\t\t\t\t\tsessionFileForTask(task.agent, index, modelOverrides[index]),\n\t\t\t\t\t),\n\t\t\t\t\tthinkingOverridesByFlatIndex: tasks.map((task, index) =>\n\t\t\t\t\t\tthinkingOverrideForTask(task.agent, index, modelOverrides[index]),\n\t\t\t\t\t),\n\t\t\t\t\tcontextForAgent: contextPolicy.contextForAgent,\n\t\t\t\t\tmaxSubagentDepth: currentMaxSubagentDepth,\n\t\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\t\tcontrolConfig,\n\t\t\t\t\tagentContract: params.agentContract,\n\t\t\t\t\tcontrolIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\t\t\tchildIntercomTarget: data.intercomBridge.active\n\t\t\t\t\t\t? (agent, index) => resolveSubagentIntercomTarget(id, agent, index)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tnestedRoute: data.nestedRoute,\n\t\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\t\ttoolBudget: data.toolBudget,\n\t\t\t\t\tconfigToolBudget: data.configToolBudget,\n\t\t\t\t\tglobalConcurrencyLimit: deps.config.globalConcurrencyLimit,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst behaviors = tasks.map((task, index) => {\n\t\tlet behavior = suppressProgressForReadOnlyTask(\n\t\t\tresolveStepBehavior(agentConfigs[index]!, behaviorOverrides[index]!),\n\t\t\ttaskTexts[index],\n\t\t);\n\t\tif (\n\t\t\tbehaviorOverrides[index]?.output === undefined &&\n\t\t\ttypeof behavior.output === \"string\" &&\n\t\t\t!path.isAbsolute(behavior.output)\n\t\t) {\n\t\t\tbehavior = { ...behavior, output: path.join(\"parallel-0\", `${index}-${task.agent}`, behavior.output) };\n\t\t}\n\t\treturn behavior;\n\t});\n\tconst firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress);\n\tconst liveResults: (SingleResult | undefined)[] = new Array(tasks.length).fill(undefined);\n\tconst liveProgress: (AgentProgress | undefined)[] = new Array(tasks.length).fill(undefined);\n\tconst foregroundControl = deps.state.foregroundControls.get(runId);\n\tconst { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(\n\t\tparams.worktree,\n\t\teffectiveCwd,\n\t\trunId,\n\t\ttasks,\n\t\tdeps.config.worktreeSetupHook,\n\t\tdeps.config.worktreeSetupHookTimeoutMs,\n\t\tdeps.config.worktreeBaseDir,\n\t);\n\tif (errorResult) return errorResult;\n\n\tlet worktreeFinalized = false;\n\ttry {\n\t\tif (worktreeSetup) {\n\t\t\twritePendingParallelHandoff({\n\t\t\t\tmanifestPath: parallelHandoffPath(artifactsDir, runId),\n\t\t\t\trunId,\n\t\t\t\tmode: \"parallel\",\n\t\t\t\tsource: \"foreground\",\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tstepIndex: 0,\n\t\t\t\tflatStartIndex: 0,\n\t\t\t\tsetup: worktreeSetup,\n\t\t\t});\n\t\t}\n\t\tconst outputBaseDir = path.join(artifactsDir, \"outputs\", runId);\n\t\tconst duplicateOutputError = findDuplicateParallelOutputPath(\n\t\t\tomitUndefinedProperties({\n\t\t\t\ttasks,\n\t\t\t\tbehaviors,\n\t\t\t\tparamsCwd: effectiveCwd,\n\t\t\t\tctxCwd: ctx.cwd,\n\t\t\t\toutputBaseDir,\n\t\t\t\tworktreeSetup,\n\t\t\t}),\n\t\t);\n\t\tif (duplicateOutputError) return buildParallelModeError(duplicateOutputError);\n\t\tfor (let index = 0; index < tasks.length; index++) {\n\t\t\tconst taskCwd = resolveParallelTaskCwd(tasks[index]!, effectiveCwd, worktreeSetup, index);\n\t\t\tconst outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir);\n\t\t\tconst validationError = validateFileOnlyOutputMode(\n\t\t\t\tbehaviors[index]?.outputMode,\n\t\t\t\toutputPath,\n\t\t\t\t`Parallel task ${index + 1} (${tasks[index]!.agent})`,\n\t\t\t);\n\t\t\tif (validationError) return buildParallelModeError(validationError);\n\t\t}\n\n\t\tconst parallelProgressPrecreated = firstProgressIndex !== -1;\n\t\tconst parallelProgressDir = path.join(artifactsDir, \"progress\", runId);\n\t\tif (parallelProgressPrecreated) writeInitialProgressFile(parallelProgressDir);\n\n\t\tconst taskDescriptions = taskTexts.map((taskText) => taskText.trim());\n\t\tfor (let i = 0; i < taskTexts.length; i++) {\n\t\t\tif (shouldForkAgent(contextPolicy, tasks[i]!.agent)) taskTexts[i] = wrapForkTask(taskTexts[i]!);\n\t\t}\n\n\t\tconst deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);\n\t\tconst results = await runForegroundParallelTasks(\n\t\t\tcompactOptional<ForegroundParallelRunInput>({\n\t\t\t\ttasks,\n\t\t\t\tpermissions: deps.config.permissions,\n\t\t\t\ttaskTexts,\n\t\t\t\ttaskDescriptions,\n\t\t\t\tagents,\n\t\t\t\tctx,\n\t\t\t\tstate: deps.state,\n\t\t\t\tintercomEvents: deps.pi.events,\n\t\t\t\tparentSessionId: data.parentSessionId,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tsignal,\n\t\t\t\trunId,\n\t\t\t\tsessionDirForIndex,\n\t\t\t\tsessionFileForIndex,\n\t\t\t\tsessionFileForTask,\n\t\t\t\tthinkingOverrideForTask,\n\t\t\t\tshareEnabled,\n\t\t\t\tartifactConfig,\n\t\t\t\tartifactsDir,\n\t\t\t\toutputBaseDir,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\tparamsCwd: effectiveCwd,\n\t\t\t\tprogressDir: parallelProgressDir,\n\t\t\t\tavailableModels,\n\t\t\t\tmodelScope: data.modelScope,\n\t\t\t\tparentModel,\n\t\t\t\tmodelOverrides,\n\t\t\t\tbehaviors,\n\t\t\t\tfirstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,\n\t\t\t\tcontrolConfig,\n\t\t\t\tcontextPolicy,\n\t\t\t\tonControlEvent,\n\t\t\t\tchildIntercomTarget: childIntercomTarget\n\t\t\t\t\t? (agent, index) => childIntercomTarget(runId, agent, index)\n\t\t\t\t\t: undefined,\n\t\t\t\torchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\t\tforegroundControl,\n\t\t\t\tconcurrencyLimit: parallelConcurrency,\n\t\t\t\tglobalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),\n\t\t\t\tmaxSubagentDepths,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tliveResults,\n\t\t\t\tliveProgress,\n\t\t\t\tonUpdate,\n\t\t\t\tworktreeSetup,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\ttoolBudgets,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t}),\n\t\t);\n\t\tfor (let i = 0; i < results.length; i++) {\n\t\t\tconst run = results[i]!;\n\t\t\trecordRun(run.agent, taskTexts[i]!, run.exitCode, run.progressSummary?.durationMs ?? 0);\n\t\t}\n\n\t\tfor (const result of results) {\n\t\t\tif (result.progress) allProgress.push(result.progress);\n\t\t\tif (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);\n\t\t}\n\n\t\tif (foregroundControl) {\n\t\t\tupdateForegroundNestedProjection(foregroundControl);\n\t\t\tattachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren);\n\t\t}\n\t\tlet handoff: ReturnType<typeof finalizeParallelWorktreeHandoff> | undefined;\n\t\tif (worktreeSetup) {\n\t\t\tworktreeFinalized = true;\n\t\t\thandoff = finalizeParallelWorktreeHandoff({\n\t\t\t\tworktreeSetup,\n\t\t\t\tartifactsDir,\n\t\t\t\trunId,\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\ttasks,\n\t\t\t\tresults,\n\t\t\t});\n\t\t}\n\t\tconst interrupted = results.find((result) => result.interrupted);\n\t\tconst totalCost = sumResultsCost(results);\n\t\tconst details = compactForegroundDetails(\n\t\t\tcompactOptional<Details>({\n\t\t\t\tmode: \"parallel\",\n\t\t\t\trunId,\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tresults,\n\t\t\t\tprogress: params.includeProgress ? allProgress : undefined,\n\t\t\t\tartifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,\n\t\t\t\ttotalChildUsage: sumResultsUsage(results),\n\t\t\t\ttotalCost,\n\t\t\t\tusageBudget: usageBudgetState(data.usageBudget, totalCost),\n\t\t\t\t...(handoff?.reference ? { parallelHandoff: handoff.reference } : {}),\n\t\t\t}),\n\t\t);\n\t\trememberForegroundRun(deps.state, {\n\t\t\trunId,\n\t\t\tmode: \"parallel\",\n\t\t\tcwd: effectiveCwd,\n\t\t\tsessionId: data.parentSessionId,\n\t\t\tresults: details.results,\n\t\t});\n\t\tif (interrupted) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails,\n\t\t\t};\n\t\t}\n\t\tconst detachedIndex = results.findIndex((result) => result.detached);\n\t\tconst detached = detachedIndex >= 0 ? results[detachedIndex] : undefined;\n\t\tif (detached) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Parallel run detached for intercom coordination (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: \"${runId}\" }). Use subagent({ action: \"status\", id: \"${runId}\" }) to recover the result; do not resume or launch a replacement while it remains detached.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails,\n\t\t\t};\n\t\t}\n\n\t\tconst suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({\n\t\t\tsuppressRoutineResultIntercom: params.suppressRoutineResultIntercom,\n\t\t\tresults,\n\t\t});\n\t\tif (foregroundControl) updateForegroundNestedProjection(foregroundControl);\n\t\tif (!suppressRoutineResultIntercom) {\n\t\t\tconst intercomReceipt = await maybeBuildForegroundIntercomReceipt({\n\t\t\t\tpi: deps.pi,\n\t\t\t\tintercomBridge: data.intercomBridge,\n\t\t\t\trunId,\n\t\t\t\tmode: \"parallel\",\n\t\t\t\tdetails,\n\t\t\t\t...(params.workflowParentRunId !== undefined ? { preserveDetailsOutputs: true } : {}),\n\t\t\t\t...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),\n\t\t\t});\n\t\t\tif (intercomReceipt) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: intercomReceipt.text }],\n\t\t\t\t\tdetails: intercomReceipt.details,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst worktreeSuffix = handoff?.suffix ?? \"\";\n\t\tconst ok = results.filter((result) => result.exitCode === 0).length;\n\t\tconst downgradeNote = backgroundRequestedWhileClarifying\n\t\t\t? \" (background requested, but clarify kept this run foreground)\"\n\t\t\t: \"\";\n\t\tconst aggregatedOutput = aggregateParallelOutputs(\n\t\t\tresults.map((result) => ({\n\t\t\t\tagent: result.agent,\n\t\t\t\toutput: result.truncation?.text || getSingleResultOutput(result),\n\t\t\t\texitCode: result.exitCode,\n\t\t\t\t...(result.error === undefined ? {} : { error: result.error }),\n\t\t\t\t...(result.timedOut === undefined ? {} : { timedOut: result.timedOut }),\n\t\t\t})),\n\t\t\t(i, agent) => `=== Task ${i + 1}: ${agent} ===`,\n\t\t);\n\n\t\tconst summary = `${ok}/${results.length} succeeded${downgradeNote}`;\n\t\tconst fullContent = worktreeSuffix\n\t\t\t? `${summary}\\n\\n${aggregatedOutput}\\n\\n${worktreeSuffix}`\n\t\t\t: `${summary}\\n\\n${aggregatedOutput}`;\n\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: fullContent }],\n\t\t\tdetails,\n\t\t};\n\t} finally {\n\t\tif (worktreeSetup && !worktreeFinalized) cleanupWorktrees(worktreeSetup);\n\t}\n}\n\nasync function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {\n\tconst {\n\t\tparams,\n\t\teffectiveCwd,\n\t\tagents,\n\t\tctx,\n\t\tsignal,\n\t\trunId,\n\t\tsessionDirForIndex,\n\t\tsessionFileForTask,\n\t\tthinkingOverrideForTask,\n\t\tshareEnabled,\n\t\tartifactConfig,\n\t\tartifactsDir,\n\t\tonUpdate,\n\t\tsessionRoot,\n\t\tcontrolConfig,\n\t\tcontextPolicy,\n\t} = data;\n\tconst onControlEvent = createForegroundControlNotifier(data, deps);\n\tconst childIntercomTarget = data.intercomBridge.active\n\t\t? resolveSubagentIntercomTarget(runId, params.agent!, 0)\n\t\t: undefined;\n\tconst allProgress: AgentProgress[] = [];\n\tconst allArtifactPaths: ArtifactPaths[] = [];\n\tconst agentConfig = agents.find((a) => a.name === params.agent);\n\tif (!agentConfig) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Unknown agent: ${params.agent}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\", results: [] },\n\t\t};\n\t}\n\tconst effectiveToolBudget = resolveEffectiveToolBudget(\n\t\tomitUndefinedProperties({\n\t\t\trunBudget: data.toolBudget,\n\t\t\tagentBudget: agentConfig.toolBudget,\n\t\t\tconfigBudget: data.configToolBudget,\n\t\t}),\n\t);\n\tif (effectiveToolBudget.error)\n\t\treturn toExecutionErrorResult(params, new Error(effectiveToolBudget.error), data.contextPolicy.contextSummary);\n\n\tconst parentModel = data.parentModel;\n\tconst currentProvider = parentModel?.provider;\n\tconst availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);\n\tlet task = params.task ?? \"\";\n\tlet modelOverride: string | undefined = resolveEffectiveSubagentModel(\n\t\tparams.model as string | undefined,\n\t\tagentConfig.model,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tcurrentProvider,\n\t\tdata.modelScope === undefined ? {} : { scope: data.modelScope },\n\t);\n\tlet skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);\n\tconst rawOutput = params.output !== undefined ? params.output : agentConfig.output;\n\tlet effectiveOutput = normalizeSingleOutputOverride(rawOutput, agentConfig.output);\n\tconst effectiveOutputMode = params.outputMode ?? \"inline\";\n\tconst currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);\n\tconst maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);\n\n\tif (params.clarify === true && ctx.hasUI) {\n\t\tconst behavior = resolveStepBehavior(\n\t\t\tagentConfig,\n\t\t\tomitUndefinedProperties({ output: effectiveOutput, skills: skillOverride }),\n\t\t);\n\t\tconst availableSkills = discoverAvailableSkills(effectiveCwd);\n\n\t\tconst result = await ctx.ui.custom<ChainClarifyResult>(\n\t\t\t(tui, theme, _kb, done) =>\n\t\t\t\tnew ChainClarifyComponent(\n\t\t\t\t\ttui,\n\t\t\t\t\ttheme,\n\t\t\t\t\t[agentConfig],\n\t\t\t\t\t[task],\n\t\t\t\t\ttask,\n\t\t\t\t\tundefined,\n\t\t\t\t\t[behavior],\n\t\t\t\t\tavailableModels,\n\t\t\t\t\tcurrentProvider,\n\t\t\t\t\tavailableSkills,\n\t\t\t\t\tdone,\n\t\t\t\t\t\"single\",\n\t\t\t\t),\n\t\t\t{ overlay: true, overlayOptions: { anchor: \"center\", width: 84, maxHeight: \"80%\" } },\n\t\t);\n\n\t\tif (!result || !result.confirmed) {\n\t\t\treturn { content: [{ type: \"text\", text: \"Cancelled\" }], details: { mode: \"single\", results: [] } };\n\t\t}\n\n\t\ttask = result.templates[0]!;\n\t\tconst override = result.behaviorOverrides[0];\n\t\tif (override?.model !== undefined)\n\t\t\tmodelOverride = resolveEffectiveSubagentModel(\n\t\t\t\toverride.model,\n\t\t\t\tagentConfig.model,\n\t\t\t\tparentModel,\n\t\t\t\tavailableModels,\n\t\t\t\tcurrentProvider,\n\t\t\t\tdata.modelScope === undefined ? {} : { scope: data.modelScope },\n\t\t\t);\n\t\tif (override?.output !== undefined)\n\t\t\teffectiveOutput = normalizeSingleOutputOverride(override.output, agentConfig.output);\n\t\tif (override?.skills !== undefined) skillOverride = override.skills;\n\n\t\tif (result.runInBackground) {\n\t\t\tif (!isAsyncAvailable()) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst id = randomUUID();\n\t\t\tconst asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1][\"ctx\"]>({\n\t\t\t\tpi: deps.pi,\n\t\t\t\tcwd: ctx.cwd,\n\t\t\t\tcurrentSessionId: data.parentSessionId!,\n\t\t\t\tparentSessionId: data.parentPiSessionId,\n\t\t\t\tcurrentModelProvider: parentModel?.provider,\n\t\t\t\tcurrentModel: parentModel,\n\t\t\t\tmodelScope: data.modelScope,\n\t\t\t\tinteractive: ctx.hasUI,\n\t\t\t\tpermissions: deps.config.permissions,\n\t\t\t});\n\t\t\treturn executeAsyncSingle(\n\t\t\t\tid,\n\t\t\t\tcompactOptional<Parameters<typeof executeAsyncSingle>[1]>({\n\t\t\t\t\tagent: params.agent!,\n\t\t\t\t\ttask: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,\n\t\t\t\t\tgoal: task,\n\t\t\t\t\tagentConfig,\n\t\t\t\t\tctx: asyncCtx,\n\t\t\t\t\tavailableModels,\n\t\t\t\t\tcwd: effectiveCwd,\n\t\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\t\tartifactConfig,\n\t\t\t\t\tshareEnabled,\n\t\t\t\t\tsessionRoot,\n\t\t\t\t\tsessionFile: sessionFileForTask(params.agent!, 0, modelOverride),\n\t\t\t\t\tcontext: contextPolicy.contextForAgent(params.agent!),\n\t\t\t\t\tskills: skillOverride === false ? [] : skillOverride,\n\t\t\t\t\toutput: effectiveOutput,\n\t\t\t\t\toutputMode: effectiveOutputMode,\n\t\t\t\t\toutputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),\n\t\t\t\t\tmodelOverride,\n\t\t\t\t\tthinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),\n\t\t\t\t\tmaxSubagentDepth,\n\t\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\t\tworktreeSetupHook: deps.config.worktreeSetupHook,\n\t\t\t\t\tworktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,\n\t\t\t\t\tworktreeBaseDir: deps.config.worktreeBaseDir,\n\t\t\t\t\tcontrolConfig,\n\t\t\t\t\tcontrolIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\t\t\tchildIntercomTarget: data.intercomBridge.active\n\t\t\t\t\t\t? (agent, index) => resolveSubagentIntercomTarget(id, agent, index)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tnestedRoute: data.nestedRoute,\n\t\t\t\t\tagentContract: params.agentContract,\n\t\t\t\t\tstructuredOutputSchema: params.outputSchema,\n\t\t\t\t\tacceptance: params.acceptance,\n\t\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\t\ttoolBudget: effectiveToolBudget.toolBudget,\n\t\t\t\t\tusageBudget: data.usageBudget,\n\t\t\t\t\tallowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (shouldForkAgent(contextPolicy, params.agent!)) {\n\t\ttask = wrapForkTask(task);\n\t}\n\tconst cleanTask = task;\n\tconst outputPath = resolveSingleOutputPath(\n\t\teffectiveOutput,\n\t\tctx.cwd,\n\t\teffectiveCwd,\n\t\tresolveSingleRunOutputBaseDir(deps, artifactsDir, runId),\n\t);\n\tconst validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`);\n\tif (validationError) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: validationError }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\", results: [] },\n\t\t};\n\t}\n\tconst structuredRuntime = params.outputSchema\n\t\t? createStructuredOutputRuntime(\n\t\t\t\tparams.outputSchema,\n\t\t\t\tartifactConfig.enabled ? path.join(artifactsDir, \"structured-output\", runId) : undefined,\n\t\t\t)\n\t\t: undefined;\n\ttask = injectSingleOutputInstruction(task, outputPath, agentConfig);\n\n\tlet effectiveSkills: string[] | undefined;\n\tif (skillOverride === false) {\n\t\teffectiveSkills = [];\n\t} else {\n\t\teffectiveSkills = skillOverride;\n\t}\n\tconst interruptController = new AbortController();\n\tlet detachForeground: ((reason?: string) => boolean) | undefined;\n\tconst foregroundControl = deps.state.foregroundControls.get(runId);\n\tif (foregroundControl) {\n\t\tconst thinking = resolveEffectiveThinking(\n\t\t\tmodelOverride,\n\t\t\tthinkingOverrideForTask(params.agent!, 0, modelOverride),\n\t\t);\n\t\tbeginForegroundChild(\n\t\t\tforegroundControl,\n\t\t\tomitUndefinedProperties({\n\t\t\t\tindex: 0,\n\t\t\t\tagent: params.agent!,\n\t\t\t\tdescription: foregroundControl.description,\n\t\t\t\t...(modelOverride ? { model: modelOverride } : {}),\n\t\t\t\t...(thinking ? { thinking } : {}),\n\t\t\t\tinterrupt: () => {\n\t\t\t\t\tif (interruptController.signal.aborted) return false;\n\t\t\t\t\tinterruptController.abort();\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t\tdetach: () => detachForeground?.(\"user request\") === true,\n\t\t\t}),\n\t\t);\n\t}\n\n\tconst forwardSingleUpdate = onUpdate\n\t\t? (update: AgentToolResult<Details>) => {\n\t\t\t\tif (foregroundControl) updateForegroundChild(foregroundControl, 0, update.details?.progress?.[0]);\n\t\t\t\tonUpdate(update);\n\t\t\t}\n\t\t: undefined;\n\n\tconst deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);\n\tlet r: Awaited<ReturnType<typeof runSync>> | undefined;\n\ttry {\n\t\tr = await runSync(\n\t\t\tctx.cwd,\n\t\t\tagents,\n\t\t\tparams.agent!,\n\t\t\ttask,\n\t\t\tcompactOptional<Parameters<typeof runSync>[4]>({\n\t\t\t\tpermissions: deps.config.permissions,\n\t\t\t\tparentSessionId: ctx.sessionManager.getSessionId() ?? undefined,\n\t\t\t\tcontext: data.contextPolicy.contextForAgent(params.agent!),\n\t\t\t\tcwd: effectiveCwd,\n\t\t\t\tsignal,\n\t\t\t\tinterruptSignal: interruptController.signal,\n\t\t\t\tallowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,\n\t\t\t\tintercomEvents: deps.pi.events,\n\t\t\t\trunId,\n\t\t\t\tsessionDir: sessionDirForIndex(0),\n\t\t\t\tsessionFile: sessionFileForTask(params.agent!, 0, modelOverride),\n\t\t\t\tshare: shareEnabled,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tmaxOutput: params.maxOutput,\n\t\t\t\toutputPath,\n\t\t\t\toutputMode: effectiveOutputMode,\n\t\t\t\tmaxSubagentDepth,\n\t\t\t\twaitToolEnabled: deps.waitToolEnabled,\n\t\t\t\tonUpdate: forwardSingleUpdate,\n\t\t\t\tcontrolConfig,\n\t\t\t\tonControlEvent,\n\t\t\t\tintercomSessionName: childIntercomTarget,\n\t\t\t\torchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,\n\t\t\t\tnestedRoute: foregroundControl?.nestedRoute,\n\t\t\t\tindex: 0,\n\t\t\t\tmodelOverride,\n\t\t\t\tthinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),\n\t\t\t\tavailableModels,\n\t\t\t\tpreferredModelProvider: currentProvider,\n\t\t\t\tmodelScope: data.modelScope,\n\t\t\t\tskills: effectiveSkills,\n\t\t\t\tstructuredOutput: structuredRuntime,\n\t\t\t\tagentContract: params.agentContract,\n\t\t\t\tacceptance: params.acceptance,\n\t\t\t\tacceptanceContext: { mode: \"single\" },\n\t\t\t\tonDetachReady: (detach) => {\n\t\t\t\t\tdetachForeground = detach;\n\t\t\t\t},\n\t\t\t\tonDetachedExit: (result) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupdateRememberedForegroundChild(deps.state, {\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\tmode: \"single\",\n\t\t\t\t\t\t\t\tcwd: effectiveCwd,\n\t\t\t\t\t\t\t\tsessionId: data.parentSessionId,\n\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\tevents: deps.pi.events,\n\t\t\t\t\t\t\t\tnotify: params.workflowParentRunId === undefined,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// Remembered foreground state is best-effort; run history and cleanup must still complete.\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tif (foregroundControl) finishForegroundChild(foregroundControl, 0);\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tremoveForegroundControlIfIdle(deps.state, runId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trecordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);\n\t\t\t\t},\n\t\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tturnBudget: data.turnBudget,\n\t\t\t\tenforceHardTurnLimit: params.enforceHardTurnLimit,\n\t\t\t\ttoolBudget: effectiveToolBudget.toolBudget,\n\t\t\t\tcapabilityCeiling: data.capabilityCeiling,\n\t\t\t\tallowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,\n\t\t\t}),\n\t\t);\n\t} finally {\n\t\t// An attached runSync rejection still owns its child and structured runtime.\n\t\t// A successful detached receipt transfers both to onDetachedExit while the\n\t\t// authoritative completion remains live.\n\t\tif (!r?.detached) {\n\t\t\tif (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);\n\t\t\tif (foregroundControl) finishForegroundChild(foregroundControl, 0);\n\t\t}\n\t}\n\tif (!r.detached) {\n\t\trecordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);\n\t}\n\n\tif (r.progress) allProgress.push(r.progress);\n\tif (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);\n\n\tconst fullOutput = getSingleResultOutput(r);\n\tconst finalizedOutput = finalizeSingleOutput(\n\t\tomitUndefinedProperties({\n\t\t\tfullOutput,\n\t\t\ttruncatedOutput: r.truncation?.text,\n\t\t\toutputPath,\n\t\t\toutputMode: r.outputMode,\n\t\t\texitCode: r.exitCode,\n\t\t\tsavedPath: r.savedOutputPath,\n\t\t\toutputReference: r.outputReference,\n\t\t\tsaveError: r.outputSaveError,\n\t\t}),\n\t);\n\tif (foregroundControl) {\n\t\tupdateForegroundNestedProjection(foregroundControl);\n\t\tattachRootChildrenToSteps(runId, [r], foregroundControl.nestedChildren);\n\t}\n\tconst totalCost = sumResultsCost([r]);\n\tconst details = compactForegroundDetails(\n\t\tcompactOptional<Details>({\n\t\t\tmode: \"single\",\n\t\t\trunId,\n\t\t\ttimeoutMs: data.timeoutMs,\n\t\t\tresults: [r],\n\t\t\t...(data.turnBudget ? { turnBudget: data.turnBudget } : {}),\n\t\t\t...(effectiveToolBudget.toolBudget ? { toolBudget: effectiveToolBudget.toolBudget } : {}),\n\t\t\tprogress: params.includeProgress ? allProgress : undefined,\n\t\t\tartifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,\n\t\t\ttruncation: r.truncation,\n\t\t\ttotalChildUsage: sumResultsUsage([r]),\n\t\t\ttotalCost,\n\t\t\tusageBudget: usageBudgetState(data.usageBudget, totalCost),\n\t\t}),\n\t);\n\trememberForegroundRun(deps.state, {\n\t\trunId,\n\t\tmode: \"single\",\n\t\tcwd: effectiveCwd,\n\t\tsessionId: data.parentSessionId,\n\t\tresults: details.results,\n\t});\n\n\tconst suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({\n\t\tsuppressRoutineResultIntercom: params.suppressRoutineResultIntercom,\n\t\tresults: [r],\n\t});\n\tif (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {\n\t\tif (foregroundControl) updateForegroundNestedProjection(foregroundControl);\n\t\tconst intercomReceipt = await maybeBuildForegroundIntercomReceipt({\n\t\t\tpi: deps.pi,\n\t\t\tintercomBridge: data.intercomBridge,\n\t\t\trunId,\n\t\t\tmode: \"single\",\n\t\t\tdetails,\n\t\t\t...(params.workflowParentRunId !== undefined ? { preserveDetailsOutputs: true } : {}),\n\t\t\t...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),\n\t\t});\n\t\tif (intercomReceipt) {\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: intercomReceipt.text }],\n\t\t\t\tdetails: intercomReceipt.details,\n\t\t\t\t...(r.exitCode !== 0 ? { isError: true } : {}),\n\t\t\t};\n\t\t}\n\t}\n\n\tif (r.detached) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with subagent_wait({ id: \"${runId}\" }). Use subagent({ action: \"status\", id: \"${runId}\" }) to recover the result; do not resume or launch a replacement while it remains detached.`,\n\t\t\t\t},\n\t\t\t],\n\t\t\tdetails,\n\t\t};\n\t}\n\n\tif (r.interrupted) {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Run paused after interrupt (${params.agent}). Waiting for explicit next action.` },\n\t\t\t],\n\t\t\tdetails,\n\t\t};\n\t}\n\n\tif (r.exitCode !== 0)\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: formatFailedSingleRunOutput(r, finalizedOutput.displayOutput) }],\n\t\t\tdetails,\n\t\t\tisError: true,\n\t\t};\n\treturn {\n\t\tcontent: [{ type: \"text\", text: finalizedOutput.displayOutput || \"(no output)\" }],\n\t\tdetails,\n\t};\n}\n\nfunction inferExecutionMode(params: SubagentParamsLike): Details[\"mode\"] {\n\tif (params.workflowScript !== undefined) return \"workflow\";\n\tif ((params.chain?.length ?? 0) > 0) return \"chain\";\n\tif ((params.tasks?.length ?? 0) > 0) return \"parallel\";\n\treturn \"single\";\n}\n\nfunction duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResult<Details> {\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"Rejected: a subagent call is already in progress. Issue exactly ONE subagent call per turn.\",\n\t\t\t},\n\t\t],\n\t\tisError: true,\n\t\tdetails: { mode: inferExecutionMode(params), results: [] },\n\t};\n}\n\nfunction workflowChildResult(key: string, result: AgentToolResult<Details>): WorkflowScriptChildResult {\n\tconst receiptOutput = result.content\n\t\t.map((part) => (part.type === \"text\" ? part.text : \"\"))\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n\tconst output =\n\t\tresult.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined\n\t\t\t? result.details.results[0].finalOutput\n\t\t\t: receiptOutput;\n\tconst artifactPaths = new Set<string>();\n\tif (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);\n\tif (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);\n\tfor (const child of result.details.results) {\n\t\tif (child.savedOutputPath) artifactPaths.add(child.savedOutputPath);\n\t\tif (child.outputReference?.path) artifactPaths.add(child.outputReference.path);\n\t\tif (child.sessionFile) artifactPaths.add(child.sessionFile);\n\t}\n\tconst structured = result.details.results\n\t\t.map((child) => child.structuredOutput)\n\t\t.filter((value) => value !== undefined);\n\treturn {\n\t\tkey,\n\t\tok: result.isError !== true,\n\t\t...(result.details.runId || result.details.asyncId\n\t\t\t? { runId: result.details.runId ?? result.details.asyncId }\n\t\t\t: {}),\n\t\toutput,\n\t\t...(result.isError === true ? { error: receiptOutput || output || \"Child run failed.\" } : {}),\n\t\t...(structured.length === 1\n\t\t\t? { structuredOutput: structured[0] }\n\t\t\t: structured.length > 1\n\t\t\t\t? { structuredOutput: structured }\n\t\t\t\t: {}),\n\t\tartifactPaths: [...artifactPaths],\n\t\tresults: result.details.results,\n\t};\n}\n\nexport function prepareWorkflowLaunchParams(\n\tworkflowDefaults: SubagentParamsLike,\n\tchildParams: Record<string, unknown>,\n\tparentWorkflowRunId: string,\n\tworkflowKey: string,\n\toptions: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean } = {},\n): SubagentParamsLike {\n\tif (typeof childParams.resume === \"string\") {\n\t\tif (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {\n\t\t\tthrow new Error(\"gate is not supported with retained resume; resume uses the retained child contract.\");\n\t\t}\n\t\tconst timeoutMs =\n\t\t\tchildParams.timeoutMs ??\n\t\t\tchildParams.maxRuntimeMs ??\n\t\t\tworkflowDefaults.timeoutMs ??\n\t\t\tworkflowDefaults.maxRuntimeMs;\n\t\tconst turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;\n\t\tconst toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;\n\t\treturn {\n\t\t\taction: \"resume\",\n\t\t\tid: childParams.resume.trim(),\n\t\t\tmessage: typeof childParams.task === \"string\" ? childParams.task.trim() : \"\",\n\t\t\tworkflowParentRunId: parentWorkflowRunId,\n\t\t\tworkflowKey,\n\t\t\t...(options.missionDetached ? { mission: false } : {}),\n\t\t\t...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),\n\t\t\t...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),\n\t\t\t...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),\n\t\t};\n\t}\n\tconst launchParams = {\n\t\t...workflowDefaults,\n\t\t...childParams,\n\t\t...(options.missionDetached ? { mission: false } : {}),\n\t\tworkflowParentRunId: parentWorkflowRunId,\n\t\tworkflowKey,\n\t\t...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),\n\t} as SubagentParamsLike;\n\tconst normalizedGate = normalizeGateParams(launchParams);\n\tif (normalizedGate.error || !normalizedGate.params) throw new Error(normalizedGate.error ?? \"Invalid gate.\");\n\treturn prepareWorkflowChildParams(normalizedGate.params);\n}\n\nfunction normalizeGateParams(params: SubagentParamsLike): { params?: SubagentParamsLike; error?: string } {\n\tif (params.gate !== undefined && params.action === \"resume\") {\n\t\treturn { error: \"gate is not supported with action='resume'; resume uses the retained child contract.\" };\n\t}\n\tconst normalized = normalizeGateAcceptance(params.gate, params.acceptance);\n\tif (normalized.error) return { error: normalized.error };\n\tif (params.gate === undefined) return { params };\n\tconst { gate: _gate, ...rest } = params;\n\treturn {\n\t\tparams: { ...rest, ...(normalized.acceptance !== undefined ? { acceptance: normalized.acceptance } : {}) },\n\t};\n}\n\nfunction prepareWorkflowChildParams(params: SubagentParamsLike): SubagentParamsLike {\n\tif (params.worktree !== true || !params.agent) return params;\n\tconst {\n\t\tagent,\n\t\ttask = \"\",\n\t\tmodel,\n\t\tskill,\n\t\toutput,\n\t\toutputMode,\n\t\toutputSchema,\n\t\tacceptance,\n\t\tagentContract,\n\t\ttoolBudget,\n\t\t...runParams\n\t} = params;\n\treturn {\n\t\t...runParams,\n\t\tworktree: true,\n\t\ttasks: [\n\t\t\t{\n\t\t\t\tagent,\n\t\t\t\ttask,\n\t\t\t\t...(model !== undefined ? { model } : {}),\n\t\t\t\t...(skill !== undefined ? { skill } : {}),\n\t\t\t\t...(output !== undefined ? { output } : {}),\n\t\t\t\t...(outputMode !== undefined ? { outputMode } : {}),\n\t\t\t\t...(outputSchema !== undefined ? { outputSchema } : {}),\n\t\t\t\t...(acceptance !== undefined ? { acceptance } : {}),\n\t\t\t\t...(agentContract !== undefined ? { agentContract } : {}),\n\t\t\t\t...(toolBudget !== undefined ? { toolBudget } : {}),\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction formatWorkflowValue(value: unknown): string {\n\tif (value === undefined) return \"(undefined)\";\n\tif (typeof value === \"string\") return value;\n\ttry {\n\t\treturn JSON.stringify(value, null, 2);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction workflowChatProgressUpdate(\n\trunId: string,\n\tchatProgress: WorkflowChatProgressProjection,\n\tworkflow: NonNullable<Details[\"workflow\"]>,\n): AgentToolResult<Details> | undefined {\n\tif (chatProgress.mode !== \"live-card\") return undefined;\n\treturn {\n\t\tcontent: [{ type: \"text\", text: \"Workflow running.\" }],\n\t\tdetails: { mode: \"workflow\", runId, results: [], workflow, chatProgress },\n\t};\n}\n\nfunction createScheduledOwnerState(\n\tsource: SubagentState,\n\townerSessionId: string,\n\tctx: ExtensionContext,\n): SubagentState {\n\tconst ownerSpawns =\n\t\tsource.subagentSpawns?.sessionId === ownerSessionId\n\t\t\t? {\n\t\t\t\t\t...source.subagentSpawns,\n\t\t\t\t\tgrantHistory: [...(source.subagentSpawns.grantHistory ?? [])],\n\t\t\t\t}\n\t\t\t: undefined;\n\treturn {\n\t\t...source,\n\t\tbaseCwd: ctx.cwd,\n\t\tcurrentSessionId: ownerSessionId,\n\t\tparentSessionFile: ctx.sessionManager.getSessionFile() ?? null,\n\t\tsubagentInProgress: false,\n\t\t...(ownerSpawns ? { subagentSpawns: ownerSpawns } : { subagentSpawns: undefined }),\n\t\tasyncJobs: new Map(),\n\t\tfleetJobs: new Map(),\n\t\tforegroundRuns: new Map(),\n\t\tforegroundControls: new Map(),\n\t\tlastForegroundControlId: null,\n\t\tcleanupTimers: new Map(),\n\t\tlastUiContext: null,\n\t\tpoller: null,\n\t\tcompletionSeen: new Map(),\n\t\twatcher: null,\n\t\twatcherRestartTimer: null,\n\t\twaitSubscriptions: new Map(),\n\t\tworkflowControllers: new Map(),\n\t};\n}\n\nexport function createSubagentExecutor(deps: ExecutorDeps): {\n\texecute: (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t) => Promise<AgentToolResult<Details>>;\n\t/** Public/model-facing execution boundary. Internal direct launch primitives use execute or executeDelegated. */\n\texecutePublic: (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t) => Promise<AgentToolResult<Details>>;\n\t/**\n\t * Correlated extension-to-extension delegation owns its request IDs and\n\t * cancellation controllers, so independent requests may execute concurrently.\n\t * The ordinary model-facing tool keeps the one-foreground-call-per-turn guard.\n\t */\n\texecuteDelegated: (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t) => Promise<AgentToolResult<Details>>;\n\t/** Scheduled launches retain their owning context without replacing the live active session. */\n\texecuteScheduled: (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tctx: ExtensionContext,\n\t) => Promise<AgentToolResult<Details>>;\n} {\n\tconst delegatedThinkingOverrides = new WeakMap<object, AgentConfig[\"thinking\"]>();\n\tconst delegatedZeroToolBudgets = new WeakSet<object>();\n\tconst warnedArtifactPackageDirs = new Set<string>();\n\tconst scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();\n\tconst execute = async (\n\t\t_id: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t\tpreserveActiveSession = false,\n\t): Promise<AgentToolResult<Details>> => {\n\t\tconst delegatedThinkingOverride = delegatedThinkingOverrides.get(params);\n\t\tconst allowZeroToolBudget = delegatedZeroToolBudgets.has(params);\n\t\tif (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;\n\t\tdeps.state.foregroundRuns ??= new Map();\n\t\tdeps.state.foregroundControls ??= new Map();\n\t\tdeps.state.lastForegroundControlId ??= null;\n\t\tconst normalizedGate = normalizeGateParams(params);\n\t\tif (normalizedGate.error || !normalizedGate.params)\n\t\t\treturn buildRequestedModeError(params, normalizedGate.error ?? \"Invalid gate.\");\n\t\tconst requestParams = normalizedGate.params;\n\t\tconst normalizedAction =\n\t\t\ttypeof requestParams.action === \"string\" ? requestParams.action.trim() : requestParams.action;\n\t\tif (requestParams.workflowScript !== undefined && normalizedAction === undefined) {\n\t\t\tconst parentCwd = ctx.cwd;\n\t\t\tconst timeout =\n\t\t\t\trequestParams.timeoutMs ??\n\t\t\t\trequestParams.maxRuntimeMs ??\n\t\t\t\t(requestParams.async === false ? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);\n\t\t\tconst workflowUsageBudget = validateUsageBudgetConfig(\n\t\t\t\trequestParams.usageBudget ?? deps.config.usageBudget,\n\t\t\t\trequestParams.usageBudget ? \"usageBudget\" : \"config.usageBudget\",\n\t\t\t);\n\t\t\tif (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);\n\t\t\tconst workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);\n\t\t\tconst chatProgressResult = resolveWorkflowChatProgress({\n\t\t\t\trequested: requestParams.chatProgress,\n\t\t\t\tparentCwd,\n\t\t\t\tworkflowCwd,\n\t\t\t\tbackground: requestParams.async !== false,\n\t\t\t});\n\t\t\tif (chatProgressResult.error)\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: chatProgressResult.error }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"workflow\", results: [] },\n\t\t\t\t};\n\t\t\tconst chatProgress = chatProgressResult.projection!;\n\t\t\tconst explicitMission = requestParams.missionId !== undefined || requestParams.mission !== undefined;\n\t\t\tlet missionBinding: MissionLaunchBinding | undefined;\n\t\t\tlet missionWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tmissionBinding = prepareMissionLaunch({\n\t\t\t\t\tparams: requestParams,\n\t\t\t\t\tprojectRoot: workflowCwd,\n\t\t\t\t\t...(deps.config.missions ? { config: deps.config.missions } : {}),\n\t\t\t\t\townerSessionId: resolveCurrentSessionId(ctx.sessionManager),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (explicitMission)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"workflow\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tmissionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\t}\n\t\t\tconst workflowState = missionBinding\n\t\t\t\t? createMissionWorkflowState(missionBinding.location, missionBinding.missionId)\n\t\t\t\t: undefined;\n\t\t\tconst attachWorkflowMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {\n\t\t\t\tif (!missionBinding)\n\t\t\t\t\treturn missionWarning ? { ...result, details: { ...result.details, missionWarning } } : result;\n\t\t\t\ttry {\n\t\t\t\t\treturn attachMissionToLaunchResult({ binding: missionBinding, result });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst warning = `Mission tracking unavailable after launch: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\t\t\treturn explicitMission\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tcontent: [...result.content, { type: \"text\", text: warning }],\n\t\t\t\t\t\t\t\tdetails: { ...result.details, missionWarning: warning },\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: { ...result, details: { ...result.details, missionWarning: warning } };\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (requestParams.async !== false) {\n\t\t\t\tconst workflowRunId = _id;\n\t\t\t\tconst asyncDir = path.join(DIRS.async, workflowRunId);\n\t\t\t\tconst resultPath = path.join(DIRS.results, `${workflowRunId}.json`);\n\t\t\t\tconst statusPath = path.join(asyncDir, \"status.json\");\n\t\t\t\tconst eventsPath = path.join(asyncDir, \"events.jsonl\");\n\t\t\t\tconst startedAt = Date.now();\n\t\t\t\tconst currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tfs.mkdirSync(asyncDir, { recursive: true });\n\t\t\t\tfs.mkdirSync(DIRS.results, { recursive: true });\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tdeps.state.workflowControllers ??= new Map();\n\t\t\t\tdeps.state.workflowControllers.set(workflowRunId, controller);\n\t\t\t\tlet status: AsyncStatus = {\n\t\t\t\t\trunId: workflowRunId,\n\t\t\t\t\tsessionId: currentSessionId ?? undefined,\n\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\tstate: \"running\",\n\t\t\t\t\tstartedAt,\n\t\t\t\t\tlastUpdate: startedAt,\n\t\t\t\t\t...(timeout !== undefined ? { deadlineAt: startedAt + timeout, timeoutMs: timeout } : {}),\n\t\t\t\t\tcwd: parentCwd,\n\t\t\t\t\tpid: process.pid,\n\t\t\t\t\tsteps: [],\n\t\t\t\t\tworkflow: { trace: [], emits: [], console: [] },\n\t\t\t\t};\n\t\t\t\tconst appendWorkflowEvent = (event: Record<string, unknown>) =>\n\t\t\t\t\tfs.appendFileSync(\n\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t`${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\\n`,\n\t\t\t\t\t\t\"utf-8\",\n\t\t\t\t\t);\n\t\t\t\tconst persist = () => {\n\t\t\t\t\tstatus.lastUpdate = Date.now();\n\t\t\t\t\twriteAtomicJson(statusPath, status);\n\t\t\t\t\tconst job = deps.state.asyncJobs.get(workflowRunId);\n\t\t\t\t\tif (job) {\n\t\t\t\t\t\tjob.status = status.state;\n\t\t\t\t\t\tjob.updatedAt = status.lastUpdate;\n\t\t\t\t\t\tif (status.steps) {\n\t\t\t\t\t\t\tjob.steps = status.steps.map((step, index) => ({ ...step, index }));\n\t\t\t\t\t\t\tjob.agents = status.steps.map((step) => step.agent);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdelete job.steps;\n\t\t\t\t\t\t\tdelete job.agents;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjob.workflow = status.workflow;\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tconst workflowJob: AsyncJobState = {\n\t\t\t\t\tasyncId: workflowRunId,\n\t\t\t\t\tasyncDir,\n\t\t\t\t\tcwd: parentCwd,\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\tsessionId: currentSessionId ?? undefined,\n\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\tagents: [],\n\t\t\t\t\tsteps: [],\n\t\t\t\t\tstartedAt,\n\t\t\t\t\tupdatedAt: startedAt,\n\t\t\t\t\t...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}),\n\t\t\t\t\tworkflow: status.workflow,\n\t\t\t\t};\n\t\t\t\tdeps.state.asyncJobs.set(workflowRunId, workflowJob);\n\t\t\t\tdeps.state.fleetJobs ??= new Map();\n\t\t\t\tdeps.state.fleetJobs.set(workflowRunId, workflowJob);\n\t\t\t\tpersist();\n\t\t\t\tappendWorkflowEvent({ type: \"subagent.workflow.started\" });\n\t\t\t\tconst {\n\t\t\t\t\tworkflowScript,\n\t\t\t\t\tasync: _workflowAsync,\n\t\t\t\t\tchatProgress: _chatProgress,\n\t\t\t\t\t...workflowRequest\n\t\t\t\t} = requestParams;\n\t\t\t\tvoid Promise.resolve().then(async () => {\n\t\t\t\t\tconst workflowResults: SingleResult[] = [];\n\t\t\t\t\tconst {\n\t\t\t\t\t\taction: _action,\n\t\t\t\t\t\tagent: _agent,\n\t\t\t\t\t\ttask: _task,\n\t\t\t\t\t\tresume: _resume,\n\t\t\t\t\t\ttasks: _tasks,\n\t\t\t\t\t\tchain: _chain,\n\t\t\t\t\t\tconcurrency: _concurrency,\n\t\t\t\t\t\tforegroundOnly: _foregroundOnly,\n\t\t\t\t\t\tclarify: _clarify,\n\t\t\t\t\t\ttimeoutMs: _timeoutMs,\n\t\t\t\t\t\tmaxRuntimeMs: _maxRuntimeMs,\n\t\t\t\t\t\tusageBudget: _usageBudget,\n\t\t\t\t\t\tmissionId: _missionId,\n\t\t\t\t\t\tmission: _mission,\n\t\t\t\t\t\t...workflowChildDefaults\n\t\t\t\t\t} = workflowRequest;\n\t\t\t\t\tconst updateTrace = (trace: NonNullable<Details[\"workflow\"]>[\"trace\"]) => {\n\t\t\t\t\t\tstatus.workflow = { ...(status.workflow ?? { emits: [], console: [] }), trace };\n\t\t\t\t\t\tfor (const entry of trace.filter((candidate) => candidate.operation === \"run\")) {\n\t\t\t\t\t\t\tconst existing = status.steps?.find((step) => step.workflowKey === entry.key);\n\t\t\t\t\t\t\tif (entry.state === \"reused\" && existing) continue;\n\t\t\t\t\t\t\tconst mapped =\n\t\t\t\t\t\t\t\tentry.state === \"started\" || entry.state === \"reused\"\n\t\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t\t: entry.state === \"completed\"\n\t\t\t\t\t\t\t\t\t\t? \"completed\"\n\t\t\t\t\t\t\t\t\t\t: \"failed\";\n\t\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t\texisting.status = mapped;\n\t\t\t\t\t\t\t\tif (entry.error === undefined) delete existing.error;\n\t\t\t\t\t\t\t\telse existing.error = entry.error;\n\t\t\t\t\t\t\t\tif (entry.durationMs === undefined) delete existing.durationMs;\n\t\t\t\t\t\t\t\telse existing.durationMs = entry.durationMs;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tstatus.steps?.push({\n\t\t\t\t\t\t\t\t\tagent: entry.key,\n\t\t\t\t\t\t\t\t\tlabel: entry.key,\n\t\t\t\t\t\t\t\t\tworkflowKey: entry.key,\n\t\t\t\t\t\t\t\t\tparentWorkflowRunId: workflowRunId,\n\t\t\t\t\t\t\t\t\tstatus: mapped,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpersist();\n\t\t\t\t\t\tappendWorkflowEvent({ type: \"subagent.workflow.trace\", trace });\n\t\t\t\t\t};\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst workflow = await runWorkflowScript({\n\t\t\t\t\t\t\tscript: workflowScript,\n\t\t\t\t\t\t\ttimeoutMs: timeout,\n\t\t\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\t\t\t...(workflowState ? { state: workflowState } : {}),\n\t\t\t\t\t\t\tonTrace: updateTrace,\n\t\t\t\t\t\t\tonEmit: (emits) => {\n\t\t\t\t\t\t\t\t// Each emit is validated at the host boundary in runWorkflowScript before onEmit fires.\n\t\t\t\t\t\t\t\tstatus.workflow = { ...(status.workflow ?? { trace: [], console: [] }), emits };\n\t\t\t\t\t\t\t\tpersist();\n\t\t\t\t\t\t\t\tappendWorkflowEvent({ type: \"subagent.workflow.emit\", value: emits.at(-1) });\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tlaunch: async (key, childParams, workflowSignal) => {\n\t\t\t\t\t\t\t\tif (workflowUsageBudget.budget && childParams.async === true)\n\t\t\t\t\t\t\t\t\treturn workflowChildResult(\n\t\t\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\t\t\tbuildRequestedModeError(\n\t\t\t\t\t\t\t\t\t\t\tchildParams as SubagentParamsLike,\n\t\t\t\t\t\t\t\t\t\t\t\"workflow usageBudget does not support async runs.run launches.\",\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst budgetState = usageBudgetState(\n\t\t\t\t\t\t\t\t\tworkflowUsageBudget.budget,\n\t\t\t\t\t\t\t\t\tsumResultsCost(workflowResults),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (budgetState?.exhausted)\n\t\t\t\t\t\t\t\t\treturn workflowChildResult(\n\t\t\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\t\t\tbuildRequestedModeError(\n\t\t\t\t\t\t\t\t\t\t\tchildParams as SubagentParamsLike,\n\t\t\t\t\t\t\t\t\t\t\tusageBudgetExceededMessage(budgetState),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst childRequest = prepareWorkflowLaunchParams(\n\t\t\t\t\t\t\t\t\tworkflowChildDefaults,\n\t\t\t\t\t\t\t\t\tchildParams,\n\t\t\t\t\t\t\t\t\tworkflowRunId,\n\t\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\t\t{ missionDetached: missionBinding !== undefined || requestParams.mission === false },\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst result = await execute(\n\t\t\t\t\t\t\t\t\trandomUUID(),\n\t\t\t\t\t\t\t\t\tchildRequest,\n\t\t\t\t\t\t\t\t\tworkflowSignal,\n\t\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\t\tpreserveActiveSession,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tworkflowResults.push(...result.details.results);\n\t\t\t\t\t\t\t\tconst child = workflowChildResult(key, result);\n\t\t\t\t\t\t\t\tif (result.details.asyncId) {\n\t\t\t\t\t\t\t\t\tconst childJob = deps.state.asyncJobs.get(result.details.asyncId);\n\t\t\t\t\t\t\t\t\tif (childJob) {\n\t\t\t\t\t\t\t\t\t\tchildJob.parentWorkflowRunId = workflowRunId;\n\t\t\t\t\t\t\t\t\t\tchildJob.workflowKey = key;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn child;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tstatus: async (keyOrRunId, workflowSignal) =>\n\t\t\t\t\t\t\t\tworkflowChildResult(\n\t\t\t\t\t\t\t\t\tkeyOrRunId,\n\t\t\t\t\t\t\t\t\tawait execute(\n\t\t\t\t\t\t\t\t\t\trandomUUID(),\n\t\t\t\t\t\t\t\t\t\t{ action: \"status\", id: keyOrRunId },\n\t\t\t\t\t\t\t\t\t\tworkflowSignal,\n\t\t\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\t\t\tpreserveActiveSession,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);\n\t\t\t\t\t\tconst emitPreview =\n\t\t\t\t\t\t\tworkflow.emits.length > 0\n\t\t\t\t\t\t\t\t? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(\", \").slice(0, 1_000)}`\n\t\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\tconst summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;\n\t\t\t\t\t\tconst workflowUsage = sumResultsUsage(workflowResults);\n\t\t\t\t\t\tstatus = {\n\t\t\t\t\t\t\t...status,\n\t\t\t\t\t\t\tstate: \"complete\",\n\t\t\t\t\t\t\tendedAt: Date.now(),\n\t\t\t\t\t\t\tworkflow: {\n\t\t\t\t\t\t\t\tvalue: workflow.value,\n\t\t\t\t\t\t\t\ttrace: workflow.trace,\n\t\t\t\t\t\t\t\temits: workflow.emits,\n\t\t\t\t\t\t\t\tconsole: workflow.console,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttotalTokens: {\n\t\t\t\t\t\t\t\tinput: workflowUsage.input,\n\t\t\t\t\t\t\t\toutput: workflowUsage.output,\n\t\t\t\t\t\t\t\ttotal: workflowUsage.input + workflowUsage.output,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttotalCost: sumResultsCost(workflowResults),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tpersist();\n\t\t\t\t\t\tappendWorkflowEvent({ type: \"subagent.workflow.completed\", state: \"complete\" });\n\t\t\t\t\t\twriteAtomicJson(resultPath, {\n\t\t\t\t\t\t\tid: workflowRunId,\n\t\t\t\t\t\t\trunId: workflowRunId,\n\t\t\t\t\t\t\tagent: \"workflow\",\n\t\t\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\tstate: \"complete\",\n\t\t\t\t\t\t\tsummary,\n\t\t\t\t\t\t\toutput: summary,\n\t\t\t\t\t\t\tresults: workflow.children.map((child) => ({\n\t\t\t\t\t\t\t\tagent: child.key,\n\t\t\t\t\t\t\t\toutput: child.output,\n\t\t\t\t\t\t\t\toutputState: child.output.trim() || child.structuredOutput !== undefined ? \"present\" : \"absent\",\n\t\t\t\t\t\t\t\tstructuredOutput: child.structuredOutput,\n\t\t\t\t\t\t\t\tsuccess: child.ok,\n\t\t\t\t\t\t\t\t...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tworkflow: status.workflow,\n\t\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\t\tcwd: parentCwd,\n\t\t\t\t\t\t\tsessionId: currentSessionId,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst partial =\n\t\t\t\t\t\t\terror instanceof WorkflowScriptError\n\t\t\t\t\t\t\t\t? error.partial\n\t\t\t\t\t\t\t\t: { trace: [], emits: [], console: [], children: [] };\n\t\t\t\t\t\tconst stopped = controller.signal.aborted;\n\t\t\t\t\t\tstatus = compactOptional<AsyncStatus>({\n\t\t\t\t\t\t\t...status,\n\t\t\t\t\t\t\tstate: stopped ? \"stopped\" : \"failed\",\n\t\t\t\t\t\t\tstopped: stopped || undefined,\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\tendedAt: Date.now(),\n\t\t\t\t\t\t\tworkflow: { trace: partial.trace, emits: partial.emits, console: partial.console },\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpersist();\n\t\t\t\t\t\tappendWorkflowEvent({\n\t\t\t\t\t\t\ttype: \"subagent.workflow.completed\",\n\t\t\t\t\t\t\tstate: status.state,\n\t\t\t\t\t\t\terror: status.error,\n\t\t\t\t\t\t});\n\t\t\t\t\t\twriteAtomicJson(resultPath, {\n\t\t\t\t\t\t\tid: workflowRunId,\n\t\t\t\t\t\t\trunId: workflowRunId,\n\t\t\t\t\t\t\tagent: \"workflow\",\n\t\t\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\tstate: status.state,\n\t\t\t\t\t\t\tsummary: status.error,\n\t\t\t\t\t\t\terror: status.error,\n\t\t\t\t\t\t\tstopped: status.stopped,\n\t\t\t\t\t\t\tresults: partial.children.map((child) => ({\n\t\t\t\t\t\t\t\tagent: child.key,\n\t\t\t\t\t\t\t\toutput: child.output,\n\t\t\t\t\t\t\t\toutputState: child.output.trim() || child.structuredOutput !== undefined ? \"present\" : \"absent\",\n\t\t\t\t\t\t\t\tstructuredOutput: child.structuredOutput,\n\t\t\t\t\t\t\t\tsuccess: child.ok,\n\t\t\t\t\t\t\t\t...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tworkflow: status.workflow,\n\t\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\t\tcwd: parentCwd,\n\t\t\t\t\t\t\tsessionId: currentSessionId,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tdeps.state.workflowControllers?.delete(workflowRunId);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn attachWorkflowMission({\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\t\trunId: workflowRunId,\n\t\t\t\t\t\tasyncId: workflowRunId,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tresults: [],\n\t\t\t\t\t\tchatProgress,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst {\n\t\t\t\tworkflowScript: _workflowScript,\n\t\t\t\taction: _action,\n\t\t\t\tagent: _agent,\n\t\t\t\ttask: _task,\n\t\t\t\tresume: _resume,\n\t\t\t\ttasks: _tasks,\n\t\t\t\tchain: _chain,\n\t\t\t\tconcurrency: _concurrency,\n\t\t\t\tasync: _async,\n\t\t\t\tforegroundOnly: _foregroundOnly,\n\t\t\t\tclarify: _clarify,\n\t\t\t\ttimeoutMs: _timeoutMs,\n\t\t\t\tmaxRuntimeMs: _maxRuntimeMs,\n\t\t\t\tusageBudget: _usageBudget,\n\t\t\t\tchatProgress: _chatProgress,\n\t\t\t\tmissionId: _missionId,\n\t\t\t\tmission: _mission,\n\t\t\t\t...workflowChildDefaults\n\t\t\t} = requestParams;\n\t\t\tconst workflowResults: SingleResult[] = [];\n\t\t\tlet liveWorkflow: NonNullable<Details[\"workflow\"]> = { trace: [], emits: [], console: [] };\n\t\t\tconst sendWorkflowProgress = () => {\n\t\t\t\tconst update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);\n\t\t\t\tif (update) onUpdate?.(update);\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst workflow = await runWorkflowScript({\n\t\t\t\t\tscript: requestParams.workflowScript,\n\t\t\t\t\ttimeoutMs: timeout,\n\t\t\t\t\tsignal,\n\t\t\t\t\t...(workflowState ? { state: workflowState } : {}),\n\t\t\t\t\tonTrace: (trace) => {\n\t\t\t\t\t\tliveWorkflow = { ...liveWorkflow, trace };\n\t\t\t\t\t\tsendWorkflowProgress();\n\t\t\t\t\t},\n\t\t\t\t\tonEmit: (emits) => {\n\t\t\t\t\t\tliveWorkflow = { ...liveWorkflow, emits };\n\t\t\t\t\t\tsendWorkflowProgress();\n\t\t\t\t\t},\n\t\t\t\t\tlaunch: async (key, childParams, workflowSignal) => {\n\t\t\t\t\t\tif (workflowUsageBudget.budget && childParams.async === true)\n\t\t\t\t\t\t\treturn workflowChildResult(\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tbuildRequestedModeError(\n\t\t\t\t\t\t\t\t\tchildParams as SubagentParamsLike,\n\t\t\t\t\t\t\t\t\t\"workflow usageBudget does not support async runs.run launches.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));\n\t\t\t\t\t\tif (budgetState?.exhausted)\n\t\t\t\t\t\t\treturn workflowChildResult(\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tbuildRequestedModeError(\n\t\t\t\t\t\t\t\t\tchildParams as SubagentParamsLike,\n\t\t\t\t\t\t\t\t\tusageBudgetExceededMessage(budgetState),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst childRequest = prepareWorkflowLaunchParams(workflowChildDefaults, childParams, _id, key, {\n\t\t\t\t\t\t\tmissionDetached: missionBinding !== undefined || requestParams.mission === false,\n\t\t\t\t\t\t\tsuppressRoutineResultIntercom: chatProgress.mode === \"live-card\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst result = await execute(\n\t\t\t\t\t\t\trandomUUID(),\n\t\t\t\t\t\t\tchildRequest,\n\t\t\t\t\t\t\tworkflowSignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tpreserveActiveSession,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tworkflowResults.push(...result.details.results);\n\t\t\t\t\t\treturn workflowChildResult(key, result);\n\t\t\t\t\t},\n\t\t\t\t\tstatus: async (keyOrRunId, workflowSignal) =>\n\t\t\t\t\t\tworkflowChildResult(\n\t\t\t\t\t\t\tkeyOrRunId,\n\t\t\t\t\t\t\tawait execute(\n\t\t\t\t\t\t\t\trandomUUID(),\n\t\t\t\t\t\t\t\t{ action: \"status\", id: keyOrRunId },\n\t\t\t\t\t\t\t\tworkflowSignal,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\tpreserveActiveSession,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t});\n\t\t\t\tconst traceLines = workflow.trace.map(\n\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t`- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : \"\"}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : \"\"}${entry.error ? ` — ${entry.error}` : \"\"}`,\n\t\t\t\t);\n\t\t\t\tconst sections = [\"Workflow completed.\", `Return:\\n${formatWorkflowValue(workflow.value)}`];\n\t\t\t\tif (workflow.emits.length > 0)\n\t\t\t\t\tsections.push(`Emitted:\\n${workflow.emits.map(formatWorkflowValue).join(\"\\n\")}`);\n\t\t\t\tif (workflow.console.length > 0)\n\t\t\t\t\tsections.push(\n\t\t\t\t\t\t`Console:\\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join(\"\\n\")}`,\n\t\t\t\t\t);\n\t\t\t\tif (traceLines.length > 0) sections.push(`Call trace:\\n${traceLines.join(\"\\n\")}`);\n\t\t\t\treturn attachWorkflowMission({\n\t\t\t\t\tcontent: [{ type: \"text\", text: sections.join(\"\\n\\n\") }],\n\t\t\t\t\tdetails: compactOptional<Details>({\n\t\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\t\trunId: _id,\n\t\t\t\t\t\tresults: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]),\n\t\t\t\t\t\ttotalChildUsage: sumResultsUsage(workflowResults),\n\t\t\t\t\t\ttotalCost: sumResultsCost(workflowResults),\n\t\t\t\t\t\tusageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)),\n\t\t\t\t\t\tworkflow: {\n\t\t\t\t\t\t\tvalue: workflow.value,\n\t\t\t\t\t\t\ttrace: workflow.trace,\n\t\t\t\t\t\t\temits: workflow.emits,\n\t\t\t\t\t\t\tconsole: workflow.console,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tchatProgress,\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst partial =\n\t\t\t\t\terror instanceof WorkflowScriptError\n\t\t\t\t\t\t? error.partial\n\t\t\t\t\t\t: { trace: [], emits: [], console: [], children: [] };\n\t\t\t\tconst text = error instanceof Error ? error.message : String(error);\n\t\t\t\tconst traceLines = partial.trace.map(\n\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t`- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : \"\"}${entry.error ? ` — ${entry.error}` : \"\"}`,\n\t\t\t\t);\n\t\t\t\tconst sections = [`Workflow failed: ${text}`];\n\t\t\t\tif (partial.emits.length > 0)\n\t\t\t\t\tsections.push(`Emitted:\\n${partial.emits.map(formatWorkflowValue).join(\"\\n\")}`);\n\t\t\t\tif (partial.console.length > 0)\n\t\t\t\t\tsections.push(\n\t\t\t\t\t\t`Console:\\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join(\"\\n\")}`,\n\t\t\t\t\t);\n\t\t\t\tif (traceLines.length > 0) sections.push(`Call trace:\\n${traceLines.join(\"\\n\")}`);\n\t\t\t\treturn attachWorkflowMission({\n\t\t\t\t\tcontent: [{ type: \"text\", text: sections.join(\"\\n\\n\") }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: compactOptional<Details>({\n\t\t\t\t\t\tmode: \"workflow\",\n\t\t\t\t\t\trunId: _id,\n\t\t\t\t\t\tresults: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]),\n\t\t\t\t\t\ttotalChildUsage: sumResultsUsage(workflowResults),\n\t\t\t\t\t\ttotalCost: sumResultsCost(workflowResults),\n\t\t\t\t\t\tusageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)),\n\t\t\t\t\t\tworkflow: { trace: partial.trace, emits: partial.emits, console: partial.console },\n\t\t\t\t\t\tchatProgress,\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst directParams = prepareWorkflowChildParams(requestParams);\n\t\tconst requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);\n\t\tconst paramsWithResolvedCwd =\n\t\t\tdirectParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };\n\t\tconst action = paramsWithResolvedCwd.action;\n\t\tlet requestSessionId = \"\";\n\t\tlet requestPiSessionId: string | undefined;\n\t\tlet requestParentModel: ParentModel | undefined;\n\t\ttry {\n\t\t\trequestSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\trequestPiSessionId = ctx.sessionManager.getSessionId() ?? undefined;\n\t\t\trequestParentModel = preserveActiveSession\n\t\t\t\t? normalizeParentModel(ctx.model)\n\t\t\t\t: rememberParentModel(deps.state, requestSessionId, ctx.model);\n\t\t} catch (error) {\n\t\t\tif (action?.toLowerCase() !== \"doctor\") throw error;\n\t\t\trequestParentModel = normalizeParentModel(ctx.model);\n\t\t}\n\t\tif (action) {\n\t\t\tif (action === \"worktree.discard\") {\n\t\t\t\tif (deps.allowMutatingManagementActions === false) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Action 'worktree.discard' is not available from child-safe subagent fanout mode.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!paramsWithResolvedCwd.handoffPath?.trim()) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"worktree.discard requires handoffPath from parallelHandoff.path or async status.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst decision = resolveAuthorityDecision({\n\t\t\t\t\taction: \"discardWorktree\",\n\t\t\t\t\t...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }),\n\t\t\t\t});\n\t\t\t\tif (decision === \"forbid\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Authority policy forbids worktree discard.\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet confirmed = decision === \"auto\";\n\t\t\t\tif (decision === \"confirm\") {\n\t\t\t\t\tif (!ctx.hasUI)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: \"Authority policy requires user confirmation for worktree discard, but this session has no interactive UI. Preserved worktrees were not changed.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\tconfirmed = await ctx.ui.confirm(\n\t\t\t\t\t\t\"Discard preserved subagent worktrees?\",\n\t\t\t\t\t\t`This permanently removes preserved worktrees and temporary branches recorded in:\\n${paramsWithResolvedCwd.handoffPath}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!confirmed)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Worktree discard canceled; preserved worktrees were not changed.\" }],\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst discarded = discardPreservedWorktrees(\n\t\t\t\t\t\tpath.isAbsolute(paramsWithResolvedCwd.handoffPath)\n\t\t\t\t\t\t\t? paramsWithResolvedCwd.handoffPath\n\t\t\t\t\t\t\t: path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: decision === \"confirm\" ? \"confirmed\" : \"policy\",\n\t\t\t\t\t\t\t...(deps.config.authorityPolicy ? { policy: deps.config.authorityPolicy } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: discarded.text }],\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn handleHerdrProjectPaneAction(\n\t\t\t\t\taction as (typeof HERDR_PROJECT_PANE_ACTIONS)[number],\n\t\t\t\t\tparamsWithResolvedCwd,\n\t\t\t\t\t{ cwd: requestCwd, signal },\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((HERDR_INSPECTOR_ACTIONS as readonly string[]).includes(action)) {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tdeps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\treturn handleHerdrInspectorAction(\n\t\t\t\t\taction as (typeof HERDR_INSPECTOR_ACTIONS)[number],\n\t\t\t\t\tparamsWithResolvedCwd,\n\t\t\t\t\t{\n\t\t\t\t\t\tstate: deps.state,\n\t\t\t\t\t\tcwd: requestCwd,\n\t\t\t\t\t\t...(deps.config.missions ? { missions: deps.config.missions } : {}),\n\t\t\t\t\t\t...(deps.config.authorityPolicy ? { authorityPolicy: deps.config.authorityPolicy } : {}),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((MISSION_ACTIONS as readonly string[]).includes(action)) {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst currentSessionId = deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined;\n\t\t\t\treturn handleMissionAction(action as (typeof MISSION_ACTIONS)[number], paramsWithResolvedCwd, {\n\t\t\t\t\tcwd: requestCwd,\n\t\t\t\t\t...(deps.config.missions ? { config: deps.config.missions } : {}),\n\t\t\t\t\t...(currentSessionId ? { currentSessionId } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst policyAction =\n\t\t\t\taction === \"stop\"\n\t\t\t\t\t? \"stopRun\"\n\t\t\t\t\t: action === \"steer\"\n\t\t\t\t\t\t? \"steerRun\"\n\t\t\t\t\t\t: action === \"schedule.create\"\n\t\t\t\t\t\t\t? \"scheduleCreate\"\n\t\t\t\t\t\t\t: undefined;\n\t\t\tif (policyAction) {\n\t\t\t\tconst decision = resolveAuthorityDecision({\n\t\t\t\t\taction: policyAction,\n\t\t\t\t\t...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }),\n\t\t\t\t});\n\t\t\t\tif (decision === \"forbid\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Authority policy forbids action '${action}'.` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (decision === \"confirm\") {\n\t\t\t\t\tif (!ctx.hasUI)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `Authority policy requires user confirmation for action '${action}', but this session has no interactive UI.`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\tconst confirmed = await ctx.ui.confirm(\n\t\t\t\t\t\t`Authorize subagent ${action}?`,\n\t\t\t\t\t\t`Authority policy requires confirmation before '${action}'.`,\n\t\t\t\t\t);\n\t\t\t\t\tif (!confirmed)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Action '${action}' canceled; authority was not granted.` }],\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((WATCHDOG_TOOL_ACTIONS as readonly string[]).includes(action)) {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\" as const, results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn handleWatchdogToolAction(action, paramsWithResolvedCwd, ctx, deps.watchdog);\n\t\t\t}\n\t\t\tif (action === \"refine\" || action === \"refine.show\" || action === \"refine.rollback\") {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn handleRefinementAction(action, paramsWithResolvedCwd, {\n\t\t\t\t\tcwd: requestCwd,\n\t\t\t\t\tstate: deps.state,\n\t\t\t\t\tsignal,\n\t\t\t\t\tlaunchProposalChild: (task, outputSchema, proposalSignal) =>\n\t\t\t\t\t\texecute(\n\t\t\t\t\t\t\trandomUUID(),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tagent: \"reviewer\",\n\t\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\t\tcontext: \"fresh\",\n\t\t\t\t\t\t\t\tasync: false,\n\t\t\t\t\t\t\t\tartifacts: false,\n\t\t\t\t\t\t\t\toutputSchema,\n\t\t\t\t\t\t\t\ttoolBudget: { hard: 1, block: [\"write\", \"edit\", \"bash\"] },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tproposalSignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (action === \"grant-spawn-budget\") {\n\t\t\t\tif (deps.allowMutatingManagementActions === false || !ctx.hasUI) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Action 'grant-spawn-budget' is available only from the root interactive parent session.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tdeps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tif (!deps.state.currentSessionId) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\", text: \"Action 'grant-spawn-budget' requires an active parent session id.\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (hasActiveSubagentChildren(deps.state)) {\n\t\t\t\t\tconst spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, deps.state.currentSessionId);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Spawn budget grants are rejected while current-session children are queued or running. Wait for them to settle, then retry the explicit grant.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst sessionId = deps.state.currentSessionId;\n\t\t\t\tconst additional = paramsWithResolvedCwd.additional ?? Number.NaN;\n\t\t\t\tconst preview = preflightSpawnBudgetGrant(deps.state, deps.config, sessionId, additional);\n\t\t\t\tif (preview.error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: preview.error }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget: preview.snapshot },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst authority = resolveAuthorityDecision({\n\t\t\t\t\taction: \"spawnBudgetGrant\",\n\t\t\t\t\t...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }),\n\t\t\t\t});\n\t\t\t\tif (authority === \"forbid\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Authority policy forbids spawn budget grants.\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget: preview.snapshot },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst confirmed =\n\t\t\t\t\tauthority === \"auto\" ||\n\t\t\t\t\t(await ctx.ui.confirm(\n\t\t\t\t\t\t\"Grant subagent spawn budget?\",\n\t\t\t\t\t\t`Add ${additional} launches to this logical session?\\n\\n${formatSpawnBudget(preview.snapshot)}\\n\\nUsage is not reset. Compaction keeps the same budget; a new parent session starts a fresh one.`,\n\t\t\t\t\t));\n\t\t\t\tif (!confirmed) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"Spawn budget grant canceled; no capacity was added.\" }],\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget: preview.snapshot },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst currentBudget = getSpawnBudgetSnapshot(deps.state, deps.config, deps.state.currentSessionId);\n\t\t\t\tif (\n\t\t\t\t\tresolveCurrentSessionId(ctx.sessionManager) !== sessionId ||\n\t\t\t\t\thasActiveSubagentChildren(deps.state) ||\n\t\t\t\t\tcurrentBudget.used !== preview.snapshot.used ||\n\t\t\t\t\tcurrentBudget.granted !== preview.snapshot.granted\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Spawn budget grant was not applied because the session, budget, or active-child state changed while confirmation was open.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget: currentBudget },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst granted = grantSpawnBudget(deps.state, deps.config, sessionId, additional);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\tgranted.error ??\n\t\t\t\t\t\t\t\t`Spawn budget grant applied: +${additional}. ${formatSpawnBudget(granted.snapshot)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\t...(granted.error ? { isError: true } : {}),\n\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget: granted.snapshot },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (action === \"children.list\") {\n\t\t\t\tdeps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tconst children = listRetainedChildren(DIRS.async, deps.state.currentSessionId);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatRetainedChildren(children) }],\n\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (action === \"doctor\") {\n\t\t\t\tlet currentSessionFile: string | null = null;\n\t\t\t\tlet currentSessionId = deps.state.currentSessionId;\n\t\t\t\tlet sessionError: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcurrentSessionFile = ctx.sessionManager.getSessionFile() ?? null;\n\t\t\t\t\tcurrentSessionId = ctx.sessionManager.getSessionId();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tsessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n\t\t\t\t}\n\t\t\t\tlet orchestratorTarget: string | undefined;\n\t\t\t\ttry {\n\t\t\t\t\torchestratorTarget = resolveIntercomSessionTarget(\n\t\t\t\t\t\tdeps.pi.getSessionName(),\n\t\t\t\t\t\tctx.sessionManager.getSessionId(),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!sessionError)\n\t\t\t\t\t\tsessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n\t\t\t\t}\n\t\t\t\tconst spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: buildDoctorReport(\n\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\tcwd: requestCwd,\n\t\t\t\t\t\t\t\t\tconfig: deps.config,\n\t\t\t\t\t\t\t\t\tstate: deps.state,\n\t\t\t\t\t\t\t\t\tcontext: paramsWithResolvedCwd.context,\n\t\t\t\t\t\t\t\t\trequestedSessionDir: paramsWithResolvedCwd.sessionDir,\n\t\t\t\t\t\t\t\t\tcurrentSessionFile,\n\t\t\t\t\t\t\t\t\tcurrentSessionId,\n\t\t\t\t\t\t\t\t\torchestratorTarget,\n\t\t\t\t\t\t\t\t\tsessionError,\n\t\t\t\t\t\t\t\t\texpandTilde: deps.expandTilde,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { mode: \"management\", results: [], spawnBudget },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (action === \"status\") {\n\t\t\t\tif (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tconst withBudget = (result: AgentToolResult<Details>) =>\n\t\t\t\t\twithSpawnBudgetStatus(result, deps.state, deps.config, deps.state.currentSessionId);\n\t\t\t\tconst targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;\n\t\t\t\tconst nestedScope = nestedResolutionScopeForExecutor(deps);\n\t\t\t\tconst sessionRoots = trustedSessionRootsForStatus(ctx, deps);\n\t\t\t\tif (paramsWithResolvedCwd.view === \"fleet\") {\n\t\t\t\t\treturn withBudget(\n\t\t\t\t\t\tinspectSubagentStatus(\n\t\t\t\t\t\t\tparamsWithResolvedCwd,\n\t\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots }),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (targetRunId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst resolved = resolveSubagentRunId(\n\t\t\t\t\t\t\ttargetRunId,\n\t\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedScope }),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (resolved?.kind === \"foreground\") {\n\t\t\t\t\t\t\tconst foreground = getForegroundControl(deps.state, resolved.id);\n\t\t\t\t\t\t\tif (foreground) {\n\t\t\t\t\t\t\t\tif (paramsWithResolvedCwd.view === \"transcript\") {\n\t\t\t\t\t\t\t\t\treturn withBudget({\n\t\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\t\ttext: \"Live foreground transcript is already visible in the expanded running subagent result. Persisted session transcript becomes inspectable after the foreground run completes when sessions are enabled.\",\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn withBudget(foregroundStatusResult(foreground));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn withBudget({\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst foreground = getForegroundControl(deps.state, undefined);\n\t\t\t\t\tif (foreground && paramsWithResolvedCwd.view !== \"transcript\")\n\t\t\t\t\t\treturn withBudget(foregroundStatusResult(foreground));\n\t\t\t\t\tif (foreground && paramsWithResolvedCwd.view === \"transcript\") {\n\t\t\t\t\t\treturn withBudget({\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: \"Live foreground transcript is already visible in the expanded running subagent result. Pass an async run id to inspect a background transcript.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn withBudget(\n\t\t\t\t\tinspectSubagentStatus(\n\t\t\t\t\t\tparamsWithResolvedCwd,\n\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (action === \"approve-checkpoint\" || action === \"reject-checkpoint\") {\n\t\t\t\tdeps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tconst targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;\n\t\t\t\tif (!targetRunId && !paramsWithResolvedCwd.dir) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `action='${action}' requires id or dir.` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst resolved = targetRunId\n\t\t\t\t\t\t? resolveSubagentRunId(\n\t\t\t\t\t\t\t\ttargetRunId,\n\t\t\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst decision = action === \"approve-checkpoint\" ? \"approved\" : \"rejected\";\n\t\t\t\t\tif (resolved?.kind === \"foreground\") {\n\t\t\t\t\t\tconst run = deps.state.foregroundRuns?.get(resolved.id);\n\t\t\t\t\t\tif (!run?.checkpoint || run.checkpoint.status !== \"pending\") {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{ type: \"text\", text: `Run '${resolved.id}' is not paused at an approval checkpoint.` },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (deps.state.currentSessionId && run.sessionId !== deps.state.currentSessionId) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Run '${resolved.id}' was not found in the active session.` }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst decidedAt = Date.now();\n\t\t\t\t\t\tconst checkpoint: NonNullable<Details[\"checkpoint\"]> =\n\t\t\t\t\t\t\tdecision === \"approved\"\n\t\t\t\t\t\t\t\t? { ...run.checkpoint, status: \"approved\", approvedAt: decidedAt }\n\t\t\t\t\t\t\t\t: { ...run.checkpoint, status: \"rejected\", rejectedAt: decidedAt };\n\t\t\t\t\t\trun.checkpoint = checkpoint;\n\t\t\t\t\t\trun.updatedAt = decidedAt;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `Checkpoint '${checkpoint.name}' ${decision} for foreground run ${resolved.id}.`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [], checkpoint },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst location = paramsWithResolvedCwd.dir\n\t\t\t\t\t\t? resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results)\n\t\t\t\t\t\t: resolved?.kind === \"async\"\n\t\t\t\t\t\t\t? resolved.location\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (!location?.asyncDir) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `action='${action}' targets paused foreground or async checkpoints. No matching run found.`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst status = readStatus(location.asyncDir);\n\t\t\t\t\tconst runId = status?.runId ?? location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir);\n\t\t\t\t\tif (!status?.checkpoint || status.state !== \"paused\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Run '${runId}' is not paused at an approval checkpoint.` }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tif (deps.state.currentSessionId && status.sessionId !== deps.state.currentSessionId) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Run '${runId}' was not found in the active session.` }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdeliverCheckpointDecisionRequest({\n\t\t\t\t\t\tasyncDir: location.asyncDir,\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\tsource: \"subagent-action\",\n\t\t\t\t\t\t...(paramsWithResolvedCwd.message ? { reason: paramsWithResolvedCwd.message } : {}),\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\", text: `Checkpoint '${status.checkpoint.name}' ${decision} for run ${runId}.` },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [], checkpoint: { ...status.checkpoint, status: decision } },\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (action === \"resume\") {\n\t\t\t\treturn resumeAsyncRun(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tparams: paramsWithResolvedCwd,\n\t\t\t\t\t\trequestCwd,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tparentModel: requestParentModel,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (action === \"steer\") {\n\t\t\t\tdeps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\t\t\tconst message = (paramsWithResolvedCwd.message ?? paramsWithResolvedCwd.task ?? \"\").trim();\n\t\t\t\tif (!message)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"action='steer' requires message.\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tconst targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;\n\t\t\t\tif (paramsWithResolvedCwd.dir) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);\n\t\t\t\t\t\tconst runId =\n\t\t\t\t\t\t\tlocation.resolvedId ??\n\t\t\t\t\t\t\ttargetRunId ??\n\t\t\t\t\t\t\tpath.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);\n\t\t\t\t\t\tif (location.asyncDir) {\n\t\t\t\t\t\t\tconst unsupported = externalRunnerControlError(location.asyncDir, \"steer\");\n\t\t\t\t\t\t\tif (unsupported) return unsupported;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn steerAsyncRun(\n\t\t\t\t\t\t\tcompactOptional<Parameters<typeof steerAsyncRun>[0]>({\n\t\t\t\t\t\t\t\tstate: deps.state,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\t\tmode: paramsWithResolvedCwd.mode,\n\t\t\t\t\t\t\t\tindex: paramsWithResolvedCwd.index,\n\t\t\t\t\t\t\t\tkill: deps.kill,\n\t\t\t\t\t\t\t\tlocation,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\t...(paramsWithResolvedCwd.steeringRecovery === false\n\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\trecover: ({ absoluteDeadlineAt, ...limits }) =>\n\t\t\t\t\t\t\t\t\t\t\t\tresumeAsyncRun(\n\t\t\t\t\t\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tparams: { ...limits, action: \"resume\", id: runId, message },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trequestCwd,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeps,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tparentModel: requestParentModel,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tabsoluteDeadlineAt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!targetRunId)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"action='steer' requires id or dir.\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tlet resolved: ResolvedSubagentRunId | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tresolved = resolveSubagentRunId(\n\t\t\t\t\t\ttargetRunId,\n\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (resolved?.kind === \"nested\")\n\t\t\t\t\treturn steerNestedRun(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\ttarget: resolved,\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\tmode: paramsWithResolvedCwd.mode,\n\t\t\t\t\t\t\tindex: paramsWithResolvedCwd.index,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\tif (resolved?.kind === \"foreground\")\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"action='steer' currently supports live async Pi child sessions only; use action='interrupt' or action='resume' for foreground runs.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tif (resolved?.kind !== \"async\")\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `No async run found for '${targetRunId}'.` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tif (resolved.location.asyncDir) {\n\t\t\t\t\tconst unsupported = externalRunnerControlError(resolved.location.asyncDir, \"steer\");\n\t\t\t\t\tif (unsupported) return unsupported;\n\t\t\t\t}\n\t\t\t\treturn steerAsyncRun(\n\t\t\t\t\tcompactOptional<Parameters<typeof steerAsyncRun>[0]>({\n\t\t\t\t\t\tstate: deps.state,\n\t\t\t\t\t\trunId: resolved.id,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tmode: paramsWithResolvedCwd.mode,\n\t\t\t\t\t\tindex: paramsWithResolvedCwd.index,\n\t\t\t\t\t\tkill: deps.kill,\n\t\t\t\t\t\tlocation: resolved.location,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t...(paramsWithResolvedCwd.steeringRecovery === false\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\trecover: ({ absoluteDeadlineAt, ...limits }) =>\n\t\t\t\t\t\t\t\t\t\tresumeAsyncRun(\n\t\t\t\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\t\t\t\tparams: { ...limits, action: \"resume\", id: resolved!.id, message },\n\t\t\t\t\t\t\t\t\t\t\t\trequestCwd,\n\t\t\t\t\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\t\t\t\t\tdeps,\n\t\t\t\t\t\t\t\t\t\t\t\tparentModel: requestParentModel,\n\t\t\t\t\t\t\t\t\t\t\t\tabsoluteDeadlineAt,\n\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (action === \"append-step\") {\n\t\t\t\treturn appendStepToAsyncChain(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tparams: paramsWithResolvedCwd,\n\t\t\t\t\t\trequestCwd,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tparentModel: requestParentModel,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (action.startsWith(\"schedule.\")) {\n\t\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Action '${action}' is not available from child-safe subagent fanout mode.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!deps.handleScheduledRunAction) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Action '${action}' is not available in this subagent context.` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn deps.handleScheduledRunAction(paramsWithResolvedCwd, ctx);\n\t\t\t}\n\t\t\tif (action === \"stop\") {\n\t\t\t\tconst targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;\n\t\t\t\tconst workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;\n\t\t\t\tif (workflowController) {\n\t\t\t\t\tworkflowController.abort(new Error(\"Workflow stopped by user.\"));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Stop requested for async workflow ${targetRunId}.` }],\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet resolved: ResolvedSubagentRunId | undefined;\n\t\t\t\tif (paramsWithResolvedCwd.dir) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);\n\t\t\t\t\t\tconst stopResult = stopAsyncRun(\n\t\t\t\t\t\t\tdeps.state,\n\t\t\t\t\t\t\tlocation.resolvedId ??\n\t\t\t\t\t\t\t\ttargetRunId ??\n\t\t\t\t\t\t\t\tpath.basename(location.asyncDir ?? paramsWithResolvedCwd.dir),\n\t\t\t\t\t\t\tdeps.kill,\n\t\t\t\t\t\t\tlocation,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tstopResult ?? {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!targetRunId)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"action='stop' requires id or dir.\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tresolved = resolveSubagentRunId(\n\t\t\t\t\t\ttargetRunId,\n\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (resolved?.kind === \"nested\")\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\", text: \"action='stop' supports current-session top-level async runs only.\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tif (resolved?.kind === \"foreground\")\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"action='stop' supports async runs only. Use action='interrupt' for foreground runs.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\tif (resolved?.kind === \"async\") {\n\t\t\t\t\tconst existingStatus = readStatus(resolved.location.asyncDir ?? \"\");\n\t\t\t\t\tif (existingStatus?.mode === \"workflow\" && existingStatus.state === \"running\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `Workflow ${resolved.id} is not controlled by this extension runtime; reload recovery cannot stop it safely.`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst stopResult = stopAsyncRun(\n\t\t\t\t\tdeps.state,\n\t\t\t\t\tresolved?.kind === \"async\" ? resolved.id : targetRunId,\n\t\t\t\t\tdeps.kill,\n\t\t\t\t\tresolved?.kind === \"async\" ? resolved.location : undefined,\n\t\t\t\t);\n\t\t\t\tif (stopResult) return stopResult;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No stoppable async run found in this session.\" }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (action === \"interrupt\") {\n\t\t\t\tconst targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;\n\t\t\t\tlet resolved: ResolvedSubagentRunId | undefined;\n\t\t\t\tif (targetRunId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresolved = resolveSubagentRunId(\n\t\t\t\t\t\t\ttargetRunId,\n\t\t\t\t\t\t\tomitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: message }],\n\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (resolved?.kind === \"nested\") return interruptNestedRun(resolved);\n\t\t\t\tconst foreground = getForegroundControl(\n\t\t\t\t\tdeps.state,\n\t\t\t\t\tresolved?.kind === \"foreground\" ? resolved.id : targetRunId,\n\t\t\t\t);\n\t\t\t\tif (foreground?.interrupt) {\n\t\t\t\t\tconst interrupted = foreground.interrupt();\n\t\t\t\t\tif (interrupted) {\n\t\t\t\t\t\tforeground.updatedAt = Date.now();\n\t\t\t\t\t\tdelete foreground.currentActivityState;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: `Interrupt requested for foreground run ${foreground.runId}.` }],\n\t\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Foreground run ${foreground.runId} has no active child step to interrupt.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst asyncInterruptResult = interruptAsyncRun(\n\t\t\t\t\tdeps.state,\n\t\t\t\t\tresolved?.kind === \"async\" ? resolved.id : targetRunId,\n\t\t\t\t\tdeps.kill,\n\t\t\t\t\tresolved?.kind === \"async\" ? resolved.location : undefined,\n\t\t\t\t);\n\t\t\t\tif (asyncInterruptResult) return asyncInterruptResult;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No interrupt-capable run found in this session.\" }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"management\", results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Unknown action: ${action}. Valid: ${SUBAGENT_ACTIONS.join(\", \")}` }],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"management\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: `Action '${action}' is not available from child-safe subagent fanout mode.` },\n\t\t\t\t\t],\n\t\t\t\t\tisError: true,\n\t\t\t\t\tdetails: { mode: \"management\" as const, results: [] },\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn handleManagementAction(action, paramsWithResolvedCwd, {\n\t\t\t\t...ctx,\n\t\t\t\tcwd: requestCwd,\n\t\t\t\tconfig: deps.config,\n\t\t\t\tcurrentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,\n\t\t\t});\n\t\t}\n\n\t\tconst { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth);\n\t\tif (blocked) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t`Nested subagent call blocked (depth=${depth}, max=${maxDepth}). ` +\n\t\t\t\t\t\t\t\"You are running at the maximum subagent nesting depth. \" +\n\t\t\t\t\t\t\t\"Complete your current task directly without delegating to further subagents.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t\t};\n\t\t}\n\n\t\tconst normalized = normalizeRepeatedParallelCounts(paramsWithResolvedCwd);\n\t\tif (normalized.error) return normalized.error;\n\t\tconst normalizedParams = normalized.params!;\n\n\t\tlet effectiveParams = applyForceTopLevelAsyncOverride(\n\t\t\tnormalizedParams,\n\t\t\tdepth,\n\t\t\tdeps.config.forceTopLevelAsync === true,\n\t\t);\n\t\tconst runToolBudget = resolveToolBudget(\n\t\t\teffectiveParams.toolBudget,\n\t\t\t\"toolBudget\",\n\t\t\tallowZeroToolBudget ? { minimumHard: 0 } : undefined,\n\t\t);\n\t\tif (runToolBudget.error) return buildRequestedModeError(effectiveParams, runToolBudget.error);\n\t\tconst configToolBudget = resolveToolBudget(deps.config.toolBudget, \"config.toolBudget\");\n\t\tif (configToolBudget.error) return buildRequestedModeError(effectiveParams, configToolBudget.error);\n\t\tconst usageBudget = validateUsageBudgetConfig(\n\t\t\teffectiveParams.usageBudget ?? deps.config.usageBudget,\n\t\t\teffectiveParams.usageBudget ? \"usageBudget\" : \"config.usageBudget\",\n\t\t);\n\t\tif (usageBudget.error) return buildRequestedModeError(effectiveParams, usageBudget.error);\n\n\t\tconst scope: AgentScope = resolveExecutionAgentScope(effectiveParams.agentScope);\n\t\tconst parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;\n\t\tconst effectiveCwd = effectiveParams.cwd ?? ctx.cwd;\n\t\tconst discovered = deps.discoverAgents(effectiveCwd, scope);\n\t\tconst discoveredAgents = discovered.agents;\n\t\tconst defaultAgent = applyDefaultDirectAgent(effectiveParams, discoveredAgents);\n\t\tif (defaultAgent.error) return buildRequestedModeError(effectiveParams, defaultAgent.error);\n\t\teffectiveParams = defaultAgent.params!;\n\t\tconst canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents);\n\t\tif (canonicalParams.error) return buildRequestedModeError(effectiveParams, canonicalParams.error);\n\t\teffectiveParams = canonicalParams.params!;\n\t\tconst modelScope = discovered.modelScope;\n\t\teffectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);\n\t\tconst turnBudget = resolveTurnBudgetConfig(effectiveParams.turnBudget ?? deps.config.turnBudget);\n\t\tif (turnBudget.error) return buildRequestedModeError(effectiveParams, turnBudget.error);\n\t\tconst contextPolicy = resolveAgentDefaultContextPolicy(effectiveParams, discoveredAgents);\n\t\teffectiveParams = contextPolicy.params;\n\t\tconst sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());\n\t\tconst intercomBridge = resolveIntercomBridge({\n\t\t\tconfig: deps.config.intercomBridge,\n\t\t\tcontext: effectiveParams.context ?? (contextPolicy.usesFork ? \"fork\" : undefined),\n\t\t\torchestratorTarget: sessionName,\n\t\t});\n\t\tconst agents = intercomBridge.active\n\t\t\t? discoveredAgents.map((agent) => applyIntercomBridgeToAgent(agent, intercomBridge))\n\t\t\t: discoveredAgents;\n\t\tconst runId = randomUUID().slice(0, 8);\n\t\tconst inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();\n\t\tconst nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;\n\t\tconst nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);\n\t\tconst shareEnabled = effectiveParams.share === true;\n\t\tconst hasChain = (effectiveParams.chain?.length ?? 0) > 0;\n\t\tconst hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;\n\t\tconst hasSingle = !hasChain && !hasTasks && Boolean(effectiveParams.agent);\n\t\tconst allowClarifyTaskPrompt =\n\t\t\thasChain &&\n\t\t\teffectiveParams.clarify === true &&\n\t\t\tctx.hasUI &&\n\t\t\t!(effectiveParams.chain?.some(isParallelStep) ?? false);\n\n\t\tconst validationError = validateExecutionInput(\n\t\t\teffectiveParams,\n\t\t\tagents,\n\t\t\thasChain,\n\t\t\thasTasks,\n\t\t\thasSingle,\n\t\t\tallowClarifyTaskPrompt,\n\t\t);\n\t\tif (validationError) return validationError;\n\n\t\tconst foregroundMode: \"single\" | \"parallel\" | \"chain\" = hasChain ? \"chain\" : hasTasks ? \"parallel\" : \"single\";\n\t\tconst requestedSpawns = countRequestedSubagentSpawns(effectiveParams, deps.config);\n\t\tconst spawnPreflight = preflightSpawnBudget(deps.state, deps.config, requestSessionId, requestedSpawns);\n\t\tif (spawnPreflight.error) return spawnBudgetErrorResult(spawnPreflight.error, foregroundMode);\n\n\t\tlet forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;\n\t\tlet forkThinkingOverrideForIndex: (idx?: number) => AgentConfig[\"thinking\"] | undefined = () => undefined;\n\t\tlet prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string): void => {};\n\t\tconst forkThinkingRequirements = new Map<number, boolean>();\n\t\tconst forkThinkingDowngrades = new Map<number, string>();\n\t\ttry {\n\t\t\tconst forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];\n\t\t\tconst parentModel = requestParentModel;\n\t\t\tprepareForkThinking = (agentName, index, modelOverride) => {\n\t\t\t\tconst agentConfig = agents.find((agent) => agent.name === agentName);\n\t\t\t\tconst primaryModel = resolveEffectiveSubagentModel(\n\t\t\t\t\tmodelOverride,\n\t\t\t\t\tagentConfig?.model,\n\t\t\t\t\tparentModel,\n\t\t\t\t\tforkAvailableModels,\n\t\t\t\t\tparentModel?.provider,\n\t\t\t\t);\n\t\t\t\tconst candidates = buildModelCandidates(\n\t\t\t\t\tprimaryModel,\n\t\t\t\t\tagentConfig?.fallbackModels,\n\t\t\t\t\tforkAvailableModels,\n\t\t\t\t\tparentModel?.provider,\n\t\t\t\t);\n\t\t\t\tforkThinkingRequirements.set(\n\t\t\t\t\tindex,\n\t\t\t\t\tcandidates.length === 0 ||\n\t\t\t\t\t\tcandidates.some((candidate) =>\n\t\t\t\t\t\t\tforkedChildRequiresThinkingOff(candidate, forkAvailableModels, parentModel?.provider),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst forkContextResolver = createForkContextResolver(\n\t\t\t\tctx.sessionManager,\n\t\t\t\tcontextPolicy.usesFork ? \"fork\" : undefined,\n\t\t\t\t{\n\t\t\t\t\tforceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,\n\t\t\t\t},\n\t\t\t);\n\t\t\tforkSessionFileForIndex = forkContextResolver.sessionFileForIndex;\n\t\t\tforkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;\n\t\t} catch (error) {\n\t\t\treturn toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);\n\t\t}\n\t\tconst requestedAsync = effectiveParams.async ?? deps.asyncByDefault;\n\t\tconst backgroundRequestedWhileClarifying =\n\t\t\t(hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;\n\t\tconst effectiveAsync = requestedAsync && effectiveParams.clarify !== true;\n\t\tconst selectedAgentNames = hasSingle\n\t\t\t? [effectiveParams.agent!]\n\t\t\t: hasTasks\n\t\t\t\t? (effectiveParams.tasks ?? []).map((task) => task.agent)\n\t\t\t\t: (effectiveParams.chain ?? []).flatMap((step) => getStepAgents(step as ChainStep));\n\t\tconst externalAgent = selectedAgentNames\n\t\t\t.map((name) => agents.find((agent) => agent.name === name))\n\t\t\t.find((agent) => agent?.runner?.type === \"external-cli\");\n\t\tif (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {\n\t\t\treturn buildRequestedModeError(\n\t\t\t\teffectiveParams,\n\t\t\t\t`Agent '${externalAgent.name}' uses runner.type='external-cli', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`,\n\t\t\t);\n\t\t}\n\t\tconst foregroundTimeout = resolveForegroundTimeout(\n\t\t\teffectiveParams,\n\t\t\teffectiveAsync ? undefined : DEFAULT_FOREGROUND_TIMEOUT_MS,\n\t\t);\n\t\tif (foregroundTimeout.error) return buildRequestedModeError(effectiveParams, foregroundTimeout.error);\n\t\tconst controlConfig = resolveControlConfig(deps.config.control, effectiveParams.control);\n\n\t\tconst artifactConfig: ArtifactConfig = omitUndefinedProperties({\n\t\t\t...DEFAULT_ARTIFACT_CONFIG,\n\t\t\tenabled: effectiveParams.artifacts !== false,\n\t\t\tdir: deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,\n\t\t});\n\t\tconst artifactsDir = getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);\n\t\tif (artifactConfig.dir === \"project\" && !warnedArtifactPackageDirs.has(effectiveCwd)) {\n\t\t\twarnedArtifactPackageDirs.add(effectiveCwd);\n\t\t\tconst warning = getProjectArtifactPackagingWarning(effectiveCwd);\n\t\t\tif (warning) console.warn(`[pi-subagents] ${warning}`);\n\t\t}\n\n\t\tlet sessionRoot: string;\n\t\tif (effectiveParams.sessionDir) {\n\t\t\tsessionRoot = path.resolve(deps.expandTilde(effectiveParams.sessionDir));\n\t\t} else {\n\t\t\tconst baseSessionRoot = deps.config.defaultSessionDir\n\t\t\t\t? path.resolve(deps.expandTilde(deps.config.defaultSessionDir))\n\t\t\t\t: deps.getSubagentSessionRoot(parentSessionFile);\n\t\t\tsessionRoot = path.join(baseSessionRoot, runId);\n\t\t}\n\t\ttry {\n\t\t\tfs.mkdirSync(sessionRoot, { recursive: true });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn toExecutionErrorResult(\n\t\t\t\teffectiveParams,\n\t\t\t\tnew Error(`Failed to create session directory '${sessionRoot}': ${message}`),\n\t\t\t\tcontextPolicy.contextSummary,\n\t\t\t);\n\t\t}\n\t\tconst sessionDirForIndex = (idx?: number) => path.join(sessionRoot, `run-${idx ?? 0}`);\n\t\tconst forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride) => {\n\t\t\tif (!shouldForkAgent(contextPolicy, agentName)) return undefined;\n\t\t\tprepareForkThinking(agentName, idx, modelOverride);\n\t\t\treturn forkSessionFileForIndex(idx);\n\t\t};\n\t\tconst explicitThinkingOverride =\n\t\t\thasSingle && effectiveParams.thinking !== undefined ? effectiveParams.thinking : delegatedThinkingOverride;\n\t\tconst forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride) => {\n\t\t\tif (!shouldForkAgent(contextPolicy, agentName)) return explicitThinkingOverride;\n\t\t\tprepareForkThinking(agentName, idx, modelOverride);\n\t\t\tconst override = forkThinkingOverrideForIndex(idx);\n\t\t\tif (override === \"off\") forkThinkingDowngrades.set(idx, agentName);\n\t\t\treturn override ?? explicitThinkingOverride;\n\t\t};\n\t\tconst childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride) =>\n\t\t\tforkSessionFileForTask(agentName, idx, modelOverride) ?? path.join(sessionDirForIndex(idx), \"session.jsonl\");\n\t\tconst childSessionFileForIndex = (idx?: number) => path.join(sessionDirForIndex(idx), \"session.jsonl\");\n\t\ttry {\n\t\t\tif (!(effectiveParams.clarify === true && ctx.hasUI)) {\n\t\t\t\tpreflightForkSessionsForStaticTasks(\n\t\t\t\t\teffectiveParams,\n\t\t\t\t\tcontextPolicy,\n\t\t\t\t\tforkSessionFileForTask,\n\t\t\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);\n\t\t}\n\t\tconst chainBindingsError = validateExecutionChainBindings(\n\t\t\teffectiveParams,\n\t\t\tdeps.config.chain?.dynamicFanout?.maxItems,\n\t\t);\n\t\tif (chainBindingsError) return withResolvedContext(chainBindingsError, contextPolicy.contextSummary);\n\n\t\tconst onUpdateWithContext = onUpdate\n\t\t\t? (r: AgentToolResult<Details>) =>\n\t\t\t\t\tonUpdate(\n\t\t\t\t\t\twithResolvedContext(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t...r,\n\t\t\t\t\t\t\t\tdetails: { ...r.details, runId },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcontextPolicy.contextSummary,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t: undefined;\n\n\t\tlet missionBinding: MissionLaunchBinding | undefined;\n\t\tlet missionWarning: string | undefined;\n\t\tconst explicitMission = effectiveParams.missionId !== undefined || effectiveParams.mission !== undefined;\n\t\ttry {\n\t\t\tmissionBinding = prepareMissionLaunch({\n\t\t\t\tparams: effectiveParams,\n\t\t\t\tprojectRoot: effectiveCwd,\n\t\t\t\t...(deps.config.missions ? { config: deps.config.missions } : {}),\n\t\t\t\townerSessionId: requestSessionId,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (explicitMission) return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);\n\t\t\tmissionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\n\t\tconst attachMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {\n\t\t\tif (!missionBinding)\n\t\t\t\treturn missionWarning ? { ...result, details: { ...result.details, missionWarning } } : result;\n\t\t\ttry {\n\t\t\t\treturn attachMissionToLaunchResult({ binding: missionBinding, result });\n\t\t\t} catch (error) {\n\t\t\t\tconst warning = `Mission tracking unavailable after launch: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\t\tif (explicitMission) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...result,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [...result.content, { type: \"text\", text: warning }],\n\t\t\t\t\t\tdetails: { ...result.details, missionWarning: warning },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { ...result, details: { ...result.details, missionWarning: warning } };\n\t\t\t}\n\t\t};\n\n\t\tconst reservation = reserveSpawnBudget(deps.state, deps.config, requestSessionId, requestedSpawns);\n\t\tif (reservation.error) return attachMission(spawnBudgetErrorResult(reservation.error, foregroundMode));\n\n\t\tconst execData: ExecutionContextData = omitUndefinedProperties({\n\t\t\tparams: effectiveParams,\n\t\t\teffectiveCwd,\n\t\t\tctx,\n\t\t\tsignal,\n\t\t\tonUpdate: onUpdateWithContext,\n\t\t\tagents,\n\t\t\trunId,\n\t\t\tshareEnabled,\n\t\t\tsessionRoot,\n\t\t\tsessionDirForIndex,\n\t\t\tsessionFileForIndex: childSessionFileForIndex,\n\t\t\tsessionFileForTask: childSessionFileForTask,\n\t\t\tthinkingOverrideForTask: forkThinkingOverrideForTask,\n\t\t\tartifactConfig,\n\t\t\tartifactsDir,\n\t\t\tbackgroundRequestedWhileClarifying,\n\t\t\teffectiveAsync,\n\t\t\tcontrolConfig,\n\t\t\tintercomBridge,\n\t\t\tnestedRoute,\n\t\t\ttimeoutMs: foregroundTimeout.timeoutMs,\n\t\t\tturnBudget: turnBudget.turnBudget,\n\t\t\ttoolBudget: runToolBudget.toolBudget,\n\t\t\tusageBudget: usageBudget.budget,\n\t\t\tallowZeroToolBudget,\n\t\t\tconfigToolBudget: configToolBudget.toolBudget,\n\t\t\tcontextPolicy,\n\t\t\tmodelScope,\n\t\t\tparentModel: requestParentModel,\n\t\t\tparentSessionId: requestSessionId,\n\t\t\tparentPiSessionId: requestPiSessionId,\n\t\t\tcapabilityCeiling: resolveCurrentSubagentCapabilityCeiling(requestSessionId),\n\t\t});\n\n\t\tconst foregroundDescription =\n\t\t\teffectiveParams.task?.trim() ||\n\t\t\teffectiveParams.tasks?.[0]?.task?.trim() ||\n\t\t\t(effectiveParams.chain ? firstRawChainTask(effectiveParams.chain)?.trim() : undefined);\n\t\tconst foregroundControl: ForegroundRunControl | undefined = effectiveAsync\n\t\t\t? undefined\n\t\t\t: compactOptional<ForegroundRunControl>({\n\t\t\t\t\trunId,\n\t\t\t\t\tsessionId: requestSessionId,\n\t\t\t\t\tmode: foregroundMode,\n\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\tcwd: effectiveCwd,\n\t\t\t\t\tcurrentAgent: undefined,\n\t\t\t\t\tcurrentIndex: undefined,\n\t\t\t\t\tdescription: foregroundDescription,\n\t\t\t\t\tcurrentActivityState: undefined,\n\t\t\t\t\tactiveChildren: new Map(),\n\t\t\t\t\t// The outer executor owns scheduling until its finally block settles.\n\t\t\t\t\tschedulingOwners: 1,\n\t\t\t\t\tnestedRoute,\n\t\t\t\t\tinterrupt: undefined,\n\t\t\t\t});\n\t\tif (foregroundControl) {\n\t\t\tdeps.state.foregroundControls.set(runId, foregroundControl);\n\t\t\tdeps.state.lastForegroundControlId = runId;\n\t\t}\n\n\t\tconst writeNestedForegroundEvent = (\n\t\t\ttype: \"subagent.nested.started\" | \"subagent.nested.completed\",\n\t\t\tresult?: AgentToolResult<Details>,\n\t\t): void => {\n\t\t\tif (!inheritedNestedRoute || !nestedParentAddress) return;\n\t\t\tconst now = Date.now();\n\t\t\tconst details = result?.details;\n\t\t\tconst state =\n\t\t\t\ttype === \"subagent.nested.started\"\n\t\t\t\t\t? \"running\"\n\t\t\t\t\t: details?.results.some((child) => child.interrupted || child.detached)\n\t\t\t\t\t\t? \"paused\"\n\t\t\t\t\t\t: result?.isError || details?.results.some((child) => child.exitCode !== 0)\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"complete\";\n\t\t\tconst errorText = result?.isError ? result.content.find((item) => item.type === \"text\")?.text : undefined;\n\t\t\tlet startedLaunches: StaticLaunchSummary[];\n\t\t\ttry {\n\t\t\t\tstartedLaunches = collectStaticLaunchSummaries({\n\t\t\t\t\tparams: effectiveParams,\n\t\t\t\t\tagents,\n\t\t\t\t\tparentModel: requestParentModel,\n\t\t\t\t\tavailableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),\n\t\t\t\t\tcurrentProvider: requestParentModel?.provider,\n\t\t\t\t\tmodelScope,\n\t\t\t\t\tthinkingOverrideForTask: forkThinkingOverrideForTask,\n\t\t\t\t\tdynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to resolve nested foreground launch metadata:\", error);\n\t\t\t\tstartedLaunches = selectedAgentNames.map((agent) => ({ agent }));\n\t\t\t}\n\t\t\tconst agentsForSummary = startedLaunches.map((launch) => launch.agent);\n\t\t\tconst leafIntercomTarget =\n\t\t\t\tintercomBridge.active && agentsForSummary[0]\n\t\t\t\t\t? resolveSubagentIntercomTarget(runId, agentsForSummary[0], 0)\n\t\t\t\t\t: undefined;\n\t\t\ttry {\n\t\t\t\twriteNestedEvent(\n\t\t\t\t\tinheritedNestedRoute,\n\t\t\t\t\tcompactOptional<Parameters<typeof writeNestedEvent>[1]>({\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tts: now,\n\t\t\t\t\t\tparentRunId: nestedParentAddress.parentRunId,\n\t\t\t\t\t\tparentStepIndex: nestedParentAddress.parentStepIndex,\n\t\t\t\t\t\tchild: compactOptional<NestedRunSummary>({\n\t\t\t\t\t\t\tid: runId,\n\t\t\t\t\t\t\tparentRunId: nestedParentAddress.parentRunId,\n\t\t\t\t\t\t\tparentStepIndex: nestedParentAddress.parentStepIndex,\n\t\t\t\t\t\t\tdepth: nestedParentAddress.depth,\n\t\t\t\t\t\t\tpath: nestedParentAddress.path,\n\t\t\t\t\t\t\townerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,\n\t\t\t\t\t\t\tleafIntercomTarget,\n\t\t\t\t\t\t\tintercomTarget: leafIntercomTarget,\n\t\t\t\t\t\t\townerState: state === \"running\" ? \"live\" : \"gone\",\n\t\t\t\t\t\t\tmode: foregroundMode,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tagent: agentsForSummary[0],\n\t\t\t\t\t\t\tagents: agentsForSummary,\n\t\t\t\t\t\t\t...(agentsForSummary.length === 1 &&\n\t\t\t\t\t\t\t(type === \"subagent.nested.started\" ? startedLaunches[0]?.model : details?.results[0]?.model)\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tmodel:\n\t\t\t\t\t\t\t\t\t\t\ttype === \"subagent.nested.started\"\n\t\t\t\t\t\t\t\t\t\t\t\t? startedLaunches[0]?.model\n\t\t\t\t\t\t\t\t\t\t\t\t: details?.results[0]?.model,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t...(agentsForSummary.length === 1 &&\n\t\t\t\t\t\t\t(type === \"subagent.nested.started\" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking)\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tthinking:\n\t\t\t\t\t\t\t\t\t\t\ttype === \"subagent.nested.started\"\n\t\t\t\t\t\t\t\t\t\t\t\t? startedLaunches[0]?.thinking\n\t\t\t\t\t\t\t\t\t\t\t\t: details?.results[0]?.thinking,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\tstartedAt: foregroundControl?.startedAt ?? now,\n\t\t\t\t\t\t\t...(state !== \"running\" ? { endedAt: now } : {}),\n\t\t\t\t\t\t\tlastUpdate: now,\n\t\t\t\t\t\t\t...(details?.totalCost ? { totalCost: details.totalCost } : {}),\n\t\t\t\t\t\t\t...(errorText ? { error: errorText } : {}),\n\t\t\t\t\t\t\t...(type === \"subagent.nested.started\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tsteps: startedLaunches.map((launch) => ({\n\t\t\t\t\t\t\t\t\t\t\tagent: launch.agent,\n\t\t\t\t\t\t\t\t\t\t\tstatus: \"running\" as const,\n\t\t\t\t\t\t\t\t\t\t\t...(launch.model ? { model: launch.model } : {}),\n\t\t\t\t\t\t\t\t\t\t\t...(launch.thinking ? { thinking: launch.thinking } : {}),\n\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: details?.results.length\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tsteps: details.results.map((child) => ({\n\t\t\t\t\t\t\t\t\t\t\t\tagent: child.agent,\n\t\t\t\t\t\t\t\t\t\t\t\tstatus:\n\t\t\t\t\t\t\t\t\t\t\t\t\tchild.interrupted || child.detached\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (\"paused\" as const)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: child.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (\"complete\" as const)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: (\"failed\" as const),\n\t\t\t\t\t\t\t\t\t\t\t\t...(child.model ? { model: child.model } : {}),\n\t\t\t\t\t\t\t\t\t\t\t\t...(child.thinking ? { thinking: child.thinking } : {}),\n\t\t\t\t\t\t\t\t\t\t\t\t...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),\n\t\t\t\t\t\t\t\t\t\t\t\t...(child.error ? { error: child.error } : {}),\n\t\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to emit nested foreground status event:\", error);\n\t\t\t}\n\t\t};\n\n\t\tlet nestedForegroundStarted = false;\n\t\ttry {\n\t\t\tconst asyncResult = runAsyncPath(execData, deps);\n\t\t\tif (asyncResult)\n\t\t\t\treturn attachMission(\n\t\t\t\t\twithResolvedContext(\n\t\t\t\t\t\twithForkThinkingNotes(asyncResult, forkThinkingDowngrades),\n\t\t\t\t\t\tcontextPolicy.contextSummary,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\tif (foregroundControl) {\n\t\t\t\twriteNestedForegroundEvent(\"subagent.nested.started\");\n\t\t\t\tnestedForegroundStarted = true;\n\t\t\t}\n\t\t\tif (hasChain && effectiveParams.chain) {\n\t\t\t\tconst result = await runChainPath(execData, deps);\n\t\t\t\twriteNestedForegroundEvent(\"subagent.nested.completed\", result);\n\t\t\t\treturn attachMission(\n\t\t\t\t\twithResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (hasTasks && effectiveParams.tasks) {\n\t\t\t\tconst result = await runParallelPath(execData, deps);\n\t\t\t\twriteNestedForegroundEvent(\"subagent.nested.completed\", result);\n\t\t\t\treturn attachMission(\n\t\t\t\t\twithResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (hasSingle) {\n\t\t\t\tconst result = await runSinglePath(execData, deps);\n\t\t\t\twriteNestedForegroundEvent(\"subagent.nested.completed\", result);\n\t\t\t\treturn attachMission(\n\t\t\t\t\twithResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary),\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst errorResult = withForkThinkingNotes(\n\t\t\t\ttoExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary),\n\t\t\t\tforkThinkingDowngrades,\n\t\t\t);\n\t\t\tif (nestedForegroundStarted) writeNestedForegroundEvent(\"subagent.nested.completed\", errorResult);\n\t\t\treturn attachMission(errorResult);\n\t\t} finally {\n\t\t\tif (foregroundControl) {\n\t\t\t\tsettleForegroundSchedulingOwner(foregroundControl);\n\t\t\t\tremoveForegroundControlIfIdle(deps.state, runId);\n\t\t\t}\n\t\t}\n\n\t\treturn withResolvedContext(\n\t\t\t{\n\t\t\t\tcontent: [{ type: \"text\", text: \"Invalid params\" }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t\t},\n\t\t\tcontextPolicy.contextSummary,\n\t\t);\n\t};\n\n\tconst executeWithSingleDispatchGuard = async (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t\tpublicBoundary = false,\n\t): Promise<AgentToolResult<Details>> => {\n\t\tconst normalizedAction = typeof params.action === \"string\" ? params.action.trim() : params.action;\n\t\tconst requestParams = normalizedAction ? { ...params, action: normalizedAction } : params;\n\t\tif (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx);\n\t\tconst { depth } = checkSubagentDepth(deps.config.maxSubagentDepth);\n\t\tconst dispatchParams = applyForceTopLevelAsyncOverride(\n\t\t\trequestParams,\n\t\t\tdepth,\n\t\t\tdeps.config.forceTopLevelAsync === true,\n\t\t);\n\t\tconst directExecution =\n\t\t\tpublicBoundary &&\n\t\t\tdispatchParams.workflowScript === undefined &&\n\t\t\tdispatchParams.task !== undefined &&\n\t\t\tdispatchParams.action === undefined;\n\t\tconst effectiveDispatchParams =\n\t\t\tdirectExecution && dispatchParams.async === undefined ? { ...dispatchParams, async: false } : dispatchParams;\n\t\tconst defaultAsync = directExecution ? false : deps.asyncByDefault;\n\t\tconst runsForeground =\n\t\t\teffectiveDispatchParams.clarify === true || (effectiveDispatchParams.async ?? defaultAsync) !== true;\n\t\tif (!runsForeground) return execute(id, effectiveDispatchParams, signal, onUpdate, ctx);\n\t\tif (deps.state.subagentInProgress === true) return duplicateSubagentCallResult(effectiveDispatchParams);\n\t\tdeps.state.subagentInProgress = true;\n\t\ttry {\n\t\t\treturn await execute(id, effectiveDispatchParams, signal, onUpdate, ctx);\n\t\t} finally {\n\t\t\tdeps.state.subagentInProgress = false;\n\t\t}\n\t};\n\n\tconst executePublic = (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<AgentToolResult<Details>> => {\n\t\tconst normalized = normalizePublicSubagentExecution(params);\n\t\tif (!normalized.ok) {\n\t\t\treturn Promise.resolve({\n\t\t\t\tcontent: [{ type: \"text\", text: normalized.error }],\n\t\t\t\tisError: true,\n\t\t\t\tdetails: { mode: normalized.mode, results: [] },\n\t\t\t});\n\t\t}\n\t\treturn executeWithSingleDispatchGuard(id, normalized.params, signal, onUpdate, ctx, true);\n\t};\n\n\tconst executeDelegated = async (\n\t\tid: string,\n\t\tparams: SubagentParamsLike,\n\t\tsignal: AbortSignal,\n\t\tonUpdate: ((r: AgentToolResult<Details>) => void) | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<AgentToolResult<Details>> => {\n\t\tconst delegatedParams = { ...params };\n\t\tconst privateParams = delegatedParams as SubagentParamsLike & {\n\t\t\tdelegatedThinkingOverride?: AgentConfig[\"thinking\"];\n\t\t\tdelegatedAllowZeroToolBudget?: true;\n\t\t};\n\t\tconst thinkingOverride = privateParams.delegatedThinkingOverride;\n\t\tconst allowZeroToolBudget = privateParams.delegatedAllowZeroToolBudget === true;\n\t\tdelete privateParams.delegatedThinkingOverride;\n\t\tdelete privateParams.delegatedAllowZeroToolBudget;\n\t\tif (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);\n\t\tif (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);\n\t\treturn execute(id, delegatedParams, signal, onUpdate, ctx);\n\t};\n\n\tconst executeScheduled = (id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => {\n\t\tconst ownerSessionId = resolveCurrentSessionId(ctx.sessionManager);\n\t\tlet ownerExecutor = scheduledOwnerExecutors.get(ownerSessionId);\n\t\tif (!ownerExecutor) {\n\t\t\townerExecutor = createSubagentExecutor({\n\t\t\t\t...deps,\n\t\t\t\tstate: createScheduledOwnerState(deps.state, ownerSessionId, ctx),\n\t\t\t});\n\t\t\tscheduledOwnerExecutors.set(ownerSessionId, ownerExecutor);\n\t\t}\n\t\treturn ownerExecutor.execute(id, params, signal, undefined, ctx);\n\t};\n\n\treturn { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };\n}\n"]}