{"version":3,"file":"subagent-runner.d.ts","sourceRoot":"","sources":["../../../../src/runs/background/subagent-runner.ts"],"names":[],"mappings":"","sourcesContent":["import { spawn, spawnSync } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Message } from \"@lpb-work/pi-ai\";\nimport { resolveSubagentIntercomTarget } from \"../../intercom/intercom-bridge.ts\";\nimport {\n\tappendJsonl as appendRawJsonl,\n\tformatOutputArtifactContent,\n\tgetArtifactPaths,\n\twriteArtifact,\n\twriteMetadata,\n} from \"../../shared/artifacts.ts\";\nimport { writeAtomicJson } from \"../../shared/atomic-json.ts\";\nimport { type ChildTranscriptWriter, createChildTranscriptWriter } from \"../../shared/child-transcript.ts\";\nimport { launchBindingDigest } from \"../../shared/launch-contract.ts\";\nimport { resolveEffectiveThinking } from \"../../shared/model-info.ts\";\nimport { attachPostExitStdioGuard, trySignalChild } from \"../../shared/post-exit-stdio-guard.ts\";\nimport { parseSessionTokens } from \"../../shared/session-tokens.ts\";\nimport { writeInitialProgressFile } from \"../../shared/settings.ts\";\nimport type { TokenUsage } from \"../../shared/types.ts\";\nimport {\n\ttype ActivityState,\n\ttype ArtifactConfig,\n\ttype ArtifactPaths,\n\ttype AsyncParallelGroupStatus,\n\ttype AsyncStatus,\n\ttype ChainOutputMap,\n\ttype CostSummary,\n\tDEFAULT_MAX_OUTPUT,\n\ttype ExternalCliRunnerStatus,\n\ttype ExternalProcessStatus,\n\tgetSubagentDepthEnv,\n\ttype LaunchResolvedChildExtensionsV1,\n\ttype MaxOutputConfig,\n\ttype ModelAttempt,\n\ttype NestedRouteInfo,\n\ttype NestedRunSummary,\n\tPOLL_INTERVAL_MS,\n\ttype ResolvedControlConfig,\n\ttype ResolvedToolBudget,\n\ttype ResolvedTurnBudget,\n\ttype RuntimeAcknowledgedChildExtensionsV1,\n\ttype SteeringTargetState,\n\ttype SteeringTargetStatus,\n\tSUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\ttype SubagentOutputState,\n\ttype SubagentRunMode,\n\ttype ToolBudgetState,\n\ttype TurnBudgetState,\n\ttruncateOutput,\n\ttype Usage,\n\ttype UsageBudgetConfig,\n\ttype WorkflowGraphSnapshot,\n} from \"../../shared/types.ts\";\nimport {\n\tdetectSubagentError,\n\textractTextFromContent,\n\textractToolArgsPreview,\n\tgetFinalOutput,\n\thasEmptyTerminalAssistantResponse,\n\treadStatus,\n} from \"../../shared/utils.ts\";\nimport {\n\tacceptChildWatchdogEvent,\n\tCHILD_WATCHDOG_CONFIG_ENV,\n\ttype ChildWatchdogStateSnapshot,\n\tchildWatchdogIsActive,\n\tdecodeChildWatchdogConfig,\n\tisChildWatchdogStatusEvent,\n\tresolveChildWatchdogConfig,\n} from \"../../watchdog/child-status.ts\";\nimport { resolveWatchdogConfig } from \"../../watchdog/settings.ts\";\nimport {\n\tacceptanceFailureMessage,\n\taggregateAcceptanceReport,\n\tbuildSkippedAcceptanceLedger,\n\tevaluateAcceptance,\n\tformatAcceptancePrompt,\n\tresolveEffectiveAcceptance,\n\tstripAcceptanceReport,\n} from \"../shared/acceptance.ts\";\nimport { attachContractProjections, isAgentContractV1 } from \"../shared/agent-contract.ts\";\nimport {\n\tdecodeSubagentCapabilityCeiling,\n\ttype ResolvedSubagentCapabilityCeiling,\n\tSUBAGENT_CAPABILITY_CEILING_ENV,\n} from \"../shared/capability-ceiling.ts\";\nimport { outputEntryFromAsyncResult, resolveOutputReferences } from \"../shared/chain-outputs.ts\";\nimport {\n\ttype ChildLifecycleAction,\n\tcreateBoundedByteTail,\n\tcreateBoundedLineReader,\n\tformatProtocolOutputLimit,\n\tMAX_CHILD_STDERR_BYTES,\n\tPI_AGGREGATE_EVENT_PROJECTOR,\n\ttype ProtocolOutputLimit,\n\tprojectChildLifecycle,\n} from \"../shared/child-protocol.ts\";\nimport { evaluateCompletionMutationGuard } from \"../shared/completion-guard.ts\";\nimport {\n\tcollectDynamicResults,\n\tDynamicFanoutError,\n\tmaterializeDynamicParallelStep,\n\tvalidateDynamicCollection,\n} from \"../shared/dynamic-fanout.ts\";\nimport { buildExternalCliPrompt, ExternalCliRunner } from \"../shared/external-cli-runner.ts\";\nimport { PiRunner } from \"../shared/runner-adapter.ts\";\nimport {\n\tcreateMutatingFailureState,\n\tdidMutatingToolFail,\n\tisMutatingTool,\n\tnextLongRunningTrigger,\n\trecordMutatingFailure,\n\tresetMutatingFailureState,\n\tresolveCurrentPath,\n\tshouldEscalateMutatingFailures,\n\tsummarizeRecentMutatingFailures,\n} from \"../shared/long-running-guard.ts\";\nimport { formatModelAttemptNote, isRetryableModelFailure } from \"../shared/model-fallback.ts\";\nimport {\n\tnestedSummaryFromAsyncStatus,\n\tprojectNestedEvents,\n\tresolveNestedAsyncDir,\n\twriteNestedEvent,\n} from \"../shared/nested-events.ts\";\nimport {\n\tformatParallelHandoffError,\n\tformatParallelHandoffReference,\n\tparallelHandoffPath,\n\twriteParallelHandoffGroup,\n\twritePendingParallelHandoff,\n} from \"../shared/parallel-handoff.ts\";\nimport {\n\taggregateParallelOutputs,\n\tDEFAULT_GLOBAL_CONCURRENCY_LIMIT,\n\tflattenSteps,\n\tisCheckpointRunnerStep,\n\tisDynamicRunnerGroup,\n\tisParallelGroup,\n\tMAX_PARALLEL_CONCURRENCY,\n\tmapConcurrent,\n\ttype RunnerStep,\n\tSemaphore,\n\ttype RunnerSubagentStep as SubagentStep,\n} from \"../shared/parallel-utils.ts\";\nimport {\n\tapplyThinkingSuffix,\n\tbuildPiArgs,\n\tcleanupTempDir,\n\tprojectLaunchResolvedChildExtensions,\n\tresolvePiLaunchToolPlan,\n} from \"../shared/pi-args.ts\";\nimport { getPiSpawnCommand, PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from \"../shared/pi-spawn.ts\";\nimport { formatProcessSignalError, isUnexplainedProcessSignal } from \"../shared/process-signal.ts\";\nimport { readRuntimeAcknowledgedExtensions } from \"../shared/runtime-acknowledged-extensions.ts\";\nimport { acquireSessionLease, type SessionLeaseRequest } from \"../shared/session-lease.ts\";\nimport {\n\tcaptureSingleOutputSnapshot,\n\textractChildWrittenOutput,\n\tfinalizeSingleOutput,\n\tformatSavedOutputReference,\n\tinjectOutputPathSystemPrompt,\n\tinjectSingleOutputInstruction,\n\tresolveSingleOutput,\n\ttype SingleOutputSnapshot,\n} from \"../shared/single-output.ts\";\nimport { createStructuredOutputRuntime, readStructuredOutput } from \"../shared/structured-output.ts\";\nimport {\n\tbuildControlEvent,\n\tclaimControlNotification,\n\tDEFAULT_CONTROL_CONFIG,\n\tderiveActivityState,\n\tformatControlIntercomMessage,\n\tformatControlNoticeMessage,\n} from \"../shared/subagent-control.ts\";\nimport {\n\tformatSubagentStartupRetryExhaustedError,\n\tformatSubagentStartupRetryNote,\n\tisRetryableSubagentStartupFailure,\n\tSUBAGENT_STARTUP_RETRY_DELAYS_MS,\n\twaitForSubagentStartupRetry,\n} from \"../shared/subagent-startup-retry.ts\";\nimport { readChildToolDiagnosticError } from \"../shared/tool-availability.ts\";\nimport { initialToolBudgetState, toolBudgetState } from \"../shared/tool-budget.ts\";\nimport {\n\tappendTurnBudgetSystemPrompt,\n\tformatTurnBudgetOutput,\n\tinitialTurnBudgetState,\n\tturnBudgetDecision,\n\tturnBudgetDeferredNote,\n\tturnBudgetDeferredState,\n\tturnBudgetExceededMessage,\n\tturnBudgetSoftNote,\n\tturnBudgetState,\n} from \"../shared/turn-budget.ts\";\nimport { usageBudgetExceededMessage, usageBudgetState } 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 {\n\tappendRunnerStepsToStatus,\n\tconsumeChainAppendRequests,\n\tcountPendingChainAppendRequests,\n\tstatusStepDescription,\n} from \"./chain-append.ts\";\nimport { waitForImportedAsyncRoot } from \"./chain-root-attachment.ts\";\nimport {\n\tcloseSteerInbox,\n\tconsumeInterruptRequest,\n\tconsumeSteerRequests,\n\tdeliverInterruptRequest,\n\tdeliverStopRequest,\n\tdeliverTimeoutRequest,\n\tenqueueStepSteer,\n\ttype SteerAck,\n\ttype SteerCapability,\n\ttype SteerRequest,\n\tsteerAcksDir,\n\tsteerCapabilityPath,\n\tstepSteerInboxDir,\n\twatchAsyncControlInbox,\n} from \"./control-channel.ts\";\nimport {\n\tmarkProcessTerminalCandidateLeaseRelease,\n\ttype ProcessTerminalCandidate,\n\twriteProcessTerminalCandidate,\n} from \"./process-terminal.ts\";\nimport {\n\tcreateSteeringStatus,\n\trecordSteeringRequest,\n\tsteeringStatus,\n\tterminalSteeringNoticeState,\n\tupdateSteeringTarget,\n} from \"./steering.ts\";\n\ninterface SubagentRunConfig {\n\tid: string;\n\tsteps: RunnerStep[];\n\tresultPath: string;\n\tcwd: string;\n\tplaceholder: string;\n\ttaskIndex?: number;\n\ttotalTasks?: number;\n\tmaxOutput?: MaxOutputConfig;\n\tartifactsDir?: string;\n\tartifactConfig?: Partial<ArtifactConfig>;\n\tshare?: boolean;\n\tsessionDir?: string;\n\tasyncDir: string;\n\tsessionId?: string | null;\n\tpiPackageRoot?: string;\n\tpiArgv1?: string;\n\tworktreeSetupHook?: string;\n\tworktreeSetupHookTimeoutMs?: number;\n\tworktreeBaseDir?: string;\n\tcontrolConfig?: ResolvedControlConfig;\n\tcontrolIntercomTarget?: string;\n\tchildIntercomTargets?: Array<string | undefined>;\n\tresultMode?: SubagentRunMode;\n\tmode?: SubagentRunMode;\n\tdynamicFanoutMaxItems?: number;\n\tworkflowGraph?: WorkflowGraphSnapshot;\n\tnestedRoute?: NestedRouteInfo;\n\tnestedSelf?: {\n\t\tparentRunId: string;\n\t\tparentStepIndex?: number;\n\t\tdepth: number;\n\t\tpath?: Array<{ runId: string; stepIndex?: number; agent?: string }>;\n\t};\n\ttimeoutMs?: number;\n\tdeadlineAt?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tusageBudget?: UsageBudgetConfig;\n\trevivalLease?: SessionLeaseRequest;\n\trevivalLeaseToken?: string;\n\t/** Global cap on simultaneously-running subagent tasks within this run. */\n\tglobalConcurrencyLimit?: number;\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n\tlaunchContractDigest?: string;\n\tlaunchResolvedExtensions?: LaunchResolvedChildExtensionsV1;\n\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\trunnerProcessInstanceId?: string;\n\tparentWorkflowRunId?: string;\n\tworkflowKey?: string;\n}\n\ninterface StepResult {\n\tagent: string;\n\tcontext?: \"fresh\" | \"fork\";\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n\tcapabilityAudit?: import(\"../shared/capability-ceiling.ts\").SubagentCapabilityAudit;\n\tlaunchResolvedExtensions?: LaunchResolvedChildExtensionsV1;\n\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\toutput: string;\n\toutputState?: SubagentOutputState;\n\terror?: string;\n\tprotocolError?: ProtocolOutputLimit;\n\tsuccess?: boolean;\n\texitCode: number | null;\n\tusage?: Usage;\n\tsavedOutputPath?: string;\n\tskipped?: boolean;\n\tinterrupted?: boolean;\n\ttimedOut?: boolean;\n\tstopped?: boolean;\n\tprocessSignal?: string | null;\n\tturnBudget?: TurnBudgetState;\n\tturnBudgetExceeded?: boolean;\n\twrapUpRequested?: boolean;\n\ttoolBudget?: ToolBudgetState;\n\ttoolBudgetBlocked?: boolean;\n\tsessionFile?: string;\n\tintercomTarget?: string;\n\tmodel?: string;\n\tattemptedModels?: string[];\n\tmodelAttempts?: ModelAttempt[];\n\ttotalCost?: CostSummary;\n\tartifactPaths?: ArtifactPaths;\n\toutputSaveError?: string;\n\tmetadataSaveError?: string;\n\ttruncated?: boolean;\n\ttranscriptPath?: string;\n\ttranscriptError?: string;\n\tagentContract?: import(\"../../shared/types.ts\").AgentContract;\n\tlaunchContractDigest?: string;\n\texecution?: import(\"../../shared/types.ts\").ExecutionProjection;\n\treview?: import(\"../../shared/types.ts\").ReviewProjection;\n\teffects?: import(\"../../shared/types.ts\").EffectsProjection;\n\tstructuredOutput?: unknown;\n\tstructuredOutputPath?: string;\n\tstructuredOutputSchemaPath?: string;\n\tacceptance?: import(\"../../shared/types.ts\").AcceptanceLedger;\n\twatchdog?: import(\"../../shared/types.ts\").ChildWatchdogProgress;\n\twriterProcesses?: Array<{\n\t\tprocessInstanceId: string;\n\t\tkind: \"pi-writer\";\n\t\tattempt: number;\n\t\tcloseObservedAt: number;\n\t\texitCode: number | null;\n\t\tsignal: string | null;\n\t}>;\n\twriterAttemptCount?: number;\n\trunner?: ExternalCliRunnerStatus;\n\texternalProcess?: ExternalProcessStatus;\n}\n\nfunction persistStepArtifacts(input: {\n\tartifactPaths: ArtifactPaths;\n\tartifactConfig?: Partial<ArtifactConfig>;\n\toutput: string;\n\tmetadata: object;\n}): { outputSaveError?: string; metadataSaveError?: string } {\n\tconst errors: { outputSaveError?: string; metadataSaveError?: string } = {};\n\tif (input.artifactConfig?.includeOutput !== false) {\n\t\ttry {\n\t\t\twriteArtifact(input.artifactPaths.outputPath, input.output);\n\t\t} catch (error) {\n\t\t\terrors.outputSaveError = `Artifact output post-processing failed: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t}\n\tif (input.artifactConfig?.includeMetadata !== false) {\n\t\ttry {\n\t\t\twriteMetadata(input.artifactPaths.metadataPath, input.metadata);\n\t\t} catch (error) {\n\t\t\terrors.metadataSaveError = `Artifact metadata post-processing failed: ${error instanceof Error ? error.message : String(error)}`;\n\t\t}\n\t}\n\treturn errors;\n}\n\nconst ASYNC_INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === \"win32\" ? \"SIGBREAK\" : \"SIGUSR2\";\nconst DEFAULT_MAX_ASYNC_EVENTS_BYTES = 50 * 1024 * 1024;\nconst ASYNC_EVENTS_MAX_BYTES_ENV = \"PI_SUBAGENT_ASYNC_EVENTS_MAX_BYTES\";\nconst RUNNER_HEARTBEAT_INTERVAL_MS = 5_000;\nconst TRUNCATED_EVENT_TYPE = \"subagent.events.truncated\";\nconst TRUNCATION_MARKER_RESERVE_BYTES = 512;\n\ninterface AsyncEventLogState {\n\tbytes: number;\n\tdiagnosticsTruncated: boolean;\n}\n\nconst asyncEventLogStates = new Map<string, AsyncEventLogState>();\n\nfunction maxAsyncEventsBytes(): number {\n\tconst raw = process.env[ASYNC_EVENTS_MAX_BYTES_ENV];\n\tif (!raw) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;\n\tconst parsed = Number(raw);\n\tif (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;\n\treturn Math.floor(parsed);\n}\n\nfunction eventLogState(filePath: string): AsyncEventLogState {\n\tlet state = asyncEventLogStates.get(filePath);\n\tif (state) return state;\n\tlet bytes = 0;\n\ttry {\n\t\tbytes = fs.statSync(filePath).size;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\t// Diagnostic event accounting is best-effort; writes below are also safe.\n\t\t}\n\t}\n\tstate = { bytes, diagnosticsTruncated: false };\n\tasyncEventLogStates.set(filePath, state);\n\treturn state;\n}\n\nfunction appendJsonl(filePath: string, line: string): void {\n\ttry {\n\t\tappendRawJsonl(filePath, line);\n\t\tconst state = asyncEventLogStates.get(filePath);\n\t\tif (state) state.bytes += Buffer.byteLength(`${line}\\n`, \"utf-8\");\n\t} catch {\n\t\t// Async event logging is diagnostic and must not fail the run.\n\t}\n}\n\nfunction appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?: string): void {\n\tif (!line.trim()) return;\n\tconst state = eventLogState(filePath);\n\tif (state.diagnosticsTruncated) return;\n\tconst maxBytes = maxAsyncEventsBytes();\n\tconst chunkBytes = Buffer.byteLength(`${line}\\n`, \"utf-8\");\n\tconst diagnosticBudget = Math.max(0, maxBytes - TRUNCATION_MARKER_RESERVE_BYTES);\n\tif (state.bytes + chunkBytes <= diagnosticBudget) {\n\t\tappendJsonl(filePath, line);\n\t\treturn;\n\t}\n\n\tconst marker = JSON.stringify({\n\t\ttype: TRUNCATED_EVENT_TYPE,\n\t\tts: Date.now(),\n\t\tmaxBytes,\n\t\tdroppedEventType,\n\t});\n\tif (state.bytes + Buffer.byteLength(`${marker}\\n`, \"utf-8\") <= maxBytes) {\n\t\tappendJsonl(filePath, marker);\n\t}\n\tstate.diagnosticsTruncated = true;\n}\n\nfunction shouldPersistChildEvent(event: Record<string, unknown>): boolean {\n\treturn event.type !== \"message_update\";\n}\n\nfunction isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean {\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return false;\n\tif (toolName === \"contact_supervisor\") {\n\t\tconst reason = (args as Record<string, unknown>).reason;\n\t\treturn reason === \"need_decision\" || reason === \"interview_request\";\n\t}\n\treturn toolName === \"intercom\" && (args as Record<string, unknown>).action === \"ask\";\n}\n\nfunction findLatestSessionFile(sessionDir: string): string | null {\n\ttry {\n\t\tconst files = fs\n\t\t\t.readdirSync(sessionDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => path.join(sessionDir, f));\n\t\tif (files.length === 0) return null;\n\t\tfiles.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);\n\t\treturn files[0] ?? null;\n\t} catch {\n\t\t// Session lookup is optional metadata.\n\t\treturn null;\n\t}\n}\n\nfunction emptyUsage(): Usage {\n\treturn { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };\n}\n\nfunction tokenUsageFromAttempts(attempts: ModelAttempt[] | undefined): TokenUsage | null {\n\tif (!attempts || attempts.length === 0) return null;\n\tlet input = 0;\n\tlet output = 0;\n\tfor (const attempt of attempts) {\n\t\tinput += attempt.usage?.input ?? 0;\n\t\toutput += attempt.usage?.output ?? 0;\n\t}\n\tconst total = input + output;\n\treturn total > 0 ? { input, output, total } : null;\n}\n\nfunction costSummaryFromAttempts(attempts: ModelAttempt[] | undefined): CostSummary | undefined {\n\tif (!attempts || attempts.length === 0) return undefined;\n\tlet inputTokens = 0;\n\tlet outputTokens = 0;\n\tlet costUsd = 0;\n\tfor (const attempt of attempts) {\n\t\tinputTokens += attempt.usage?.input ?? 0;\n\t\toutputTokens += attempt.usage?.output ?? 0;\n\t\tcostUsd += attempt.usage?.cost ?? 0;\n\t}\n\treturn inputTokens > 0 || outputTokens > 0 || costUsd > 0 ? { inputTokens, outputTokens, costUsd } : undefined;\n}\n\nfunction appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {\n\tconst nonEmpty = lines.filter((line) => line.trim());\n\tif (nonEmpty.length === 0) return;\n\tstep.recentOutput ??= [];\n\tstep.recentOutput.push(...nonEmpty);\n\tif (step.recentOutput.length > 50) {\n\t\tstep.recentOutput.splice(0, step.recentOutput.length - 50);\n\t}\n}\n\nfunction assistantStartsToolCall(message: Message): boolean {\n\treturn (\n\t\tArray.isArray(message.content) && message.content.some((part) => (part as { type?: string }).type === \"toolCall\")\n\t);\n}\n\nfunction isTerminalAssistantStop(message: Message): boolean {\n\treturn (message as { stopReason?: string }).stopReason === \"stop\" && !assistantStartsToolCall(message);\n}\n\ntype UndefinedOmitted<T extends object> = {\n\t[K in keyof T]: Exclude<T[K], undefined>;\n};\n\nfunction omitUndefinedProperties<const T extends object>(value: T): UndefinedOmitted<T> {\n\tfor (const key in value) {\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\nfunction setOptionalProperty<T extends object, K extends keyof T>(target: T, key: K, value: T[K]): void {\n\tif (value === undefined) delete target[key];\n\telse target[key] = value;\n}\n\nfunction resetStepLiveDetail(step: RunnerStatusStep): void {\n\tdelete step.currentTool;\n\tdelete step.currentToolArgs;\n\tdelete step.currentToolStartedAt;\n\tdelete step.currentPath;\n\tstep.recentTools = [];\n\tstep.recentOutput = [];\n}\n\ninterface ChildEventContext {\n\teventsPath: string;\n\trunId: string;\n\tstepIndex: number;\n\tagent: string;\n}\n\ninterface ChildUsage {\n\tinput?: number;\n\tinputTokens?: number;\n\toutput?: number;\n\toutputTokens?: number;\n\tcacheRead?: number;\n\tcacheWrite?: number;\n\tcost?: { total?: number };\n}\n\ntype ChildMessage = Message & {\n\tmodel?: string;\n\terrorMessage?: string;\n\tusage?: ChildUsage;\n};\n\ninterface ChildEvent {\n\ttype?: string;\n\tmessage?: ChildMessage;\n\ttoolName?: string;\n\targs?: Record<string, unknown>;\n\twillRetry?: unknown;\n}\n\ninterface RunPiStreamingResult {\n\tstderr: string;\n\texitCode: number | null;\n\tmessages: Message[];\n\tusage: Usage;\n\ttoolCount: number;\n\tdurationMs: number;\n\tmodel?: string;\n\terror?: string;\n\tprotocolError?: ProtocolOutputLimit;\n\tfinalOutput: string;\n\toutputState: SubagentOutputState;\n\tinterrupted?: boolean;\n\ttimedOut?: boolean;\n\tstopped?: boolean;\n\tturnBudget?: TurnBudgetState;\n\tturnBudgetExceeded?: boolean;\n\twrapUpRequested?: boolean;\n\ttoolBudget?: ToolBudgetState;\n\ttoolBudgetBlocked?: boolean;\n\tobservedMutationAttempt?: boolean;\n\twatchdog?: ChildWatchdogStateSnapshot;\n\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\tprocessInstanceId: string;\n\tprocessCloseObservedAt?: number;\n\tprocessSignal?: string | null;\n}\n\nfunction runPiStreaming(\n\targs: string[],\n\tcwd: string,\n\toutputFile: string,\n\tenv?: Record<string, string | undefined>,\n\tpiPackageRoot?: string,\n\tpiArgv1?: string,\n\tmaxSubagentDepth?: number,\n\tchildEventContext?: ChildEventContext,\n\tregisterInterrupt?: (interrupt: (() => void) | undefined) => void,\n\tonChildEvent?: (event: ChildEvent) => void,\n\ttranscriptWriter?: ChildTranscriptWriter,\n\tregisterTimeout?: (interrupt: (() => void) | undefined) => void,\n\ttimeoutMessage?: string,\n\tregisterStop?: (stop: (() => void) | undefined) => void,\n\tstopMessage?: string,\n\tregisterTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void,\n\tonWriterProcess?: (writer: { state: \"none\" | \"spawning\" } | { state: \"running\"; pid: number }) => void,\n): Promise<RunPiStreamingResult> {\n\treturn new Promise((resolve) => {\n\t\tconst startedAt = Date.now();\n\t\tconst processInstanceId = randomUUID();\n\t\tonWriterProcess?.({ state: \"spawning\" });\n\t\tconst outputStream = fs.createWriteStream(outputFile, { flags: \"w\" });\n\t\tconst spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };\n\t\tconst spawnSpec = getPiSpawnCommand(args, {\n\t\t\t...(piPackageRoot ? { piPackageRoot } : {}),\n\t\t\t...(piArgv1 ? { argv1: piArgv1 } : {}),\n\t\t});\n\t\tconst child = spawn(spawnSpec.command, spawnSpec.args, {\n\t\t\tcwd,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tenv: spawnEnv,\n\t\t\twindowsHide: true,\n\t\t});\n\t\tconst stderrTail = createBoundedByteTail();\n\t\tconst rawStdoutTail = createBoundedByteTail();\n\t\tconst messages: Message[] = [];\n\t\tconst usage = emptyUsage();\n\t\tlet model: string | undefined;\n\t\tlet writerRegistrationError: string | undefined;\n\t\tif (typeof child.pid === \"number\") {\n\t\t\ttry {\n\t\t\t\tonWriterProcess?.({ state: \"running\", pid: child.pid });\n\t\t\t} catch (writerError) {\n\t\t\t\twriterRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`;\n\t\t\t\ttrySignalChild(child, \"SIGKILL\");\n\t\t\t}\n\t\t}\n\t\tlet error: string | undefined = writerRegistrationError;\n\t\tlet assistantError: string | undefined;\n\t\tlet interrupted = false;\n\t\tlet timedOut = false;\n\t\tlet stopped = false;\n\t\tlet turnBudgetExceeded = false;\n\t\tlet turnBudgetMessage: string | undefined;\n\t\tlet turnBudget: TurnBudgetState | undefined;\n\t\tlet observedMutationAttempt = false;\n\t\tlet toolCount = 0;\n\t\tconst childWatchdogConfig = decodeChildWatchdogConfig(env?.[CHILD_WATCHDOG_CONFIG_ENV]);\n\t\tlet childWatchdogState: ChildWatchdogStateSnapshot | undefined;\n\t\tlet applyChildLifecycle = (_action: ChildLifecycleAction): void => {};\n\t\tconst updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {\n\t\t\tchildWatchdogState = snapshot;\n\t\t};\n\n\t\tconst writeOutputLine = (line: string) => {\n\t\t\tif (!line.trim()) return;\n\t\t\toutputStream.write(`${line}\\n`);\n\t\t};\n\n\t\tconst writeOutputText = (text: string) => {\n\t\t\tfor (const line of text.split(\"\\n\")) {\n\t\t\t\twriteOutputLine(line);\n\t\t\t}\n\t\t};\n\n\t\tconst appendChildEvent = (event: Record<string, unknown>) => {\n\t\t\tif (!childEventContext) return;\n\t\t\tif (!shouldPersistChildEvent(event)) return;\n\t\t\tappendDiagnosticJsonl(\n\t\t\t\tchildEventContext.eventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\t...event,\n\t\t\t\t\tsubagentSource: \"child\",\n\t\t\t\t\tsubagentRunId: childEventContext.runId,\n\t\t\t\t\tsubagentStepIndex: childEventContext.stepIndex,\n\t\t\t\t\tsubagentAgent: childEventContext.agent,\n\t\t\t\t\tobservedAt: Date.now(),\n\t\t\t\t}),\n\t\t\t\ttypeof event.type === \"string\" ? event.type : undefined,\n\t\t\t);\n\t\t};\n\n\t\tconst appendChildLine = (type: \"subagent.child.stdout\" | \"subagent.child.stderr\", line: string) => {\n\t\t\tappendChildEvent({ type, line });\n\t\t\tif (type === \"subagent.child.stdout\") transcriptWriter?.writeStdoutLine(line);\n\t\t\telse transcriptWriter?.writeStderrLine(line);\n\t\t};\n\n\t\tconst processStdoutLine = (line: string) => {\n\t\t\tif (!line.trim()) return;\n\t\t\tlet event: ChildEvent;\n\t\t\ttry {\n\t\t\t\tevent = JSON.parse(line) as ChildEvent;\n\t\t\t} catch {\n\t\t\t\trawStdoutTail.push(`${line}\\n`);\n\t\t\t\twriteOutputLine(line);\n\t\t\t\tappendChildLine(\"subagent.child.stdout\", line);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tappendChildEvent(event as unknown as Record<string, unknown>);\n\t\t\ttranscriptWriter?.writeChildEvent(event);\n\t\t\tif (event.type === \"agent_settled\") agentSettledReceived = true;\n\t\t\tapplyChildLifecycle(projectChildLifecycle(event));\n\n\t\t\tif (isChildWatchdogStatusEvent(event)) {\n\t\t\t\tif (!childWatchdogConfig) return;\n\t\t\t\tconst next = acceptChildWatchdogEvent({\n\t\t\t\t\tcurrent: childWatchdogState,\n\t\t\t\t\tevent,\n\t\t\t\t\t...(childEventContext\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\trunId: childEventContext.runId,\n\t\t\t\t\t\t\t\tagent: childEventContext.agent,\n\t\t\t\t\t\t\t\tchildIndex: childEventContext.stepIndex,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\tif (!next) return;\n\t\t\t\tupdateChildWatchdogState(next);\n\t\t\t\tonChildEvent?.(event);\n\t\t\t\tif (childWatchdogIsActive(next)) {\n\t\t\t\t\tif (finalDrainTimer) {\n\t\t\t\t\t\tclearTimeout(finalDrainTimer);\n\t\t\t\t\t\tfinalDrainTimer = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tif (finalHardKillTimer) {\n\t\t\t\t\t\tclearTimeout(finalHardKillTimer);\n\t\t\t\t\t\tfinalHardKillTimer = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tarmWatchdogTail();\n\t\t\t\t} else {\n\t\t\t\t\tclearWatchdogTailTimer();\n\t\t\t\t\tif (cleanTerminalAssistantStopReceived || agentSettledReceived) startFinalDrain();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tonChildEvent?.(event);\n\n\t\t\tif (event.type === \"tool_execution_start\" && event.toolName) {\n\t\t\t\ttoolCount += 1;\n\t\t\t\tobservedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);\n\t\t\t\tconst toolArgs = extractToolArgsPreview(event.args ?? {});\n\t\t\t\twriteOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ((event.type === \"message_end\" || event.type === \"tool_result_end\") && event.message) {\n\t\t\t\tmessages.push(event.message);\n\t\t\t\tconst text = extractTextFromContent(event.message.content);\n\t\t\t\tif (text) writeOutputText(text);\n\n\t\t\t\tif (event.type !== \"message_end\" || event.message.role !== \"assistant\") return;\n\t\t\t\tif (event.message.model) model = event.message.model;\n\t\t\t\tif (event.message.errorMessage) assistantError = event.message.errorMessage;\n\t\t\t\tconst eventUsage = event.message.usage;\n\t\t\t\tif (eventUsage) {\n\t\t\t\t\tusage.turns++;\n\t\t\t\t\tusage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;\n\t\t\t\t\tusage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;\n\t\t\t\t\tusage.cacheRead += eventUsage.cacheRead ?? 0;\n\t\t\t\t\tusage.cacheWrite += eventUsage.cacheWrite ?? 0;\n\t\t\t\t\tusage.cost += eventUsage.cost?.total ?? 0;\n\t\t\t\t}\n\t\t\t\tif (isTerminalAssistantStop(event.message)) {\n\t\t\t\t\tif (!event.message.errorMessage && extractTextFromContent(event.message.content).trim())\n\t\t\t\t\t\tassistantError = undefined;\n\t\t\t\t\tcleanTerminalAssistantStopReceived ||= !event.message.errorMessage;\n\t\t\t\t\tapplyChildLifecycle(projectChildLifecycle(event, true));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Guard both cases that can leave the parent waiting on `close` forever:\n\t\t// a lingering stdio holder after `exit`, or a child that never exits.\n\t\tconst FINAL_STOP_GRACE_MS = 1000;\n\t\tconst HARD_KILL_MS = 3000;\n\t\tconst TIMEOUT_HARD_KILL_MS = 3000;\n\t\tlet childExited = false;\n\t\tlet forcedTerminationSignal = false;\n\t\tlet cleanTerminalAssistantStopReceived = false;\n\t\tlet agentSettledReceived = false;\n\t\tlet finalDrainTimer: NodeJS.Timeout | undefined;\n\t\tlet finalHardKillTimer: NodeJS.Timeout | undefined;\n\t\tlet watchdogTailTimer: NodeJS.Timeout | undefined;\n\t\tlet timeoutHardKillTimer: NodeJS.Timeout | undefined;\n\t\tlet turnBudgetTerminationTimer: NodeJS.Timeout | undefined;\n\t\tlet turnBudgetHardKillTimer: NodeJS.Timeout | undefined;\n\t\tlet protocolHardKillTimer: NodeJS.Timeout | undefined;\n\t\tlet protocolError: ProtocolOutputLimit | undefined;\n\t\tlet settled = false;\n\t\tapplyChildLifecycle = (action: ChildLifecycleAction): void => {\n\t\t\tif (action === \"cancel-drain\") {\n\t\t\t\tif (finalDrainTimer) {\n\t\t\t\t\tclearTimeout(finalDrainTimer);\n\t\t\t\t\tfinalDrainTimer = undefined;\n\t\t\t\t}\n\t\t\t\tif (finalHardKillTimer) {\n\t\t\t\t\tclearTimeout(finalHardKillTimer);\n\t\t\t\t\tfinalHardKillTimer = undefined;\n\t\t\t\t}\n\t\t\t\tclearWatchdogTailTimer();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action === \"start-drain\") startFinalDrain();\n\t\t};\n\t\tconst failProtocol = (limit: ProtocolOutputLimit): void => {\n\t\t\tif (protocolError) return;\n\t\t\tprotocolError = limit;\n\t\t\terror = formatProtocolOutputLimit(limit);\n\t\t\tif (!childExited) {\n\t\t\t\ttrySignalChild(child, \"SIGTERM\");\n\t\t\t\tprotocolHardKillTimer = setTimeout(() => {\n\t\t\t\t\tif (!settled) trySignalChild(child, \"SIGKILL\");\n\t\t\t\t}, 3000);\n\t\t\t\tprotocolHardKillTimer.unref?.();\n\t\t\t}\n\t\t};\n\t\tconst stdoutReader = createBoundedLineReader({\n\t\t\toversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,\n\t\t\tonLine: processStdoutLine,\n\t\t\tonLimit: failProtocol,\n\t\t});\n\t\tconst stderrReader = createBoundedLineReader({\n\t\t\tstream: \"stderr\",\n\t\t\tmaxPendingLineBytes: MAX_CHILD_STDERR_BYTES,\n\t\t\tonLine: (line) => appendChildLine(\"subagent.child.stderr\", line),\n\t\t\tonLimit: (limit) => appendChildLine(\"subagent.child.stderr\", formatProtocolOutputLimit(limit)),\n\t\t});\n\t\tconst clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });\n\t\tchild.stdout.on(\"data\", (chunk: Buffer) => stdoutReader.push(chunk));\n\t\tchild.stderr.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrTail.push(chunk);\n\t\t\tstderrReader.push(chunk);\n\t\t\toutputStream.write(chunk);\n\t\t});\n\t\tregisterInterrupt?.(() => {\n\t\t\tif (settled || timedOut || stopped) return;\n\t\t\tinterrupted = true;\n\t\t\tif (!error) error = \"Interrupted. Waiting for explicit next action.\";\n\t\t\ttrySignalChild(child, \"SIGINT\");\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (!settled && !timedOut && !stopped) trySignalChild(child, \"SIGTERM\");\n\t\t\t}, 1000).unref?.();\n\t\t});\n\t\tregisterTimeout?.(() => {\n\t\t\tif (settled || timedOut || stopped) return;\n\t\t\ttimedOut = true;\n\t\t\tinterrupted = false;\n\t\t\terror = timeoutMessage ?? \"Subagent timed out.\";\n\t\t\ttrySignalChild(child, \"SIGTERM\");\n\t\t\ttimeoutHardKillTimer = setTimeout(() => {\n\t\t\t\tif (!settled) trySignalChild(child, \"SIGKILL\");\n\t\t\t}, TIMEOUT_HARD_KILL_MS);\n\t\t\ttimeoutHardKillTimer.unref?.();\n\t\t});\n\t\tregisterStop?.(() => {\n\t\t\tif (settled || timedOut || stopped) return;\n\t\t\tstopped = true;\n\t\t\tinterrupted = false;\n\t\t\terror = stopMessage ?? \"Subagent stopped by user.\";\n\t\t\ttrySignalChild(child, \"SIGTERM\");\n\t\t\ttimeoutHardKillTimer = setTimeout(() => {\n\t\t\t\tif (!settled) trySignalChild(child, \"SIGKILL\");\n\t\t\t}, TIMEOUT_HARD_KILL_MS);\n\t\t\ttimeoutHardKillTimer.unref?.();\n\t\t});\n\t\tregisterTurnBudgetAbort?.((message, state) => {\n\t\t\tif (settled || timedOut || stopped || turnBudgetExceeded) return;\n\t\t\tturnBudgetExceeded = true;\n\t\t\tturnBudgetMessage = message;\n\t\t\tturnBudget = state;\n\t\t\tinterrupted = false;\n\t\t\terror = message;\n\t\t\ttrySignalChild(child, \"SIGINT\");\n\t\t\tturnBudgetTerminationTimer = setTimeout(() => {\n\t\t\t\tif (!settled && !timedOut && !stopped) trySignalChild(child, \"SIGTERM\");\n\t\t\t}, 1000);\n\t\t\tturnBudgetTerminationTimer.unref?.();\n\t\t\tturnBudgetHardKillTimer = setTimeout(() => {\n\t\t\t\tif (!settled && !timedOut && !stopped) trySignalChild(child, \"SIGKILL\");\n\t\t\t}, 4000);\n\t\t\tturnBudgetHardKillTimer.unref?.();\n\t\t});\n\t\tconst clearDrainTimers = () => {\n\t\t\tif (finalDrainTimer) {\n\t\t\t\tclearTimeout(finalDrainTimer);\n\t\t\t\tfinalDrainTimer = undefined;\n\t\t\t}\n\t\t\tif (finalHardKillTimer) {\n\t\t\t\tclearTimeout(finalHardKillTimer);\n\t\t\t\tfinalHardKillTimer = undefined;\n\t\t\t}\n\t\t\tclearWatchdogTailTimer();\n\t\t\tif (timeoutHardKillTimer) {\n\t\t\t\tclearTimeout(timeoutHardKillTimer);\n\t\t\t\ttimeoutHardKillTimer = undefined;\n\t\t\t}\n\t\t\tif (turnBudgetTerminationTimer) {\n\t\t\t\tclearTimeout(turnBudgetTerminationTimer);\n\t\t\t\tturnBudgetTerminationTimer = undefined;\n\t\t\t}\n\t\t\tif (turnBudgetHardKillTimer) {\n\t\t\t\tclearTimeout(turnBudgetHardKillTimer);\n\t\t\t\tturnBudgetHardKillTimer = undefined;\n\t\t\t}\n\t\t\tif (protocolHardKillTimer) {\n\t\t\t\tclearTimeout(protocolHardKillTimer);\n\t\t\t\tprotocolHardKillTimer = undefined;\n\t\t\t}\n\t\t};\n\t\tfunction startFinalDrain(): void {\n\t\t\tif (childWatchdogIsActive(childWatchdogState)) {\n\t\t\t\tarmWatchdogTail();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (childExited || finalDrainTimer || settled) return;\n\t\t\tfinalDrainTimer = setTimeout(() => {\n\t\t\t\tif (settled) return;\n\t\t\t\tconst termSent = trySignalChild(child, \"SIGTERM\");\n\t\t\t\tif (!termSent) return;\n\t\t\t\tforcedTerminationSignal = true;\n\t\t\t\tif (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {\n\t\t\t\t\terror = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;\n\t\t\t\t}\n\t\t\t\tfinalHardKillTimer = setTimeout(() => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tforcedTerminationSignal = trySignalChild(child, \"SIGKILL\") || forcedTerminationSignal;\n\t\t\t\t}, HARD_KILL_MS);\n\t\t\t\tfinalHardKillTimer.unref?.();\n\t\t\t}, FINAL_STOP_GRACE_MS);\n\t\t\tfinalDrainTimer.unref?.();\n\t\t}\n\t\tfunction clearWatchdogTailTimer(): void {\n\t\t\tif (watchdogTailTimer) {\n\t\t\t\tclearTimeout(watchdogTailTimer);\n\t\t\t\twatchdogTailTimer = undefined;\n\t\t\t}\n\t\t}\n\t\tfunction armWatchdogTail(): void {\n\t\t\tif ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || settled) return;\n\t\t\twatchdogTailTimer = setTimeout(() => {\n\t\t\t\twatchdogTailTimer = undefined;\n\t\t\t\tupdateChildWatchdogState({\n\t\t\t\t\tphase: \"stale\",\n\t\t\t\t\tseq: (childWatchdogState?.seq ?? 0) + 1,\n\t\t\t\t\tlastUpdate: Date.now(),\n\t\t\t\t\tfollowUpPending: false,\n\t\t\t\t\treason: \"child watchdog tail timeout\",\n\t\t\t\t\ttimedOut: true,\n\t\t\t\t});\n\t\t\t\tstartFinalDrain();\n\t\t\t}, childWatchdogConfig?.watchdogTailTimeoutMs ?? 120_000);\n\t\t\twatchdogTailTimer.unref?.();\n\t\t}\n\t\tchild.on(\"exit\", () => {\n\t\t\tchildExited = true;\n\t\t\tclearDrainTimers();\n\t\t});\n\t\tchild.on(\"close\", (exitCode, signal) => {\n\t\t\tsettled = true;\n\t\t\tconst processCloseObservedAt = Date.now();\n\t\t\ttry {\n\t\t\t\tonWriterProcess?.({ state: \"none\" });\n\t\t\t} catch {\n\t\t\t\t// The runner still owns and releases the lease during finalization.\n\t\t\t}\n\t\t\tregisterInterrupt?.(undefined);\n\t\t\tregisterTimeout?.(undefined);\n\t\t\tregisterStop?.(undefined);\n\t\t\tregisterTurnBudgetAbort?.(undefined);\n\t\t\tclearDrainTimers();\n\t\t\tclearStdioGuard();\n\t\t\tstdoutReader.end();\n\t\t\tstderrReader.end();\n\t\t\toutputStream.end();\n\t\t\tconst stderr = stderrTail.text();\n\t\t\tconst finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();\n\t\t\tconst finalError = error ?? assistantError;\n\t\t\tconst forcedDrainAfterFinalSuccess =\n\t\t\t\tBoolean(forcedTerminationSignal || signal) &&\n\t\t\t\t(cleanTerminalAssistantStopReceived || agentSettledReceived) &&\n\t\t\t\t!finalError;\n\t\t\tconst signalError = isUnexplainedProcessSignal({\n\t\t\t\tprocessSignal: signal,\n\t\t\t\tinterrupted,\n\t\t\t\ttimedOut,\n\t\t\t\tstopped,\n\t\t\t\tturnBudgetExceeded,\n\t\t\t\tforcedDrainAfterFinalSuccess,\n\t\t\t})\n\t\t\t\t? formatProcessSignalError(signal!)\n\t\t\t\t: undefined;\n\t\t\tresolve(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tstderr,\n\t\t\t\t\texitCode:\n\t\t\t\t\t\ttimedOut || stopped\n\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: interrupted || forcedDrainAfterFinalSuccess\n\t\t\t\t\t\t\t\t\t? 0\n\t\t\t\t\t\t\t\t\t: forcedTerminationSignal || signal\n\t\t\t\t\t\t\t\t\t\t? (exitCode ?? 1)\n\t\t\t\t\t\t\t\t\t\t: exitCode,\n\t\t\t\t\tmessages,\n\t\t\t\t\tusage,\n\t\t\t\t\ttoolCount,\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\tmodel,\n\t\t\t\t\terror: stopped\n\t\t\t\t\t\t? (stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t\t\t\t? turnBudgetMessage\n\t\t\t\t\t\t\t\t: interrupted || forcedDrainAfterFinalSuccess\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: (finalError ?? signalError),\n\t\t\t\t\tprotocolError,\n\t\t\t\t\tfinalOutput:\n\t\t\t\t\t\t(timedOut || stopped) && !finalOutput.trim()\n\t\t\t\t\t\t\t? stopped\n\t\t\t\t\t\t\t\t? (stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t\t\t\t\t: (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: finalOutput,\n\t\t\t\t\toutputState: finalOutput.trim() ? \"present\" : \"absent\",\n\t\t\t\t\tinterrupted,\n\t\t\t\t\ttimedOut,\n\t\t\t\t\tstopped,\n\t\t\t\t\tturnBudget,\n\t\t\t\t\tturnBudgetExceeded,\n\t\t\t\t\twrapUpRequested:\n\t\t\t\t\t\tturnBudget?.outcome === \"wrap-up-requested\" ||\n\t\t\t\t\t\tturnBudget?.outcome === \"termination-deferred\" ||\n\t\t\t\t\t\tturnBudgetExceeded ||\n\t\t\t\t\t\tundefined,\n\t\t\t\t\tobservedMutationAttempt,\n\t\t\t\t\twatchdog: childWatchdogState,\n\t\t\t\t\tprocessInstanceId,\n\t\t\t\t\tprocessCloseObservedAt,\n\t\t\t\t\tprocessSignal: signal,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\n\t\tchild.on(\"error\", (spawnError) => {\n\t\t\tsettled = true;\n\t\t\ttry {\n\t\t\t\tonWriterProcess?.({ state: \"none\" });\n\t\t\t} catch {\n\t\t\t\t// The runner still owns and releases the lease during finalization.\n\t\t\t}\n\t\t\tregisterInterrupt?.(undefined);\n\t\t\tregisterTimeout?.(undefined);\n\t\t\tregisterStop?.(undefined);\n\t\t\tregisterTurnBudgetAbort?.(undefined);\n\t\t\tclearDrainTimers();\n\t\t\tclearStdioGuard();\n\t\t\tstdoutReader.end();\n\t\t\tstderrReader.end();\n\t\t\toutputStream.end();\n\t\t\tconst stderr = stderrTail.text();\n\t\t\tconst finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();\n\t\t\tconst spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);\n\t\t\tresolve(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tstderr,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\tmessages,\n\t\t\t\t\tusage,\n\t\t\t\t\ttoolCount,\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\tmodel,\n\t\t\t\t\terror: stopped\n\t\t\t\t\t\t? (stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t\t\t\t? turnBudgetMessage\n\t\t\t\t\t\t\t\t: (error ?? assistantError ?? spawnErrorMessage),\n\t\t\t\t\tprotocolError,\n\t\t\t\t\tfinalOutput:\n\t\t\t\t\t\t(timedOut || stopped) && !finalOutput.trim()\n\t\t\t\t\t\t\t? stopped\n\t\t\t\t\t\t\t\t? (stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t\t\t\t\t: (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: finalOutput,\n\t\t\t\t\toutputState: finalOutput.trim() ? \"present\" : \"absent\",\n\t\t\t\t\ttimedOut,\n\t\t\t\t\tstopped,\n\t\t\t\t\tturnBudget,\n\t\t\t\t\tturnBudgetExceeded,\n\t\t\t\t\twrapUpRequested:\n\t\t\t\t\t\tturnBudget?.outcome === \"wrap-up-requested\" ||\n\t\t\t\t\t\tturnBudget?.outcome === \"termination-deferred\" ||\n\t\t\t\t\t\tturnBudgetExceeded ||\n\t\t\t\t\t\tundefined,\n\t\t\t\t\tobservedMutationAttempt,\n\t\t\t\t\twatchdog: childWatchdogState,\n\t\t\t\t\tprocessInstanceId,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\t});\n}\n\nfunction resolvePiPackageRootFallback(): string {\n\tconst root = resolveInstalledPiPackageRoot();\n\tif (root) return root;\n\tthrow new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);\n}\n\nasync function exportSessionHtml(sessionFile: string, outputDir: string, piPackageRoot?: string): Promise<string> {\n\tconst pkgRoot = piPackageRoot ?? resolvePiPackageRootFallback();\n\tconst exportModulePath = path.join(pkgRoot, \"dist\", \"core\", \"export-html\", \"index.js\");\n\tconst moduleUrl = pathToFileURL(exportModulePath).href;\n\tconst mod = await import(moduleUrl);\n\tconst exportFromFile = (mod as { exportFromFile?: (inputPath: string, options?: { outputPath?: string }) => string })\n\t\t.exportFromFile;\n\tif (typeof exportFromFile !== \"function\") {\n\t\tthrow new Error(\"exportFromFile not available\");\n\t}\n\tconst outputPath = path.join(outputDir, `${path.basename(sessionFile, \".jsonl\")}.html`);\n\treturn exportFromFile(sessionFile, { outputPath });\n}\n\nfunction createShareLink(htmlPath: string): { shareUrl: string; gistUrl: string } | { error: string } {\n\ttry {\n\t\tconst auth = spawnSync(\"gh\", [\"auth\", \"status\"], { encoding: \"utf-8\" });\n\t\tif (auth.status !== 0) {\n\t\t\treturn { error: \"GitHub CLI is not logged in. Run 'gh auth login' first.\" };\n\t\t}\n\t} catch {\n\t\treturn { error: \"GitHub CLI (gh) is not installed.\" };\n\t}\n\n\ttry {\n\t\tconst result = spawnSync(\"gh\", [\"gist\", \"create\", htmlPath], { encoding: \"utf-8\" });\n\t\tif (result.status !== 0) {\n\t\t\tconst err = (result.stderr || \"\").trim() || \"Failed to create gist.\";\n\t\t\treturn { error: err };\n\t\t}\n\t\tconst gistUrl = (result.stdout || \"\").trim();\n\t\tconst gistId = gistUrl.split(\"/\").pop();\n\t\tif (!gistId) return { error: \"Failed to parse gist ID.\" };\n\t\tconst shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;\n\t\treturn { shareUrl, gistUrl };\n\t} catch (err) {\n\t\treturn { error: String(err) };\n\t}\n}\n\nfunction formatDuration(ms: number): string {\n\tif (ms < 1000) return `${ms}ms`;\n\tif (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n\tconst minutes = Math.floor(ms / 60000);\n\tconst seconds = Math.floor((ms % 60000) / 1000);\n\treturn `${minutes}m${seconds}s`;\n}\n\nfunction writeRunLog(\n\tlogPath: string,\n\tinput: {\n\t\tid: string;\n\t\tmode: SubagentRunMode;\n\t\tcwd: string;\n\t\tstartedAt: number;\n\t\tendedAt: number;\n\t\tsteps: Array<{\n\t\t\tagent: string;\n\t\t\tstatus: string;\n\t\t\tdurationMs?: number;\n\t\t}>;\n\t\tsummary: string;\n\t\ttruncated: boolean;\n\t\tartifactsDir?: string;\n\t\tsessionFile?: string;\n\t\tshareUrl?: string;\n\t\tshareError?: string;\n\t},\n): void {\n\tconst lines: string[] = [];\n\tlines.push(`# Subagent run ${input.id}`);\n\tlines.push(\"\");\n\tlines.push(`- **Mode:** ${input.mode}`);\n\tlines.push(`- **CWD:** ${input.cwd}`);\n\tlines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);\n\tlines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);\n\tlines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);\n\tif (input.sessionFile) lines.push(`- **Session:** ${input.sessionFile}`);\n\tif (input.shareUrl) lines.push(`- **Share:** ${input.shareUrl}`);\n\tif (input.shareError) lines.push(`- **Share error:** ${input.shareError}`);\n\tif (input.artifactsDir) lines.push(`- **Artifacts:** ${input.artifactsDir}`);\n\tlines.push(\"\");\n\tlines.push(\"## Steps\");\n\tlines.push(\"| Step | Agent | Status | Duration |\");\n\tlines.push(\"| --- | --- | --- | --- |\");\n\tinput.steps.forEach((step, i) => {\n\t\tconst duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : \"-\";\n\t\tlines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);\n\t});\n\tlines.push(\"\");\n\tlines.push(\"## Summary\");\n\tif (input.truncated) {\n\t\tlines.push(\"_Output truncated_\");\n\t\tlines.push(\"\");\n\t}\n\tlines.push(input.summary.trim() || \"(no output)\");\n\tlines.push(\"\");\n\tfs.writeFileSync(logPath, lines.join(\"\\n\"), \"utf-8\");\n}\n\n/** Context for running a single step */\ninterface SingleStepContext {\n\tpreviousOutput: string;\n\toutputs?: ChainOutputMap;\n\tplaceholder: string;\n\tcwd: string;\n\tsessionEnabled: boolean;\n\tsessionDir?: string;\n\tartifactsDir?: string;\n\tartifactConfig?: Partial<ArtifactConfig>;\n\tid: string;\n\tflatIndex: number;\n\tflatStepCount: number;\n\toutputFile: string;\n\tsteerInboxDir?: string;\n\tsteerCapabilityPath?: string;\n\tsteerAckDir?: string;\n\ttranscriptPath?: string;\n\tpiPackageRoot?: string;\n\tpiArgv1?: string;\n\tregisterInterrupt?: (interrupt: (() => void) | undefined) => void;\n\tregisterTimeout?: (interrupt: (() => void) | undefined) => void;\n\tregisterStop?: (stop: (() => void) | undefined) => void;\n\tregisterTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void;\n\ttimeoutSignal?: AbortSignal;\n\tstopSignal?: AbortSignal;\n\ttimeoutMessage?: string;\n\tstopMessage?: string;\n\tturnBudget?: ResolvedTurnBudget;\n\tchildIntercomTarget?: string;\n\torchestratorIntercomTarget?: string;\n\tnestedRoute?: NestedRouteInfo;\n\tcapabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n\tonAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;\n\tonChildEvent?: (event: ChildEvent) => void;\n\tonWriterProcess?: (writer: { state: \"none\" | \"spawning\" } | { state: \"running\"; pid: number }) => void;\n\tonExternalProcess?: (process: ExternalProcessStatus) => void;\n\tskipAcceptance?: () => boolean;\n}\n\n/** Run a single pi agent step, returning output and metadata */\nasync function runSingleStep(\n\tstep: SubagentStep,\n\tctx: SingleStepContext,\n): Promise<StepResult & { completionGuardTriggered?: boolean }> {\n\tif (step.importAsyncRoot) {\n\t\tlet importTimedOut = false;\n\t\tlet importStopped = false;\n\t\tctx.registerTimeout?.(() => {\n\t\t\timportTimedOut = true;\n\t\t\tlet pid: number | undefined;\n\t\t\ttry {\n\t\t\t\tpid = readStatus(step.importAsyncRoot!.asyncDir)?.pid;\n\t\t\t} catch {\n\t\t\t\tpid = undefined;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdeliverTimeoutRequest(\n\t\t\t\t\tomitUndefinedProperties({ asyncDir: step.importAsyncRoot!.asyncDir, pid, source: \"ancestor-timeout\" }),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// The parent runner's own timeout result is authoritative for the attached step.\n\t\t\t}\n\t\t});\n\t\tctx.registerStop?.(() => {\n\t\t\timportStopped = true;\n\t\t\tlet pid: number | undefined;\n\t\t\ttry {\n\t\t\t\tpid = readStatus(step.importAsyncRoot!.asyncDir)?.pid;\n\t\t\t} catch {\n\t\t\t\tpid = undefined;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdeliverStopRequest(\n\t\t\t\t\tomitUndefinedProperties({ asyncDir: step.importAsyncRoot!.asyncDir, pid, source: \"ancestor-stop\" }),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// The parent runner's own stopped result is authoritative for the attached step.\n\t\t\t}\n\t\t});\n\t\ttry {\n\t\t\tconst imported = await waitForImportedAsyncRoot(\n\t\t\t\tstep.importAsyncRoot,\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tshouldAbort: () =>\n\t\t\t\t\t\timportTimedOut ||\n\t\t\t\t\t\timportStopped ||\n\t\t\t\t\t\tctx.timeoutSignal?.aborted === true ||\n\t\t\t\t\t\tctx.stopSignal?.aborted === true ||\n\t\t\t\t\t\tctx.skipAcceptance?.() === true,\n\t\t\t\t\ttimeoutMessage: importStopped || ctx.stopSignal?.aborted === true ? ctx.stopMessage : ctx.timeoutMessage,\n\t\t\t\t}),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tfs.writeFileSync(ctx.outputFile, imported.output, \"utf-8\");\n\t\t\t} catch {\n\t\t\t\t// Output files are observability only for imported roots.\n\t\t\t}\n\t\t\tconst stopped = importStopped || imported.stopped === true || ctx.stopSignal?.aborted === true;\n\t\t\tconst timedOut =\n\t\t\t\t!stopped &&\n\t\t\t\t(importTimedOut ||\n\t\t\t\t\timported.timedOut === true ||\n\t\t\t\t\tctx.timeoutSignal?.aborted === true ||\n\t\t\t\t\tctx.skipAcceptance?.() === true);\n\t\t\tconst message = stopped\n\t\t\t\t? (ctx.stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t: (ctx.timeoutMessage ?? \"Subagent timed out.\");\n\t\t\treturn omitUndefinedProperties({\n\t\t\t\tagent: imported.agent,\n\t\t\t\toutput: timedOut || stopped ? message : imported.output,\n\t\t\t\texitCode: timedOut || stopped ? 1 : imported.exitCode,\n\t\t\t\terror: timedOut || stopped ? message : imported.error,\n\t\t\t\ttimedOut: timedOut ? true : undefined,\n\t\t\t\tstopped: stopped ? true : undefined,\n\t\t\t\tsessionFile: imported.sessionFile,\n\t\t\t\tintercomTarget: imported.intercomTarget,\n\t\t\t\tmodel: imported.model,\n\t\t\t\tattemptedModels: imported.attemptedModels,\n\t\t\t\tmodelAttempts: imported.modelAttempts,\n\t\t\t\ttotalCost: imported.totalCost,\n\t\t\t\tstructuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,\n\t\t\t\tstructuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,\n\t\t\t\tstructuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,\n\t\t\t\tacceptance: timedOut || stopped ? undefined : imported.acceptance,\n\t\t\t});\n\t\t} finally {\n\t\t\tctx.registerTimeout?.(undefined);\n\t\t\tctx.registerStop?.(undefined);\n\t\t}\n\t}\n\n\tconst effectiveStructuredOutput =\n\t\tstep.structuredOutput ??\n\t\t(step.structuredOutputSchema\n\t\t\t? createStructuredOutputRuntime(\n\t\t\t\t\tstep.structuredOutputSchema,\n\t\t\t\t\tpath.join(path.dirname(ctx.outputFile), \"structured-output\"),\n\t\t\t\t)\n\t\t\t: undefined);\n\tconst placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), \"g\");\n\tlet task = step.task.replace(placeholderRegex, () => ctx.previousOutput);\n\tif (ctx.outputs) task = resolveOutputReferences(task, ctx.outputs);\n\tconst taskForCompletionGuard = task;\n\tif (step.effectiveAcceptance) {\n\t\tconst acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, {\n\t\t\treportOptional: isAgentContractV1(step.agentContract),\n\t\t});\n\t\tif (acceptancePrompt) task = `${task}\\n${acceptancePrompt}`;\n\t}\n\tconst sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;\n\tconst sessionDir = step.sessionFile ? undefined : ctx.sessionDir;\n\n\tlet artifactPaths: ArtifactPaths | undefined;\n\tlet transcriptWriter: ChildTranscriptWriter | undefined;\n\tif (ctx.artifactsDir && ctx.artifactConfig?.enabled !== false) {\n\t\tconst index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;\n\t\tartifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);\n\t\tfs.mkdirSync(ctx.artifactsDir, { recursive: true });\n\t\tif (ctx.artifactConfig?.includeInput !== false) {\n\t\t\tfs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\\n\\n${task}`, \"utf-8\");\n\t\t}\n\t\tif (ctx.artifactConfig?.includeTranscript !== false) {\n\t\t\ttranscriptWriter = createChildTranscriptWriter({\n\t\t\t\ttranscriptPath: artifactPaths.transcriptPath,\n\t\t\t\tsource: \"async\",\n\t\t\t\trunId: ctx.id,\n\t\t\t\tagent: step.agent,\n\t\t\t\tchildIndex: ctx.flatIndex,\n\t\t\t\tcwd: step.cwd ?? ctx.cwd,\n\t\t\t});\n\t\t}\n\t}\n\ttranscriptWriter?.writeInitialUserMessage(task);\n\n\tif (step.runner?.type === \"external-cli\") {\n\t\tconst runner: ExternalCliRunnerStatus = {\n\t\t\ttype: \"external-cli\",\n\t\t\tcommand: step.runner.command,\n\t\t\targs: step.runner.args ?? [],\n\t\t\tpromptDelivery: step.runner.promptDelivery ?? \"stdin\",\n\t\t\t...(step.runner.retry ? { retry: step.runner.retry } : {}),\n\t\t\tcapabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },\n\t\t};\n\t\tconst outputSnapshot = captureSingleOutputSnapshot(step.outputPath);\n\t\tconst external = await new ExternalCliRunner(step.runner).run({\n\t\t\tcommand: runner.command,\n\t\t\targs: runner.args,\n\t\t\tcwd: step.cwd ?? ctx.cwd,\n\t\t\tprompt: buildExternalCliPrompt(step.systemPrompt ?? \"\", task),\n\t\t\tasyncDir: path.dirname(ctx.outputFile),\n\t\t\tstepIndex: ctx.flatIndex,\n\t\t\tsignal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),\n\t\t\tregisterTimeout: ctx.registerTimeout,\n\t\t\tregisterStop: ctx.registerStop,\n\t\t\ttimeoutMessage: ctx.timeoutMessage,\n\t\t\tstopMessage: ctx.stopMessage,\n\t\t\tonProcess: ctx.onExternalProcess,\n\t\t});\n\t\ttry {\n\t\t\tfs.writeFileSync(ctx.outputFile, external.output, \"utf-8\");\n\t\t} catch {\n\t\t\t/* Observability output is best-effort. */\n\t\t}\n\t\tconst resolvedOutput =\n\t\t\tstep.outputPath && external.exitCode === 0\n\t\t\t\t? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)\n\t\t\t\t: { fullOutput: external.output };\n\t\tconst outputReference = resolvedOutput.savedPath\n\t\t\t? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput)\n\t\t\t: undefined;\n\t\tconst finalizedOutput = finalizeSingleOutput(\n\t\t\tomitUndefinedProperties({\n\t\t\t\tfullOutput: resolvedOutput.fullOutput,\n\t\t\t\toutputPath: step.outputPath,\n\t\t\t\toutputMode: step.outputMode,\n\t\t\t\texitCode: external.exitCode ?? 1,\n\t\t\t\tsavedPath: resolvedOutput.savedPath,\n\t\t\t\toutputReference,\n\t\t\t\tsaveError: resolvedOutput.saveError,\n\t\t\t}),\n\t\t);\n\t\tconst artifactErrors =\n\t\t\tartifactPaths && ctx.artifactConfig?.enabled !== false\n\t\t\t\t? persistStepArtifacts({\n\t\t\t\t\t\tartifactPaths,\n\t\t\t\t\t\tartifactConfig: ctx.artifactConfig,\n\t\t\t\t\t\toutput: formatOutputArtifactContent(\n\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\toutput: resolvedOutput.fullOutput,\n\t\t\t\t\t\t\t\terror: external.error,\n\t\t\t\t\t\t\t\tmetadataPath:\n\t\t\t\t\t\t\t\t\tctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\trunId: ctx.id,\n\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\trunner,\n\t\t\t\t\t\t\texternalProcess: external.externalProcess,\n\t\t\t\t\t\t\texitCode: external.exitCode,\n\t\t\t\t\t\t\terror: external.error,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\treturn omitUndefinedProperties({\n\t\t\tagent: step.agent,\n\t\t\tcontext: step.context,\n\t\t\toutput: finalizedOutput.displayOutput,\n\t\t\toutputState: external.output.trim() ? \"present\" : \"absent\",\n\t\t\texitCode: external.exitCode,\n\t\t\terror: external.error,\n\t\t\ttimedOut: external.timedOut,\n\t\t\tstopped: external.stopped,\n\t\t\tprocessSignal: external.processSignal,\n\t\t\tartifactPaths,\n\t\t\toutputSaveError: artifactErrors.outputSaveError,\n\t\t\tmetadataSaveError: artifactErrors.metadataSaveError,\n\t\t\trunner,\n\t\t\texternalProcess: external.externalProcess,\n\t\t});\n\t}\n\n\tconst candidates =\n\t\tstep.modelCandidates && step.modelCandidates.length > 0\n\t\t\t? step.modelCandidates\n\t\t\t: step.model\n\t\t\t\t? [step.model]\n\t\t\t\t: [undefined];\n\tconst attemptedModels: string[] = [];\n\tlet capabilityAudit: import(\"../shared/capability-ceiling.ts\").SubagentCapabilityAudit | undefined;\n\tlet launchResolvedExtensions = step.launchResolvedExtensions;\n\tconst modelAttempts: ModelAttempt[] = [];\n\tconst writerProcesses: Array<{\n\t\tprocessInstanceId: string;\n\t\tkind: \"pi-writer\";\n\t\tattempt: number;\n\t\tcloseObservedAt: number;\n\t\texitCode: number | null;\n\t\tsignal: string | null;\n\t}> = [];\n\tlet writerAttemptCount = 0;\n\tconst attemptNotes: string[] = [];\n\tconst eventsPath = path.join(path.dirname(ctx.outputFile), \"events.jsonl\");\n\tlet finalResult: RunPiStreamingResult | undefined;\n\tlet finalOutputSnapshot: SingleOutputSnapshot | undefined;\n\tlet completionGuardTriggeredFinal = false;\n\tlet turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;\n\tlet toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;\n\tlet toolBudgetBlocked = false;\n\tlet actualLaunchContractDigest = step.launchContractDigest;\n\n\tlet modelIndex = 0;\n\tlet startupAttemptIndex = 0;\n\tconst piRunner = new PiRunner((request: Parameters<typeof runPiStreaming>) => runPiStreaming(...request));\n\twhile (modelIndex < candidates.length) {\n\t\tif (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break;\n\t\tconst candidate = candidates[modelIndex];\n\t\tctx.onAttemptStart?.(\n\t\t\tomitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) }),\n\t\t);\n\t\tconst outputSnapshot = captureSingleOutputSnapshot(step.outputPath);\n\t\tif (effectiveStructuredOutput) {\n\t\t\ttry {\n\t\t\t\tif (fs.existsSync(effectiveStructuredOutput.outputPath))\n\t\t\t\t\tfs.unlinkSync(effectiveStructuredOutput.outputPath);\n\t\t\t} catch {\n\t\t\t\t// Missing/stale structured-output files are handled after the child exits.\n\t\t\t}\n\t\t}\n\t\tconst watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);\n\t\tconst childWatchdog = watchdogConfig.ok\n\t\t\t? resolveChildWatchdogConfig({\n\t\t\t\t\tconfig: watchdogConfig.config,\n\t\t\t\t\tagent: step.agent,\n\t\t\t\t\trunId: ctx.id,\n\t\t\t\t\tchildIndex: ctx.flatIndex,\n\t\t\t\t})\n\t\t\t: undefined;\n\t\tconst {\n\t\t\targs,\n\t\t\tenv,\n\t\t\ttempDir,\n\t\t\ttoolDiagnosticPath,\n\t\t\truntimeAcknowledgedExtensionsPath,\n\t\t\tcapabilityAudit: attemptCapabilityAudit,\n\t\t} = buildPiArgs(\n\t\t\tomitUndefinedProperties({\n\t\t\t\tparentSessionId: step.parentSessionId,\n\t\t\t\tbaseArgs: [\"--mode\", \"json\", \"-p\"],\n\t\t\t\ttask,\n\t\t\t\tsessionEnabled,\n\t\t\t\tsessionDir,\n\t\t\t\tsessionFile: step.sessionFile,\n\t\t\t\tmodel: candidate,\n\t\t\t\tinheritProjectContext: step.inheritProjectContext,\n\t\t\t\tinheritSkills: step.inheritSkills,\n\t\t\t\trequireReadTool: Boolean(step.skills?.length),\n\t\t\t\ttools: step.tools,\n\t\t\t\textensions: step.extensions,\n\t\t\t\tsubagentOnlyExtensions: step.subagentOnlyExtensions,\n\t\t\t\tsystemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? \"\", ctx.turnBudget),\n\t\t\t\tsystemPromptMode: step.systemPromptMode,\n\t\t\t\tmcpDirectTools: step.mcpDirectTools,\n\t\t\t\tcapabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,\n\t\t\t\tcwd: step.cwd ?? ctx.cwd,\n\t\t\t\tpromptFileStem: step.agent,\n\t\t\t\tintercomSessionName: ctx.childIntercomTarget,\n\t\t\t\torchestratorIntercomTarget: ctx.orchestratorIntercomTarget,\n\t\t\t\trunId: ctx.id,\n\t\t\t\tchildAgentName: step.agent,\n\t\t\t\tchildIndex: ctx.flatIndex,\n\t\t\t\tparentEventSink: ctx.nestedRoute?.eventSink,\n\t\t\t\tparentControlInbox: ctx.nestedRoute?.controlInbox,\n\t\t\t\tparentRootRunId: ctx.nestedRoute?.rootRunId,\n\t\t\t\tparentCapabilityToken: ctx.nestedRoute?.capabilityToken,\n\t\t\t\tsteerInboxDir: ctx.steerInboxDir,\n\t\t\t\tsteerCapabilityPath: ctx.steerCapabilityPath,\n\t\t\t\tsteerAckDir: ctx.steerAckDir,\n\t\t\t\tstructuredOutput: effectiveStructuredOutput,\n\t\t\t\ttoolBudget: step.toolBudget,\n\t\t\t\tpermissionRules: step.permissionRules,\n\t\t\t\tpermissionAuditPath:\n\t\t\t\t\tstep.permissionRules && ctx.artifactsDir\n\t\t\t\t\t\t? path.join(ctx.artifactsDir, \"permission-audit\", `${ctx.id}-${ctx.flatIndex}.jsonl`)\n\t\t\t\t\t\t: undefined,\n\t\t\t\tchildWatchdog,\n\t\t\t\twaitToolEnabled: step.waitToolEnabled,\n\t\t\t}),\n\t\t);\n\t\tif (step.definitionDigest) {\n\t\t\tconst toolPlan = resolvePiLaunchToolPlan(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\ttools: step.tools,\n\t\t\t\t\textensions: step.extensions,\n\t\t\t\t\tsubagentOnlyExtensions: step.subagentOnlyExtensions,\n\t\t\t\t\tmcpDirectTools: step.mcpDirectTools,\n\t\t\t\t\tcwd: step.cwd ?? ctx.cwd,\n\t\t\t\t\trequireReadTool: Boolean(step.skills?.length),\n\t\t\t\t\tstructuredOutput: Boolean(effectiveStructuredOutput),\n\t\t\t\t\tcapabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,\n\t\t\t\t\tinheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(\n\t\t\t\t\t\tprocess.env[SUBAGENT_CAPABILITY_CEILING_ENV],\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tlaunchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);\n\t\t\tactualLaunchContractDigest = launchBindingDigest(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tdefinitionDigest: step.definitionDigest,\n\t\t\t\t\ttask: step.launchBindingTask ?? task,\n\t\t\t\t\t...(candidate ? { model: candidate } : {}),\n\t\t\t\t\tmodelCandidates: candidates as string[],\n\t\t\t\t\t...(resolveEffectiveThinking(candidate, step.thinking)\n\t\t\t\t\t\t? { thinking: resolveEffectiveThinking(candidate, step.thinking) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tsystemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? \"\", ctx.turnBudget),\n\t\t\t\t\tsystemPromptMode: step.systemPromptMode,\n\t\t\t\t\tinheritProjectContext: step.inheritProjectContext,\n\t\t\t\t\tinheritSkills: step.inheritSkills,\n\t\t\t\t\tskills: step.skills,\n\t\t\t\t\ttools: toolPlan.effectiveToolAllowlist,\n\t\t\t\t\textensions: toolPlan.extensionArgs,\n\t\t\t\t\tmcpDirectTools: toolPlan.effectiveMcpTools,\n\t\t\t\t\t...(step.outputPath ? { outputPath: step.outputPath } : {}),\n\t\t\t\t\t...(step.outputMode ? { outputMode: step.outputMode } : {}),\n\t\t\t\t\t...(step.structuredOutputSchema ? { structuredOutputSchema: step.structuredOutputSchema } : {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tcapabilityAudit = attemptCapabilityAudit;\n\t\twriterAttemptCount += 1;\n\t\tconst run = await piRunner.run([\n\t\t\targs,\n\t\t\tstep.cwd ?? ctx.cwd,\n\t\t\tctx.outputFile,\n\t\t\tenv,\n\t\t\tctx.piPackageRoot,\n\t\t\tctx.piArgv1,\n\t\t\tstep.maxSubagentDepth,\n\t\t\t{ eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },\n\t\t\tctx.registerInterrupt,\n\t\t\tctx.onChildEvent,\n\t\t\ttranscriptWriter,\n\t\t\tctx.registerTimeout,\n\t\t\tctx.timeoutMessage,\n\t\t\tctx.registerStop,\n\t\t\tctx.stopMessage,\n\t\t\tctx.registerTurnBudgetAbort,\n\t\t\tctx.onWriterProcess,\n\t\t] as Parameters<typeof runPiStreaming>);\n\t\tif (run.processCloseObservedAt !== undefined) {\n\t\t\twriterProcesses.push({\n\t\t\t\tprocessInstanceId: run.processInstanceId,\n\t\t\t\tkind: \"pi-writer\",\n\t\t\t\tattempt: writerAttemptCount - 1,\n\t\t\t\tcloseObservedAt: run.processCloseObservedAt,\n\t\t\t\texitCode: run.exitCode,\n\t\t\t\tsignal: run.processSignal ?? null,\n\t\t\t});\n\t\t}\n\t\tif (run.turnBudget) turnBudget = run.turnBudget;\n\t\telse if (ctx.turnBudget) {\n\t\t\tconst assistantMessages = run.messages.filter((message) => message.role === \"assistant\");\n\t\t\tconst turnCount = assistantMessages.length;\n\t\t\tconst lastAssistantMessage = assistantMessages.at(-1);\n\t\t\tif (turnCount > 0 && turnCount < ctx.turnBudget.maxTurns) {\n\t\t\t\tturnBudget = { ...ctx.turnBudget, outcome: \"within-budget\", turnCount };\n\t\t\t} else if (turnCount >= ctx.turnBudget.maxTurns) {\n\t\t\t\tconst decision = turnBudgetDecision(\n\t\t\t\t\tctx.turnBudget,\n\t\t\t\t\tturnCount,\n\t\t\t\t\tlastAssistantMessage ? isTerminalAssistantStop(lastAssistantMessage) : false,\n\t\t\t\t\tlastAssistantMessage ? assistantStartsToolCall(lastAssistantMessage) : false,\n\t\t\t\t);\n\t\t\t\tturnBudget =\n\t\t\t\t\tdecision === \"defer\"\n\t\t\t\t\t\t? turnBudgetDeferredState(ctx.turnBudget, turnCount)\n\t\t\t\t\t\t: turnBudgetState(ctx.turnBudget, turnCount, decision === \"abort\");\n\t\t\t}\n\t\t}\n\t\tconst toolAvailabilityError =\n\t\t\trun.exitCode === 0 && !run.error ? readChildToolDiagnosticError(toolDiagnosticPath) : undefined;\n\t\tconst runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);\n\t\tcleanupTempDir(tempDir);\n\n\t\tconst hiddenError =\n\t\t\trun.exitCode === 0 && !run.error && !toolAvailabilityError ? detectSubagentError(run.messages) : null;\n\t\tconst missingStructuredOutput = effectiveStructuredOutput\n\t\t\t? !fs.existsSync(effectiveStructuredOutput.outputPath)\n\t\t\t: false;\n\t\tconst emptyOutputError =\n\t\t\trun.exitCode === 0 &&\n\t\t\t!run.error &&\n\t\t\t!toolAvailabilityError &&\n\t\t\t!run.finalOutput.trim() &&\n\t\t\t(!effectiveStructuredOutput || missingStructuredOutput) &&\n\t\t\t(!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))\n\t\t\t\t? \"Subagent produced no output (possible model cold-start or empty response).\"\n\t\t\t\t: undefined;\n\t\tlet structuredOutput: unknown;\n\t\tlet structuredError: string | undefined;\n\t\tif (\n\t\t\teffectiveStructuredOutput &&\n\t\t\trun.exitCode === 0 &&\n\t\t\t!run.error &&\n\t\t\t!toolAvailabilityError &&\n\t\t\t!hiddenError?.hasError &&\n\t\t\t!emptyOutputError\n\t\t) {\n\t\t\tconst structured = await readStructuredOutput({\n\t\t\t\tschema: effectiveStructuredOutput.schema,\n\t\t\t\tschemaPath: effectiveStructuredOutput.schemaPath,\n\t\t\t\toutputPath: effectiveStructuredOutput.outputPath,\n\t\t\t});\n\t\t\tif (structured.error) structuredError = structured.error;\n\t\t\telse structuredOutput = structured.value;\n\t\t}\n\t\tconst completionGuardEnabled = isAgentContractV1(step.agentContract)\n\t\t\t? step.completionGuard === true\n\t\t\t: step.completionGuard !== false;\n\t\tconst completionGuard =\n\t\t\trun.exitCode === 0 &&\n\t\t\t!run.error &&\n\t\t\t!toolAvailabilityError &&\n\t\t\t!hiddenError?.hasError &&\n\t\t\t!emptyOutputError &&\n\t\t\tcompletionGuardEnabled\n\t\t\t\t? evaluateCompletionMutationGuard(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\ttask: taskForCompletionGuard,\n\t\t\t\t\t\t\tmessages: run.messages,\n\t\t\t\t\t\t\ttools: step.tools,\n\t\t\t\t\t\t\tmcpDirectTools: step.mcpDirectTools,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tconst completionGuardTriggered = completionGuard?.triggered === true && !run.observedMutationAttempt;\n\t\tconst fileMutationEffect = completionGuard\n\t\t\t? {\n\t\t\t\t\tstatus: completionGuard.expectedMutation\n\t\t\t\t\t\t? completionGuardTriggered\n\t\t\t\t\t\t\t? (\"missing\" as const)\n\t\t\t\t\t\t\t: (\"observed\" as const)\n\t\t\t\t\t\t: (\"not-applicable\" as const),\n\t\t\t\t\texpected: completionGuard.expectedMutation,\n\t\t\t\t\tattempted: completionGuard.attemptedMutation || run.observedMutationAttempt === true,\n\t\t\t\t\t...(completionGuardTriggered\n\t\t\t\t\t\t? { message: \"Subagent completed without making edits for an implementation task.\" }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst completionGuardError =\n\t\t\tcompletionGuardTriggered && !isAgentContractV1(step.agentContract)\n\t\t\t\t? \"Subagent completed without making edits for an implementation task.\\nIt appears to have returned planning or scratchpad output instead of applying changes.\"\n\t\t\t\t: undefined;\n\t\tconst effectiveExitCode =\n\t\t\ttoolAvailabilityError ||\n\t\t\t(completionGuardTriggered && !isAgentContractV1(step.agentContract)) ||\n\t\t\tstructuredError ||\n\t\t\temptyOutputError\n\t\t\t\t? 1\n\t\t\t\t: hiddenError?.hasError\n\t\t\t\t\t? (hiddenError.exitCode ?? 1)\n\t\t\t\t\t: run.error && run.exitCode === 0\n\t\t\t\t\t\t? 1\n\t\t\t\t\t\t: run.exitCode;\n\t\tconst signalError =\n\t\t\trun.exitCode !== 0 &&\n\t\t\tisUnexplainedProcessSignal(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tprocessSignal: run.processSignal,\n\t\t\t\t\tinterrupted: run.interrupted,\n\t\t\t\t\ttimedOut: run.timedOut,\n\t\t\t\t\tstopped: run.stopped,\n\t\t\t\t\tturnBudgetExceeded: run.turnBudgetExceeded,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t\t? formatProcessSignalError(run.processSignal!)\n\t\t\t\t: undefined;\n\t\tconst error =\n\t\t\ttoolAvailabilityError ??\n\t\t\tcompletionGuardError ??\n\t\t\tstructuredError ??\n\t\t\temptyOutputError ??\n\t\t\t(hiddenError?.hasError\n\t\t\t\t? hiddenError.details\n\t\t\t\t\t? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`\n\t\t\t\t\t: `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`\n\t\t\t\t: run.error || signalError || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined));\n\t\tconst attempt: ModelAttempt = omitUndefinedProperties({\n\t\t\tmodel: candidate ?? run.model ?? step.model ?? \"default\",\n\t\t\tsuccess: effectiveExitCode === 0 && !error,\n\t\t\texitCode: effectiveExitCode,\n\t\t\terror,\n\t\t\tusage: run.usage,\n\t\t});\n\t\tmodelAttempts.push(attempt);\n\t\tif (candidate && startupAttemptIndex === 0) attemptedModels.push(candidate);\n\t\tcompletionGuardTriggeredFinal = completionGuardTriggered;\n\t\tfinalOutputSnapshot = outputSnapshot;\n\t\tif (step.toolBudget) {\n\t\t\tconst toolMessages = run.messages.filter((message) => message.role === \"toolResult\");\n\t\t\tconst blockedMessage = toolMessages.find((message) =>\n\t\t\t\textractTextFromContent(message.content).includes(\"Tool budget hard limit reached\"),\n\t\t\t);\n\t\t\ttoolBudgetBlocked = Boolean(blockedMessage);\n\t\t\ttoolBudget = toolBudgetState(\n\t\t\t\tstep.toolBudget,\n\t\t\t\ttoolMessages.length,\n\t\t\t\tblockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined,\n\t\t\t);\n\t\t}\n\t\tfinalResult = {\n\t\t\t...run,\n\t\t\texitCode: effectiveExitCode,\n\t\t\tmodel: candidate ?? run.model,\n\t\t\terror,\n\t\t\tstructuredOutput,\n\t\t\truntimeAcknowledgedExtensions,\n\t\t\t...(step.agentContract ? { agentContract: step.agentContract } : {}),\n\t\t\t...(fileMutationEffect ? { effects: { fileMutation: fileMutationEffect } } : {}),\n\t\t} as RunPiStreamingResult & {\n\t\t\tstructuredOutput?: unknown;\n\t\t\tagentContract?: import(\"../../shared/types.ts\").AgentContract;\n\t\t\teffects?: import(\"../../shared/types.ts\").EffectsProjection;\n\t\t};\n\t\tif (run.turnBudgetExceeded) break;\n\t\tif (\n\t\t\trun.stopped ||\n\t\t\trun.timedOut ||\n\t\t\tctx.timeoutSignal?.aborted ||\n\t\t\tctx.stopSignal?.aborted ||\n\t\t\tctx.skipAcceptance?.()\n\t\t)\n\t\t\tbreak;\n\t\tif (attempt.success || completionGuardTriggered) break;\n\n\t\tconst startupFailure = isRetryableSubagentStartupFailure(\n\t\t\tomitUndefinedProperties({\n\t\t\t\texitCode: effectiveExitCode,\n\t\t\t\terror,\n\t\t\t\tfinalOutput: run.finalOutput,\n\t\t\t\tmessageCount: run.messages.length,\n\t\t\t\ttoolCount: run.toolCount,\n\t\t\t\tusage: run.usage,\n\t\t\t\tdurationMs: run.durationMs,\n\t\t\t\tprotocolError: run.protocolError,\n\t\t\t\tprocessSignal: run.processSignal,\n\t\t\t\tobservedMutationAttempt: run.observedMutationAttempt,\n\t\t\t\tinterrupted: run.interrupted,\n\t\t\t\ttimedOut: run.timedOut,\n\t\t\t\tstopped: run.stopped,\n\t\t\t\tturnBudgetExceeded: run.turnBudgetExceeded,\n\t\t\t}),\n\t\t);\n\t\tconst retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];\n\t\tif (startupFailure && retryDelayMs !== undefined) {\n\t\t\tconst retryNote = formatSubagentStartupRetryNote({\n\t\t\t\tmodel: attempt.model,\n\t\t\t\tattempt: startupAttemptIndex + 1,\n\t\t\t\tmaxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,\n\t\t\t\tdelayMs: retryDelayMs,\n\t\t\t});\n\t\t\tconst shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [ctx.timeoutSignal, ctx.stopSignal]);\n\t\t\tif (!shouldRetry || ctx.skipAcceptance?.()) break;\n\t\t\tattempt.error = retryNote;\n\t\t\tattemptNotes.push(retryNote);\n\t\t\tstartupAttemptIndex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (startupFailure) {\n\t\t\tconst startupError = formatSubagentStartupRetryExhaustedError({\n\t\t\t\tmodel: attempt.model,\n\t\t\t\tattempts: startupAttemptIndex + 1,\n\t\t\t});\n\t\t\tattempt.error = startupError;\n\t\t\tfinalResult.error = startupError;\n\t\t\tfinalResult.finalOutput = startupError;\n\t\t\tbreak;\n\t\t}\n\t\tif (!isRetryableModelFailure(error) || modelIndex === candidates.length - 1) break;\n\t\tattemptNotes.push(formatModelAttemptNote(attempt, candidates[modelIndex + 1]));\n\t\tmodelIndex += 1;\n\t\tstartupAttemptIndex = 0;\n\t}\n\n\tconst rawOutput = finalResult?.finalOutput ?? \"\";\n\tconst outputForPersistence = stripAcceptanceReport(rawOutput);\n\tconst resolvedOutput =\n\t\tstep.outputPath && finalResult?.exitCode === 0\n\t\t\t? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)\n\t\t\t: { fullOutput: outputForPersistence };\n\tconst output = stripAcceptanceReport(resolvedOutput.fullOutput);\n\tconst outputReference = resolvedOutput.savedPath\n\t\t? formatSavedOutputReference(resolvedOutput.savedPath, output)\n\t\t: undefined;\n\tlet outputForSummary = output;\n\tif (attemptNotes.length > 0) {\n\t\toutputForSummary = `${attemptNotes.join(\"\\n\")}\\n\\n${outputForSummary}`.trim();\n\t}\n\tif (finalResult?.stopped && !outputForSummary.trim()) {\n\t\toutputForSummary = ctx.stopMessage ?? \"Subagent stopped by user.\";\n\t} else if (!finalResult?.timedOut && !finalResult?.stopped && finalResult?.turnBudgetExceeded && turnBudget) {\n\t\toutputForSummary = formatTurnBudgetOutput(\n\t\t\tturnBudgetExceededMessage(turnBudget, turnBudget.turnCount),\n\t\t\toutputForSummary,\n\t\t);\n\t} else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === \"termination-deferred\") {\n\t\tconst note = turnBudgetDeferredNote(turnBudget, turnBudget.terminationDeferredAtTurn ?? turnBudget.turnCount);\n\t\toutputForSummary = outputForSummary.trim() ? `${note}\\n\\n${outputForSummary}` : note;\n\t} else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === \"wrap-up-requested\") {\n\t\tconst note = turnBudgetSoftNote(turnBudget, turnBudget.wrapUpRequestedAtTurn ?? turnBudget.turnCount);\n\t\toutputForSummary = outputForSummary.trim() ? `${note}\\n\\n${outputForSummary}` : note;\n\t}\n\tconst outputForAcceptance = rawOutput;\n\tconst childWrittenOutput = step.outputPath\n\t\t? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)\n\t\t: undefined;\n\tconst outputState: SubagentOutputState =\n\t\tfinalResult?.outputState === \"present\" ||\n\t\t(finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !==\n\t\t\tundefined ||\n\t\tBoolean(childWrittenOutput?.trim())\n\t\t\t? \"present\"\n\t\t\t: resolvedOutput.savedPath\n\t\t\t\t? \"unknown\"\n\t\t\t\t: (finalResult?.outputState ?? \"unknown\");\n\tconst finalizedOutput = finalizeSingleOutput(\n\t\tomitUndefinedProperties({\n\t\t\tfullOutput: outputForSummary,\n\t\t\toutputPath: step.outputPath,\n\t\t\toutputMode: step.outputMode,\n\t\t\texitCode: finalResult?.exitCode ?? 1,\n\t\t\tsavedPath: resolvedOutput.savedPath,\n\t\t\toutputReference,\n\t\t\tsaveError: resolvedOutput.saveError,\n\t\t}),\n\t);\n\toutputForSummary = finalizedOutput.displayOutput;\n\tconst acceptance =\n\t\tstep.effectiveAcceptance &&\n\t\t!finalResult?.stopped &&\n\t\t!finalResult?.turnBudgetExceeded &&\n\t\t!ctx.timeoutSignal?.aborted &&\n\t\t!ctx.stopSignal?.aborted &&\n\t\t!ctx.skipAcceptance?.()\n\t\t\t? await evaluateAcceptance(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tacceptance: step.effectiveAcceptance,\n\t\t\t\t\t\toutput: outputForAcceptance,\n\t\t\t\t\t\tfileOutput:\n\t\t\t\t\t\t\tchildWrittenOutput !== undefined && step.outputPath\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tcontent: childWrittenOutput,\n\t\t\t\t\t\t\t\t\t\tpath: step.outputPath,\n\t\t\t\t\t\t\t\t\t\tauthoritative: step.outputMode === \"file-only\",\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tcwd: step.cwd ?? ctx.cwd,\n\t\t\t\t\t\tsignal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),\n\t\t\t\t\t\tabortMessage: ctx.stopSignal?.aborted\n\t\t\t\t\t\t\t? (ctx.stopMessage ?? \"Subagent stopped by user.\")\n\t\t\t\t\t\t\t: (ctx.timeoutMessage ?? \"Subagent timed out.\"),\n\t\t\t\t\t\treportOptional: isAgentContractV1(step.agentContract),\n\t\t\t\t\t\tartifactsDir: ctx.artifactsDir,\n\t\t\t\t\t\trunId: ctx.id,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t: undefined;\n\tconst stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;\n\tconst timedOutAfterAcceptance =\n\t\t!stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);\n\tconst turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;\n\tconst effectiveAcceptance = step.effectiveAcceptance\n\t\t? stoppedAfterAcceptance\n\t\t\t? buildSkippedAcceptanceLedger(step.effectiveAcceptance, {\n\t\t\t\t\tid: \"stopped\",\n\t\t\t\t\tmessage: \"Acceptance was not evaluated because the subagent was stopped.\",\n\t\t\t\t})\n\t\t\t: timedOutAfterAcceptance\n\t\t\t\t? buildSkippedAcceptanceLedger(step.effectiveAcceptance, {\n\t\t\t\t\t\tid: \"timeout\",\n\t\t\t\t\t\tmessage: \"Acceptance was not evaluated because the subagent timed out.\",\n\t\t\t\t\t})\n\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t? buildSkippedAcceptanceLedger(step.effectiveAcceptance, {\n\t\t\t\t\t\t\tid: \"turn-budget\",\n\t\t\t\t\t\t\tmessage: \"Acceptance was not evaluated because the subagent exceeded its turn budget.\",\n\t\t\t\t\t\t})\n\t\t\t\t\t: acceptance\n\t\t: undefined;\n\tconst acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;\n\tconst acceptanceCanFailRun =\n\t\tacceptanceFailure &&\n\t\teffectiveAcceptance?.explicit &&\n\t\t(finalResult?.exitCode ?? 1) === 0 &&\n\t\t!finalResult?.interrupted &&\n\t\t!timedOutAfterAcceptance &&\n\t\t!stoppedAfterAcceptance &&\n\t\t!turnBudgetExceeded &&\n\t\t!isAgentContractV1(step.agentContract);\n\tconst effectiveFinalExitCode =\n\t\ttimedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded\n\t\t\t? 1\n\t\t\t: acceptanceCanFailRun\n\t\t\t\t? 1\n\t\t\t\t: (finalResult?.exitCode ?? 1);\n\tconst effectiveFinalError = stoppedAfterAcceptance\n\t\t? (ctx.stopMessage ?? \"Subagent stopped by user.\")\n\t\t: timedOutAfterAcceptance\n\t\t\t? (ctx.timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t: turnBudgetExceeded\n\t\t\t\t? (finalResult?.error ??\n\t\t\t\t\t(turnBudget\n\t\t\t\t\t\t? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount)\n\t\t\t\t\t\t: \"Subagent exceeded turn budget.\"))\n\t\t\t\t: acceptanceCanFailRun\n\t\t\t\t\t? finalResult?.error\n\t\t\t\t\t\t? `${finalResult.error}\\n${acceptanceFailure}`\n\t\t\t\t\t\t: acceptanceFailure\n\t\t\t\t\t: finalResult?.error;\n\n\tconst artifactErrors =\n\t\tartifactPaths && ctx.artifactConfig?.enabled !== false\n\t\t\t? persistStepArtifacts({\n\t\t\t\t\tartifactPaths,\n\t\t\t\t\tartifactConfig: ctx.artifactConfig,\n\t\t\t\t\toutput: formatOutputArtifactContent(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\terror: effectiveFinalError,\n\t\t\t\t\t\t\ttranscriptPath: transcriptWriter ? artifactPaths.transcriptPath : undefined,\n\t\t\t\t\t\t\tmetadataPath:\n\t\t\t\t\t\t\t\tctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\trunId: ctx.id,\n\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\texitCode: effectiveFinalExitCode,\n\t\t\t\t\t\tmodel: finalResult?.model,\n\t\t\t\t\t\tattemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,\n\t\t\t\t\t\tmodelAttempts,\n\t\t\t\t\t\terror: effectiveFinalError,\n\t\t\t\t\t\tacceptance: effectiveAcceptance,\n\t\t\t\t\t\t...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),\n\t\t\t\t\t\tlaunchContractDigest: actualLaunchContractDigest,\n\t\t\t\t\t\tlaunchResolvedExtensions,\n\t\t\t\t\t\t...((\n\t\t\t\t\t\t\tfinalResult as\n\t\t\t\t\t\t\t\t| (RunPiStreamingResult & {\n\t\t\t\t\t\t\t\t\t\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\t\t\t\t\t\t\t\t  })\n\t\t\t\t\t\t\t\t| undefined\n\t\t\t\t\t\t)?.runtimeAcknowledgedExtensions\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\truntimeAcknowledgedExtensions: (\n\t\t\t\t\t\t\t\t\t\tfinalResult as RunPiStreamingResult & {\n\t\t\t\t\t\t\t\t\t\t\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t).runtimeAcknowledgedExtensions,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),\n\t\t\t\t\t\ttranscriptError: transcriptWriter?.getError(),\n\t\t\t\t\t\tskills: step.skills,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: {};\n\n\tconst result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({\n\t\tagent: step.agent,\n\t\tcontext: step.context,\n\t\t...(step.agentContract ? { agentContract: step.agentContract } : {}),\n\t\tlaunchContractDigest: actualLaunchContractDigest,\n\t\toutput: outputForSummary,\n\t\toutputState,\n\t\texitCode: effectiveFinalExitCode,\n\t\terror: effectiveFinalError,\n\t\tprotocolError: finalResult?.protocolError,\n\t\tsessionFile: step.sessionFile,\n\t\tintercomTarget: ctx.childIntercomTarget,\n\t\tmodel: finalResult?.model,\n\t\tattemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,\n\t\tmodelAttempts,\n\t\ttotalCost: costSummaryFromAttempts(modelAttempts),\n\t\tartifactPaths,\n\t\toutputSaveError: artifactErrors.outputSaveError,\n\t\tmetadataSaveError: artifactErrors.metadataSaveError,\n\t\ttranscriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,\n\t\ttranscriptError: transcriptWriter?.getError(),\n\t\tinterrupted:\n\t\t\ttimedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,\n\t\ttimedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,\n\t\tstopped: stoppedAfterAcceptance ? true : finalResult?.stopped,\n\t\tprocessSignal: finalResult?.processSignal,\n\t\tturnBudget,\n\t\tturnBudgetExceeded: turnBudgetExceeded || undefined,\n\t\twrapUpRequested:\n\t\t\tfinalResult?.wrapUpRequested ||\n\t\t\tturnBudget?.outcome === \"wrap-up-requested\" ||\n\t\t\tturnBudget?.outcome === \"termination-deferred\" ||\n\t\t\tturnBudgetExceeded ||\n\t\t\tundefined,\n\t\ttoolBudget,\n\t\ttoolBudgetBlocked: toolBudgetBlocked || undefined,\n\t\tcompletionGuardTriggered: completionGuardTriggeredFinal,\n\t\t...((\n\t\t\tfinalResult as\n\t\t\t\t| (RunPiStreamingResult & { effects?: import(\"../../shared/types.ts\").EffectsProjection })\n\t\t\t\t| undefined\n\t\t)?.effects\n\t\t\t? {\n\t\t\t\t\teffects: (\n\t\t\t\t\t\tfinalResult as RunPiStreamingResult & { effects?: import(\"../../shared/types.ts\").EffectsProjection }\n\t\t\t\t\t).effects,\n\t\t\t\t}\n\t\t\t: {}),\n\t\tstructuredOutput:\n\t\t\ttimedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded\n\t\t\t\t? undefined\n\t\t\t\t: (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,\n\t\tstructuredOutputPath:\n\t\t\ttimedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded\n\t\t\t\t? undefined\n\t\t\t\t: effectiveStructuredOutput?.outputPath,\n\t\tstructuredOutputSchemaPath:\n\t\t\ttimedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded\n\t\t\t\t? undefined\n\t\t\t\t: effectiveStructuredOutput?.schemaPath,\n\t\tacceptance: effectiveAcceptance,\n\t\twatchdog: finalResult?.watchdog,\n\t\t...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),\n\t\tlaunchResolvedExtensions,\n\t\t...((\n\t\t\tfinalResult as\n\t\t\t\t| (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 })\n\t\t\t\t| undefined\n\t\t)?.runtimeAcknowledgedExtensions\n\t\t\t? {\n\t\t\t\t\truntimeAcknowledgedExtensions: (\n\t\t\t\t\t\tfinalResult as RunPiStreamingResult & {\n\t\t\t\t\t\t\truntimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;\n\t\t\t\t\t\t}\n\t\t\t\t\t).runtimeAcknowledgedExtensions,\n\t\t\t\t}\n\t\t\t: {}),\n\t\twriterProcesses,\n\t\twriterAttemptCount,\n\t});\n\treturn isAgentContractV1(step.agentContract)\n\t\t? (attachContractProjections(\n\t\t\t\tresult as unknown as import(\"../../shared/types.ts\").SingleResult,\n\t\t\t) as unknown as typeof result)\n\t\t: result;\n}\n\ntype RunnerStatusStep = NonNullable<AsyncStatus[\"steps\"]>[number] & {\n\texitCode?: number | null;\n\tdescription?: string;\n};\n\nfunction externalRunnerStatus(runner: SubagentStep[\"runner\"]): ExternalCliRunnerStatus | undefined {\n\tif (runner?.type !== \"external-cli\") return undefined;\n\treturn {\n\t\ttype: \"external-cli\",\n\t\tcommand: runner.command,\n\t\targs: runner.args ?? [],\n\t\tpromptDelivery: runner.promptDelivery ?? \"stdin\",\n\t\t...(runner.retry ? { retry: runner.retry } : {}),\n\t\tcapabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },\n\t};\n}\n\nfunction appendCapabilityCeilingAppliedEvent(\n\teventsPath: string,\n\trunId: string,\n\tstepIndex: number,\n\tagent: string,\n\tresult: StepResult,\n): void {\n\tif (!result.capabilityCeiling) return;\n\tappendJsonl(\n\t\teventsPath,\n\t\tJSON.stringify({\n\t\t\ttype: \"subagent.capability-ceiling.applied\",\n\t\t\tts: Date.now(),\n\t\t\trunId,\n\t\t\tstepIndex,\n\t\t\tagent,\n\t\t\tcapabilityCeiling: result.capabilityCeiling,\n\t\t\t...(result.capabilityAudit ? { capabilityAudit: result.capabilityAudit } : {}),\n\t\t}),\n\t);\n}\n\ntype RunnerStatusPayload = Omit<\n\tAsyncStatus,\n\t\"steps\" | \"parallelGroups\" | \"pid\" | \"cwd\" | \"currentStep\" | \"chainStepCount\" | \"lastUpdate\"\n> & {\n\tpid: number;\n\tcwd: string;\n\tcurrentStep: number;\n\tchainStepCount: number;\n\tparallelGroups: AsyncParallelGroupStatus[];\n\tsteps: RunnerStatusStep[];\n\tlastUpdate: number;\n\tartifactsDir?: string;\n\tshareUrl?: string;\n\tgistUrl?: string;\n\tshareError?: string;\n\terror?: string;\n};\n\nfunction requiredStatusStep(statusPayload: RunnerStatusPayload, index: number): RunnerStatusStep {\n\tconst step = statusPayload.steps[index];\n\tif (!step) throw new Error(`Missing status step at index ${index}`);\n\treturn step;\n}\n\nfunction markParallelGroupSetupFailure(input: {\n\tstatusPayload: RunnerStatusPayload;\n\tresults: StepResult[];\n\tgroup: Extract<RunnerStep, { parallel: SubagentStep[] }>;\n\tgroupStartFlatIndex: number;\n\tsetupError: string;\n\tfailedAt: number;\n\tstatusPath: string;\n\teventsPath: string;\n\tasyncDir: string;\n\trunId: string;\n\tstepIndex: number;\n}): void {\n\tfor (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {\n\t\tconst flatTaskIndex = input.groupStartFlatIndex + taskIndex;\n\t\tconst statusStep = requiredStatusStep(input.statusPayload, flatTaskIndex);\n\t\tconst task = input.group.parallel[taskIndex];\n\t\tif (!task) throw new Error(`Missing parallel task at index ${taskIndex}`);\n\t\tstatusStep.status = \"failed\";\n\t\tstatusStep.startedAt = input.failedAt;\n\t\tstatusStep.endedAt = input.failedAt;\n\t\tstatusStep.durationMs = 0;\n\t\tstatusStep.exitCode = 1;\n\t\tinput.results.push(\n\t\t\tomitUndefinedProperties({\n\t\t\t\tagent: task.agent,\n\t\t\t\tcontext: task.context,\n\t\t\t\toutput: input.setupError,\n\t\t\t\tsuccess: false,\n\t\t\t\texitCode: 1,\n\t\t\t\tsessionFile: task.sessionFile,\n\t\t\t}),\n\t\t);\n\t}\n\tinput.statusPayload.currentStep = input.groupStartFlatIndex;\n\tinput.statusPayload.lastUpdate = input.failedAt;\n\tinput.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);\n\twriteAtomicJson(input.statusPath, input.statusPayload);\n\tappendJsonl(\n\t\tinput.eventsPath,\n\t\tJSON.stringify({\n\t\t\ttype: \"subagent.parallel.completed\",\n\t\t\tts: input.failedAt,\n\t\t\trunId: input.runId,\n\t\t\tstepIndex: input.stepIndex,\n\t\t\tsuccess: false,\n\t\t}),\n\t);\n}\n\nfunction markParallelGroupRunning(input: {\n\tstatusPayload: RunnerStatusPayload;\n\tgroup: Extract<RunnerStep, { parallel: SubagentStep[] }>;\n\tgroupStartFlatIndex: number;\n\tgroupStartTime: number;\n\tstatusPath: string;\n\teventsPath: string;\n\tasyncDir: string;\n\trunId: string;\n\tstepIndex: number;\n}): void {\n\tfor (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {\n\t\tconst flatTaskIndex = input.groupStartFlatIndex + taskIndex;\n\t\tconst statusStep = requiredStatusStep(input.statusPayload, flatTaskIndex);\n\t\tstatusStep.status = \"pending\";\n\t\tdelete statusStep.startedAt;\n\t\tdelete statusStep.endedAt;\n\t\tdelete statusStep.durationMs;\n\t\tdelete statusStep.lastActivityAt;\n\t\tdelete statusStep.activityState;\n\t\tdelete statusStep.error;\n\t}\n\tinput.statusPayload.currentStep = input.groupStartFlatIndex;\n\tdelete input.statusPayload.activityState;\n\tinput.statusPayload.lastActivityAt = input.groupStartTime;\n\tinput.statusPayload.lastUpdate = input.groupStartTime;\n\tinput.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);\n\twriteAtomicJson(input.statusPath, input.statusPayload);\n\tappendJsonl(\n\t\tinput.eventsPath,\n\t\tJSON.stringify({\n\t\t\ttype: \"subagent.parallel.started\",\n\t\t\tts: input.groupStartTime,\n\t\t\trunId: input.runId,\n\t\t\tstepIndex: input.stepIndex,\n\t\t\tagents: input.group.parallel.map((task) => task.agent),\n\t\t\tcount: input.group.parallel.length,\n\t\t}),\n\t);\n}\n\nfunction prepareParallelTaskRun(\n\ttask: SubagentStep,\n\tcwd: string,\n\tworktreeSetup: WorktreeSetup | undefined,\n\ttaskIndex: number,\n): { taskForRun: SubagentStep; taskCwd: string } {\n\tif (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };\n\tconst { cwd: _taskCwd, ...taskForRun } = task;\n\treturn {\n\t\ttaskForRun,\n\t\ttaskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,\n\t};\n}\n\nfunction captureParallelWorktreeDiffs(\n\tworktreeSetup: WorktreeSetup,\n\tasyncDir: string,\n\tstepIndex: number,\n\tgroup: Extract<RunnerStep, { parallel: SubagentStep[] }>,\n): { diffs: ReturnType<typeof diffWorktrees>; summary: string } {\n\tconst diffsDir = path.join(asyncDir, \"worktree-diffs\", `step-${stepIndex}`);\n\tconst diffs = diffWorktrees(\n\t\tworktreeSetup,\n\t\tgroup.parallel.map((task) => task.agent),\n\t\tdiffsDir,\n\t);\n\treturn { diffs, summary: formatWorktreeDiffSummary(diffs) };\n}\n\nfunction ensureParallelProgressFile(cwd: string, group: Extract<RunnerStep, { parallel: SubagentStep[] }>): void {\n\tconst progressPath = path.join(cwd, \"progress.md\");\n\tif (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`))) return;\n\twriteInitialProgressFile(cwd);\n}\n\nfunction resolveAsyncStepTranscriptPath(input: {\n\tartifactsDir?: string;\n\tartifactConfig?: Partial<ArtifactConfig>;\n\trunId: string;\n\tagent: string;\n\tflatIndex: number;\n\tflatStepCount: number;\n}): string | undefined {\n\tif (\n\t\t!input.artifactsDir ||\n\t\tinput.artifactConfig?.enabled === false ||\n\t\tinput.artifactConfig?.includeTranscript === false\n\t)\n\t\treturn undefined;\n\treturn getArtifactPaths(\n\t\tinput.artifactsDir,\n\t\tinput.runId,\n\t\tinput.agent,\n\t\tinput.flatStepCount > 1 ? input.flatIndex : undefined,\n\t).transcriptPath;\n}\n\ntype SingleStepResult = Awaited<ReturnType<typeof runSingleStep>>;\n\nfunction combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {\n\tconst activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));\n\tif (activeSignals.length === 0) return undefined;\n\tif (activeSignals.length === 1) return activeSignals[0];\n\tconst controller = new AbortController();\n\tconst abort = (): void => controller.abort();\n\tfor (const signal of activeSignals) {\n\t\tif (signal.aborted) {\n\t\t\tabort();\n\t\t\tbreak;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t}\n\treturn controller.signal;\n}\n\nasync function runSubagent(\n\tconfig: SubagentRunConfig,\n\tonWriterProcess?: (writer: { state: \"none\" | \"spawning\" } | { state: \"running\"; pid: number }) => void,\n): Promise<void> {\n\tconst { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =\n\t\tconfig;\n\tconst globalSemaphore = new Semaphore(config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);\n\tlet previousOutput = \"\";\n\tconst outputs: ChainOutputMap = {};\n\tconst results: StepResult[] = [];\n\tconst overallStartTime = Date.now();\n\tconst shareEnabled = config.share === true;\n\tconst asyncDir = config.asyncDir;\n\tconst statusPath = path.join(asyncDir, \"status.json\");\n\tconst eventsPath = path.join(asyncDir, \"events.jsonl\");\n\tconst logPath = path.join(asyncDir, `subagent-log-${id}.md`);\n\tconst controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;\n\tconst activeChildInterrupts = new Map<number, () => void>();\n\tconst activeChildTimeouts = new Map<number, () => void>();\n\tconst activeChildStops = new Map<number, () => void>();\n\tconst activeChildTurnBudgetAborts = new Map<number, (message: string, state?: TurnBudgetState) => void>();\n\tconst pendingStepSteers: SteerRequest[] = [];\n\tconst steeringCapabilities = new Map<number, SteerCapability>();\n\tlet interrupted = false;\n\tlet currentActivityState: ActivityState | undefined;\n\tlet activityTimer: NodeJS.Timeout | undefined;\n\tlet heartbeatTimer: NodeJS.Timeout | undefined;\n\tlet timeoutTimer: NodeJS.Timeout | undefined;\n\tlet timedOut = false;\n\tlet stopped = false;\n\tlet turnBudgetExceeded = false;\n\tlet usageBudgetExceeded = false;\n\tlet checkpointRejected = false;\n\tlet pendingCheckpointDecision: \"approved\" | \"rejected\" | undefined;\n\tlet wakeCheckpointDecision: (() => void) | undefined;\n\tconst timeoutMessage =\n\t\tconfig.timeoutMs !== undefined ? `Subagent timed out after ${config.timeoutMs}ms.` : undefined;\n\tconst stopMessage = \"Subagent stopped by user.\";\n\tconst timeoutAbortController = new AbortController();\n\tconst stopAbortController = new AbortController();\n\tlet previousCumulativeTokens: TokenUsage = { input: 0, output: 0, total: 0 };\n\tlet latestSessionFile: string | undefined;\n\n\tconst flatSteps = flattenSteps(steps);\n\tconst initialFlatStepCount = flatSteps.length;\n\tconst parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];\n\tconst initialStatusSteps: RunnerStatusStep[] = [];\n\tlet flatStepCount = 0;\n\tfor (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {\n\t\tconst step = steps[stepIndex]!;\n\t\tif (isCheckpointRunnerStep(step)) {\n\t\t\tinitialStatusSteps.push(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: `checkpoint:${step.checkpoint}`,\n\t\t\t\t\tphase: step.phase,\n\t\t\t\t\tlabel: step.label ?? step.checkpoint,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tcheckpoint: {\n\t\t\t\t\t\tname: step.checkpoint,\n\t\t\t\t\t\t...(step.message ? { message: step.message } : {}),\n\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t},\n\t\t\t\t\trecentTools: [],\n\t\t\t\t\trecentOutput: [],\n\t\t\t\t}),\n\t\t\t);\n\t\t\tflatStepCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (isParallelGroup(step)) {\n\t\t\tparallelGroups.push({ start: flatStepCount, count: step.parallel.length, stepIndex });\n\t\t\tfor (const task of step.parallel) {\n\t\t\t\tconst taskFlatIndex = flatStepCount;\n\t\t\t\tconst transcriptPath = resolveAsyncStepTranscriptPath(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tartifactsDir,\n\t\t\t\t\t\tartifactConfig,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\tflatIndex: taskFlatIndex,\n\t\t\t\t\t\tflatStepCount: initialFlatStepCount,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tinitialStatusSteps.push(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),\n\t\t\t\t\t\t...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),\n\t\t\t\t\t\t...(task.context ? { context: task.context } : {}),\n\t\t\t\t\t\tphase: task.phase,\n\t\t\t\t\t\tlabel: task.label,\n\t\t\t\t\t\toutputName: task.outputName,\n\t\t\t\t\t\tstructured: task.structured,\n\t\t\t\t\t\t...(task.agentContract ? { agentContract: task.agentContract } : {}),\n\t\t\t\t\t\t...(task.launchContractDigest ? { launchContractDigest: task.launchContractDigest } : {}),\n\t\t\t\t\t\t...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),\n\t\t\t\t\t\t...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),\n\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\t...(task.toolBudget ? { toolBudget: initialToolBudgetState(task.toolBudget) } : {}),\n\t\t\t\t\t\t...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),\n\t\t\t\t\t\t...(transcriptPath ? { transcriptPath } : {}),\n\t\t\t\t\t\tskills: task.skills,\n\t\t\t\t\t\tmodel: task.model,\n\t\t\t\t\t\tthinking: task.thinking,\n\t\t\t\t\t\tattemptedModels:\n\t\t\t\t\t\t\ttask.modelCandidates && task.modelCandidates.length > 0\n\t\t\t\t\t\t\t\t? task.modelCandidates\n\t\t\t\t\t\t\t\t: task.model\n\t\t\t\t\t\t\t\t\t? [task.model]\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\trecentTools: [],\n\t\t\t\t\t\trecentOutput: [],\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tflatStepCount++;\n\t\t\t}\n\t\t} else if (isDynamicRunnerGroup(step)) {\n\t\t\tparallelGroups.push({ start: flatStepCount, count: 1, stepIndex });\n\t\t\tinitialStatusSteps.push(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: `expand:${step.parallel.agent}`,\n\t\t\t\t\t...(externalRunnerStatus(step.parallel.runner)\n\t\t\t\t\t\t? { runner: externalRunnerStatus(step.parallel.runner) }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(step.parallel.context ? { context: step.parallel.context } : {}),\n\t\t\t\t\tphase: step.phase ?? step.parallel.phase,\n\t\t\t\t\tlabel: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,\n\t\t\t\t\toutputName: step.collect.as,\n\t\t\t\t\tstructured: Boolean(step.collect.outputSchema),\n\t\t\t\t\t...(step.agentContract ? { agentContract: step.agentContract } : {}),\n\t\t\t\t\t...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t...(step.parallel.toolBudget ? { toolBudget: initialToolBudgetState(step.parallel.toolBudget) } : {}),\n\t\t\t\t\trecentTools: [],\n\t\t\t\t\trecentOutput: [],\n\t\t\t\t}),\n\t\t\t);\n\t\t\tflatStepCount++;\n\t\t} else {\n\t\t\tconst stepFlatIndex = flatStepCount;\n\t\t\tconst transcriptPath = resolveAsyncStepTranscriptPath(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tartifactsDir,\n\t\t\t\t\tartifactConfig,\n\t\t\t\t\trunId: id,\n\t\t\t\t\tagent: step.agent,\n\t\t\t\t\tflatIndex: stepFlatIndex,\n\t\t\t\t\tflatStepCount: initialFlatStepCount,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tinitialStatusSteps.push(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),\n\t\t\t\t\t...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),\n\t\t\t\t\t...(step.context ? { context: step.context } : {}),\n\t\t\t\t\tphase: step.phase,\n\t\t\t\t\tlabel: step.label,\n\t\t\t\t\toutputName: step.outputName,\n\t\t\t\t\tstructured: step.structured,\n\t\t\t\t\t...(step.agentContract ? { agentContract: step.agentContract } : {}),\n\t\t\t\t\t...(step.launchContractDigest ? { launchContractDigest: step.launchContractDigest } : {}),\n\t\t\t\t\t...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),\n\t\t\t\t\t...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t...(step.toolBudget ? { toolBudget: initialToolBudgetState(step.toolBudget) } : {}),\n\t\t\t\t\t...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),\n\t\t\t\t\t...(transcriptPath ? { transcriptPath } : {}),\n\t\t\t\t\tskills: step.skills,\n\t\t\t\t\tmodel: step.model,\n\t\t\t\t\tthinking: step.thinking,\n\t\t\t\t\tattemptedModels:\n\t\t\t\t\t\tstep.modelCandidates && step.modelCandidates.length > 0\n\t\t\t\t\t\t\t? step.modelCandidates\n\t\t\t\t\t\t\t: step.model\n\t\t\t\t\t\t\t\t? [step.model]\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\trecentTools: [],\n\t\t\t\t\trecentOutput: [],\n\t\t\t\t}),\n\t\t\t);\n\t\t\tflatStepCount++;\n\t\t}\n\t}\n\tconst sessionEnabled =\n\t\tBoolean(config.sessionDir) || shareEnabled || flatSteps.some((step) => Boolean(step.sessionFile));\n\tif (config.runnerProcessInstanceId) {\n\t\tfor (const step of initialStatusSteps) {\n\t\t\tstep.processTerminal = {\n\t\t\t\tversion: 1,\n\t\t\t\tstate: \"pending\",\n\t\t\t\trunId: id,\n\t\t\t\trunnerProcessInstanceId: config.runnerProcessInstanceId,\n\t\t\t};\n\t\t}\n\t}\n\tconst statusPayload: RunnerStatusPayload = omitUndefinedProperties({\n\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\trunId: id,\n\t\t...(config.sessionId ? { sessionId: config.sessionId } : {}),\n\t\tmode: config.resultMode ?? (flatSteps.length > 1 ? \"chain\" : \"single\"),\n\t\t...(config.nestedRoute ? { isNested: true } : {}),\n\t\tstate: \"running\",\n\t\tsteering: createSteeringStatus(),\n\t\tlastActivityAt: overallStartTime,\n\t\tstartedAt: overallStartTime,\n\t\tlastUpdate: overallStartTime,\n\t\t...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n\t\t...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),\n\t\t...(config.turnBudget ? { turnBudget: initialTurnBudgetState(config.turnBudget) } : {}),\n\t\t...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),\n\t\t...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),\n\t\tpid: process.pid,\n\t\tcwd,\n\t\tcurrentStep: 0,\n\t\tchainStepCount: steps.length,\n\t\tparallelGroups,\n\t\tworkflowGraph: config.workflowGraph,\n\t\t...(config.launchContractDigest ? { launchContractDigest: config.launchContractDigest } : {}),\n\t\t...(config.launchResolvedExtensions ? { launchResolvedExtensions: config.launchResolvedExtensions } : {}),\n\t\t...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),\n\t\t...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),\n\t\t...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),\n\t\t...(config.runnerProcessInstanceId\n\t\t\t? {\n\t\t\t\t\tprocessTerminal: {\n\t\t\t\t\t\tversion: 1 as const,\n\t\t\t\t\t\tstate: \"pending\" as const,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\trunnerProcessInstanceId: config.runnerProcessInstanceId,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tsteps: initialStatusSteps,\n\t\tartifactsDir,\n\t\tsessionDir: config.sessionDir,\n\t\toutputFile: path.join(asyncDir, \"output-0.log\"),\n\t});\n\n\tfs.mkdirSync(asyncDir, { recursive: true });\n\twriteAtomicJson(statusPath, statusPayload);\n\tlet pendingParallelUsageCost: CostSummary = { inputTokens: 0, outputTokens: 0, costUsd: 0 };\n\tconst currentUsageTotals = (): CostSummary => {\n\t\tconst cost = results.reduce<CostSummary>(\n\t\t\t(sum, result) => ({\n\t\t\t\tinputTokens: sum.inputTokens + (result.totalCost?.inputTokens ?? result.usage?.input ?? 0),\n\t\t\t\toutputTokens: sum.outputTokens + (result.totalCost?.outputTokens ?? result.usage?.output ?? 0),\n\t\t\t\tcostUsd: sum.costUsd + (result.totalCost?.costUsd ?? result.usage?.cost ?? 0),\n\t\t\t}),\n\t\t\t{\n\t\t\t\tinputTokens: pendingParallelUsageCost.inputTokens,\n\t\t\t\toutputTokens: pendingParallelUsageCost.outputTokens,\n\t\t\t\tcostUsd: pendingParallelUsageCost.costUsd,\n\t\t\t},\n\t\t);\n\t\treturn {\n\t\t\tinputTokens: Math.max(cost.inputTokens, statusPayload.totalTokens?.input ?? 0),\n\t\t\toutputTokens: Math.max(cost.outputTokens, statusPayload.totalTokens?.output ?? 0),\n\t\t\tcostUsd: cost.costUsd,\n\t\t};\n\t};\n\tconst refreshUsageBudget = () => {\n\t\tsetOptionalProperty(statusPayload, \"usageBudget\", usageBudgetState(config.usageBudget, currentUsageTotals()));\n\t\treturn statusPayload.usageBudget;\n\t};\n\tconst emitNestedSelfEvent = (type: \"subagent.nested.updated\" | \"subagent.nested.completed\"): void => {\n\t\tif (!config.nestedRoute || !config.nestedSelf) return;\n\t\ttry {\n\t\t\twriteNestedEvent(\n\t\t\t\tconfig.nestedRoute,\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\ttype,\n\t\t\t\t\tts: Date.now(),\n\t\t\t\t\tparentRunId: config.nestedSelf.parentRunId,\n\t\t\t\t\tparentStepIndex: config.nestedSelf.parentStepIndex,\n\t\t\t\t\tchild: nestedSummaryFromAsyncStatus(\n\t\t\t\t\t\tstatusPayload,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tparentRunId: config.nestedSelf.parentRunId,\n\t\t\t\t\t\t\tparentStepIndex: config.nestedSelf.parentStepIndex,\n\t\t\t\t\t\t\tdepth: config.nestedSelf.depth,\n\t\t\t\t\t\t\tpath: config.nestedSelf.path,\n\t\t\t\t\t\t\tmode: statusPayload.mode,\n\t\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to emit nested async status event:\", error);\n\t\t}\n\t};\n\tconst refreshWorkflowGraph = (): void => {\n\t\tif (!config.workflowGraph) return;\n\t\tconst graph = structuredClone(statusPayload.workflowGraph ?? config.workflowGraph);\n\t\tconst normalize = (\n\t\t\tstatus: RunnerStatusStep[\"status\"],\n\t\t): \"pending\" | \"running\" | \"completed\" | \"failed\" | \"paused\" | \"stopped\" | \"detached\" | \"rejected\" => {\n\t\t\tif (status === \"complete\" || status === \"completed\") return \"completed\";\n\t\t\tif (\n\t\t\t\tstatus === \"running\" ||\n\t\t\t\tstatus === \"failed\" ||\n\t\t\t\tstatus === \"paused\" ||\n\t\t\t\tstatus === \"stopped\" ||\n\t\t\t\tstatus === \"pending\" ||\n\t\t\t\tstatus === \"rejected\"\n\t\t\t)\n\t\t\t\treturn status;\n\t\t\treturn \"pending\";\n\t\t};\n\t\tconst updateNode = (node: NonNullable<typeof graph.nodes>[number]): void => {\n\t\t\tif (node.flatIndex !== undefined) {\n\t\t\t\tconst step = statusPayload.steps[node.flatIndex];\n\t\t\t\tif (step) {\n\t\t\t\t\tnode.status = normalize(step.status);\n\t\t\t\t\tsetOptionalProperty(node, \"error\", step.error);\n\t\t\t\t\tsetOptionalProperty(node, \"acceptanceStatus\", step.acceptance?.status);\n\t\t\t\t\tsetOptionalProperty(node, \"checkpoint\", step.checkpoint);\n\t\t\t\t}\n\t\t\t\tif (statusPayload.currentStep === node.flatIndex) graph.currentNodeId = node.id;\n\t\t\t}\n\t\t\tfor (const child of node.children ?? []) updateNode(child);\n\t\t\tif (node.children?.length) {\n\t\t\t\tif (node.children.every((child) => child.status === \"completed\")) node.status = \"completed\";\n\t\t\t\telse if (node.children.some((child) => child.status === \"running\")) node.status = \"running\";\n\t\t\t\telse if (node.children.some((child) => child.status === \"stopped\")) node.status = \"stopped\";\n\t\t\t\telse if (node.children.some((child) => child.status === \"rejected\")) node.status = \"rejected\";\n\t\t\t\telse if (node.children.some((child) => child.status === \"failed\")) node.status = \"failed\";\n\t\t\t\telse if (node.children.some((child) => child.status === \"paused\")) node.status = \"paused\";\n\t\t\t}\n\t\t\tif (node.error && node.status !== \"stopped\" && node.status !== \"rejected\") node.status = \"failed\";\n\t\t};\n\t\tfor (const node of graph.nodes) updateNode(node);\n\t\tstatusPayload.workflowGraph = graph;\n\t};\n\tconst writeStatusPayload = (): void => {\n\t\trefreshWorkflowGraph();\n\t\twriteAtomicJson(statusPath, statusPayload);\n\t\temitNestedSelfEvent(\n\t\t\tstatusPayload.state === \"running\" || statusPayload.state === \"queued\"\n\t\t\t\t? \"subagent.nested.updated\"\n\t\t\t\t: \"subagent.nested.completed\",\n\t\t);\n\t};\n\tconst updateExternalProcess = (index: number, process: ExternalProcessStatus): void => {\n\t\trequiredStatusStep(statusPayload, index).externalProcess = process;\n\t\tstatusPayload.lastUpdate = Date.now();\n\t\twriteStatusPayload();\n\t};\n\tconst registerStepInterrupt = (flatIndex: number, interrupt: (() => void) | undefined): void => {\n\t\tif (!interrupt) {\n\t\t\tactiveChildInterrupts.delete(flatIndex);\n\t\t\treturn;\n\t\t}\n\t\tactiveChildInterrupts.set(flatIndex, interrupt);\n\t\tif (interrupted) interrupt();\n\t};\n\tconst registerStepTimeout = (flatIndex: number, interrupt: (() => void) | undefined): void => {\n\t\tif (!interrupt) {\n\t\t\tactiveChildTimeouts.delete(flatIndex);\n\t\t\treturn;\n\t\t}\n\t\tactiveChildTimeouts.set(flatIndex, interrupt);\n\t\tif (timedOut) interrupt();\n\t};\n\tconst registerStepStop = (flatIndex: number, stop: (() => void) | undefined): void => {\n\t\tif (!stop) {\n\t\t\tactiveChildStops.delete(flatIndex);\n\t\t\treturn;\n\t\t}\n\t\tactiveChildStops.set(flatIndex, stop);\n\t\tif (stopped) stop();\n\t};\n\tconst registerStepTurnBudgetAbort = (\n\t\tflatIndex: number,\n\t\tabort: ((message: string, state?: TurnBudgetState) => void) | undefined,\n\t): void => {\n\t\tif (!abort) {\n\t\t\tactiveChildTurnBudgetAborts.delete(flatIndex);\n\t\t\treturn;\n\t\t}\n\t\tactiveChildTurnBudgetAborts.set(flatIndex, abort);\n\t};\n\tconst interruptActiveChildren = (): void => {\n\t\tfor (const interrupt of [...activeChildInterrupts.values()]) interrupt();\n\t};\n\tconst timeoutActiveChildren = (): void => {\n\t\tfor (const interrupt of [...activeChildTimeouts.values()]) interrupt();\n\t};\n\tconst stopActiveChildren = (): void => {\n\t\tfor (const stop of [...activeChildStops.values()]) stop();\n\t};\n\tconst nestedRuns = function* (children: NestedRunSummary[] | undefined): Generator<NestedRunSummary> {\n\t\tfor (const child of children ?? []) {\n\t\t\tyield child;\n\t\t\tyield* nestedRuns(child.children);\n\t\t\tyield* nestedRuns(child.steps?.flatMap((step) => step.children ?? []));\n\t\t}\n\t};\n\tconst interruptNestedAsyncDescendants = (): void => {\n\t\tif (!config.nestedRoute) return;\n\t\tlet registry: ReturnType<typeof projectNestedEvents>;\n\t\ttry {\n\t\t\tregistry = projectNestedEvents(config.nestedRoute);\n\t\t} catch (error) {\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.nested.interrupt_failed\",\n\t\t\t\t\tts: Date.now(),\n\t\t\t\t\trunId: id,\n\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfor (const run of nestedRuns(registry.children)) {\n\t\t\tif (run.state !== \"running\" && run.state !== \"queued\") continue;\n\t\t\tconst nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);\n\t\t\tif (!nestedAsyncDir) continue;\n\t\t\ttry {\n\t\t\t\tdeliverInterruptRequest(\n\t\t\t\t\tomitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: \"ancestor-interrupt\" }),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.nested.interrupt_failed\",\n\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\ttargetRunId: run.id,\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n\tconst stopNestedAsyncDescendants = (): void => {\n\t\tif (!config.nestedRoute) return;\n\t\tlet registry: ReturnType<typeof projectNestedEvents>;\n\t\ttry {\n\t\t\tregistry = projectNestedEvents(config.nestedRoute);\n\t\t} catch (error) {\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.nested.stop_failed\",\n\t\t\t\t\tts: Date.now(),\n\t\t\t\t\trunId: id,\n\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfor (const run of nestedRuns(registry.children)) {\n\t\t\tif (run.state !== \"running\" && run.state !== \"queued\") continue;\n\t\t\tconst nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);\n\t\t\tif (!nestedAsyncDir) continue;\n\t\t\ttry {\n\t\t\t\tdeliverStopRequest(\n\t\t\t\t\tomitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: \"ancestor-stop\" }),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.nested.stop_failed\",\n\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\ttargetRunId: run.id,\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n\tconst timeoutNestedAsyncDescendants = (): void => {\n\t\tif (!config.nestedRoute) return;\n\t\tlet registry: ReturnType<typeof projectNestedEvents>;\n\t\ttry {\n\t\t\tregistry = projectNestedEvents(config.nestedRoute);\n\t\t} catch (error) {\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.nested.timeout_failed\",\n\t\t\t\t\tts: Date.now(),\n\t\t\t\t\trunId: id,\n\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfor (const run of nestedRuns(registry.children)) {\n\t\t\tif (run.state !== \"running\" && run.state !== \"queued\") continue;\n\t\t\tconst nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);\n\t\t\tif (!nestedAsyncDir) continue;\n\t\t\ttry {\n\t\t\t\tdeliverTimeoutRequest(\n\t\t\t\t\tomitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: \"ancestor-timeout\" }),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.nested.timeout_failed\",\n\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\ttargetRunId: run.id,\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n\tconst pausedStepResult = (agent: string, context?: \"fresh\" | \"fork\"): SingleStepResult =>\n\t\tomitUndefinedProperties({\n\t\t\tagent,\n\t\t\tcontext,\n\t\t\toutput: \"Paused after interrupt. Waiting for explicit next action.\",\n\t\t\texitCode: 0,\n\t\t\tinterrupted: true,\n\t\t});\n\tconst timedOutStepResult = (agent: string, context?: \"fresh\" | \"fork\"): SingleStepResult =>\n\t\tomitUndefinedProperties({\n\t\t\tagent,\n\t\t\tcontext,\n\t\t\toutput: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\terror: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\texitCode: 1,\n\t\t\ttimedOut: true,\n\t\t});\n\tconst stoppedStepResult = (agent: string, context?: \"fresh\" | \"fork\"): SingleStepResult =>\n\t\tomitUndefinedProperties({\n\t\t\tagent,\n\t\t\tcontext,\n\t\t\toutput: stopMessage,\n\t\t\terror: stopMessage,\n\t\t\texitCode: 1,\n\t\t\tstopped: true,\n\t\t});\n\tconst consumePendingAppendRequests = (): void => {\n\t\tif (statusPayload.mode !== \"chain\" || statusPayload.state !== \"running\") return;\n\t\tconst requests = consumeChainAppendRequests(asyncDir);\n\t\tif (requests.length === 0) {\n\t\t\tconst pendingAppends = countPendingChainAppendRequests(asyncDir);\n\t\t\tif ((statusPayload.pendingAppends ?? 0) !== pendingAppends) {\n\t\t\t\tstatusPayload.pendingAppends = pendingAppends;\n\t\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\t\twriteStatusPayload();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst appendedSteps = requests.flatMap((request) => request.steps);\n\t\tsteps.push(...appendedSteps);\n\t\tconst now = Date.now();\n\t\tconst pendingAppends = countPendingChainAppendRequests(asyncDir);\n\t\tconst added = appendRunnerStepsToStatus({\n\t\t\tstatus: statusPayload,\n\t\t\tsteps: appendedSteps,\n\t\t\tnow,\n\t\t\tpendingAppends,\n\t\t});\n\t\tmutatingFailureStates.push(...Array.from({ length: added.addedFlatSteps }, () => createMutatingFailureState()));\n\t\tpendingToolResults.push(...Array.from({ length: added.addedFlatSteps }, () => undefined));\n\t\tif (config.childIntercomTargets) {\n\t\t\tconfig.childIntercomTargets = statusPayload.steps.map((statusStep, index) =>\n\t\t\t\tresolveSubagentIntercomTarget(id, statusStep.agent, index),\n\t\t\t);\n\t\t}\n\t\twriteStatusPayload();\n\t\tfor (const request of requests) {\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.chain.append.accepted\",\n\t\t\t\t\tts: now,\n\t\t\t\t\trunId: id,\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\tstepCount: request.steps.length,\n\t\t\t\t\tpendingAppends,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t};\n\tconst markDynamicGraphGroup = (\n\t\tstepIndex: number,\n\t\tstatus: \"completed\" | \"failed\" | \"running\" | \"stopped\",\n\t\terror?: string,\n\t\tacceptance?: import(\"../../shared/types.ts\").AcceptanceLedger,\n\t): void => {\n\t\tconst groupNode = statusPayload.workflowGraph?.nodes.find((node) => node.id === `step-${stepIndex}`);\n\t\tif (!groupNode) return;\n\t\tgroupNode.status = status;\n\t\tsetOptionalProperty(groupNode, \"error\", error);\n\t\tsetOptionalProperty(groupNode, \"acceptanceStatus\", acceptance?.status ?? groupNode.acceptanceStatus);\n\t};\n\n\tconst stepOutputActivityAt = (index: number): number => {\n\t\tconst step = statusPayload.steps[index];\n\t\tlet lastActivityAt = step?.lastActivityAt ?? step?.startedAt ?? overallStartTime;\n\t\tconst outputPath = path.join(asyncDir, `output-${index}.log`);\n\t\ttry {\n\t\t\tlastActivityAt = Math.max(lastActivityAt, fs.statSync(outputPath).mtimeMs);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\t\tconsole.error(`Failed to inspect async output file '${outputPath}':`, error);\n\t\t\t}\n\t\t}\n\t\treturn lastActivityAt;\n\t};\n\tconst emittedControlEventKeys = new Set<string>();\n\tconst activeLongRunningSteps = new Set<number>();\n\tconst mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());\n\tconst pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> =\n\t\tinitialStatusSteps.map(() => undefined);\n\tconst supervisorAttentionSteps = new Map<number, ActivityState | undefined>();\n\tconst mutatingFailureWindowMs = 5 * 60_000;\n\tconst appendControlEvent = (event: ReturnType<typeof buildControlEvent>) => {\n\t\tif (!controlConfig.enabled) return;\n\t\tconst childIntercomTarget = config.childIntercomTargets?.[event.index ?? statusPayload.currentStep];\n\t\tconst channels =\n\t\t\tevent.type === \"active_long_running\"\n\t\t\t\t? controlConfig.notifyChannels.filter((channel) => channel !== \"intercom\")\n\t\t\t\t: controlConfig.notifyChannels;\n\t\tif (\n\t\t\tchannels.length === 0 ||\n\t\t\t!claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget)\n\t\t)\n\t\t\treturn;\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.control\",\n\t\t\t\tevent,\n\t\t\t\tchannels,\n\t\t\t\tchildIntercomTarget,\n\t\t\t\tnoticeText: formatControlNoticeMessage(event, childIntercomTarget),\n\t\t\t\t...(config.controlIntercomTarget && channels.includes(\"intercom\")\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tintercom: {\n\t\t\t\t\t\t\t\tto: config.controlIntercomTarget,\n\t\t\t\t\t\t\t\tmessage: formatControlIntercomMessage(event, childIntercomTarget),\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}),\n\t\t);\n\t};\n\tconst syncTopLevelCurrentTool = (): void => {\n\t\tconst activeStep = statusPayload.steps\n\t\t\t.filter(\n\t\t\t\t(step) => step.status === \"running\" && typeof step.currentTool === \"string\" && step.currentTool.length > 0,\n\t\t\t)\n\t\t\t.sort((left, right) => (right.currentToolStartedAt ?? 0) - (left.currentToolStartedAt ?? 0))[0];\n\t\tsetOptionalProperty(statusPayload, \"currentTool\", activeStep?.currentTool);\n\t\tsetOptionalProperty(statusPayload, \"currentToolStartedAt\", activeStep?.currentToolStartedAt);\n\t\tsetOptionalProperty(statusPayload, \"currentPath\", activeStep?.currentPath);\n\t};\n\tconst syncAggregateActivityState = (): void => {\n\t\tconst nextRunState = statusPayload.steps.some((step) => step.activityState === \"needs_attention\")\n\t\t\t? \"needs_attention\"\n\t\t\t: statusPayload.steps.some((step) => step.activityState === \"active_long_running\")\n\t\t\t\t? \"active_long_running\"\n\t\t\t\t: undefined;\n\t\tcurrentActivityState = nextRunState;\n\t\tsetOptionalProperty(statusPayload, \"activityState\", nextRunState);\n\t};\n\tconst maybeEmitActiveLongRunning = (flatIndex: number, now: number): boolean => {\n\t\tif (!controlConfig.enabled || activeLongRunningSteps.has(flatIndex)) return false;\n\t\tconst step = statusPayload.steps[flatIndex];\n\t\tif (!step || step.status !== \"running\" || step.activityState === \"needs_attention\") return false;\n\t\tconst reason = nextLongRunningTrigger(controlConfig, {\n\t\t\tstartedAt: step.startedAt ?? overallStartTime,\n\t\t\tnow,\n\t\t\tturns: step.turnCount ?? 0,\n\t\t\ttokens: step.tokens?.total ?? 0,\n\t\t});\n\t\tif (!reason) return false;\n\t\tactiveLongRunningSteps.add(flatIndex);\n\t\tconst previous = step.activityState;\n\t\tstep.activityState = \"active_long_running\";\n\t\tstatusPayload.activityState =\n\t\t\tstatusPayload.activityState === \"needs_attention\" ? \"needs_attention\" : \"active_long_running\";\n\t\tconst event = buildControlEvent(\n\t\t\tomitUndefinedProperties({\n\t\t\t\ttype: \"active_long_running\",\n\t\t\t\tfrom: previous,\n\t\t\t\tto: \"active_long_running\",\n\t\t\t\trunId: id,\n\t\t\t\tagent: step.agent,\n\t\t\t\tindex: flatIndex,\n\t\t\t\tts: now,\n\t\t\t\tmessage: `${step.agent} is still active but long-running`,\n\t\t\t\treason,\n\t\t\t\tturns: step.turnCount,\n\t\t\t\ttokens: step.tokens?.total,\n\t\t\t\ttoolCount: step.toolCount,\n\t\t\t\tcurrentTool: step.currentTool,\n\t\t\t\tcurrentToolDurationMs: step.currentToolStartedAt ? Math.max(0, now - step.currentToolStartedAt) : undefined,\n\t\t\t\tcurrentPath: step.currentPath,\n\t\t\t\telapsedMs: now - (step.startedAt ?? overallStartTime),\n\t\t\t}),\n\t\t);\n\t\tappendControlEvent(event);\n\t\treturn true;\n\t};\n\tconst steeringMarkerPath = (requestId: string): string =>\n\t\tpath.join(asyncDir, \"control\", \"steer-recovery\", `${Buffer.from(requestId).toString(\"base64url\")}.json`);\n\tconst markSteeringAttention = (index: number): void => {\n\t\tconst step = statusPayload.steps[index];\n\t\tif (step) step.activityState = \"needs_attention\";\n\t\tstatusPayload.activityState = \"needs_attention\";\n\t};\n\tconst emitSteeringEvent = (\n\t\ttype: string,\n\t\trequest: SteerRequest,\n\t\tindex?: number,\n\t\textra: Record<string, unknown> = {},\n\t): void => {\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype,\n\t\t\t\tts: Date.now(),\n\t\t\t\trunId: id,\n\t\t\t\trequestId: request.id,\n\t\t\t\t...(index !== undefined ? { index } : {}),\n\t\t\t\t...extra,\n\t\t\t}),\n\t\t);\n\t};\n\tconst emitSteeringNotice = (requestId: string, state: \"failed\" | \"partial\" | \"recovered\", message: string): void => {\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.steering.notice\",\n\t\t\t\tts: Date.now(),\n\t\t\t\trunId: id,\n\t\t\t\trequestId,\n\t\t\t\tstate,\n\t\t\t\tmessage,\n\t\t\t\t...(config.sessionId ? { currentSessionId: config.sessionId } : {}),\n\t\t\t}),\n\t\t);\n\t};\n\tconst recordSteeringLifecycle = (\n\t\trequest: SteerRequest,\n\t\ttargets: Array<{ index: number; state: SteeringTargetState; reason?: string }>,\n\t): void => {\n\t\tconst lifecycle = steeringStatus(statusPayload);\n\t\trecordSteeringRequest(\n\t\t\tlifecycle,\n\t\t\tomitUndefinedProperties({\n\t\t\t\tid: request.id,\n\t\t\t\trequestedAt: request.ts,\n\t\t\t\tsource: request.source,\n\t\t\t\tmessage: request.message,\n\t\t\t\ttargets,\n\t\t\t}),\n\t\t);\n\t\tfor (const target of targets) {\n\t\t\tconst step = statusPayload.steps[target.index];\n\t\t\tif (!step) continue;\n\t\t\tstep.steering ??= createSteeringStatus();\n\t\t\trecordSteeringRequest(\n\t\t\t\tstep.steering,\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tid: request.id,\n\t\t\t\t\trequestedAt: request.ts,\n\t\t\t\t\tsource: request.source,\n\t\t\t\t\tmessage: request.message,\n\t\t\t\t\ttargets: [target],\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t};\n\tconst updateSteeringLifecycleTarget = (\n\t\trequestId: string,\n\t\tindex: number,\n\t\tstate: SteeringTargetState,\n\t\tnow: number,\n\t\tfields: Pick<SteeringTargetStatus, \"reason\" | \"replacementRunId\"> = {},\n\t): SteeringTargetStatus | undefined => {\n\t\tconst updated = updateSteeringTarget(steeringStatus(statusPayload), requestId, index, state, now, fields);\n\t\tconst step = statusPayload.steps[index];\n\t\tif (step?.steering) updateSteeringTarget(step.steering, requestId, index, state, now, fields);\n\t\treturn updated;\n\t};\n\tconst emitTerminalSteeringNotice = (requestId: string, failureMessage: string): void => {\n\t\tconst state = terminalSteeringNoticeState(steeringStatus(statusPayload), requestId);\n\t\tif (state === \"partial\") emitSteeringNotice(requestId, \"partial\", `Steering partially delivered for run ${id}.`);\n\t\telse if (state === \"failed\") emitSteeringNotice(requestId, \"failed\", failureMessage);\n\t};\n\tconst deliverSteerRequest = (request: SteerRequest): void => {\n\t\tif (statusPayload.state !== \"running\") {\n\t\t\tconst reason = `run became ${statusPayload.state} before steering request was consumed`;\n\t\t\tconst indexes =\n\t\t\t\trequest.targetIndex !== undefined\n\t\t\t\t\t? [request.targetIndex]\n\t\t\t\t\t: request.targetIndexes?.length\n\t\t\t\t\t\t? request.targetIndexes\n\t\t\t\t\t\t: statusPayload.steps.map((_, index) => index);\n\t\t\tconst targets = indexes.map((index) => ({ index, state: \"failed\" as const, reason }));\n\t\t\trecordSteeringLifecycle(request, targets);\n\t\t\temitSteeringEvent(\"subagent.steer.requested\", request, undefined, { targets });\n\t\t\tfor (const target of targets) emitSteeringEvent(\"subagent.steer.failed\", request, target.index, { reason });\n\t\t\temitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: ${reason}.`);\n\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\twriteStatusPayload();\n\t\t\treturn;\n\t\t}\n\t\tconst runningIndexes = statusPayload.steps\n\t\t\t.map((step, index) => ({ step, index }))\n\t\t\t.filter(({ step }) => step.status === \"running\")\n\t\t\t.map(({ index }) => index);\n\t\tconst targets =\n\t\t\trequest.targetIndex !== undefined\n\t\t\t\t? [request.targetIndex]\n\t\t\t\t: request.targetIndexes?.length\n\t\t\t\t\t? request.targetIndexes\n\t\t\t\t\t: runningIndexes.length > 0\n\t\t\t\t\t\t? runningIndexes\n\t\t\t\t\t\t: statusPayload.mode === \"single\" && statusPayload.steps[0]?.status === \"pending\"\n\t\t\t\t\t\t\t? [0]\n\t\t\t\t\t\t\t: [];\n\t\tconst now = Date.now();\n\t\tconst targetStates = targets.map((index) => {\n\t\t\tconst step = statusPayload.steps[index];\n\t\t\tif (!step) return { index, state: \"failed\" as const, reason: \"child index out of range\" };\n\t\t\tif (step.status === \"pending\") return { index, state: \"scheduled\" as const };\n\t\t\tif (step.status !== \"running\") return { index, state: \"failed\" as const, reason: `child is ${step.status}` };\n\t\t\tif (steeringCapabilities.get(index)?.supported === false)\n\t\t\t\treturn { index, state: \"failed\" as const, reason: \"child Pi session does not support steering\" };\n\t\t\treturn { index, state: \"routed\" as const };\n\t\t});\n\t\trecordSteeringLifecycle(request, targetStates);\n\t\temitSteeringEvent(\"subagent.steer.requested\", request, undefined, { targets: targetStates });\n\t\tfor (const target of targetStates) {\n\t\t\tif (target.state === \"routed\") {\n\t\t\t\ttry {\n\t\t\t\t\tenqueueStepSteer(asyncDir, target.index, request);\n\t\t\t\t\tupdateSteeringLifecycleTarget(request.id, target.index, \"routed\", now);\n\t\t\t\t\temitSteeringEvent(\"subagent.steer.routed\", request, target.index);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tmarkSteeringAttention(target.index);\n\t\t\t\t\tupdateSteeringLifecycleTarget(request.id, target.index, \"failed\", now, {\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t});\n\t\t\t\t\temitSteeringEvent(\"subagent.steer.failed\", request, target.index, {\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (target.state === \"failed\") {\n\t\t\t\tmarkSteeringAttention(target.index);\n\t\t\t\temitSteeringEvent(\"subagent.steer.failed\", request, target.index, { reason: target.reason });\n\t\t\t} else {\n\t\t\t\temitSteeringEvent(\"subagent.steer.scheduled\", request, target.index);\n\t\t\t}\n\t\t}\n\t\temitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: no requested child remained steerable.`);\n\t\tstatusPayload.lastUpdate = now;\n\t\twriteStatusPayload();\n\t};\n\tconst consumeSteerAck = (ack: SteerAck): void => {\n\t\tconst lifecycle = steeringStatus(statusPayload);\n\t\tconst request = lifecycle.recent.find((candidate) => candidate.id === ack.requestId);\n\t\tif (!request || !request.targets.some((target) => target.index === ack.index)) return;\n\t\tconst late = fs.existsSync(steeringMarkerPath(ack.requestId));\n\t\tconst now = Date.now();\n\t\tif (ack.state === \"delivered\") {\n\t\t\tupdateSteeringLifecycleTarget(\n\t\t\t\tack.requestId,\n\t\t\t\tack.index,\n\t\t\t\tlate ? \"late\" : \"delivered\",\n\t\t\t\tnow,\n\t\t\t\tomitUndefinedProperties({ reason: late ? \"acknowledged after recovery commit\" : undefined }),\n\t\t\t);\n\t\t\temitSteeringEvent(\n\t\t\t\t\"subagent.steer.delivered\",\n\t\t\t\t{ type: \"steer\", id: ack.requestId, ts: now, message: ack.message },\n\t\t\t\tack.index,\n\t\t\t\t{ late, deliveryStatus: \"delivered\", message: ack.message },\n\t\t\t);\n\t\t} else if (ack.state === \"queued\") {\n\t\t\tupdateSteeringLifecycleTarget(ack.requestId, ack.index, \"queued\", now);\n\t\t\temitSteeringEvent(\n\t\t\t\t\"subagent.steer.queued\",\n\t\t\t\t{ type: \"steer\", id: ack.requestId, ts: now, message: ack.message },\n\t\t\t\tack.index,\n\t\t\t\t{ deliveryStatus: \"queued\", message: ack.message },\n\t\t\t);\n\t\t} else {\n\t\t\tmarkSteeringAttention(ack.index);\n\t\t\tupdateSteeringLifecycleTarget(ack.requestId, ack.index, \"failed\", now, { reason: ack.message });\n\t\t\temitSteeringEvent(\n\t\t\t\t\"subagent.steer.failed\",\n\t\t\t\t{ type: \"steer\", id: ack.requestId, ts: now, message: ack.message },\n\t\t\t\tack.index,\n\t\t\t\t{ reason: ack.message },\n\t\t\t);\n\t\t}\n\t\temitTerminalSteeringNotice(ack.requestId, `Steering failed for run ${id}: ${ack.message}`);\n\t\tstatusPayload.lastUpdate = now;\n\t\twriteStatusPayload();\n\t};\n\tconst flushPendingStepSteers = (flatIndex: number): void => {\n\t\tconst remaining: SteerRequest[] = [];\n\t\tfor (const request of pendingStepSteers.splice(0)) {\n\t\t\tif (request.targetIndex === undefined) deliverSteerRequest({ ...request, targetIndex: flatIndex });\n\t\t\telse if (request.targetIndex === flatIndex) deliverSteerRequest(request);\n\t\t\telse remaining.push(request);\n\t\t}\n\t\tpendingStepSteers.push(...remaining);\n\t};\n\tconst updateStepModel = (\n\t\tflatIndex: number,\n\t\tmodel: string | undefined,\n\t\tthinking: string | undefined,\n\t\tnow = Date.now(),\n\t): void => {\n\t\tconst step = statusPayload.steps[flatIndex];\n\t\tif (!step) return;\n\t\tsetOptionalProperty(step, \"model\", model);\n\t\tsetOptionalProperty(step, \"thinking\", thinking);\n\t\tstatusPayload.lastUpdate = now;\n\t\twriteStatusPayload();\n\t};\n\tconst updateStepTurnBudget = (\n\t\tflatIndex: number,\n\t\tturnCount: number,\n\t\tnow: number,\n\t\tterminalAssistantStop: boolean,\n\t\ttoolWorkActiveOrStarting: boolean,\n\t): void => {\n\t\tconst budget = config.turnBudget;\n\t\tconst step = statusPayload.steps[flatIndex];\n\t\tif (!budget || !step || timedOut || stopped || turnBudgetExceeded || step.turnBudgetExceeded) return;\n\t\tif (turnCount < budget.maxTurns) {\n\t\t\tconst state: TurnBudgetState = { ...budget, outcome: \"within-budget\", turnCount };\n\t\t\tstep.turnBudget = state;\n\t\t\tstatusPayload.turnBudget = state;\n\t\t\treturn;\n\t\t}\n\t\tif (!step.wrapUpRequested) {\n\t\t\tstep.wrapUpRequested = true;\n\t\t\tstatusPayload.wrapUpRequested = true;\n\t\t\tappendRecentStepOutput(step, [turnBudgetSoftNote(budget, turnCount)]);\n\t\t}\n\t\tconst decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting);\n\t\tif (decision === \"defer\") {\n\t\t\tconst firstDeferredTurn = step.turnBudget?.terminationDeferredAtTurn;\n\t\t\tconst deferredState = turnBudgetDeferredState(budget, turnCount, firstDeferredTurn);\n\t\t\tstep.turnBudget = deferredState;\n\t\t\tstatusPayload.turnBudget = deferredState;\n\t\t\tif (firstDeferredTurn === undefined) {\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.step.turn_budget_deferred\",\n\t\t\t\t\t\tts: now,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex: flatIndex,\n\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\tturnCount,\n\t\t\t\t\t\tmaxTurns: budget.maxTurns,\n\t\t\t\t\t\tgraceTurns: budget.graceTurns,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst state = turnBudgetState(budget, turnCount, false);\n\t\tstep.turnBudget = state;\n\t\tstatusPayload.turnBudget = state;\n\t\tif (decision !== \"abort\") return;\n\t\tconst exceededState = turnBudgetState(budget, turnCount, true);\n\t\tconst message = turnBudgetExceededMessage(budget, turnCount);\n\t\tstep.turnBudget = exceededState;\n\t\tstep.turnBudgetExceeded = true;\n\t\tstep.wrapUpRequested = true;\n\t\tstep.error = message;\n\t\tturnBudgetExceeded = true;\n\t\tstatusPayload.turnBudget = exceededState;\n\t\tstatusPayload.turnBudgetExceeded = true;\n\t\tstatusPayload.wrapUpRequested = true;\n\t\tstatusPayload.error = message;\n\t\tstatusPayload.lastUpdate = now;\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.step.turn_budget_exceeded\",\n\t\t\t\tts: now,\n\t\t\t\trunId: id,\n\t\t\t\tstepIndex: flatIndex,\n\t\t\t\tagent: step.agent,\n\t\t\t\tturnCount,\n\t\t\t\tmaxTurns: budget.maxTurns,\n\t\t\t\tgraceTurns: budget.graceTurns,\n\t\t\t\tmessage,\n\t\t\t}),\n\t\t);\n\t\tactiveChildTurnBudgetAborts.get(flatIndex)?.(message, exceededState);\n\t};\n\tconst updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {\n\t\tconst step = statusPayload.steps[flatIndex];\n\t\tif (!step) return;\n\t\tconst now = Date.now();\n\t\tstatusPayload.currentStep = flatIndex;\n\t\tif (isChildWatchdogStatusEvent(event)) {\n\t\t\tconst next = acceptChildWatchdogEvent({\n\t\t\t\tcurrent: step.watchdog,\n\t\t\t\tevent,\n\t\t\t\trunId: id,\n\t\t\t\tagent: step.agent,\n\t\t\t\tchildIndex: flatIndex,\n\t\t\t});\n\t\t\tif (!next) return;\n\t\t\tstep.watchdog = next;\n\t\t\tstep.lastActivityAt = now;\n\t\t\tstatusPayload.lastActivityAt = now;\n\t\t\tstatusPayload.lastUpdate = now;\n\t\t\twriteStatusPayload();\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"tool_execution_start\" && event.toolName) {\n\t\t\tconst mutates = isMutatingTool(event.toolName, event.args);\n\t\t\tconst currentPath = resolveCurrentPath(event.toolName, event.args);\n\t\t\tstep.toolCount = (step.toolCount ?? 0) + 1;\n\t\t\tconst configuredToolBudget = flatSteps[flatIndex]?.toolBudget;\n\t\t\tif (configuredToolBudget) {\n\t\t\t\tstep.toolBudget = toolBudgetState(configuredToolBudget, step.toolCount);\n\t\t\t\tstatusPayload.toolBudget = step.toolBudget;\n\t\t\t}\n\t\t\tstep.currentTool = event.toolName;\n\t\t\tstep.currentToolArgs = extractToolArgsPreview(event.args ?? {});\n\t\t\tstep.currentToolStartedAt = now;\n\t\t\tsetOptionalProperty(step, \"currentPath\", currentPath);\n\t\t\tpendingToolResults[flatIndex] = omitUndefinedProperties({\n\t\t\t\ttool: event.toolName,\n\t\t\t\tpath: currentPath,\n\t\t\t\tmutates,\n\t\t\t\tstartedAt: now,\n\t\t\t});\n\t\t\tstatusPayload.toolCount = (statusPayload.toolCount ?? 0) + 1;\n\t\t\tsyncTopLevelCurrentTool();\n\t\t\tif (\n\t\t\t\tcontrolConfig.enabled &&\n\t\t\t\tisBlockingSupervisorTool(event.toolName, event.args) &&\n\t\t\t\tstep.activityState !== \"needs_attention\"\n\t\t\t) {\n\t\t\t\tconst previous = step.activityState;\n\t\t\t\tstep.activityState = \"needs_attention\";\n\t\t\t\tsupervisorAttentionSteps.set(flatIndex, previous);\n\t\t\t\tcurrentActivityState = \"needs_attention\";\n\t\t\t\tstatusPayload.activityState = \"needs_attention\";\n\t\t\t\tappendControlEvent(\n\t\t\t\t\tbuildControlEvent(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\ttype: \"needs_attention\",\n\t\t\t\t\t\t\tfrom: previous,\n\t\t\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\tindex: flatIndex,\n\t\t\t\t\t\t\tts: now,\n\t\t\t\t\t\t\tmessage: `${step.agent} is waiting for a supervisor reply`,\n\t\t\t\t\t\t\treason: \"supervisor_request\",\n\t\t\t\t\t\t\tturns: step.turnCount,\n\t\t\t\t\t\t\ttokens: step.tokens?.total,\n\t\t\t\t\t\t\ttoolCount: step.toolCount,\n\t\t\t\t\t\t\tcurrentTool: step.currentTool,\n\t\t\t\t\t\t\tcurrentToolDurationMs: 0,\n\t\t\t\t\t\t\tcurrentPath: step.currentPath,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (event.type === \"tool_execution_end\") {\n\t\t\tif (step.currentTool) {\n\t\t\t\tstep.recentTools ??= [];\n\t\t\t\tstep.recentTools.push({ tool: step.currentTool, args: step.currentToolArgs || \"\", endMs: now });\n\t\t\t}\n\t\t\tconst supervisorPreviousActivity = supervisorAttentionSteps.get(flatIndex);\n\t\t\tconst clearedSupervisorAttention = supervisorAttentionSteps.delete(flatIndex);\n\t\t\tdelete step.currentTool;\n\t\t\tdelete step.currentToolArgs;\n\t\t\tdelete step.currentToolStartedAt;\n\t\t\tdelete step.currentPath;\n\t\t\tif (clearedSupervisorAttention && step.activityState === \"needs_attention\") {\n\t\t\t\tsetOptionalProperty(step, \"activityState\", supervisorPreviousActivity);\n\t\t\t\tsyncAggregateActivityState();\n\t\t\t}\n\t\t\tsyncTopLevelCurrentTool();\n\t\t} else if (event.type === \"tool_result_end\" && event.message) {\n\t\t\tconst toolSnapshot = pendingToolResults[flatIndex];\n\t\t\tpendingToolResults[flatIndex] = undefined;\n\t\t\tconst resultText = extractTextFromContent(event.message.content);\n\t\t\tif (toolSnapshot && resultText.includes(\"Tool budget hard limit reached\")) {\n\t\t\t\tconst configuredToolBudget = flatSteps[flatIndex]?.toolBudget;\n\t\t\t\tif (configuredToolBudget) {\n\t\t\t\t\tstep.toolBudget = toolBudgetState(configuredToolBudget, step.toolCount ?? 0, toolSnapshot.tool);\n\t\t\t\t\tstep.toolBudgetBlocked = true;\n\t\t\t\t\tstatusPayload.toolBudget = step.toolBudget;\n\t\t\t\t\tstatusPayload.toolBudgetBlocked = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tappendRecentStepOutput(step, resultText.split(\"\\n\").slice(-10));\n\t\t\tif (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {\n\t\t\t\tconst state = mutatingFailureStates[flatIndex]!;\n\t\t\t\trecordMutatingFailure(\n\t\t\t\t\tstate,\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\ttool: toolSnapshot.tool,\n\t\t\t\t\t\tpath: toolSnapshot.path,\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\tresultText\n\t\t\t\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t\t\t\t.find((line) => line.trim())\n\t\t\t\t\t\t\t\t?.trim()\n\t\t\t\t\t\t\t\t.slice(0, 180) ?? \"mutating tool failed\",\n\t\t\t\t\t\tts: now,\n\t\t\t\t\t}),\n\t\t\t\t\tmutatingFailureWindowMs,\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tcontrolConfig.enabled &&\n\t\t\t\t\tshouldEscalateMutatingFailures(state, controlConfig.failedToolAttemptsBeforeAttention) &&\n\t\t\t\t\tstep.activityState !== \"needs_attention\"\n\t\t\t\t) {\n\t\t\t\t\tconst previous = step.activityState;\n\t\t\t\t\tstep.activityState = \"needs_attention\";\n\t\t\t\t\tstatusPayload.activityState = \"needs_attention\";\n\t\t\t\t\tappendControlEvent(\n\t\t\t\t\t\tbuildControlEvent(\n\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\ttype: \"needs_attention\",\n\t\t\t\t\t\t\t\tfrom: previous,\n\t\t\t\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\t\tindex: flatIndex,\n\t\t\t\t\t\t\t\tts: now,\n\t\t\t\t\t\t\t\tmessage: `${step.agent} needs attention after repeated mutating tool failures`,\n\t\t\t\t\t\t\t\treason: \"tool_failures\",\n\t\t\t\t\t\t\t\tturns: step.turnCount,\n\t\t\t\t\t\t\t\ttokens: step.tokens?.total,\n\t\t\t\t\t\t\t\ttoolCount: step.toolCount,\n\t\t\t\t\t\t\t\tcurrentTool: toolSnapshot.tool,\n\t\t\t\t\t\t\t\tcurrentToolDurationMs: toolSnapshot.startedAt\n\t\t\t\t\t\t\t\t\t? Math.max(0, now - toolSnapshot.startedAt)\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\tcurrentPath: toolSnapshot.path,\n\t\t\t\t\t\t\t\trecentFailureSummary: summarizeRecentMutatingFailures(state),\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}\n\t\t\t} else if (toolSnapshot?.mutates) {\n\t\t\t\tresetMutatingFailureState(mutatingFailureStates[flatIndex]!);\n\t\t\t}\n\t\t} else if (event.type === \"message_end\" && event.message?.role === \"assistant\") {\n\t\t\tappendRecentStepOutput(\n\t\t\t\tstep,\n\t\t\t\tstripAcceptanceReport(extractTextFromContent(event.message.content)).split(\"\\n\").slice(-10),\n\t\t\t);\n\t\t\tstep.turnCount = (step.turnCount ?? 0) + 1;\n\t\t\tconst usage = event.message.usage;\n\t\t\tif (usage) {\n\t\t\t\tconst input = usage.input ?? usage.inputTokens ?? 0;\n\t\t\t\tconst output = usage.output ?? usage.outputTokens ?? 0;\n\t\t\t\tconst previousInput = step.tokens?.input ?? 0;\n\t\t\t\tconst previousOutput = step.tokens?.output ?? 0;\n\t\t\t\tstep.tokens = {\n\t\t\t\t\tinput: previousInput + input,\n\t\t\t\t\toutput: previousOutput + output,\n\t\t\t\t\ttotal: previousInput + previousOutput + input + output,\n\t\t\t\t};\n\t\t\t\tconst totalInput = statusPayload.totalTokens?.input ?? 0;\n\t\t\t\tconst totalOutput = statusPayload.totalTokens?.output ?? 0;\n\t\t\t\tstatusPayload.totalTokens = {\n\t\t\t\t\tinput: totalInput + input,\n\t\t\t\t\toutput: totalOutput + output,\n\t\t\t\t\ttotal: totalInput + totalOutput + input + output,\n\t\t\t\t};\n\t\t\t\trefreshUsageBudget();\n\t\t\t}\n\t\t\tstatusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);\n\t\t\tupdateStepTurnBudget(\n\t\t\t\tflatIndex,\n\t\t\t\tstep.turnCount,\n\t\t\t\tnow,\n\t\t\t\tisTerminalAssistantStop(event.message),\n\t\t\t\tassistantStartsToolCall(event.message) || Boolean(step.currentTool),\n\t\t\t);\n\t\t}\n\t\tsyncTopLevelCurrentTool();\n\t\tstep.lastActivityAt = now;\n\t\tstatusPayload.lastActivityAt = now;\n\t\tstatusPayload.lastUpdate = now;\n\t\tmaybeEmitActiveLongRunning(flatIndex, now);\n\t\twriteStatusPayload();\n\t};\n\tconst updateRunnerActivityState = (now: number): boolean => {\n\t\tif (!controlConfig.enabled) return false;\n\t\tlet changed = false;\n\t\tlet runLastActivityAt = statusPayload.lastActivityAt ?? overallStartTime;\n\t\tfor (let index = 0; index < statusPayload.steps.length; index++) {\n\t\t\tconst step = statusPayload.steps[index]!;\n\t\t\tif (step.status !== \"running\") continue;\n\t\t\tconst lastActivityAt = stepOutputActivityAt(index);\n\t\t\trunLastActivityAt = Math.max(runLastActivityAt, lastActivityAt);\n\t\t\tif (step.lastActivityAt !== lastActivityAt) {\n\t\t\t\tstep.lastActivityAt = lastActivityAt;\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t\tconst idleState = deriveActivityState(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tconfig: controlConfig,\n\t\t\t\t\tstartedAt: step.startedAt ?? overallStartTime,\n\t\t\t\t\tlastActivityAt,\n\t\t\t\t\tcurrentTool: step.currentTool,\n\t\t\t\t\tnow,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (idleState === \"needs_attention\") {\n\t\t\t\tconst previous = step.activityState;\n\t\t\t\tstep.activityState = \"needs_attention\";\n\t\t\t\tif (previous !== \"needs_attention\") {\n\t\t\t\t\tappendControlEvent(\n\t\t\t\t\t\tbuildControlEvent(\n\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\tfrom: previous,\n\t\t\t\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\tagent: step.agent,\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t\tts: now,\n\t\t\t\t\t\t\t\tlastActivityAt,\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\tchanged = true;\n\t\t\t\t}\n\t\t\t} else if (maybeEmitActiveLongRunning(index, now)) {\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t\tif (statusPayload.lastActivityAt !== runLastActivityAt) {\n\t\t\tstatusPayload.lastActivityAt = runLastActivityAt;\n\t\t\tchanged = true;\n\t\t}\n\t\tconst nextRunState = statusPayload.steps.some((step) => step.activityState === \"needs_attention\")\n\t\t\t? \"needs_attention\"\n\t\t\t: statusPayload.steps.some((step) => step.activityState === \"active_long_running\")\n\t\t\t\t? \"active_long_running\"\n\t\t\t\t: undefined;\n\t\tif (nextRunState !== currentActivityState) {\n\t\t\tcurrentActivityState = nextRunState;\n\t\t\tsetOptionalProperty(statusPayload, \"activityState\", nextRunState);\n\t\t\tchanged = true;\n\t\t}\n\t\tstatusPayload.lastUpdate = now;\n\t\tif (changed) writeStatusPayload();\n\t\treturn changed;\n\t};\n\tif (controlConfig.enabled) {\n\t\tactivityTimer = setInterval(() => {\n\t\t\tif (statusPayload.state !== \"running\") return;\n\t\t\tconst now = Date.now();\n\t\t\tupdateRunnerActivityState(now);\n\t\t}, 1000);\n\t\tactivityTimer.unref?.();\n\t}\n\theartbeatTimer = setInterval(() => {\n\t\tif (statusPayload.state !== \"running\" && statusPayload.state !== \"queued\") return;\n\t\tstatusPayload.lastUpdate = Date.now();\n\t\twriteStatusPayload();\n\t}, RUNNER_HEARTBEAT_INTERVAL_MS);\n\theartbeatTimer.unref?.();\n\n\tconst interruptRunner = () => {\n\t\tconsumeInterruptRequest(asyncDir);\n\t\tif (interrupted || statusPayload.state !== \"running\") return;\n\t\tinterrupted = true;\n\t\tconst now = Date.now();\n\t\tstatusPayload.state = \"paused\";\n\t\tcurrentActivityState = undefined;\n\t\tdelete statusPayload.activityState;\n\t\tstatusPayload.lastUpdate = now;\n\t\tfor (const step of statusPayload.steps) {\n\t\t\tif (step.status === \"running\") {\n\t\t\t\tstep.status = \"paused\";\n\t\t\t\tdelete step.activityState;\n\t\t\t\tstep.endedAt = now;\n\t\t\t\tsetOptionalProperty(step, \"durationMs\", step.startedAt ? now - step.startedAt : undefined);\n\t\t\t\tstep.lastActivityAt = now;\n\t\t\t}\n\t\t}\n\t\twriteStatusPayload();\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.run.paused\",\n\t\t\t\tts: now,\n\t\t\t\trunId: id,\n\t\t\t}),\n\t\t);\n\t\tinterruptNestedAsyncDescendants();\n\t\tinterruptActiveChildren();\n\t};\n\tconst stopRunner = () => {\n\t\tif (stopped || timedOut || interrupted || statusPayload.state !== \"running\") return;\n\t\tstopped = true;\n\t\tconst now = Date.now();\n\t\tstatusPayload.state = \"stopped\";\n\t\tstatusPayload.stopped = true;\n\t\tstatusPayload.error = stopMessage;\n\t\tcurrentActivityState = undefined;\n\t\tdelete statusPayload.activityState;\n\t\tstatusPayload.lastUpdate = now;\n\t\tfor (const step of statusPayload.steps) {\n\t\t\tif (step.status !== \"running\" && step.status !== \"pending\") continue;\n\t\t\tstep.status = \"stopped\";\n\t\t\tstep.error = stopMessage;\n\t\t\tstep.exitCode = 1;\n\t\t\tstep.stopped = true;\n\t\t\tdelete step.activityState;\n\t\t\tstep.endedAt = now;\n\t\t\tstep.durationMs = step.startedAt ? now - step.startedAt : 0;\n\t\t\tstep.lastActivityAt = now;\n\t\t}\n\t\twriteStatusPayload();\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.run.stopped\",\n\t\t\t\tts: now,\n\t\t\t\trunId: id,\n\t\t\t\tmessage: stopMessage,\n\t\t\t}),\n\t\t);\n\t\tstopAbortController.abort();\n\t\tstopNestedAsyncDescendants();\n\t\tstopActiveChildren();\n\t};\n\tconst timeoutRunner = () => {\n\t\tif (timedOut || stopped || interrupted || statusPayload.state !== \"running\") return;\n\t\ttimedOut = true;\n\t\tconst now = Date.now();\n\t\tconst message = timeoutMessage ?? \"Subagent timed out.\";\n\t\tstatusPayload.state = \"failed\";\n\t\tstatusPayload.timedOut = true;\n\t\tstatusPayload.error = message;\n\t\tcurrentActivityState = undefined;\n\t\tdelete statusPayload.activityState;\n\t\tstatusPayload.lastUpdate = now;\n\t\tfor (const step of statusPayload.steps) {\n\t\t\tif (step.status !== \"running\" && step.status !== \"pending\") continue;\n\t\t\tstep.status = \"failed\";\n\t\t\tstep.error = message;\n\t\t\tstep.exitCode = 1;\n\t\t\tstep.timedOut = true;\n\t\t\tdelete step.activityState;\n\t\t\tstep.endedAt = now;\n\t\t\tstep.durationMs = step.startedAt ? now - step.startedAt : 0;\n\t\t\tstep.lastActivityAt = now;\n\t\t}\n\t\twriteStatusPayload();\n\t\tappendJsonl(\n\t\t\teventsPath,\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"subagent.run.timed_out\",\n\t\t\t\tts: now,\n\t\t\t\trunId: id,\n\t\t\t\ttimeoutMs: config.timeoutMs,\n\t\t\t\tdeadlineAt: config.deadlineAt,\n\t\t\t\tmessage,\n\t\t\t}),\n\t\t);\n\t\ttimeoutAbortController.abort();\n\t\ttimeoutNestedAsyncDescendants();\n\t\ttimeoutActiveChildren();\n\t};\n\tprocess.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);\n\t// Portable control inbox: the parent drops control request files here when\n\t// it cannot deliver OS signals (e.g. ENOSYS on Windows) or when steering a\n\t// live child. Interrupts still route into the same graceful interruptRunner().\n\tconst disposeControlInbox = watchAsyncControlInbox(asyncDir, {\n\t\tonInterrupt: interruptRunner,\n\t\tonTimeout: timeoutRunner,\n\t\tonStop: stopRunner,\n\t\tonCheckpointDecision: (decision) => {\n\t\t\tpendingCheckpointDecision = decision;\n\t\t\twakeCheckpointDecision?.();\n\t\t},\n\t\tonSteer: (request) => {\n\t\t\tconst targetStep = request.targetIndex !== undefined ? statusPayload.steps[request.targetIndex] : undefined;\n\t\t\tif (targetStep?.status === \"pending\") {\n\t\t\t\tdeliverSteerRequest(request);\n\t\t\t\tpendingStepSteers.push(request);\n\t\t\t} else if (\n\t\t\t\trequest.targetIndexes !== undefined ||\n\t\t\t\trequest.targetIndex !== undefined ||\n\t\t\t\tstatusPayload.steps.some((step) => step.status === \"running\")\n\t\t\t) {\n\t\t\t\tdeliverSteerRequest(request);\n\t\t\t} else {\n\t\t\t\tdeliverSteerRequest(request);\n\t\t\t\tpendingStepSteers.push(request);\n\t\t\t}\n\t\t},\n\t\tonSteerCapability: (capability) => {\n\t\t\tsteeringCapabilities.set(capability.index, capability);\n\t\t\tif (!capability.supported) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst lifecycle = steeringStatus(statusPayload);\n\t\t\t\tfor (const request of lifecycle.recent) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!request.targets.some(\n\t\t\t\t\t\t\t(target) =>\n\t\t\t\t\t\t\t\ttarget.index === capability.index &&\n\t\t\t\t\t\t\t\t(target.state === \"routed\" || target.state === \"scheduled\"),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tmarkSteeringAttention(capability.index);\n\t\t\t\t\tupdateSteeringLifecycleTarget(request.id, capability.index, \"failed\", now, {\n\t\t\t\t\t\treason: \"child Pi session does not support steering\",\n\t\t\t\t\t});\n\t\t\t\t\temitSteeringEvent(\n\t\t\t\t\t\t\"subagent.steer.failed\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"steer\",\n\t\t\t\t\t\t\tid: request.id,\n\t\t\t\t\t\t\tts: request.requestedAt,\n\t\t\t\t\t\t\tmessage: \"child Pi session does not support steering\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcapability.index,\n\t\t\t\t\t\t{ reason: \"child Pi session does not support steering\" },\n\t\t\t\t\t);\n\t\t\t\t\temitTerminalSteeringNotice(\n\t\t\t\t\t\trequest.id,\n\t\t\t\t\t\t`Steering failed for run ${id}: child ${capability.index} does not support steering.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tstatusPayload.lastUpdate = now;\n\t\t\t\twriteStatusPayload();\n\t\t\t}\n\t\t},\n\t\tonSteerAck: consumeSteerAck,\n\t});\n\tif (config.deadlineAt !== undefined) {\n\t\tconst remainingMs = Math.max(0, config.deadlineAt - Date.now());\n\t\ttimeoutTimer = setTimeout(timeoutRunner, remainingMs);\n\t\ttimeoutTimer.unref?.();\n\t}\n\tappendJsonl(\n\t\teventsPath,\n\t\tJSON.stringify({\n\t\t\ttype: \"subagent.run.started\",\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tts: overallStartTime,\n\t\t\trunId: id,\n\t\t\tmode: statusPayload.mode,\n\t\t\tcwd,\n\t\t\tpid: process.pid,\n\t\t}),\n\t);\n\n\tlet flatIndex = 0;\n\tlet stepCursor = 0;\n\tconst waitForCheckpointDecision = async (): Promise<\"approved\" | \"rejected\" | undefined> => {\n\t\twhile (!pendingCheckpointDecision && !interrupted && !timedOut && !stopped) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\twakeCheckpointDecision = resolve;\n\t\t\t\tconst timer = setTimeout(resolve, POLL_INTERVAL_MS);\n\t\t\t\ttimer.unref?.();\n\t\t\t});\n\t\t\twakeCheckpointDecision = undefined;\n\t\t}\n\t\tconst decision = pendingCheckpointDecision;\n\t\tpendingCheckpointDecision = undefined;\n\t\treturn decision;\n\t};\n\n\twhile (true) {\n\t\tif (interrupted || timedOut || stopped || turnBudgetExceeded) break;\n\t\tconsumePendingAppendRequests();\n\t\tif (stepCursor >= steps.length) break;\n\t\trefreshUsageBudget();\n\t\tif (statusPayload.usageBudget?.exhausted) {\n\t\t\tusageBudgetExceeded = true;\n\t\t\tstatusPayload.state = \"failed\";\n\t\t\tstatusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);\n\t\t\tstatusPayload.currentStep = flatIndex;\n\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\twriteStatusPayload();\n\t\t\tbreak;\n\t\t}\n\t\tconst stepIndex = stepCursor++;\n\t\tconst step = steps[stepIndex]!;\n\n\t\tif (isCheckpointRunnerStep(step)) {\n\t\t\tconst now = Date.now();\n\t\t\tconst statusStep = statusPayload.steps[flatIndex];\n\t\t\tconst checkpoint = {\n\t\t\t\tname: step.checkpoint,\n\t\t\t\t...(step.message ? { message: step.message } : {}),\n\t\t\t\tstatus: \"pending\" as const,\n\t\t\t\tstepIndex,\n\t\t\t};\n\t\t\tstatusPayload.state = \"paused\";\n\t\t\tstatusPayload.currentStep = flatIndex;\n\t\t\tstatusPayload.checkpoint = checkpoint;\n\t\t\tdelete statusPayload.activityState;\n\t\t\tstatusPayload.lastUpdate = now;\n\t\t\tif (statusStep) {\n\t\t\t\tstatusStep.status = \"paused\";\n\t\t\t\tstatusStep.startedAt = now;\n\t\t\t\tstatusStep.checkpoint = checkpoint;\n\t\t\t}\n\t\t\twriteStatusPayload();\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({ type: \"subagent.checkpoint.paused\", ts: now, runId: id, stepIndex, checkpoint }),\n\t\t\t);\n\t\t\tconst decision = await waitForCheckpointDecision();\n\t\t\tif (decision === \"approved\") {\n\t\t\t\tconst approvedAt = Date.now();\n\t\t\t\tconst approved = { ...checkpoint, status: \"approved\" as const, approvedAt };\n\t\t\t\tstatusPayload.state = \"running\";\n\t\t\t\tstatusPayload.checkpoint = approved;\n\t\t\t\tif (statusStep) {\n\t\t\t\t\tstatusStep.status = \"complete\";\n\t\t\t\t\tstatusStep.endedAt = approvedAt;\n\t\t\t\t\tstatusStep.durationMs = approvedAt - now;\n\t\t\t\t\tstatusStep.exitCode = 0;\n\t\t\t\t\tstatusStep.checkpoint = approved;\n\t\t\t\t}\n\t\t\t\tstatusPayload.lastUpdate = approvedAt;\n\t\t\t\twriteStatusPayload();\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.checkpoint.approved\",\n\t\t\t\t\t\tts: approvedAt,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tcheckpoint: approved,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tflatIndex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (decision === \"rejected\") {\n\t\t\t\tconst rejectedAt = Date.now();\n\t\t\t\tconst rejected = { ...checkpoint, status: \"rejected\" as const, rejectedAt };\n\t\t\t\tcheckpointRejected = true;\n\t\t\t\tstatusPayload.state = \"rejected\";\n\t\t\t\tstatusPayload.error = `Checkpoint '${step.checkpoint}' rejected.`;\n\t\t\t\tstatusPayload.checkpoint = rejected;\n\t\t\t\tif (statusStep) {\n\t\t\t\t\tstatusStep.status = \"rejected\";\n\t\t\t\t\tstatusStep.error = statusPayload.error;\n\t\t\t\t\tstatusStep.endedAt = rejectedAt;\n\t\t\t\t\tstatusStep.durationMs = rejectedAt - now;\n\t\t\t\t\tstatusStep.exitCode = 1;\n\t\t\t\t\tstatusStep.checkpoint = rejected;\n\t\t\t\t}\n\t\t\t\tstatusPayload.lastUpdate = rejectedAt;\n\t\t\t\twriteStatusPayload();\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.checkpoint.rejected\",\n\t\t\t\t\t\tts: rejectedAt,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tcheckpoint: rejected,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif (isDynamicRunnerGroup(step)) {\n\t\t\tconst groupStartFlatIndex = flatIndex;\n\t\t\tlet materialized: ReturnType<typeof materializeDynamicParallelStep>;\n\t\t\ttry {\n\t\t\t\tmaterialized = materializeDynamicParallelStep(\n\t\t\t\t\tstep as Parameters<typeof materializeDynamicParallelStep>[0],\n\t\t\t\t\toutputs,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tomitUndefinedProperties({ maxItems: config.dynamicFanoutMaxItems, allowRunnerFields: true }),\n\t\t\t\t);\n\t\t\t\tif (materialized.parallel.length > 1 && step.parallel.outputPath && !step.parallel.namespaceOutputPath) {\n\t\t\t\t\tthrow new DynamicFanoutError(\n\t\t\t\t\t\t`Dynamic chain step ${stepIndex + 1} materialized ${materialized.parallel.length} items that resolve output to the same path: ${step.parallel.outputPath}. Remove the explicit output path or use an inherited relative agent output so each item can be isolated.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (materialized.collectedOnEmpty)\n\t\t\t\t\tawait validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);\n\t\t\t} catch (error) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst message =\n\t\t\t\t\terror instanceof DynamicFanoutError\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: String(error);\n\t\t\t\tstatusPayload.state = \"failed\";\n\t\t\t\tstatusPayload.error = message;\n\t\t\t\tstatusPayload.currentStep = flatIndex;\n\t\t\t\tconst placeholder = statusPayload.steps[groupStartFlatIndex];\n\t\t\t\tif (placeholder) {\n\t\t\t\t\tplaceholder.status = \"failed\";\n\t\t\t\t\tplaceholder.error = message;\n\t\t\t\t\tplaceholder.startedAt = now;\n\t\t\t\t\tplaceholder.endedAt = now;\n\t\t\t\t\tplaceholder.durationMs = 0;\n\t\t\t\t\tplaceholder.exitCode = 1;\n\t\t\t\t}\n\t\t\t\tstatusPayload.lastUpdate = now;\n\t\t\t\tmarkDynamicGraphGroup(stepIndex, \"failed\", message);\n\t\t\t\twriteStatusPayload();\n\t\t\t\tresults.push(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\tcontext: step.parallel.context,\n\t\t\t\t\t\toutput: message,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst effectiveDynamicGroupAcceptance = resolveEffectiveAcceptance(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\texplicit: step.acceptanceInput,\n\t\t\t\t\tagentName: step.parallel.agent,\n\t\t\t\t\tacceptanceRole: step.acceptanceRole,\n\t\t\t\t\ttask:\n\t\t\t\t\t\tmaterialized.parallel.map((task) => task.task ?? step.parallel.task).join(\"\\n\") || step.parallel.task,\n\t\t\t\t\tmode: config.mode,\n\t\t\t\t\tasync: true,\n\t\t\t\t\tdynamicGroup: true,\n\t\t\t\t\tagentContract: step.agentContract,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tif (materialized.parallel.length === 0) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst collection = materialized.collectedOnEmpty ?? [];\n\t\t\t\toutputs[step.collect.as] = {\n\t\t\t\t\ttext: JSON.stringify(collection),\n\t\t\t\t\tstructured: collection,\n\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\tstepIndex,\n\t\t\t\t};\n\t\t\t\tstatusPayload.outputs = outputs;\n\t\t\t\tconst placeholder = statusPayload.steps[groupStartFlatIndex];\n\t\t\t\tif (placeholder) {\n\t\t\t\t\tplaceholder.status = \"complete\";\n\t\t\t\t\tplaceholder.startedAt = now;\n\t\t\t\t\tplaceholder.endedAt = now;\n\t\t\t\t\tplaceholder.durationMs = 0;\n\t\t\t\t}\n\t\t\t\tpreviousOutput = \"Dynamic fanout produced 0 results.\";\n\t\t\t\tconst groupAcceptance =\n\t\t\t\t\teffectiveDynamicGroupAcceptance.explicit && !timedOut && !stopped\n\t\t\t\t\t\t? await evaluateAcceptance(\n\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\tacceptance: effectiveDynamicGroupAcceptance,\n\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\treport: aggregateAcceptanceReport({\n\t\t\t\t\t\t\t\t\t\tresults: [],\n\t\t\t\t\t\t\t\t\t\tnotes: \"Dynamic fanout produced 0 results.\",\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\tsignal: combinedAbortSignal([timeoutAbortController.signal, stopAbortController.signal]),\n\t\t\t\t\t\t\t\t\tabortMessage: stopAbortController.signal.aborted\n\t\t\t\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t\t\t\t: (timeoutMessage ?? \"Subagent timed out.\"),\n\t\t\t\t\t\t\t\t\treportOptional: isAgentContractV1(step.agentContract),\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\tconst groupStopped = stopped || stopAbortController.signal.aborted;\n\t\t\t\tconst groupTimedOut = !groupStopped && (timedOut || timeoutAbortController.signal.aborted);\n\t\t\t\tconst effectiveGroupAcceptance = groupTimedOut || groupStopped ? undefined : groupAcceptance;\n\t\t\t\tif (placeholder && effectiveGroupAcceptance) placeholder.acceptance = effectiveGroupAcceptance;\n\t\t\t\tconst groupAcceptanceFailure =\n\t\t\t\t\teffectiveGroupAcceptance && (!isAgentContractV1(step.agentContract) || step.gateOn === \"acceptance\")\n\t\t\t\t\t\t? acceptanceFailureMessage(effectiveGroupAcceptance)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (groupTimedOut || groupStopped || groupAcceptanceFailure) {\n\t\t\t\t\tconst errorMessage = groupStopped\n\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t: groupTimedOut\n\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: groupAcceptanceFailure!;\n\t\t\t\t\tstatusPayload.state = groupStopped ? \"stopped\" : \"failed\";\n\t\t\t\t\tstatusPayload.error = errorMessage;\n\t\t\t\t\tsetOptionalProperty(statusPayload, \"stopped\", groupStopped ? true : statusPayload.stopped);\n\t\t\t\t\tif (placeholder) {\n\t\t\t\t\t\tplaceholder.status = groupStopped ? \"stopped\" : \"failed\";\n\t\t\t\t\t\tplaceholder.error = errorMessage;\n\t\t\t\t\t\tplaceholder.exitCode = 1;\n\t\t\t\t\t\tsetOptionalProperty(placeholder, \"timedOut\", groupTimedOut ? true : undefined);\n\t\t\t\t\t\tsetOptionalProperty(placeholder, \"stopped\", groupStopped ? true : undefined);\n\t\t\t\t\t}\n\t\t\t\t\tmarkDynamicGraphGroup(\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tgroupStopped ? \"stopped\" : \"failed\",\n\t\t\t\t\t\terrorMessage,\n\t\t\t\t\t\teffectiveGroupAcceptance,\n\t\t\t\t\t);\n\t\t\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\t\tcontext: step.parallel.context,\n\t\t\t\t\t\t\toutput: errorMessage,\n\t\t\t\t\t\t\terror: errorMessage,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\ttimedOut: groupTimedOut ? true : undefined,\n\t\t\t\t\t\t\tstopped: groupStopped ? true : undefined,\n\t\t\t\t\t\t\tacceptance: effectiveGroupAcceptance,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tflatIndex++;\n\t\t\t\tstatusPayload.lastUpdate = now;\n\t\t\t\tmarkDynamicGraphGroup(stepIndex, \"completed\", undefined, effectiveGroupAcceptance);\n\t\t\t\twriteStatusPayload();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst dynamicSteps = materialized.parallel.map((task, itemIndex) => {\n\t\t\t\tconst thinkingOverride = step.thinkingOverrides?.[itemIndex];\n\t\t\t\tconst model = thinkingOverride\n\t\t\t\t\t? applyThinkingSuffix(step.parallel.model, thinkingOverride, true)\n\t\t\t\t\t: step.parallel.model;\n\t\t\t\tconst thinking = thinkingOverride ? resolveEffectiveThinking(model, thinkingOverride) : undefined;\n\t\t\t\tconst outputPath =\n\t\t\t\t\tstep.parallel.namespaceOutputPath && step.parallel.outputPath\n\t\t\t\t\t\t? path.join(\n\t\t\t\t\t\t\t\tpath.dirname(step.parallel.outputPath),\n\t\t\t\t\t\t\t\t`dynamic-${stepIndex}`,\n\t\t\t\t\t\t\t\t`${itemIndex}-${step.parallel.agent}`,\n\t\t\t\t\t\t\t\tpath.basename(step.parallel.outputPath),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: step.parallel.outputPath;\n\t\t\t\tconst taskText = task.task ?? step.parallel.task;\n\t\t\t\tconst materializedTask = step.parallel.namespaceOutputPath\n\t\t\t\t\t? injectSingleOutputInstruction(taskText, outputPath, step.parallel)\n\t\t\t\t\t: taskText;\n\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\t...step.parallel,\n\t\t\t\t\ttask: materializedTask,\n\t\t\t\t\teffectiveAcceptance: resolveEffectiveAcceptance(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\texplicit: step.parallel.acceptanceInput,\n\t\t\t\t\t\t\tagentName: step.parallel.agent,\n\t\t\t\t\t\t\tacceptanceRole: step.parallel.acceptanceRole,\n\t\t\t\t\t\t\ttask: materializedTask,\n\t\t\t\t\t\t\tmode: config.mode,\n\t\t\t\t\t\t\tasync: true,\n\t\t\t\t\t\t\tdynamic: step.parallel.acceptanceInput === undefined,\n\t\t\t\t\t\t\tagentContract: step.parallel.agentContract ?? step.agentContract,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tsystemPrompt: step.parallel.namespaceOutputPath\n\t\t\t\t\t\t? injectOutputPathSystemPrompt(step.parallel.systemPrompt ?? \"\", outputPath, step.parallel)\n\t\t\t\t\t\t: step.parallel.systemPrompt,\n\t\t\t\t\toutputPath,\n\t\t\t\t\tlabel: task.label ?? step.parallel.label,\n\t\t\t\t\t...(step.sessionFiles?.[itemIndex] ? { sessionFile: step.sessionFiles[itemIndex] } : {}),\n\t\t\t\t\t...(thinkingOverride\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...(model ? { model } : {}),\n\t\t\t\t\t\t\t\t...(thinking ? { thinking } : {}),\n\t\t\t\t\t\t\t\t...(step.parallel.modelCandidates\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tmodelCandidates: step.parallel.modelCandidates.flatMap((candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst resolved = applyThinkingSuffix(candidate, thinkingOverride, true);\n\t\t\t\t\t\t\t\t\t\t\t\treturn resolved ? [resolved] : [];\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\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tstructuredOutputSchema: step.parallel.structuredOutputSchema ?? step.parallel.structuredOutput?.schema,\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst dynamicFlatStepCount = Math.max(statusPayload.steps.length - 1 + dynamicSteps.length, 1);\n\t\t\tconst dynamicStatusSteps: RunnerStatusStep[] = dynamicSteps.map((task, itemIndex) => {\n\t\t\t\tconst transcriptPath = resolveAsyncStepTranscriptPath(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tartifactsDir,\n\t\t\t\t\t\tartifactConfig,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\tflatIndex: groupStartFlatIndex + itemIndex,\n\t\t\t\t\t\tflatStepCount: dynamicFlatStepCount,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),\n\t\t\t\t\t...(task.context ? { context: task.context } : {}),\n\t\t\t\t\t...((task.phase ?? step.phase) ? { phase: task.phase ?? step.phase } : {}),\n\t\t\t\t\t...(task.label ? { label: task.label } : {}),\n\t\t\t\t\tstructured: Boolean(task.structuredOutputSchema),\n\t\t\t\t\t...(task.agentContract ? { agentContract: task.agentContract } : {}),\n\t\t\t\t\t...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),\n\t\t\t\t\t...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),\n\t\t\t\t\t...(transcriptPath ? { transcriptPath } : {}),\n\t\t\t\t\t...(task.skills ? { skills: task.skills } : {}),\n\t\t\t\t\t...(task.model ? { model: task.model } : {}),\n\t\t\t\t\t...(task.thinking ? { thinking: task.thinking } : {}),\n\t\t\t\t\t...(task.modelCandidates && task.modelCandidates.length > 0\n\t\t\t\t\t\t? { attemptedModels: task.modelCandidates }\n\t\t\t\t\t\t: task.model\n\t\t\t\t\t\t\t? { attemptedModels: [task.model] }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\trecentTools: [],\n\t\t\t\t\trecentOutput: [],\n\t\t\t\t});\n\t\t\t});\n\t\t\tstatusPayload.steps.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps);\n\t\t\tif (config.childIntercomTargets) {\n\t\t\t\tconfig.childIntercomTargets = statusPayload.steps.map((statusStep, index) =>\n\t\t\t\t\tresolveSubagentIntercomTarget(id, statusStep.agent, index),\n\t\t\t\t);\n\t\t\t}\n\t\t\tmutatingFailureStates.splice(\n\t\t\t\tgroupStartFlatIndex,\n\t\t\t\t1,\n\t\t\t\t...dynamicStatusSteps.map(() => createMutatingFailureState()),\n\t\t\t);\n\t\t\tpendingToolResults.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => undefined));\n\t\t\tconst materializedDelta = dynamicStatusSteps.length - 1;\n\t\t\tfor (const group of statusPayload.parallelGroups) {\n\t\t\t\tif (group.stepIndex === stepIndex) {\n\t\t\t\t\tgroup.start = groupStartFlatIndex;\n\t\t\t\t\tgroup.count = dynamicStatusSteps.length;\n\t\t\t\t} else if (group.start > groupStartFlatIndex) {\n\t\t\t\t\tgroup.start += materializedDelta;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (statusPayload.workflowGraph) {\n\t\t\t\tconst shiftFlatIndexes = (nodes: NonNullable<typeof statusPayload.workflowGraph>[\"nodes\"]): void => {\n\t\t\t\t\tfor (const node of nodes) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tnode.stepIndex !== undefined &&\n\t\t\t\t\t\t\tnode.stepIndex > stepIndex &&\n\t\t\t\t\t\t\tnode.flatIndex !== undefined &&\n\t\t\t\t\t\t\tnode.flatIndex >= groupStartFlatIndex\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tnode.flatIndex += dynamicStatusSteps.length;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (node.children) shiftFlatIndexes(node.children);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tshiftFlatIndexes(statusPayload.workflowGraph.nodes);\n\t\t\t\tconst groupNode = statusPayload.workflowGraph.nodes.find((node) => node.id === `step-${stepIndex}`);\n\t\t\t\tif (groupNode) {\n\t\t\t\t\tgroupNode.children = materialized.items.map((item, itemIndex) =>\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tid: `step-${stepIndex}-item-${item.idKey}`,\n\t\t\t\t\t\t\tkind: \"agent\",\n\t\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\t\tphase: dynamicSteps[itemIndex]?.phase ?? step.phase,\n\t\t\t\t\t\t\tlabel: dynamicSteps[itemIndex]?.label?.trim() || `${step.parallel.agent} ${item.key}`,\n\t\t\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\t\t\tflatIndex: groupStartFlatIndex + itemIndex,\n\t\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\t\titemKey: item.key,\n\t\t\t\t\t\t\tstructured: Boolean(dynamicSteps[itemIndex]?.structuredOutputSchema),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteStatusPayload();\n\n\t\t\tconst concurrency = step.concurrency ?? MAX_PARALLEL_CONCURRENCY;\n\t\t\tconst failFast = step.failFast ?? false;\n\t\t\tlet aborted = false;\n\t\t\tconst parallelResults = await mapConcurrent(\n\t\t\t\tdynamicSteps,\n\t\t\t\tconcurrency,\n\t\t\t\tasync (task, taskIdx): Promise<StepResult> => {\n\t\t\t\t\tconst fi = groupStartFlatIndex + taskIdx;\n\t\t\t\t\trefreshUsageBudget();\n\t\t\t\t\tif (statusPayload.usageBudget?.exhausted) {\n\t\t\t\t\t\tconst skippedAt = Date.now();\n\t\t\t\t\t\tconst message = usageBudgetExceededMessage(statusPayload.usageBudget);\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"failed\";\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).error = message;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = skippedAt;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = skippedAt;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = 0;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode = 1;\n\t\t\t\t\t\tstatusPayload.lastUpdate = skippedAt;\n\t\t\t\t\t\tusageBudgetExceeded = true;\n\t\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\ttype: \"subagent.step.failed\",\n\t\t\t\t\t\t\t\tts: skippedAt,\n\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\tdurationMs: 0,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\tcontext: task.context,\n\t\t\t\t\t\t\toutput: message,\n\t\t\t\t\t\t\terror: message,\n\t\t\t\t\t\t\texitCode: 1 as number | null,\n\t\t\t\t\t\t\tskipped: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (timedOut) return timedOutStepResult(task.agent, task.context);\n\t\t\t\t\tif (stopped) return stoppedStepResult(task.agent, task.context);\n\t\t\t\t\tif (interrupted) return pausedStepResult(task.agent, task.context);\n\t\t\t\t\tif (aborted && failFast) {\n\t\t\t\t\t\tconst skippedAt = Date.now();\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"failed\";\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).error = \"Skipped due to fail-fast\";\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = skippedAt;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = skippedAt;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = 0;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode = -1;\n\t\t\t\t\t\tstatusPayload.lastUpdate = skippedAt;\n\t\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\tcontext: task.context,\n\t\t\t\t\t\t\toutput: \"(skipped — fail-fast)\",\n\t\t\t\t\t\t\texitCode: -1 as number | null,\n\t\t\t\t\t\t\tskipped: true,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst taskStartTime = Date.now();\n\t\t\t\t\tstatusPayload.currentStep = fi;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"running\";\n\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).error;\n\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).activityState;\n\t\t\t\t\tresetStepLiveDetail(requiredStatusStep(statusPayload, fi));\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = taskStartTime;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).lastActivityAt = taskStartTime;\n\t\t\t\t\tstatusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);\n\t\t\t\t\tstatusPayload.lastActivityAt = taskStartTime;\n\t\t\t\t\tstatusPayload.lastUpdate = taskStartTime;\n\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\ttype: \"subagent.step.started\",\n\t\t\t\t\t\t\tts: taskStartTime,\n\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tflushPendingStepSteers(fi);\n\t\t\t\t\tconst singleResult = await runSingleStep(\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\tcompactOptional<SingleStepContext>({\n\t\t\t\t\t\t\tpreviousOutput,\n\t\t\t\t\t\t\tplaceholder,\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tsessionEnabled,\n\t\t\t\t\t\t\toutputs,\n\t\t\t\t\t\t\tsessionDir: config.sessionDir\n\t\t\t\t\t\t\t\t? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tartifactsDir,\n\t\t\t\t\t\t\tartifactConfig,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tflatIndex: fi,\n\t\t\t\t\t\t\tflatStepCount: Math.max(statusPayload.steps.length, 1),\n\t\t\t\t\t\t\toutputFile: path.join(asyncDir, `output-${fi}.log`),\n\t\t\t\t\t\t\tsteerInboxDir: stepSteerInboxDir(asyncDir, fi),\n\t\t\t\t\t\t\tsteerCapabilityPath: steerCapabilityPath(asyncDir, fi),\n\t\t\t\t\t\t\tsteerAckDir: steerAcksDir(asyncDir, fi),\n\t\t\t\t\t\t\tpiPackageRoot: config.piPackageRoot,\n\t\t\t\t\t\t\tpiArgv1: config.piArgv1,\n\t\t\t\t\t\t\tchildIntercomTarget: config.childIntercomTargets?.[fi],\n\t\t\t\t\t\t\torchestratorIntercomTarget: config.controlIntercomTarget,\n\t\t\t\t\t\t\tnestedRoute: config.nestedRoute,\n\t\t\t\t\t\t\tcapabilityCeiling: config.capabilityCeiling,\n\t\t\t\t\t\t\tregisterInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),\n\t\t\t\t\t\t\tregisterTimeout: (interrupt) => registerStepTimeout(fi, interrupt),\n\t\t\t\t\t\t\tregisterStop: (stop) => registerStepStop(fi, stop),\n\t\t\t\t\t\t\tregisterTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),\n\t\t\t\t\t\t\ttimeoutSignal: timeoutAbortController.signal,\n\t\t\t\t\t\t\tstopSignal: stopAbortController.signal,\n\t\t\t\t\t\t\ttimeoutMessage,\n\t\t\t\t\t\t\tstopMessage,\n\t\t\t\t\t\t\tturnBudget: config.turnBudget,\n\t\t\t\t\t\t\tonAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),\n\t\t\t\t\t\t\tonChildEvent: (event) => updateStepFromChildEvent(fi, event),\n\t\t\t\t\t\t\tonWriterProcess,\n\t\t\t\t\t\t\tonExternalProcess: (process) => updateExternalProcess(fi, process),\n\t\t\t\t\t\t\tskipAcceptance: () => timedOut || stopped,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tconst taskEndTime = Date.now();\n\t\t\t\t\tconst childInterrupted = singleResult.interrupted === true;\n\t\t\t\t\tconst childStopped = singleResult.stopped === true;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).status =\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? \"stopped\"\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t\t\t? \"paused\"\n\t\t\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t? \"complete\"\n\t\t\t\t\t\t\t\t\t\t: \"failed\";\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = taskEndTime;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = taskEndTime - taskStartTime;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode =\n\t\t\t\t\t\tstopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"timedOut\",\n\t\t\t\t\t\ttimedOut || singleResult.timedOut ? true : undefined,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"stopped\",\n\t\t\t\t\t\tstopped || childStopped ? true : undefined,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"turnBudget\", singleResult.turnBudget);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"turnBudgetExceeded\",\n\t\t\t\t\t\tsingleResult.turnBudgetExceeded,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"wrapUpRequested\",\n\t\t\t\t\t\tsingleResult.wrapUpRequested,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"toolBudget\", singleResult.toolBudget);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"toolBudgetBlocked\",\n\t\t\t\t\t\tsingleResult.toolBudgetBlocked,\n\t\t\t\t\t);\n\t\t\t\t\tif (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;\n\t\t\t\t\tif (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;\n\t\t\t\t\tif (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;\n\t\t\t\t\tif (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;\n\t\t\t\t\tif (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"model\", singleResult.model);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"thinking\",\n\t\t\t\t\t\tresolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking),\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"attemptedModels\",\n\t\t\t\t\t\tsingleResult.attemptedModels,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"modelAttempts\", singleResult.modelAttempts);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"totalCost\", singleResult.totalCost);\n\t\t\t\t\tif (singleResult.totalCost) {\n\t\t\t\t\t\tpendingParallelUsageCost = {\n\t\t\t\t\t\t\tinputTokens: pendingParallelUsageCost.inputTokens + singleResult.totalCost.inputTokens,\n\t\t\t\t\t\t\toutputTokens: pendingParallelUsageCost.outputTokens + singleResult.totalCost.outputTokens,\n\t\t\t\t\t\t\tcostUsd: pendingParallelUsageCost.costUsd + singleResult.totalCost.costUsd,\n\t\t\t\t\t\t};\n\t\t\t\t\t\trefreshUsageBudget();\n\t\t\t\t\t}\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t\t: singleResult.error,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"transcriptPath\",\n\t\t\t\t\t\tsingleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"transcriptError\",\n\t\t\t\t\t\tsingleResult.transcriptError,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"agentContract\", singleResult.agentContract);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"launchContractDigest\",\n\t\t\t\t\t\tsingleResult.launchContractDigest,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"launchResolvedExtensions\",\n\t\t\t\t\t\tsingleResult.launchResolvedExtensions,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"runtimeAcknowledgedExtensions\",\n\t\t\t\t\t\tsingleResult.runtimeAcknowledgedExtensions,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"effects\", singleResult.effects);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"execution\", singleResult.execution);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"review\", singleResult.review);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"structuredOutput\",\n\t\t\t\t\t\tsingleResult.structuredOutput,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"structuredOutputPath\",\n\t\t\t\t\t\tsingleResult.structuredOutputPath,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"structuredOutputSchemaPath\",\n\t\t\t\t\t\tsingleResult.structuredOutputSchemaPath,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"acceptance\", singleResult.acceptance);\n\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"watchdog\", singleResult.watchdog);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"capabilityCeiling\",\n\t\t\t\t\t\tsingleResult.capabilityCeiling,\n\t\t\t\t\t);\n\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\"capabilityAudit\",\n\t\t\t\t\t\tsingleResult.capabilityAudit,\n\t\t\t\t\t);\n\t\t\t\t\tif (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;\n\t\t\t\t\tif (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;\n\t\t\t\t\tstatusPayload.lastUpdate = taskEndTime;\n\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\tappendCapabilityCeilingAppliedEvent(eventsPath, id, fi, task.agent, singleResult);\n\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\ttype:\n\t\t\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t\t\t? \"subagent.step.stopped\"\n\t\t\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t\t\t? \"subagent.step.failed\"\n\t\t\t\t\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t\t\t\t\t? \"subagent.step.paused\"\n\t\t\t\t\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t\t\t? \"subagent.step.completed\"\n\t\t\t\t\t\t\t\t\t\t\t\t: \"subagent.step.failed\",\n\t\t\t\t\t\t\tts: taskEndTime,\n\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\texitCode:\n\t\t\t\t\t\t\t\tstopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode,\n\t\t\t\t\t\t\tdurationMs: taskEndTime - taskStartTime,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tif (singleResult.exitCode !== 0 && failFast) aborted = true;\n\t\t\t\t\treturn stopped || childStopped\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...singleResult,\n\t\t\t\t\t\t\t\toutput: stopMessage,\n\t\t\t\t\t\t\t\terror: stopMessage,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\tinterrupted: false,\n\t\t\t\t\t\t\t\ttimedOut: false,\n\t\t\t\t\t\t\t\tstopped: true,\n\t\t\t\t\t\t\t\tskipped: false,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...singleResult,\n\t\t\t\t\t\t\t\t\toutput: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\t\t\t\t\t\t\terror: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\tinterrupted: false,\n\t\t\t\t\t\t\t\t\ttimedOut: true,\n\t\t\t\t\t\t\t\t\tskipped: false,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: { ...singleResult, skipped: false };\n\t\t\t\t},\n\t\t\t\tglobalSemaphore,\n\t\t\t);\n\n\t\t\tflatIndex += dynamicSteps.length;\n\t\t\tfor (const pr of parallelResults) {\n\t\t\t\tresults.push(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: pr.agent,\n\t\t\t\t\t\tcontext: pr.context,\n\t\t\t\t\t\tagentContract: pr.agentContract,\n\t\t\t\t\t\tlaunchContractDigest: pr.launchContractDigest,\n\t\t\t\t\t\tlaunchResolvedExtensions: pr.launchResolvedExtensions,\n\t\t\t\t\t\truntimeAcknowledgedExtensions: pr.runtimeAcknowledgedExtensions,\n\t\t\t\t\t\toutput: pr.output,\n\t\t\t\t\t\toutputState: pr.outputState,\n\t\t\t\t\t\terror: pr.error,\n\t\t\t\t\t\tprotocolError: pr.protocolError,\n\t\t\t\t\t\tsuccess: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,\n\t\t\t\t\t\texitCode: pr.interrupted === true ? 0 : pr.exitCode,\n\t\t\t\t\t\tskipped: pr.skipped,\n\t\t\t\t\t\tinterrupted: pr.interrupted,\n\t\t\t\t\t\ttimedOut: pr.timedOut,\n\t\t\t\t\t\tstopped: pr.stopped,\n\t\t\t\t\t\tturnBudget: pr.turnBudget,\n\t\t\t\t\t\tturnBudgetExceeded: pr.turnBudgetExceeded,\n\t\t\t\t\t\twrapUpRequested: pr.wrapUpRequested,\n\t\t\t\t\t\ttoolBudget: pr.toolBudget,\n\t\t\t\t\t\ttoolBudgetBlocked: pr.toolBudgetBlocked,\n\t\t\t\t\t\tsessionFile: pr.sessionFile,\n\t\t\t\t\t\tintercomTarget: pr.intercomTarget,\n\t\t\t\t\t\tmodel: pr.model,\n\t\t\t\t\t\tattemptedModels: pr.attemptedModels,\n\t\t\t\t\t\tmodelAttempts: pr.modelAttempts,\n\t\t\t\t\t\ttotalCost: pr.totalCost,\n\t\t\t\t\t\tartifactPaths: pr.artifactPaths,\n\t\t\t\t\t\ttranscriptPath: pr.transcriptPath,\n\t\t\t\t\t\ttranscriptError: pr.transcriptError,\n\t\t\t\t\t\teffects: pr.effects,\n\t\t\t\t\t\texecution: pr.execution,\n\t\t\t\t\t\treview: pr.review,\n\t\t\t\t\t\tstructuredOutput: pr.structuredOutput,\n\t\t\t\t\t\tstructuredOutputPath: pr.structuredOutputPath,\n\t\t\t\t\t\tstructuredOutputSchemaPath: pr.structuredOutputSchemaPath,\n\t\t\t\t\t\tacceptance: pr.acceptance,\n\t\t\t\t\t\twatchdog: pr.watchdog,\n\t\t\t\t\t\tcapabilityCeiling: pr.capabilityCeiling,\n\t\t\t\t\t\tcapabilityAudit: pr.capabilityAudit,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tpendingParallelUsageCost = { inputTokens: 0, outputTokens: 0, costUsd: 0 };\n\t\t\trefreshUsageBudget();\n\t\t\tconst collection = collectDynamicResults(\n\t\t\t\tstep as Parameters<typeof collectDynamicResults>[0],\n\t\t\t\tmaterialized.items,\n\t\t\t\tparallelResults,\n\t\t\t);\n\t\t\tconst failures = parallelResults.filter((result) => result.exitCode !== 0 && result.exitCode !== -1);\n\t\t\tconst acceptanceFailures = parallelResults\n\t\t\t\t.map((result, originalIndex) => ({ result, originalIndex, task: dynamicSteps[originalIndex] }))\n\t\t\t\t.filter(\n\t\t\t\t\t({ result, task }) =>\n\t\t\t\t\t\tisAgentContractV1(task?.agentContract ?? step.agentContract) &&\n\t\t\t\t\t\ttask?.gateOn === \"acceptance\" &&\n\t\t\t\t\t\tresult.acceptance?.status === \"rejected\",\n\t\t\t\t);\n\t\t\tif (acceptanceFailures.length > 0) {\n\t\t\t\tconst message = acceptanceFailures\n\t\t\t\t\t.map(\n\t\t\t\t\t\t({ result, originalIndex }) =>\n\t\t\t\t\t\t\t`Dynamic item ${originalIndex + 1} (${result.agent}, key ${materialized.items[originalIndex]?.key ?? originalIndex}) acceptance rejected: ${(result.acceptance ? acceptanceFailureMessage(result.acceptance) : undefined) ?? \"acceptance rejected\"}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tresults.push(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\tcontext: step.parallel.context,\n\t\t\t\t\t\toutput: message,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\tstructuredOutput: collection,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tstatusPayload.error = message;\n\t\t\t\tmarkDynamicGraphGroup(stepIndex, \"failed\", message);\n\t\t\t}\n\t\t\tif (failures.length === 0 && acceptanceFailures.length === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait validateDynamicCollection(step.collect.outputSchema, collection);\n\t\t\t\t\toutputs[step.collect.as] = {\n\t\t\t\t\t\ttext: JSON.stringify(collection),\n\t\t\t\t\t\tstructured: collection,\n\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t};\n\t\t\t\t\tstatusPayload.outputs = outputs;\n\t\t\t\t\tconst groupAcceptance =\n\t\t\t\t\t\t!timedOut && !stopped\n\t\t\t\t\t\t\t? await evaluateAcceptance(\n\t\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\t\tacceptance: effectiveDynamicGroupAcceptance,\n\t\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\t\treport: aggregateAcceptanceReport({\n\t\t\t\t\t\t\t\t\t\t\tresults: parallelResults,\n\t\t\t\t\t\t\t\t\t\t\tnotes: `Dynamic fanout collected ${collection.length} result(s) into ${step.collect.as}.`,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\t\tsignal: combinedAbortSignal([timeoutAbortController.signal, stopAbortController.signal]),\n\t\t\t\t\t\t\t\t\t\tabortMessage: stopAbortController.signal.aborted\n\t\t\t\t\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t\t\t\t\t: (timeoutMessage ?? \"Subagent timed out.\"),\n\t\t\t\t\t\t\t\t\t\treportOptional: isAgentContractV1(step.agentContract),\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: undefined;\n\t\t\t\t\tconst groupStopped = stopped || stopAbortController.signal.aborted;\n\t\t\t\t\tconst groupTimedOut = !groupStopped && (timedOut || timeoutAbortController.signal.aborted);\n\t\t\t\t\tconst effectiveGroupAcceptance = groupTimedOut || groupStopped ? undefined : groupAcceptance;\n\t\t\t\t\tconst groupAcceptanceFailure =\n\t\t\t\t\t\teffectiveDynamicGroupAcceptance.explicit &&\n\t\t\t\t\t\teffectiveGroupAcceptance &&\n\t\t\t\t\t\t(!isAgentContractV1(step.agentContract) || step.gateOn === \"acceptance\")\n\t\t\t\t\t\t\t? acceptanceFailureMessage(effectiveGroupAcceptance)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst groupError = groupStopped\n\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t: groupTimedOut\n\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: groupAcceptanceFailure;\n\t\t\t\t\tmarkDynamicGraphGroup(\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tgroupError ? (groupStopped ? \"stopped\" : \"failed\") : \"completed\",\n\t\t\t\t\t\tgroupError,\n\t\t\t\t\t\teffectiveGroupAcceptance,\n\t\t\t\t\t);\n\t\t\t\t\tif (groupError) {\n\t\t\t\t\t\tresults.push(\n\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\t\t\toutput: groupError,\n\t\t\t\t\t\t\t\terror: groupError,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\ttimedOut: groupTimedOut ? true : undefined,\n\t\t\t\t\t\t\t\tstopped: groupStopped ? true : undefined,\n\t\t\t\t\t\t\t\tstructuredOutput: collection,\n\t\t\t\t\t\t\t\tacceptance: effectiveGroupAcceptance,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstatusPayload.error = groupError;\n\t\t\t\t\t\tsetOptionalProperty(statusPayload, \"stopped\", groupStopped ? true : statusPayload.stopped);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message =\n\t\t\t\t\t\terror instanceof DynamicFanoutError\n\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t\t\t: String(error);\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagent: step.parallel.agent,\n\t\t\t\t\t\t\tcontext: step.parallel.context,\n\t\t\t\t\t\t\toutput: message,\n\t\t\t\t\t\t\terror: message,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\tstructuredOutput: collection,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tstatusPayload.error = message;\n\t\t\t\t\tmarkDynamicGraphGroup(stepIndex, \"failed\", message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpreviousOutput = aggregateParallelOutputs(\n\t\t\t\tparallelResults.map((r, i) =>\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tagent: r.agent,\n\t\t\t\t\t\ttaskIndex: i,\n\t\t\t\t\t\toutput: r.output,\n\t\t\t\t\t\texitCode: r.exitCode,\n\t\t\t\t\t\terror: r.error,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\t(i, agent) => `=== Dynamic Item ${i + 1} (${agent}, key ${materialized.items[i]?.key ?? i}) ===`,\n\t\t\t);\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.dynamic.completed\",\n\t\t\t\t\tts: Date.now(),\n\t\t\t\t\trunId: id,\n\t\t\t\t\tstepIndex,\n\t\t\t\t\tsuccess: failures.length === 0 && acceptanceFailures.length === 0,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (failures.length > 0)\n\t\t\t\tmarkDynamicGraphGroup(stepIndex, \"failed\", failures[0]?.error ?? \"Dynamic fanout child failed.\");\n\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\twriteStatusPayload();\n\t\t\tif (failures.length > 0 || statusPayload.error) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isParallelGroup(step)) {\n\t\t\tconst group = step;\n\t\t\tconst concurrency = group.concurrency ?? MAX_PARALLEL_CONCURRENCY;\n\t\t\tconst failFast = group.failFast ?? false;\n\t\t\tconst groupStartFlatIndex = flatIndex;\n\t\t\tlet aborted = false;\n\t\t\tlet worktreeSetup: WorktreeSetup | undefined;\n\t\t\tlet worktreeFinalized = false;\n\t\t\tif (group.worktree) {\n\t\t\t\tconst worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, cwd);\n\t\t\t\tif (worktreeTaskCwdConflict) {\n\t\t\t\t\tconst failedAt = Date.now();\n\t\t\t\t\tmarkParallelGroupSetupFailure({\n\t\t\t\t\t\tstatusPayload,\n\t\t\t\t\t\tresults,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t\tgroupStartFlatIndex,\n\t\t\t\t\t\tsetupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, cwd),\n\t\t\t\t\t\tfailedAt,\n\t\t\t\t\t\tstatusPath,\n\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t});\n\t\t\t\t\tflatIndex += group.parallel.length;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tworktreeSetup = createWorktrees(\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t`${id}-s${stepIndex}`,\n\t\t\t\t\t\tgroup.parallel.length,\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagents: group.parallel.map((task) => task.agent),\n\t\t\t\t\t\t\tsetupHook: config.worktreeSetupHook\n\t\t\t\t\t\t\t\t? omitUndefinedProperties({\n\t\t\t\t\t\t\t\t\t\thookPath: config.worktreeSetupHook,\n\t\t\t\t\t\t\t\t\t\ttimeoutMs: config.worktreeSetupHookTimeoutMs,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tbaseDir: config.worktreeBaseDir,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst setupError = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tconst failedAt = Date.now();\n\t\t\t\t\tmarkParallelGroupSetupFailure({\n\t\t\t\t\t\tstatusPayload,\n\t\t\t\t\t\tresults,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t\tgroupStartFlatIndex,\n\t\t\t\t\t\tsetupError,\n\t\t\t\t\t\tfailedAt,\n\t\t\t\t\t\tstatusPath,\n\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t});\n\t\t\t\t\tflatIndex += group.parallel.length;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (worktreeSetup) {\n\t\t\t\t\twritePendingParallelHandoff({\n\t\t\t\t\t\tmanifestPath: parallelHandoffPath(asyncDir),\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tmode: (config.resultMode ?? statusPayload.mode) === \"parallel\" ? \"parallel\" : \"chain\",\n\t\t\t\t\t\tsource: \"async\",\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tflatStartIndex: groupStartFlatIndex,\n\t\t\t\t\t\tsetup: worktreeSetup,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (group.worktree) ensureParallelProgressFile(cwd, group);\n\t\t\t\tconst groupStartTime = Date.now();\n\t\t\t\tmarkParallelGroupRunning({\n\t\t\t\t\tstatusPayload,\n\t\t\t\t\tgroup,\n\t\t\t\t\tgroupStartFlatIndex,\n\t\t\t\t\tgroupStartTime,\n\t\t\t\t\tstatusPath,\n\t\t\t\t\teventsPath,\n\t\t\t\t\tasyncDir,\n\t\t\t\t\trunId: id,\n\t\t\t\t\tstepIndex,\n\t\t\t\t});\n\t\t\t\tconst parallelResults = await mapConcurrent(\n\t\t\t\t\tgroup.parallel,\n\t\t\t\t\tconcurrency,\n\t\t\t\t\tasync (task, taskIdx): Promise<StepResult> => {\n\t\t\t\t\t\tconst fi = groupStartFlatIndex + taskIdx;\n\t\t\t\t\t\trefreshUsageBudget();\n\t\t\t\t\t\tif (statusPayload.usageBudget?.exhausted) {\n\t\t\t\t\t\t\tconst skippedAt = Date.now();\n\t\t\t\t\t\t\tconst message = usageBudgetExceededMessage(statusPayload.usageBudget);\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"failed\";\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).error = message;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = skippedAt;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = skippedAt;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = 0;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode = 1;\n\t\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).activityState;\n\t\t\t\t\t\t\tstatusPayload.lastUpdate = skippedAt;\n\t\t\t\t\t\t\tusageBudgetExceeded = true;\n\t\t\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t\ttype: \"subagent.step.failed\",\n\t\t\t\t\t\t\t\t\tts: skippedAt,\n\t\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\tdurationMs: 0,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\tcontext: task.context,\n\t\t\t\t\t\t\t\toutput: message,\n\t\t\t\t\t\t\t\terror: message,\n\t\t\t\t\t\t\t\texitCode: 1 as number | null,\n\t\t\t\t\t\t\t\tskipped: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (timedOut) return timedOutStepResult(task.agent, task.context);\n\t\t\t\t\t\tif (stopped) return stoppedStepResult(task.agent, task.context);\n\t\t\t\t\t\tif (interrupted) return pausedStepResult(task.agent, task.context);\n\t\t\t\t\t\tif (aborted && failFast) {\n\t\t\t\t\t\t\tconst skippedAt = Date.now();\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"failed\";\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).error = \"Skipped due to fail-fast\";\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = skippedAt;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = skippedAt;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = 0;\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode = -1;\n\t\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).activityState;\n\t\t\t\t\t\t\tstatusPayload.lastUpdate = skippedAt;\n\t\t\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t\ttype: \"subagent.step.failed\",\n\t\t\t\t\t\t\t\t\tts: skippedAt,\n\t\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\t\texitCode: -1,\n\t\t\t\t\t\t\t\t\tdurationMs: 0,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn omitUndefinedProperties({\n\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\tcontext: task.context,\n\t\t\t\t\t\t\t\toutput: \"(skipped — fail-fast)\",\n\t\t\t\t\t\t\t\texitCode: -1 as number | null,\n\t\t\t\t\t\t\t\tskipped: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst taskStartTime = Date.now();\n\t\t\t\t\t\tstatusPayload.currentStep = fi;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status = \"running\";\n\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).error;\n\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).activityState;\n\t\t\t\t\t\tresetStepLiveDetail(requiredStatusStep(statusPayload, fi));\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).startedAt = taskStartTime;\n\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).endedAt;\n\t\t\t\t\t\tdelete requiredStatusStep(statusPayload, fi).durationMs;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).lastActivityAt = taskStartTime;\n\t\t\t\t\t\tstatusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);\n\t\t\t\t\t\tstatusPayload.lastActivityAt = taskStartTime;\n\t\t\t\t\t\tstatusPayload.lastUpdate = taskStartTime;\n\t\t\t\t\t\twriteStatusPayload();\n\n\t\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\ttype: \"subagent.step.started\",\n\t\t\t\t\t\t\t\tts: taskStartTime,\n\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst taskSessionDir = config.sessionDir\n\t\t\t\t\t\t\t? path.join(config.sessionDir, `parallel-${taskIdx}`)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst { taskForRun, taskCwd } = prepareParallelTaskRun(task, cwd, worktreeSetup, taskIdx);\n\t\t\t\t\t\tflushPendingStepSteers(fi);\n\n\t\t\t\t\t\tconst singleResult = await runSingleStep(\n\t\t\t\t\t\t\ttaskForRun,\n\t\t\t\t\t\t\tcompactOptional<SingleStepContext>({\n\t\t\t\t\t\t\t\tpreviousOutput,\n\t\t\t\t\t\t\t\tplaceholder,\n\t\t\t\t\t\t\t\tcwd: taskCwd,\n\t\t\t\t\t\t\t\tsessionEnabled,\n\t\t\t\t\t\t\t\toutputs,\n\t\t\t\t\t\t\t\tsessionDir: taskSessionDir,\n\t\t\t\t\t\t\t\tartifactsDir,\n\t\t\t\t\t\t\t\tartifactConfig,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tflatIndex: fi,\n\t\t\t\t\t\t\t\tflatStepCount: Math.max(statusPayload.steps.length, 1),\n\t\t\t\t\t\t\t\toutputFile: path.join(asyncDir, `output-${fi}.log`),\n\t\t\t\t\t\t\t\tsteerInboxDir: stepSteerInboxDir(asyncDir, fi),\n\t\t\t\t\t\t\t\tsteerCapabilityPath: steerCapabilityPath(asyncDir, fi),\n\t\t\t\t\t\t\t\tsteerAckDir: steerAcksDir(asyncDir, fi),\n\t\t\t\t\t\t\t\tpiPackageRoot: config.piPackageRoot,\n\t\t\t\t\t\t\t\tpiArgv1: config.piArgv1,\n\t\t\t\t\t\t\t\tchildIntercomTarget: config.childIntercomTargets?.[fi],\n\t\t\t\t\t\t\t\torchestratorIntercomTarget: config.controlIntercomTarget,\n\t\t\t\t\t\t\t\tnestedRoute: config.nestedRoute,\n\t\t\t\t\t\t\t\tcapabilityCeiling: config.capabilityCeiling,\n\t\t\t\t\t\t\t\tregisterInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),\n\t\t\t\t\t\t\t\tregisterTimeout: (interrupt) => registerStepTimeout(fi, interrupt),\n\t\t\t\t\t\t\t\tregisterStop: (stop) => registerStepStop(fi, stop),\n\t\t\t\t\t\t\t\tregisterTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),\n\t\t\t\t\t\t\t\ttimeoutSignal: timeoutAbortController.signal,\n\t\t\t\t\t\t\t\tstopSignal: stopAbortController.signal,\n\t\t\t\t\t\t\t\ttimeoutMessage,\n\t\t\t\t\t\t\t\tstopMessage,\n\t\t\t\t\t\t\t\tturnBudget: config.turnBudget,\n\t\t\t\t\t\t\t\tonAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),\n\t\t\t\t\t\t\t\tonChildEvent: (event) => updateStepFromChildEvent(fi, event),\n\t\t\t\t\t\t\t\tonWriterProcess,\n\t\t\t\t\t\t\t\tonExternalProcess: (process) => updateExternalProcess(fi, process),\n\t\t\t\t\t\t\t\tskipAcceptance: () => timedOut || stopped,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (task.sessionFile) {\n\t\t\t\t\t\t\tlatestSessionFile = task.sessionFile;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst taskEndTime = Date.now();\n\t\t\t\t\t\tconst taskDuration = taskEndTime - taskStartTime;\n\t\t\t\t\t\tconst childInterrupted = singleResult.interrupted === true;\n\t\t\t\t\t\tconst childStopped = singleResult.stopped === true;\n\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).status =\n\t\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t\t? \"stopped\"\n\t\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t\t\t\t? \"paused\"\n\t\t\t\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t\t? \"complete\"\n\t\t\t\t\t\t\t\t\t\t\t: \"failed\";\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).endedAt = taskEndTime;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).durationMs = taskDuration;\n\t\t\t\t\t\trequiredStatusStep(statusPayload, fi).exitCode =\n\t\t\t\t\t\t\tstopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"timedOut\",\n\t\t\t\t\t\t\ttimedOut || singleResult.timedOut ? true : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"stopped\",\n\t\t\t\t\t\t\tstopped || childStopped ? true : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"turnBudget\", singleResult.turnBudget);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"turnBudgetExceeded\",\n\t\t\t\t\t\t\tsingleResult.turnBudgetExceeded,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"wrapUpRequested\",\n\t\t\t\t\t\t\tsingleResult.wrapUpRequested,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"toolBudget\", singleResult.toolBudget);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"toolBudgetBlocked\",\n\t\t\t\t\t\t\tsingleResult.toolBudgetBlocked,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;\n\t\t\t\t\t\tif (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;\n\t\t\t\t\t\tif (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;\n\t\t\t\t\t\tif (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;\n\t\t\t\t\t\tif (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"model\", singleResult.model);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"thinking\",\n\t\t\t\t\t\t\tresolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"attemptedModels\",\n\t\t\t\t\t\t\tsingleResult.attemptedModels,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"modelAttempts\",\n\t\t\t\t\t\t\tsingleResult.modelAttempts,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"totalCost\", singleResult.totalCost);\n\t\t\t\t\t\tif (singleResult.totalCost) {\n\t\t\t\t\t\t\tpendingParallelUsageCost = {\n\t\t\t\t\t\t\t\tinputTokens: pendingParallelUsageCost.inputTokens + singleResult.totalCost.inputTokens,\n\t\t\t\t\t\t\t\toutputTokens: pendingParallelUsageCost.outputTokens + singleResult.totalCost.outputTokens,\n\t\t\t\t\t\t\t\tcostUsd: pendingParallelUsageCost.costUsd + singleResult.totalCost.costUsd,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\trefreshUsageBudget();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t\t\t: singleResult.error,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"transcriptPath\",\n\t\t\t\t\t\t\tsingleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"transcriptError\",\n\t\t\t\t\t\t\tsingleResult.transcriptError,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"agentContract\",\n\t\t\t\t\t\t\tsingleResult.agentContract,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"launchResolvedExtensions\",\n\t\t\t\t\t\t\tsingleResult.launchResolvedExtensions,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"runtimeAcknowledgedExtensions\",\n\t\t\t\t\t\t\tsingleResult.runtimeAcknowledgedExtensions,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"effects\", singleResult.effects);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"execution\", singleResult.execution);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"review\", singleResult.review);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"structuredOutput\",\n\t\t\t\t\t\t\tsingleResult.structuredOutput,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"structuredOutputPath\",\n\t\t\t\t\t\t\tsingleResult.structuredOutputPath,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"structuredOutputSchemaPath\",\n\t\t\t\t\t\t\tsingleResult.structuredOutputSchemaPath,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"acceptance\", singleResult.acceptance);\n\t\t\t\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, fi), \"watchdog\", singleResult.watchdog);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"capabilityCeiling\",\n\t\t\t\t\t\t\tsingleResult.capabilityCeiling,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tsetOptionalProperty(\n\t\t\t\t\t\t\trequiredStatusStep(statusPayload, fi),\n\t\t\t\t\t\t\t\"capabilityAudit\",\n\t\t\t\t\t\t\tsingleResult.capabilityAudit,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;\n\t\t\t\t\t\tif (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;\n\t\t\t\t\t\tstatusPayload.lastUpdate = taskEndTime;\n\t\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\t\tappendCapabilityCeilingAppliedEvent(eventsPath, id, fi, task.agent, singleResult);\n\n\t\t\t\t\t\tappendJsonl(\n\t\t\t\t\t\t\teventsPath,\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\ttype:\n\t\t\t\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t\t\t\t? \"subagent.step.stopped\"\n\t\t\t\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t\t\t\t? \"subagent.step.failed\"\n\t\t\t\t\t\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t\t\t\t\t\t? \"subagent.step.paused\"\n\t\t\t\t\t\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t? \"subagent.step.completed\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t: \"subagent.step.failed\",\n\t\t\t\t\t\t\t\tts: taskEndTime,\n\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\tstepIndex: fi,\n\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\texitCode:\n\t\t\t\t\t\t\t\t\tstopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode,\n\t\t\t\t\t\t\t\tdurationMs: taskDuration,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (singleResult.completionGuardTriggered) {\n\t\t\t\t\t\t\tconst event = buildControlEvent(\n\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\tfrom: requiredStatusStep(statusPayload, fi).activityState,\n\t\t\t\t\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\t\t\t\tagent: task.agent,\n\t\t\t\t\t\t\t\t\tindex: fi,\n\t\t\t\t\t\t\t\t\tts: taskEndTime,\n\t\t\t\t\t\t\t\t\tmessage: `${task.agent} completed without making edits for an implementation task`,\n\t\t\t\t\t\t\t\t\treason: \"completion_guard\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tappendControlEvent(event);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (singleResult.exitCode !== 0 && failFast) aborted = true;\n\t\t\t\t\t\treturn stopped || childStopped\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t...singleResult,\n\t\t\t\t\t\t\t\t\toutput: stopMessage,\n\t\t\t\t\t\t\t\t\terror: stopMessage,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\tinterrupted: false,\n\t\t\t\t\t\t\t\t\ttimedOut: false,\n\t\t\t\t\t\t\t\t\tstopped: true,\n\t\t\t\t\t\t\t\t\tskipped: false,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t...singleResult,\n\t\t\t\t\t\t\t\t\t\toutput: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\t\t\t\t\t\t\t\terror: timeoutMessage ?? \"Subagent timed out.\",\n\t\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\t\tinterrupted: false,\n\t\t\t\t\t\t\t\t\t\ttimedOut: true,\n\t\t\t\t\t\t\t\t\t\tskipped: false,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: { ...singleResult, skipped: false };\n\t\t\t\t\t},\n\t\t\t\t\tglobalSemaphore,\n\t\t\t\t);\n\n\t\t\t\tflatIndex += group.parallel.length;\n\n\t\t\t\tfor (let t = 0; t < group.parallel.length; t++) {\n\t\t\t\t\tconst fi = groupStartFlatIndex + t;\n\t\t\t\t\tconst sessionTokens = config.sessionDir\n\t\t\t\t\t\t? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))\n\t\t\t\t\t\t: null;\n\t\t\t\t\tconst taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);\n\t\t\t\t\tif (!taskTokens) continue;\n\t\t\t\t\trequiredStatusStep(statusPayload, fi).tokens = taskTokens;\n\t\t\t\t\tpreviousCumulativeTokens = {\n\t\t\t\t\t\tinput: previousCumulativeTokens.input + taskTokens.input,\n\t\t\t\t\t\toutput: previousCumulativeTokens.output + taskTokens.output,\n\t\t\t\t\t\ttotal: previousCumulativeTokens.total + taskTokens.total,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tstatusPayload.totalTokens = { ...previousCumulativeTokens };\n\t\t\t\tstatusPayload.lastUpdate = Date.now();\n\t\t\t\twriteStatusPayload();\n\n\t\t\t\tfor (const pr of parallelResults) {\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagent: pr.agent,\n\t\t\t\t\t\t\tcontext: pr.context,\n\t\t\t\t\t\t\tagentContract: pr.agentContract,\n\t\t\t\t\t\t\tlaunchContractDigest: pr.launchContractDigest,\n\t\t\t\t\t\t\tlaunchResolvedExtensions: pr.launchResolvedExtensions,\n\t\t\t\t\t\t\toutput: pr.output,\n\t\t\t\t\t\t\toutputState: pr.outputState,\n\t\t\t\t\t\t\terror: pr.error,\n\t\t\t\t\t\t\tprotocolError: pr.protocolError,\n\t\t\t\t\t\t\tsuccess: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,\n\t\t\t\t\t\t\texitCode: pr.interrupted === true ? 0 : pr.exitCode,\n\t\t\t\t\t\t\tskipped: pr.skipped,\n\t\t\t\t\t\t\tinterrupted: pr.interrupted,\n\t\t\t\t\t\t\ttimedOut: pr.timedOut,\n\t\t\t\t\t\t\tstopped: pr.stopped,\n\t\t\t\t\t\t\tturnBudget: pr.turnBudget,\n\t\t\t\t\t\t\tturnBudgetExceeded: pr.turnBudgetExceeded,\n\t\t\t\t\t\t\twrapUpRequested: pr.wrapUpRequested,\n\t\t\t\t\t\t\ttoolBudget: pr.toolBudget,\n\t\t\t\t\t\t\ttoolBudgetBlocked: pr.toolBudgetBlocked,\n\t\t\t\t\t\t\tsessionFile: pr.sessionFile,\n\t\t\t\t\t\t\tintercomTarget: pr.intercomTarget,\n\t\t\t\t\t\t\tmodel: pr.model,\n\t\t\t\t\t\t\tattemptedModels: pr.attemptedModels,\n\t\t\t\t\t\t\tmodelAttempts: pr.modelAttempts,\n\t\t\t\t\t\t\ttotalCost: pr.totalCost,\n\t\t\t\t\t\t\tartifactPaths: pr.artifactPaths,\n\t\t\t\t\t\t\ttranscriptPath: pr.transcriptPath,\n\t\t\t\t\t\t\ttranscriptError: pr.transcriptError,\n\t\t\t\t\t\t\teffects: pr.effects,\n\t\t\t\t\t\t\texecution: pr.execution,\n\t\t\t\t\t\t\treview: pr.review,\n\t\t\t\t\t\t\tstructuredOutput: pr.structuredOutput,\n\t\t\t\t\t\t\tstructuredOutputPath: pr.structuredOutputPath,\n\t\t\t\t\t\t\tstructuredOutputSchemaPath: pr.structuredOutputSchemaPath,\n\t\t\t\t\t\t\tacceptance: pr.acceptance,\n\t\t\t\t\t\t\twatchdog: pr.watchdog,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tpendingParallelUsageCost = { inputTokens: 0, outputTokens: 0, costUsd: 0 };\n\t\t\t\trefreshUsageBudget();\n\t\t\t\tfor (let t = 0; t < group.parallel.length; t++) {\n\t\t\t\t\tconst outputName = group.parallel[t]?.outputName;\n\t\t\t\t\tif (outputName)\n\t\t\t\t\t\toutputs[outputName] = outputEntryFromAsyncResult(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tagent: parallelResults[t]!.agent,\n\t\t\t\t\t\t\t\toutput: parallelResults[t]!.output,\n\t\t\t\t\t\t\t\tstructuredOutput: parallelResults[t]!.structuredOutput,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tstatusPayload.outputs = outputs;\n\n\t\t\t\tpreviousOutput = aggregateParallelOutputs(\n\t\t\t\t\tparallelResults.map((r) =>\n\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\tagent: r.agent,\n\t\t\t\t\t\t\toutput: r.output,\n\t\t\t\t\t\t\texitCode: r.exitCode,\n\t\t\t\t\t\t\terror: r.error,\n\t\t\t\t\t\t\tmodel: r.model,\n\t\t\t\t\t\t\tattemptedModels: r.attemptedModels,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (worktreeSetup) {\n\t\t\t\t\tconst captured = captureParallelWorktreeDiffs(worktreeSetup, asyncDir, stepIndex, group);\n\t\t\t\t\tif (captured.summary) previousOutput = `${previousOutput}\\n\\n${captured.summary}`;\n\t\t\t\t\tworktreeFinalized = true;\n\t\t\t\t\tconst manifestPath = parallelHandoffPath(asyncDir);\n\t\t\t\t\tconst handoff = {\n\t\t\t\t\t\tmanifestPath,\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tmode:\n\t\t\t\t\t\t\t(config.resultMode ?? statusPayload.mode) === \"parallel\"\n\t\t\t\t\t\t\t\t? (\"parallel\" as const)\n\t\t\t\t\t\t\t\t: (\"chain\" as const),\n\t\t\t\t\t\tsource: \"async\" as const,\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tflatStartIndex: groupStartFlatIndex,\n\t\t\t\t\t\tsetup: worktreeSetup,\n\t\t\t\t\t\tdiffs: captured.diffs,\n\t\t\t\t\t\tresults: parallelResults.map((result) => ({\n\t\t\t\t\t\t\tagent: result.agent,\n\t\t\t\t\t\t\tstatus:\n\t\t\t\t\t\t\t\tresult.stopped ||\n\t\t\t\t\t\t\t\t(result.exitCode !== 0 &&\n\t\t\t\t\t\t\t\t\tisUnexplainedProcessSignal(\n\t\t\t\t\t\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\t\t\t\t\t\tprocessSignal: result.processSignal,\n\t\t\t\t\t\t\t\t\t\t\tinterrupted: result.interrupted,\n\t\t\t\t\t\t\t\t\t\t\ttimedOut: result.timedOut,\n\t\t\t\t\t\t\t\t\t\t\tstopped: result.stopped,\n\t\t\t\t\t\t\t\t\t\t\tturnBudgetExceeded: result.turnBudgetExceeded,\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\t? (\"stopped\" as const)\n\t\t\t\t\t\t\t\t\t: result.interrupted\n\t\t\t\t\t\t\t\t\t\t? (\"paused\" as const)\n\t\t\t\t\t\t\t\t\t\t: result.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t\t? (\"completed\" as const)\n\t\t\t\t\t\t\t\t\t\t\t: (\"failed\" as const),\n\t\t\t\t\t\t\tsummary: result.output || result.error || \"(no output)\",\n\t\t\t\t\t\t\t...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),\n\t\t\t\t\t\t\t...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),\n\t\t\t\t\t\t\t...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),\n\t\t\t\t\t\t\t...(result.sessionFile ? { sessionPath: result.sessionFile } : {}),\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t\ttry {\n\t\t\t\t\t\twriteParallelHandoffGroup(handoff);\n\t\t\t\t\t\tconst cleanup = cleanupWorktrees(worktreeSetup, {\n\t\t\t\t\t\t\tkind: \"preserve\",\n\t\t\t\t\t\t\tcapturedDiffs: captured.diffs,\n\t\t\t\t\t\t\thandoffManifestPath: manifestPath,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstatusPayload.parallelHandoff = writeParallelHandoffGroup({ ...handoff, cleanup });\n\t\t\t\t\t\tpreviousOutput = `${previousOutput}\\n\\n${formatParallelHandoffReference(statusPayload.parallelHandoff)}`;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tpreviousOutput = `${previousOutput}\\n\\n${formatParallelHandoffError(error)}`;\n\t\t\t\t\t}\n\t\t\t\t\twriteStatusPayload();\n\t\t\t\t}\n\n\t\t\t\tappendJsonl(\n\t\t\t\t\teventsPath,\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: \"subagent.parallel.completed\",\n\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tstepIndex,\n\t\t\t\t\t\tsuccess:\n\t\t\t\t\t\t\tparallelResults.every((r) => r.exitCode === 0 || r.exitCode === -1) &&\n\t\t\t\t\t\t\tparallelResults.every(\n\t\t\t\t\t\t\t\t(result, index) =>\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tisAgentContractV1(group.parallel[index]?.agentContract) &&\n\t\t\t\t\t\t\t\t\t\tgroup.parallel[index]?.gateOn === \"acceptance\" &&\n\t\t\t\t\t\t\t\t\t\tresult.acceptance?.status === \"rejected\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tconst acceptanceGateFailure = parallelResults\n\t\t\t\t\t.map((result, index) => ({ result, index, task: group.parallel[index] }))\n\t\t\t\t\t.find(\n\t\t\t\t\t\t({ result, task }) =>\n\t\t\t\t\t\t\tisAgentContractV1(task?.agentContract) &&\n\t\t\t\t\t\t\ttask?.gateOn === \"acceptance\" &&\n\t\t\t\t\t\t\tresult.acceptance?.status === \"rejected\",\n\t\t\t\t\t);\n\t\t\t\tif (acceptanceGateFailure) {\n\t\t\t\t\tstatusPayload.error =\n\t\t\t\t\t\t(acceptanceGateFailure.result.acceptance\n\t\t\t\t\t\t\t? acceptanceFailureMessage(acceptanceGateFailure.result.acceptance)\n\t\t\t\t\t\t\t: undefined) ?? \"Parallel acceptance gate rejected the step.\";\n\t\t\t\t\twriteStatusPayload();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (parallelResults.some((r) => r.exitCode !== 0 && r.exitCode !== -1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tif (worktreeSetup && !worktreeFinalized) cleanupWorktrees(worktreeSetup);\n\t\t\t}\n\t\t} else {\n\t\t\tconst seqStep = step as SubagentStep;\n\t\t\tconst stepStartTime = Date.now();\n\t\t\tstatusPayload.currentStep = flatIndex;\n\t\t\trequiredStatusStep(statusPayload, flatIndex).status = \"running\";\n\t\t\tdelete requiredStatusStep(statusPayload, flatIndex).activityState;\n\t\t\tdelete statusPayload.activityState;\n\t\t\tresetStepLiveDetail(requiredStatusStep(statusPayload, flatIndex));\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"skills\", seqStep.skills);\n\t\t\trequiredStatusStep(statusPayload, flatIndex).startedAt = stepStartTime;\n\t\t\trequiredStatusStep(statusPayload, flatIndex).lastActivityAt = stepStartTime;\n\t\t\tstatusPayload.lastActivityAt = stepStartTime;\n\t\t\tstatusPayload.lastUpdate = stepStartTime;\n\t\t\tstatusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);\n\t\t\twriteStatusPayload();\n\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype: \"subagent.step.started\",\n\t\t\t\t\tts: stepStartTime,\n\t\t\t\t\trunId: id,\n\t\t\t\t\tstepIndex: flatIndex,\n\t\t\t\t\tagent: seqStep.agent,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tflushPendingStepSteers(flatIndex);\n\t\t\tconst singleResult = await runSingleStep(\n\t\t\t\tseqStep,\n\t\t\t\tcompactOptional<SingleStepContext>({\n\t\t\t\t\tpreviousOutput,\n\t\t\t\t\tplaceholder,\n\t\t\t\t\tcwd,\n\t\t\t\t\tsessionEnabled,\n\t\t\t\t\toutputs: statusPayload.mode === \"single\" ? undefined : outputs,\n\t\t\t\t\tsessionDir: config.sessionDir,\n\t\t\t\t\tartifactsDir,\n\t\t\t\t\tartifactConfig,\n\t\t\t\t\tid,\n\t\t\t\t\tflatIndex,\n\t\t\t\t\tflatStepCount: Math.max(statusPayload.steps.length, 1),\n\t\t\t\t\toutputFile: path.join(asyncDir, `output-${flatIndex}.log`),\n\t\t\t\t\tsteerInboxDir: stepSteerInboxDir(asyncDir, flatIndex),\n\t\t\t\t\tsteerCapabilityPath: steerCapabilityPath(asyncDir, flatIndex),\n\t\t\t\t\tsteerAckDir: steerAcksDir(asyncDir, flatIndex),\n\t\t\t\t\tpiPackageRoot: config.piPackageRoot,\n\t\t\t\t\tpiArgv1: config.piArgv1,\n\t\t\t\t\tchildIntercomTarget: config.childIntercomTargets?.[flatIndex],\n\t\t\t\t\torchestratorIntercomTarget: config.controlIntercomTarget,\n\t\t\t\t\tnestedRoute: config.nestedRoute,\n\t\t\t\t\tcapabilityCeiling: config.capabilityCeiling,\n\t\t\t\t\tregisterInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),\n\t\t\t\t\tregisterTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),\n\t\t\t\t\tregisterStop: (stop) => registerStepStop(flatIndex, stop),\n\t\t\t\t\tregisterTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(flatIndex, abort),\n\t\t\t\t\ttimeoutSignal: timeoutAbortController.signal,\n\t\t\t\t\tstopSignal: stopAbortController.signal,\n\t\t\t\t\ttimeoutMessage,\n\t\t\t\t\tstopMessage,\n\t\t\t\t\tturnBudget: config.turnBudget,\n\t\t\t\t\tonAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),\n\t\t\t\t\tonChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),\n\t\t\t\t\tonWriterProcess,\n\t\t\t\t\tonExternalProcess: (process) => updateExternalProcess(flatIndex, process),\n\t\t\t\t\tskipAcceptance: () => timedOut || stopped,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (seqStep.sessionFile) {\n\t\t\t\tlatestSessionFile = seqStep.sessionFile;\n\t\t\t}\n\n\t\t\tpreviousOutput = singleResult.output;\n\t\t\tconst childStopped = singleResult.stopped === true;\n\t\t\tresults.push(\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: singleResult.agent,\n\t\t\t\t\tcontext: singleResult.context,\n\t\t\t\t\tagentContract: singleResult.agentContract,\n\t\t\t\t\tlaunchContractDigest: singleResult.launchContractDigest,\n\t\t\t\t\tlaunchResolvedExtensions: singleResult.launchResolvedExtensions,\n\t\t\t\t\truntimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t\t: singleResult.output,\n\t\t\t\t\toutputState: singleResult.outputState,\n\t\t\t\t\terror:\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? stopMessage\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t\t: singleResult.error,\n\t\t\t\t\tprotocolError: singleResult.protocolError,\n\t\t\t\t\tsuccess:\n\t\t\t\t\t\t!stopped &&\n\t\t\t\t\t\t!childStopped &&\n\t\t\t\t\t\t!timedOut &&\n\t\t\t\t\t\tsingleResult.interrupted !== true &&\n\t\t\t\t\t\tsingleResult.exitCode === 0,\n\t\t\t\t\texitCode:\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: singleResult.interrupted === true\n\t\t\t\t\t\t\t\t\t? 0\n\t\t\t\t\t\t\t\t\t: singleResult.exitCode,\n\t\t\t\t\tsessionFile: singleResult.sessionFile,\n\t\t\t\t\tintercomTarget: singleResult.intercomTarget,\n\t\t\t\t\tmodel: singleResult.model,\n\t\t\t\t\tattemptedModels: singleResult.attemptedModels,\n\t\t\t\t\tmodelAttempts: singleResult.modelAttempts,\n\t\t\t\t\ttotalCost: singleResult.totalCost,\n\t\t\t\t\tartifactPaths: singleResult.artifactPaths,\n\t\t\t\t\ttranscriptPath: singleResult.transcriptPath,\n\t\t\t\t\ttranscriptError: singleResult.transcriptError,\n\t\t\t\t\teffects: singleResult.effects,\n\t\t\t\t\texecution: singleResult.execution,\n\t\t\t\t\treview: singleResult.review,\n\t\t\t\t\tstructuredOutput: singleResult.structuredOutput,\n\t\t\t\t\tstructuredOutputPath: singleResult.structuredOutputPath,\n\t\t\t\t\tstructuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,\n\t\t\t\t\tacceptance: singleResult.acceptance,\n\t\t\t\t\twatchdog: singleResult.watchdog,\n\t\t\t\t\tcapabilityCeiling: singleResult.capabilityCeiling,\n\t\t\t\t\tcapabilityAudit: singleResult.capabilityAudit,\n\t\t\t\t\tinterrupted: singleResult.interrupted,\n\t\t\t\t\ttimedOut: timedOut || singleResult.timedOut ? true : undefined,\n\t\t\t\t\tstopped: stopped || childStopped ? true : undefined,\n\t\t\t\t\tturnBudget: singleResult.turnBudget,\n\t\t\t\t\tturnBudgetExceeded: singleResult.turnBudgetExceeded,\n\t\t\t\t\twrapUpRequested: singleResult.wrapUpRequested,\n\t\t\t\t\ttoolBudget: singleResult.toolBudget,\n\t\t\t\t\ttoolBudgetBlocked: singleResult.toolBudgetBlocked,\n\t\t\t\t\trunner: singleResult.runner,\n\t\t\t\t\texternalProcess: singleResult.externalProcess,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (seqStep.outputName) {\n\t\t\t\toutputs[seqStep.outputName] = outputEntryFromAsyncResult(\n\t\t\t\t\t{\n\t\t\t\t\t\tagent: singleResult.agent,\n\t\t\t\t\t\toutput: singleResult.output,\n\t\t\t\t\t\tstructuredOutput: singleResult.structuredOutput,\n\t\t\t\t\t},\n\t\t\t\t\tstepIndex,\n\t\t\t\t);\n\t\t\t}\n\t\t\tstatusPayload.outputs = outputs;\n\n\t\t\tconst cumulativeTokens = config.sessionDir ? parseSessionTokens(config.sessionDir) : null;\n\t\t\tlet stepTokens: TokenUsage | null = cumulativeTokens\n\t\t\t\t? {\n\t\t\t\t\t\tinput: cumulativeTokens.input - previousCumulativeTokens.input,\n\t\t\t\t\t\toutput: cumulativeTokens.output - previousCumulativeTokens.output,\n\t\t\t\t\t\ttotal: cumulativeTokens.total - previousCumulativeTokens.total,\n\t\t\t\t\t}\n\t\t\t\t: null;\n\t\t\tif (cumulativeTokens) {\n\t\t\t\tpreviousCumulativeTokens = cumulativeTokens;\n\t\t\t} else {\n\t\t\t\tstepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);\n\t\t\t\tif (stepTokens) {\n\t\t\t\t\tpreviousCumulativeTokens = {\n\t\t\t\t\t\tinput: previousCumulativeTokens.input + stepTokens.input,\n\t\t\t\t\t\toutput: previousCumulativeTokens.output + stepTokens.output,\n\t\t\t\t\t\ttotal: previousCumulativeTokens.total + stepTokens.total,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst stepEndTime = Date.now();\n\t\t\tconst childInterrupted = singleResult.interrupted === true;\n\t\t\trequiredStatusStep(statusPayload, flatIndex).status =\n\t\t\t\tstopped || childStopped\n\t\t\t\t\t? \"stopped\"\n\t\t\t\t\t: timedOut\n\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t? \"paused\"\n\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t? \"complete\"\n\t\t\t\t\t\t\t\t: \"failed\";\n\t\t\trequiredStatusStep(statusPayload, flatIndex).endedAt = stepEndTime;\n\t\t\trequiredStatusStep(statusPayload, flatIndex).durationMs = stepEndTime - stepStartTime;\n\t\t\trequiredStatusStep(statusPayload, flatIndex).exitCode =\n\t\t\t\tstopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"timedOut\",\n\t\t\t\ttimedOut || singleResult.timedOut ? true : undefined,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"stopped\",\n\t\t\t\tstopped || childStopped ? true : undefined,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"turnBudget\", singleResult.turnBudget);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"turnBudgetExceeded\",\n\t\t\t\tsingleResult.turnBudgetExceeded,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"wrapUpRequested\",\n\t\t\t\tsingleResult.wrapUpRequested,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"toolBudget\", singleResult.toolBudget);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"toolBudgetBlocked\",\n\t\t\t\tsingleResult.toolBudgetBlocked,\n\t\t\t);\n\t\t\tif (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;\n\t\t\tif (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;\n\t\t\tif (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;\n\t\t\tif (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;\n\t\t\tif (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"model\", singleResult.model);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"thinking\",\n\t\t\t\tresolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, flatIndex).thinking),\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"attemptedModels\",\n\t\t\t\tsingleResult.attemptedModels,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"modelAttempts\", singleResult.modelAttempts);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"totalCost\", singleResult.totalCost);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"error\",\n\t\t\t\tstopped || childStopped\n\t\t\t\t\t? stopMessage\n\t\t\t\t\t: timedOut\n\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t: singleResult.error,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"transcriptPath\",\n\t\t\t\tsingleResult.transcriptPath ?? requiredStatusStep(statusPayload, flatIndex).transcriptPath,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"transcriptError\",\n\t\t\t\tsingleResult.transcriptError,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"agentContract\", singleResult.agentContract);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"launchResolvedExtensions\",\n\t\t\t\tsingleResult.launchResolvedExtensions,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"runtimeAcknowledgedExtensions\",\n\t\t\t\tsingleResult.runtimeAcknowledgedExtensions,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"effects\", singleResult.effects);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"execution\", singleResult.execution);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"review\", singleResult.review);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"structuredOutput\",\n\t\t\t\tsingleResult.structuredOutput,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"structuredOutputPath\",\n\t\t\t\tsingleResult.structuredOutputPath,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"structuredOutputSchemaPath\",\n\t\t\t\tsingleResult.structuredOutputSchemaPath,\n\t\t\t);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"acceptance\", singleResult.acceptance);\n\t\t\tsetOptionalProperty(requiredStatusStep(statusPayload, flatIndex), \"watchdog\", singleResult.watchdog);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"capabilityCeiling\",\n\t\t\t\tsingleResult.capabilityCeiling,\n\t\t\t);\n\t\t\tsetOptionalProperty(\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex),\n\t\t\t\t\"capabilityAudit\",\n\t\t\t\tsingleResult.capabilityAudit,\n\t\t\t);\n\t\t\tif (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;\n\t\t\tif (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;\n\t\t\tif (stepTokens) {\n\t\t\t\trequiredStatusStep(statusPayload, flatIndex).tokens = stepTokens;\n\t\t\t\tstatusPayload.totalTokens = { ...previousCumulativeTokens };\n\t\t\t}\n\t\t\tstatusPayload.lastUpdate = stepEndTime;\n\t\t\twriteStatusPayload();\n\t\t\tappendCapabilityCeilingAppliedEvent(eventsPath, id, flatIndex, seqStep.agent, singleResult);\n\n\t\t\tappendJsonl(\n\t\t\t\teventsPath,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\ttype:\n\t\t\t\t\t\tstopped || childStopped\n\t\t\t\t\t\t\t? \"subagent.step.stopped\"\n\t\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t\t? \"subagent.step.failed\"\n\t\t\t\t\t\t\t\t: childInterrupted\n\t\t\t\t\t\t\t\t\t? \"subagent.step.paused\"\n\t\t\t\t\t\t\t\t\t: singleResult.exitCode === 0\n\t\t\t\t\t\t\t\t\t\t? \"subagent.step.completed\"\n\t\t\t\t\t\t\t\t\t\t: \"subagent.step.failed\",\n\t\t\t\t\tts: stepEndTime,\n\t\t\t\t\trunId: id,\n\t\t\t\t\tstepIndex: flatIndex,\n\t\t\t\t\tagent: seqStep.agent,\n\t\t\t\t\texitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode,\n\t\t\t\t\tdurationMs: stepEndTime - stepStartTime,\n\t\t\t\t\ttokens: stepTokens,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (singleResult.completionGuardTriggered) {\n\t\t\t\tconst event = buildControlEvent(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tfrom: requiredStatusStep(statusPayload, flatIndex).activityState,\n\t\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\t\trunId: id,\n\t\t\t\t\t\tagent: seqStep.agent,\n\t\t\t\t\t\tindex: flatIndex,\n\t\t\t\t\t\tts: stepEndTime,\n\t\t\t\t\t\tmessage: `${seqStep.agent} completed without making edits for an implementation task`,\n\t\t\t\t\t\treason: \"completion_guard\",\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tappendControlEvent(event);\n\t\t\t}\n\n\t\t\tflatIndex++;\n\t\t\tif (\n\t\t\t\tisAgentContractV1(seqStep.agentContract) &&\n\t\t\t\tseqStep.gateOn === \"acceptance\" &&\n\t\t\t\tsingleResult.acceptance?.status === \"rejected\"\n\t\t\t) {\n\t\t\t\tstatusPayload.error =\n\t\t\t\t\tacceptanceFailureMessage(singleResult.acceptance) ?? \"Chain acceptance gate rejected the step.\";\n\t\t\t\twriteStatusPayload();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (singleResult.exitCode !== 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tlet summary = results.map((r) => `${r.agent}:\\n${r.output}`).join(\"\\n\\n\");\n\tlet truncated = false;\n\n\tif (maxOutput) {\n\t\tconst config = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };\n\t\tconst lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;\n\t\tconst truncResult = truncateOutput(summary, config, lastArtifactPath);\n\t\tif (truncResult.truncated) {\n\t\t\tsummary = truncResult.text;\n\t\t\ttruncated = true;\n\t\t}\n\t}\n\n\tconst resultMode = config.resultMode ?? statusPayload.mode;\n\tconst singleRuntimeAcknowledgedExtensions =\n\t\tresults.length === 1 ? results[0]?.runtimeAcknowledgedExtensions : undefined;\n\tconst totalCost = results.reduce<CostSummary>(\n\t\t(sum, result) => ({\n\t\t\tinputTokens: sum.inputTokens + (result.totalCost?.inputTokens ?? 0),\n\t\t\toutputTokens: sum.outputTokens + (result.totalCost?.outputTokens ?? 0),\n\t\t\tcostUsd: sum.costUsd + (result.totalCost?.costUsd ?? 0),\n\t\t}),\n\t\t{ inputTokens: 0, outputTokens: 0, costUsd: 0 },\n\t);\n\tconst finalTotalCost =\n\t\ttotalCost.inputTokens > 0 || totalCost.outputTokens > 0 || totalCost.costUsd > 0 ? totalCost : undefined;\n\tconst finalFlatAgents = statusPayload.steps.map((step) => step.agent);\n\tconst agentName =\n\t\tfinalFlatAgents.length === 1\n\t\t\t? finalFlatAgents[0]!\n\t\t\t: resultMode === \"parallel\"\n\t\t\t\t? `parallel:${finalFlatAgents.join(\"+\")}`\n\t\t\t\t: `chain:${finalFlatAgents.join(\"->\")}`;\n\tlet sessionFile: string | undefined;\n\tlet shareUrl: string | undefined;\n\tlet gistUrl: string | undefined;\n\tlet shareError: string | undefined;\n\n\tif (shareEnabled) {\n\t\tsessionFile = config.sessionDir ? (findLatestSessionFile(config.sessionDir) ?? undefined) : undefined;\n\t\tif (!sessionFile && latestSessionFile) {\n\t\t\tsessionFile = latestSessionFile;\n\t\t}\n\t\tif (sessionFile) {\n\t\t\ttry {\n\t\t\t\tconst exportDir = config.sessionDir ?? path.dirname(sessionFile);\n\t\t\t\tconst htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);\n\t\t\t\tconst share = createShareLink(htmlPath);\n\t\t\t\tif (\"error\" in share) shareError = share.error;\n\t\t\t\telse {\n\t\t\t\t\tshareUrl = share.shareUrl;\n\t\t\t\t\tgistUrl = share.gistUrl;\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tshareError = String(err);\n\t\t\t}\n\t\t} else {\n\t\t\tshareError = \"Session file not found.\";\n\t\t}\n\t}\n\n\tclearInterval(heartbeatTimer);\n\theartbeatTimer = undefined;\n\tif (activityTimer) {\n\t\tclearInterval(activityTimer);\n\t\tactivityTimer = undefined;\n\t}\n\tif (timeoutTimer) {\n\t\tclearTimeout(timeoutTimer);\n\t\ttimeoutTimer = undefined;\n\t}\n\tconst signalTerminated =\n\t\t!stopped &&\n\t\t!timedOut &&\n\t\t!turnBudgetExceeded &&\n\t\t!interrupted &&\n\t\tresults.some(\n\t\t\t(result) =>\n\t\t\t\tresult.exitCode !== 0 &&\n\t\t\t\tisUnexplainedProcessSignal(\n\t\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\t\tprocessSignal: result.processSignal,\n\t\t\t\t\t\tinterrupted: result.interrupted,\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);\n\tstatusPayload.state = checkpointRejected\n\t\t? \"rejected\"\n\t\t: stopped || signalTerminated\n\t\t\t? \"stopped\"\n\t\t\t: timedOut || turnBudgetExceeded || usageBudgetExceeded || statusPayload.error\n\t\t\t\t? \"failed\"\n\t\t\t\t: interrupted\n\t\t\t\t\t? \"paused\"\n\t\t\t\t\t: results.every((r) => r.success)\n\t\t\t\t\t\t? \"complete\"\n\t\t\t\t\t\t: \"failed\";\n\tcloseSteerInbox(asyncDir, statusPayload.state);\n\tdisposeControlInbox();\n\tfor (const request of consumeSteerRequests(asyncDir)) deliverSteerRequest(request);\n\tconst effectiveSessionFile = sessionFile ?? latestSessionFile;\n\tconst steeringLifecycle = steeringStatus(statusPayload);\n\tfor (const request of steeringLifecycle.recent) {\n\t\tlet changed = false;\n\t\tfor (const target of request.targets) {\n\t\t\tif (target.state !== \"scheduled\" && target.state !== \"routed\" && target.state !== \"queued\") continue;\n\t\t\tchanged = true;\n\t\t\tconst reason =\n\t\t\t\ttarget.state === \"queued\"\n\t\t\t\t\t? \"run ended before queued follow-up delivery\"\n\t\t\t\t\t: \"child terminated before steering delivery\";\n\t\t\tupdateSteeringLifecycleTarget(request.id, target.index, \"failed\", Date.now(), { reason });\n\t\t\tmarkSteeringAttention(target.index);\n\t\t\temitSteeringEvent(\n\t\t\t\t\"subagent.steer.failed\",\n\t\t\t\t{ type: \"steer\", id: request.id, ts: request.requestedAt, message: reason },\n\t\t\t\ttarget.index,\n\t\t\t\t{ reason },\n\t\t\t);\n\t\t}\n\t\tif (changed)\n\t\t\temitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: child terminated before delivery.`);\n\t}\n\tconst runEndedAt = Date.now();\n\tdelete statusPayload.activityState;\n\tif (stopped) {\n\t\tstatusPayload.stopped = true;\n\t\tstatusPayload.error = stopMessage;\n\t} else if (signalTerminated && !statusPayload.error) {\n\t\tsetOptionalProperty(statusPayload, \"error\", results.find((result) => result.processSignal)?.error);\n\t}\n\tif (timedOut) {\n\t\tstatusPayload.timedOut = true;\n\t\tstatusPayload.error = timeoutMessage ?? \"Subagent timed out.\";\n\t}\n\tif (turnBudgetExceeded && !statusPayload.error) {\n\t\tconst budget = statusPayload.turnBudget;\n\t\tstatusPayload.error = budget\n\t\t\t? turnBudgetExceededMessage(budget, budget.turnCount)\n\t\t\t: \"Subagent exceeded turn budget.\";\n\t}\n\tif (usageBudgetExceeded && statusPayload.usageBudget && !statusPayload.error) {\n\t\tstatusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);\n\t}\n\tstatusPayload.endedAt = runEndedAt;\n\tstatusPayload.lastUpdate = runEndedAt;\n\tsetOptionalProperty(statusPayload, \"sessionFile\", effectiveSessionFile);\n\tif (singleRuntimeAcknowledgedExtensions)\n\t\tstatusPayload.runtimeAcknowledgedExtensions = singleRuntimeAcknowledgedExtensions;\n\tsetOptionalProperty(statusPayload, \"totalCost\", finalTotalCost);\n\tsetOptionalProperty(statusPayload, \"usageBudget\", usageBudgetState(config.usageBudget, currentUsageTotals()));\n\tsetOptionalProperty(statusPayload, \"shareUrl\", shareUrl);\n\tsetOptionalProperty(statusPayload, \"gistUrl\", gistUrl);\n\tsetOptionalProperty(statusPayload, \"shareError\", shareError);\n\tif (statusPayload.state === \"failed\" && !statusPayload.error) {\n\t\tconst failedStep = statusPayload.steps.find((s) => s.status === \"failed\");\n\t\tif (failedStep?.agent) {\n\t\t\tstatusPayload.error = `Step failed: ${failedStep.agent}`;\n\t\t}\n\t}\n\twriteStatusPayload();\n\tappendJsonl(\n\t\teventsPath,\n\t\tJSON.stringify({\n\t\t\ttype: \"subagent.run.completed\",\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tts: runEndedAt,\n\t\t\trunId: id,\n\t\t\tstatus: statusPayload.state,\n\t\t\tdurationMs: runEndedAt - overallStartTime,\n\t\t\ttotalTokens: statusPayload.totalTokens,\n\t\t\ttotalCost: finalTotalCost,\n\t\t\tusageBudget: statusPayload.usageBudget,\n\t\t}),\n\t);\n\twriteRunLog(\n\t\tlogPath,\n\t\tomitUndefinedProperties({\n\t\t\tid,\n\t\t\tmode: statusPayload.mode,\n\t\t\tcwd,\n\t\t\tstartedAt: overallStartTime,\n\t\t\tendedAt: runEndedAt,\n\t\t\tsteps: statusPayload.steps.map((step) =>\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: step.agent,\n\t\t\t\t\tstatus: step.status,\n\t\t\t\t\tdurationMs: step.durationMs,\n\t\t\t\t}),\n\t\t\t),\n\t\t\tsummary,\n\t\t\ttruncated,\n\t\t\tartifactsDir,\n\t\t\tsessionFile: effectiveSessionFile,\n\t\t\tshareUrl,\n\t\t\tshareError,\n\t\t}),\n\t);\n\n\ttry {\n\t\twriteAtomicJson(resultPath, {\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tid,\n\t\t\tagent: agentName,\n\t\t\tmode: resultMode,\n\t\t\tsuccess:\n\t\t\t\t!checkpointRejected &&\n\t\t\t\t!stopped &&\n\t\t\t\t!timedOut &&\n\t\t\t\t!turnBudgetExceeded &&\n\t\t\t\t!usageBudgetExceeded &&\n\t\t\t\t!interrupted &&\n\t\t\t\t!signalTerminated &&\n\t\t\t\tresults.every((r) => r.success),\n\t\t\tstate: checkpointRejected\n\t\t\t\t? \"rejected\"\n\t\t\t\t: stopped || signalTerminated\n\t\t\t\t\t? \"stopped\"\n\t\t\t\t\t: timedOut || turnBudgetExceeded || usageBudgetExceeded\n\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t: interrupted\n\t\t\t\t\t\t\t? \"paused\"\n\t\t\t\t\t\t\t: results.every((r) => r.success)\n\t\t\t\t\t\t\t\t? \"complete\"\n\t\t\t\t\t\t\t\t: \"failed\",\n\t\t\tsummary: checkpointRejected\n\t\t\t\t? (statusPayload.error ?? \"Checkpoint rejected.\")\n\t\t\t\t: stopped\n\t\t\t\t\t? stopMessage\n\t\t\t\t\t: signalTerminated\n\t\t\t\t\t\t? (statusPayload.error ?? \"Subagent process terminated by signal.\")\n\t\t\t\t\t\t: timedOut\n\t\t\t\t\t\t\t? (timeoutMessage ?? \"Subagent timed out.\")\n\t\t\t\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t\t\t\t? (statusPayload.error ?? \"Subagent exceeded turn budget.\")\n\t\t\t\t\t\t\t\t: usageBudgetExceeded\n\t\t\t\t\t\t\t\t\t? (statusPayload.error ?? \"Usage budget exhausted.\")\n\t\t\t\t\t\t\t\t\t: interrupted\n\t\t\t\t\t\t\t\t\t\t? \"Paused after interrupt. Waiting for explicit next action.\"\n\t\t\t\t\t\t\t\t\t\t: summary,\n\t\t\t...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n\t\t\t...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),\n\t\t\t...(statusPayload.turnBudget ? { turnBudget: statusPayload.turnBudget } : {}),\n\t\t\t...(statusPayload.turnBudgetExceeded ? { turnBudgetExceeded: true } : {}),\n\t\t\t...(statusPayload.wrapUpRequested ? { wrapUpRequested: true } : {}),\n\t\t\t...(statusPayload.toolBudget ? { toolBudget: statusPayload.toolBudget } : {}),\n\t\t\t...(statusPayload.toolBudgetBlocked ? { toolBudgetBlocked: true } : {}),\n\t\t\t...(statusPayload.usageBudget ? { usageBudget: statusPayload.usageBudget } : {}),\n\t\t\t...(statusPayload.checkpoint ? { checkpoint: statusPayload.checkpoint } : {}),\n\t\t\t...(stopped\n\t\t\t\t? { stopped: true, error: stopMessage }\n\t\t\t\t: timedOut\n\t\t\t\t\t? { timedOut: true, error: timeoutMessage ?? \"Subagent timed out.\" }\n\t\t\t\t\t: turnBudgetExceeded\n\t\t\t\t\t\t? { error: statusPayload.error ?? \"Subagent exceeded turn budget.\" }\n\t\t\t\t\t\t: usageBudgetExceeded\n\t\t\t\t\t\t\t? { error: statusPayload.error ?? \"Usage budget exhausted.\" }\n\t\t\t\t\t\t\t: {}),\n\t\t\tresults: results.map((r) =>\n\t\t\t\tomitUndefinedProperties({\n\t\t\t\t\tagent: r.agent,\n\t\t\t\t\tcontext: r.context,\n\t\t\t\t\toutput: r.output,\n\t\t\t\t\toutputState: r.outputState,\n\t\t\t\t\terror: r.error,\n\t\t\t\t\tprotocolError: r.protocolError,\n\t\t\t\t\tsuccess: r.success,\n\t\t\t\t\tskipped: r.skipped || undefined,\n\t\t\t\t\tinterrupted: r.interrupted || undefined,\n\t\t\t\t\ttimedOut: r.timedOut || undefined,\n\t\t\t\t\tstopped: r.stopped || undefined,\n\t\t\t\t\tprocessSignal: r.processSignal || undefined,\n\t\t\t\t\tturnBudget: r.turnBudget,\n\t\t\t\t\tturnBudgetExceeded: r.turnBudgetExceeded || undefined,\n\t\t\t\t\twrapUpRequested: r.wrapUpRequested || undefined,\n\t\t\t\t\ttoolBudget: r.toolBudget,\n\t\t\t\t\ttoolBudgetBlocked: r.toolBudgetBlocked || undefined,\n\t\t\t\t\tsessionFile: r.sessionFile,\n\t\t\t\t\tintercomTarget: r.intercomTarget,\n\t\t\t\t\tmodel: r.model,\n\t\t\t\t\tattemptedModels: r.attemptedModels,\n\t\t\t\t\tmodelAttempts: r.modelAttempts,\n\t\t\t\t\ttotalCost: r.totalCost,\n\t\t\t\t\tartifactPaths: r.artifactPaths,\n\t\t\t\t\toutputSaveError: r.outputSaveError,\n\t\t\t\t\tmetadataSaveError: r.metadataSaveError,\n\t\t\t\t\ttruncated: r.truncated,\n\t\t\t\t\ttranscriptPath: r.transcriptPath,\n\t\t\t\t\ttranscriptError: r.transcriptError,\n\t\t\t\t\tagentContract: r.agentContract,\n\t\t\t\t\tlaunchContractDigest: r.launchContractDigest,\n\t\t\t\t\tlaunchResolvedExtensions: r.launchResolvedExtensions,\n\t\t\t\t\truntimeAcknowledgedExtensions: r.runtimeAcknowledgedExtensions,\n\t\t\t\t\trunner: r.runner,\n\t\t\t\t\texternalProcess: r.externalProcess,\n\t\t\t\t\texecution: r.execution,\n\t\t\t\t\treview: r.review,\n\t\t\t\t\teffects: r.effects,\n\t\t\t\t\tstructuredOutput: r.structuredOutput,\n\t\t\t\t\tstructuredOutputPath: r.structuredOutputPath,\n\t\t\t\t\tstructuredOutputSchemaPath: r.structuredOutputSchemaPath,\n\t\t\t\t\tacceptance: r.acceptance,\n\t\t\t\t\twatchdog: r.watchdog,\n\t\t\t\t\tcapabilityCeiling: r.capabilityCeiling,\n\t\t\t\t\tcapabilityAudit: r.capabilityAudit,\n\t\t\t\t}),\n\t\t\t),\n\t\t\toutputs,\n\t\t\tworkflowGraph: statusPayload.workflowGraph,\n\t\t\tparallelHandoff: statusPayload.parallelHandoff,\n\t\t\tcapabilityCeiling: statusPayload.capabilityCeiling,\n\t\t\tcapabilityAudit: statusPayload.capabilityAudit,\n\t\t\t...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),\n\t\t\t...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),\n\t\t\texitCode:\n\t\t\t\tcheckpointRejected || stopped || timedOut || turnBudgetExceeded || usageBudgetExceeded\n\t\t\t\t\t? 1\n\t\t\t\t\t: interrupted || results.every((r) => r.success)\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: 1,\n\t\t\ttimestamp: runEndedAt,\n\t\t\tdurationMs: runEndedAt - overallStartTime,\n\t\t\ttotalTokens: statusPayload.totalTokens,\n\t\t\ttotalCost: finalTotalCost,\n\t\t\tusageBudget: statusPayload.usageBudget,\n\t\t\tcheckpoint: statusPayload.checkpoint,\n\t\t\ttruncated,\n\t\t\tartifactsDir,\n\t\t\tcwd,\n\t\t\tasyncDir,\n\t\t\tlaunchContractDigest: config.launchContractDigest,\n\t\t\tlaunchResolvedExtensions: config.launchResolvedExtensions,\n\t\t\truntimeAcknowledgedExtensions: singleRuntimeAcknowledgedExtensions,\n\t\t\tsessionId: config.sessionId,\n\t\t\tsessionFile: effectiveSessionFile,\n\t\t\tintercomTarget: config.controlIntercomTarget,\n\t\t\tshareUrl,\n\t\t\tgistUrl,\n\t\t\tshareError,\n\t\t\t...(taskIndex !== undefined && { taskIndex }),\n\t\t\t...(totalTasks !== undefined && { totalTasks }),\n\t\t});\n\t} catch (err) {\n\t\tconsole.error(`Failed to write result file ${resultPath}:`, err);\n\t}\n\tif (config.runnerProcessInstanceId) {\n\t\tconst writers: Record<\n\t\t\tstring,\n\t\t\tArray<{\n\t\t\t\tprocessInstanceId: string;\n\t\t\t\tkind: \"pi-writer\";\n\t\t\t\tattempt: number;\n\t\t\t\tcloseObservedAt: number;\n\t\t\t\texitCode: number | null;\n\t\t\t\tsignal: string | null;\n\t\t\t}>\n\t\t> = {};\n\t\tconst expectedWriters: Record<string, number> = {};\n\t\tfor (const [index, result] of results.entries()) {\n\t\t\twriters[String(index)] = result.writerProcesses ?? [];\n\t\t\texpectedWriters[String(index)] = result.writerAttemptCount ?? 0;\n\t\t}\n\t\tconst candidate: ProcessTerminalCandidate = {\n\t\t\tversion: 1,\n\t\t\trunId: id,\n\t\t\trunnerProcessInstanceId: config.runnerProcessInstanceId,\n\t\t\twriters,\n\t\t\texpectedWriters,\n\t\t\t...(config.revivalLease?.sessionFile ? { sessionFile: config.revivalLease.sessionFile } : {}),\n\t\t\t...(config.revivalLeaseToken ? { revivalLeaseToken: config.revivalLeaseToken } : {}),\n\t\t};\n\t\ttry {\n\t\t\twriteProcessTerminalCandidate(asyncDir, candidate);\n\t\t} catch (error) {\n\t\t\tconsole.error(`Failed to write process-terminal candidate for '${id}':`, error);\n\t\t}\n\t}\n}\n\nasync function waitForStartupControl(\n\tcontrolPath: string,\n\ttoken: string,\n\taction: \"ack\" | \"proceed\",\n\ttimeoutMs = 30_000,\n): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (fs.existsSync(controlPath)) {\n\t\t\tlet payload: { action?: unknown; token?: unknown };\n\t\t\ttry {\n\t\t\t\tpayload = JSON.parse(fs.readFileSync(controlPath, \"utf-8\")) as { action?: unknown; token?: unknown };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (payload.token !== token)\n\t\t\t\tthrow new Error(\"Runner startup control token does not match the acquired session lease.\");\n\t\t\tif (payload.action === action) return;\n\t\t\tif (payload.action !== \"ack\" && payload.action !== \"proceed\")\n\t\t\t\tthrow new Error(\"Runner startup control action is invalid.\");\n\t\t}\n\t\tawait new Promise((resolve) => setTimeout(resolve, 20));\n\t}\n\tthrow new Error(`Timed out after ${timeoutMs}ms waiting for runner startup control '${action}'.`);\n}\n\nasync function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {\n\tlet lease: ReturnType<typeof acquireSessionLease> | undefined;\n\tlet startupCommitted = config.revivalLease === undefined;\n\tconst startupPath = path.join(config.asyncDir, \"runner-startup.json\");\n\tconst startupAckPath = path.join(config.asyncDir, \"runner-startup-ack.json\");\n\tconst startupProceedPath = path.join(config.asyncDir, \"runner-startup-proceed.json\");\n\tconst releaseOnExit = (): void => {\n\t\ttry {\n\t\t\tlease?.release();\n\t\t} catch {\n\t\t\t// Exit cleanup is best effort; a dead-owner lease is reclaimed on the next revival.\n\t\t}\n\t};\n\tprocess.once(\"exit\", releaseOnExit);\n\ttry {\n\t\tif (config.revivalLease) {\n\t\t\tlease = acquireSessionLease(config.revivalLease);\n\t\t\tconfig.revivalLeaseToken = lease.owner.token;\n\t\t\twriteAtomicJson(startupPath, {\n\t\t\t\tstate: \"ready\",\n\t\t\t\ttoken: lease.owner.token,\n\t\t\t\tpid: process.pid,\n\t\t\t\towner: lease.owner,\n\t\t\t});\n\t\t\tawait waitForStartupControl(startupAckPath, lease.owner.token, \"ack\");\n\t\t\twriteAtomicJson(startupPath, { state: \"acknowledged\", token: lease.owner.token, pid: process.pid });\n\t\t\tawait waitForStartupControl(startupProceedPath, lease.owner.token, \"proceed\");\n\t\t\tstartupCommitted = true;\n\t\t\tfor (const controlPath of [startupAckPath, startupProceedPath]) {\n\t\t\t\ttry {\n\t\t\t\t\tfs.rmSync(controlPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Startup control cleanup is best effort after the parent commits the run.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tawait runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined);\n\t} catch (error) {\n\t\tif (config.revivalLease && !startupCommitted) {\n\t\t\ttry {\n\t\t\t\twriteAtomicJson(startupPath, {\n\t\t\t\t\tstate: \"error\",\n\t\t\t\t\tpid: process.pid,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// The parent will time out and terminate this runner if the handshake cannot be written.\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tprocess.off(\"exit\", releaseOnExit);\n\t\tif (lease) {\n\t\t\tlet acknowledged = false;\n\t\t\ttry {\n\t\t\t\tacknowledged = lease.release();\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to release session revival lease:\", error);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tmarkProcessTerminalCandidateLeaseRelease(config.asyncDir, lease.owner.token, acknowledged);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to record session revival lease release:\", error);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction startConfiguredSubagent(config: SubagentRunConfig): void {\n\trunConfiguredSubagent(config).catch((runErr) => {\n\t\tconsole.error(\"Subagent runner error:\", runErr);\n\t\tprocess.exit(1);\n\t});\n}\n\nconst configArg = process.argv[2];\nif (configArg) {\n\ttry {\n\t\tconst configJson = fs.readFileSync(configArg, \"utf-8\");\n\t\tconst config = JSON.parse(configJson) as SubagentRunConfig;\n\t\ttry {\n\t\t\tfs.unlinkSync(configArg);\n\t\t} catch {\n\t\t\t// Temp config cleanup is best effort.\n\t\t}\n\t\tstartConfiguredSubagent(config);\n\t} catch (err) {\n\t\tconsole.error(\"Subagent runner error:\", err);\n\t\tprocess.exit(1);\n\t}\n} else {\n\tlet input = \"\";\n\tprocess.stdin.setEncoding(\"utf-8\");\n\tprocess.stdin.on(\"data\", (chunk) => {\n\t\tinput += chunk;\n\t});\n\tprocess.stdin.on(\"end\", () => {\n\t\ttry {\n\t\t\tconst config = JSON.parse(input) as SubagentRunConfig;\n\t\t\tstartConfiguredSubagent(config);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Subagent runner error:\", err);\n\t\t\tprocess.exit(1);\n\t\t}\n\t});\n}\n"]}