@xzzpig/pi-subagents 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,13 +2,12 @@
2
2
  * Core execution logic for running subagents
3
3
  */
4
4
 
5
- import { spawn } from "node:child_process";
6
- import { existsSync, unlinkSync } from "node:fs";
5
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
7
6
  import * as path from "node:path";
8
7
  import type { Message } from "@earendil-works/pi-ai";
9
- import type { AgentConfig } from "../../agents/agents.ts";
8
+ import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext, type AgentConfig } from "../../agents/agents.ts";
10
9
  import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
11
- import { alignForkedSessionCwd } from "../../shared/fork-context.ts";
10
+ import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.ts";
12
11
  import {
13
12
  ensureArtifactsDir,
14
13
  formatOutputArtifactContent,
@@ -31,7 +30,6 @@ import {
31
30
  type AcceptanceLedger,
32
31
  type ResolvedAcceptanceConfig,
33
32
  truncateOutput,
34
- getSubagentDepthEnv,
35
33
  } from "../../shared/types.ts";
36
34
  import {
37
35
  DEFAULT_CONTROL_CONFIG,
@@ -46,8 +44,10 @@ import {
46
44
  findLatestSessionFile,
47
45
  detectSubagentError,
48
46
  hasEmptyTerminalAssistantResponse,
47
+ formatEmptyTerminalAssistantResponseError,
49
48
  extractToolArgsPreview,
50
49
  extractTextFromContent,
50
+ MAX_STREAMED_RECENT_TOOLS,
51
51
  boundStreamedRecentTools,
52
52
  boundStreamedRecentOutput,
53
53
  boundStreamedToolCalls,
@@ -55,39 +55,33 @@ import {
55
55
  import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
56
56
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
57
57
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
58
- import { evaluateCompletionMutationGuard, validateImplementationToolContract } from "../shared/completion-guard.ts";
58
+ import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
59
+ import { planCompletionEvidence } from "../shared/completion-evidence.ts";
60
+ import { planAbortRecovery } from "../shared/abort-recovery.ts";
59
61
  import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
60
- import { getPiSpawnCommand } from "../shared/pi-spawn.ts";
62
+ import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
61
63
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
62
64
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
63
- import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
65
+ import { clearSandboxStartupDiagnostic, readSandboxStartupDiagnostic } from "../shared/sandbox-startup-diagnostics.ts";
64
66
  import { resolvePermissionRules } from "../shared/permissions.ts";
65
- import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, type SubagentTaskDelivery } from "../shared/pi-args.ts";
66
- import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
67
- import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV } from "../shared/capability-ceiling.ts";
67
+ import { applyThinkingSuffix, deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
68
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
69
+ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
68
70
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
69
- import { assertThinkingWithinCeiling, decodeThinkingCeiling, intersectThinkingCeilings, SUBAGENT_THINKING_CEILING_ENV } from "../../shared/thinking-ceiling.ts";
70
- import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
71
- import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
72
- import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
71
+ import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
72
+ import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
73
+ import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
74
+ import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
73
75
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
74
- import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
76
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
75
77
  import {
76
78
  buildModelCandidates,
77
79
  formatSubagentModelVerificationError,
78
80
  formatModelAttemptNote,
79
81
  isContextOverflow,
80
- isRetryableModelFailure,
82
+ isRetryableModelFailureAttempt,
81
83
  recordRetryableModelFailure,
82
84
  } from "../shared/model-fallback.ts";
83
- import {
84
- SUBAGENT_STARTUP_RETRY_DELAYS_MS,
85
- formatSubagentExtensionConflictError,
86
- formatSubagentStartupRetryExhaustedError,
87
- formatSubagentStartupRetryNote,
88
- isRetryableSubagentStartupFailure,
89
- waitForSubagentStartupRetry,
90
- } from "../shared/subagent-startup-retry.ts";
91
85
  import {
92
86
  createMutatingFailureState,
93
87
  didMutatingToolFail,
@@ -102,18 +96,22 @@ import {
102
96
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
103
97
  import { PROMPT_REDACTED } from "../../shared/utils.ts";
104
98
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
105
- import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
106
99
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
107
100
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
108
101
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
109
- import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
102
+ import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
103
+ import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
110
104
  import {
111
105
  acceptChildWatchdogEvent,
106
+ applyChildWatchdogMessage,
112
107
  childWatchdogIsActive,
113
108
  isChildWatchdogStatusEvent,
114
109
  resolveChildWatchdogConfig,
115
110
  type ChildWatchdogStateSnapshot,
111
+ type ChildWatchdogStatusEvent,
116
112
  } from "../../watchdog/child-status.ts";
113
+ import { buildInProcessChildLaunch } from "../shared/child-launch.ts";
114
+ import { childSessionFactory, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
117
115
 
118
116
  const artifactOutputByResult = new WeakMap<SingleResult, string>();
119
117
  const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
@@ -167,6 +165,7 @@ function persistSingleResultMetadata(input: {
167
165
  toolCount: target.progressSummary?.toolCount,
168
166
  error: target.error,
169
167
  agentContract: target.agentContract,
168
+ sandbox: target.sandbox,
170
169
  launchContractDigest: target.launchContractDigest,
171
170
  launchResolvedExtensions: target.launchResolvedExtensions,
172
171
  runtimeAcknowledgedExtensions: target.runtimeAcknowledgedExtensions,
@@ -281,8 +280,8 @@ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleRe
281
280
  /**
282
281
  * Streaming variant of snapshotResult for `onUpdate` progress events: it drops the
283
282
  * unbounded `messages` transcript in favour of compact tool-call summaries so a
284
- * single `tool_execution_update` line stays well under the child-stdout protocol
285
- * cap (`MAX_CHILD_PENDING_LINE_BYTES`). Non-streaming consumers such as
283
+ * single `tool_execution_update` event stays small; the parent records every
284
+ * one in its transcript and `events.jsonl`. Non-streaming consumers such as
286
285
  * foreground detach receipts and terminal consumers use snapshotResult directly.
287
286
  */
288
287
  function snapshotStreamResult(result: SingleResult, progress: AgentProgress): SingleResult {
@@ -292,6 +291,61 @@ function snapshotStreamResult(result: SingleResult, progress: AgentProgress): Si
292
291
  return snapshot;
293
292
  }
294
293
 
294
+ interface StructuredDelegationProgressState {
295
+ currentTool?: string;
296
+ currentToolArgs?: string;
297
+ recentOutput: string[];
298
+ recentTools: Array<{ tool: string; args: string }>;
299
+ activityState?: AgentProgress["activityState"];
300
+ model?: string;
301
+ toolCount: number;
302
+ tokens: number;
303
+ }
304
+
305
+ function captureStructuredDelegationProgressState(progress: AgentProgress, result: SingleResult): StructuredDelegationProgressState {
306
+ return {
307
+ currentTool: progress.currentTool,
308
+ currentToolArgs: progress.currentToolArgs,
309
+ recentOutput: [...progress.recentOutput],
310
+ recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
311
+ activityState: progress.activityState,
312
+ model: progress.model ?? result.model,
313
+ toolCount: progress.toolCount,
314
+ tokens: progress.tokens,
315
+ };
316
+ }
317
+
318
+ function structuredDelegationProgressChanged(
319
+ previous: StructuredDelegationProgressState,
320
+ progress: AgentProgress,
321
+ result: SingleResult,
322
+ ): boolean {
323
+ if (previous.currentTool !== progress.currentTool
324
+ || previous.currentToolArgs !== progress.currentToolArgs
325
+ || previous.activityState !== progress.activityState
326
+ || previous.model !== (progress.model ?? result.model)
327
+ || previous.toolCount !== progress.toolCount
328
+ || previous.tokens !== progress.tokens
329
+ || previous.recentOutput.length !== progress.recentOutput.length) return true;
330
+ for (let index = 0; index < progress.recentOutput.length; index++) {
331
+ if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
332
+ }
333
+ const recentToolsStart = Math.max(0, progress.recentTools.length - MAX_STREAMED_RECENT_TOOLS);
334
+ if (previous.recentTools.length !== progress.recentTools.length - recentToolsStart) return true;
335
+ for (let index = recentToolsStart; index < progress.recentTools.length; index++) {
336
+ const previousTool = previous.recentTools[index - recentToolsStart];
337
+ const currentTool = progress.recentTools[index];
338
+ if (previousTool?.tool !== currentTool?.tool || previousTool?.args !== currentTool?.args) return true;
339
+ }
340
+ return false;
341
+ }
342
+
343
+ const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
344
+ type AbortRecoverySingleResult = SingleResult & { [AFTER_COMPACTION_SETTLEMENT]?: true };
345
+
346
+ const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
347
+
348
+
295
349
  async function runSingleAttempt(
296
350
  runtimeCwd: string,
297
351
  agent: AgentConfig,
@@ -310,7 +364,6 @@ async function runSingleAttempt(
310
364
  attemptNotes: string[];
311
365
  outputSnapshot?: SingleOutputSnapshot;
312
366
  originalTask?: string;
313
- taskDelivery?: SubagentTaskDelivery;
314
367
  orcaProgressTab?: OrcaProgressTab;
315
368
  launchWarnings: { emitted: boolean };
316
369
  verifyModel: boolean;
@@ -321,6 +374,10 @@ async function runSingleAttempt(
321
374
  assertThinkingWithinCeiling({ model: modelArg, configThinking: effectiveThinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
322
375
  const expectedModelForVerification = shared.verifyModel ? modelArg : undefined;
323
376
  const resolvedThinking = resolveEffectiveThinking(modelArg, effectiveThinking);
377
+ // Display name for the child session: applied inside the child through its
378
+ // runtime config and echoed back on the result payload so hosts can label
379
+ // this run without reading the child's session file.
380
+ const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task });
324
381
  const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
325
382
  const childWatchdog = watchdogConfig.ok
326
383
  ? resolveChildWatchdogConfig({
@@ -331,78 +388,66 @@ async function runSingleAttempt(
331
388
  })
332
389
  : undefined;
333
390
  const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
391
+ const sandbox = options.sandbox ?? agent.sandbox;
334
392
  const permissionAuditPath = permissionRules && options.artifactsDir
335
393
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
336
394
  : undefined;
337
- const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit, warnings } = buildPiArgs({
338
- baseArgs: ["--mode", "json", "-p"],
339
- task,
340
- taskDelivery: shared.taskDelivery,
395
+ let onWatchdogStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined;
396
+ const launch = buildInProcessChildLaunch({
341
397
  sessionEnabled: shared.sessionEnabled,
342
398
  sessionDir: options.sessionDir,
343
399
  sessionFile: options.sessionFile,
344
400
  model: modelArg,
345
- thinking: effectiveThinking,
346
401
  systemPromptMode: agent.systemPromptMode,
347
402
  inheritProjectContext: agent.inheritProjectContext,
403
+ inheritGlobalContext: agent.inheritGlobalContext,
348
404
  inheritSkills: agent.inheritSkills,
349
405
  requireReadTool: Boolean(shared.resolvedSkillNames?.length),
350
406
  tools: agent.tools,
407
+ excludeTools: agent.excludeTools,
408
+ allowNestedSubagents: agent.allowNestedSubagents,
351
409
  extensions: agent.extensions,
352
410
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
353
- systemPrompt: appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget),
411
+ systemPrompt: shared.systemPrompt,
354
412
  mcpDirectTools: agent.mcpDirectTools,
355
413
  cwd: options.cwd ?? runtimeCwd,
356
- promptFileStem: agent.name,
357
414
  intercomSessionName: options.intercomSessionName,
415
+ sessionName: childSessionName,
358
416
  orchestratorIntercomTarget: options.orchestratorIntercomTarget,
359
417
  runId: options.runId,
360
418
  childAgentName: agent.name,
361
419
  childIndex: options.index ?? 0,
362
- parentEventSink: options.nestedRoute?.eventSink,
363
- parentControlInbox: options.nestedRoute?.controlInbox,
364
- parentRootRunId: options.nestedRoute?.rootRunId,
365
- parentCapabilityToken: options.nestedRoute?.capabilityToken,
420
+ nestedRoute: options.nestedRoute,
366
421
  runFanoutBudget: options.runFanoutBudget,
367
422
  parentSessionId: options.parentSessionId,
368
- steerInboxDir: options.steerInboxDir,
369
- steerCapabilityPath: options.steerCapabilityPath,
370
- steerAckDir: options.steerAckDir,
423
+ forkCacheKey: options.context === "fork" ? deriveForkPromptCacheKey(options.parentSessionId) : undefined,
371
424
  structuredOutput: options.structuredOutput,
372
425
  fast: options.fast ?? agent.fast,
373
426
  modelCandidates: shared.modelCandidates,
374
427
  toolBudget: options.toolBudget,
375
- allowZeroToolBudget: options.allowZeroToolBudget,
376
428
  permissionRules,
377
429
  permissionAuditPath,
430
+ sandbox,
431
+ projectTrusted: options.projectTrusted,
432
+ trustedProjectCwd: options.trustedProjectCwd,
378
433
  childWatchdog,
434
+ watchdogStatus: (event) => onWatchdogStatus?.(event),
379
435
  waitToolEnabled: options.waitToolEnabled,
436
+ waitToolDefaultTimeoutMs: options.waitToolDefaultTimeoutMs,
380
437
  capabilityCeiling: options.capabilityCeiling,
381
438
  thinkingCeiling: options.thinkingCeiling,
382
- extensionBindings: options.extensionBindings,
439
+ maxSubagentDepth: options.maxSubagentDepth,
440
+ runtimeSnapshotHost: options.runtimeSnapshotHost,
441
+ inherited: options.childRuntime,
442
+ host: "parent",
383
443
  });
444
+ const { toolPlan, capabilityAudit, warnings, launchResolvedExtensions, capture } = launch;
384
445
  if (!shared.launchWarnings.emitted && warnings.length > 0) {
385
446
  for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
386
447
  shared.launchWarnings.emitted = true;
387
448
  }
388
449
 
389
- const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget);
390
- const toolPlan = resolvePiLaunchToolPlan({
391
- tools: agent.tools,
392
- extensions: agent.extensions,
393
- subagentOnlyExtensions: agent.subagentOnlyExtensions,
394
- mcpDirectTools: agent.mcpDirectTools,
395
- cwd: options.cwd ?? runtimeCwd,
396
- requireReadTool: Boolean(shared.resolvedSkillNames?.length),
397
- structuredOutput: Boolean(options.structuredOutput),
398
- fast: options.fast ?? agent.fast,
399
- model: modelArg,
400
- modelCandidates: shared.modelCandidates,
401
- capabilityCeiling: options.capabilityCeiling,
402
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
403
- agentName: agent.name,
404
- permissionRules,
405
- });
450
+ const effectiveSystemPrompt = shared.systemPrompt;
406
451
  const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
407
452
  const contractError = validateImplementationToolContract({
408
453
  agent: agent.name,
@@ -415,11 +460,11 @@ async function runSingleAttempt(
415
460
  completionGuard: agent.completionGuard,
416
461
  });
417
462
  if (contractError) {
418
- cleanupTempDir(tempDir);
419
463
  return {
420
464
  index: options.index ?? 0,
421
465
  agent: agent.name,
422
466
  task,
467
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
423
468
  messages: [],
424
469
  finalOutput: "",
425
470
  exitCode: 1,
@@ -433,7 +478,6 @@ async function runSingleAttempt(
433
478
  ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
434
479
  };
435
480
  }
436
- const launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
437
481
  const launchContractDigest = launchBindingDigest({
438
482
  definitionDigest: agentDefinitionDigest(agent),
439
483
  task: shared.originalTask ?? task,
@@ -445,9 +489,12 @@ async function runSingleAttempt(
445
489
  systemPrompt: effectiveSystemPrompt,
446
490
  systemPromptMode: agent.systemPromptMode,
447
491
  inheritProjectContext: agent.inheritProjectContext,
492
+ inheritGlobalContext: agent.inheritGlobalContext,
448
493
  inheritSkills: agent.inheritSkills,
494
+ sandbox,
449
495
  skills: shared.resolvedSkillNames ?? [],
450
496
  tools: toolPlan.effectiveToolAllowlist,
497
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
451
498
  extensions: toolPlan.extensionArgs,
452
499
  mcpDirectTools: toolPlan.effectiveMcpTools,
453
500
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
@@ -459,7 +506,9 @@ async function runSingleAttempt(
459
506
  index: options.index ?? 0,
460
507
  agent: agent.name,
461
508
  task: shared.originalTask ?? task,
509
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
462
510
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
511
+ ...(sandbox ? { sandbox } : {}),
463
512
  launchContractDigest,
464
513
  launchResolvedExtensions,
465
514
  exitCode: 0,
@@ -472,19 +521,11 @@ async function runSingleAttempt(
472
521
  transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
473
522
  skills: shared.resolvedSkillNames,
474
523
  skillsWarning: shared.skillsWarning,
475
- ...(options.turnBudget ? { turnBudget: initialTurnBudgetState(options.turnBudget) } : {}),
476
524
  ...(options.toolBudget ? { toolBudget: initialToolBudgetState(options.toolBudget) } : {}),
477
525
  ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
478
526
  ...(capabilityAudit ? { capabilityAudit } : {}),
479
527
  }, options.context);
480
528
  const startTime = Date.now();
481
- if (options.structuredOutput) {
482
- try {
483
- if (existsSync(options.structuredOutput.outputPath)) unlinkSync(options.structuredOutput.outputPath);
484
- } catch {
485
- // Missing/stale structured-output files are handled after the child exits.
486
- }
487
- }
488
529
  const controlConfig = options.controlConfig ?? DEFAULT_CONTROL_CONFIG;
489
530
  let interruptedByControl = false;
490
531
  const allControlEvents: ControlEvent[] = [];
@@ -501,6 +542,7 @@ async function runSingleAttempt(
501
542
  const progress: AgentProgress = {
502
543
  index: options.index ?? 0,
503
544
  agent: agent.name,
545
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
504
546
  status: "running",
505
547
  task,
506
548
  skills: shared.resolvedSkillNames,
@@ -518,7 +560,6 @@ async function runSingleAttempt(
518
560
  result.progress = progress;
519
561
  const attemptTimeout = resolveAttemptTimeout(options);
520
562
  if (attemptTimeout?.remainingMs === 0) {
521
- cleanupTempDir(tempDir);
522
563
  result.exitCode = 1;
523
564
  result.timedOut = true;
524
565
  result.error = attemptTimeout.message;
@@ -532,23 +573,38 @@ async function runSingleAttempt(
532
573
  };
533
574
  return result;
534
575
  }
535
- const spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) };
536
576
  const mutationSnapshot = snapshotTrackedMutations(options.cwd ?? runtimeCwd);
537
577
  let observedMutationAttempt = false;
538
578
  let structuredOutputToolInvoked = false;
539
579
  let structuredOutputMessageStartIndex: number | undefined;
540
580
  let toolAvailabilityError: string | undefined;
581
+ let abortedBySignal = options.signal?.aborted === true;
541
582
 
542
- const exitCode = await new Promise<number>((resolve) => {
543
- const spawnSpec = getPiSpawnCommand(args);
544
- const proc = spawn(spawnSpec.command, spawnSpec.args, {
545
- cwd: options.cwd ?? runtimeCwd,
546
- env: spawnEnv,
547
- stdio: ["ignore", "pipe", "pipe"],
548
- windowsHide: true,
583
+ if (options.workflowChildPermitLaunch) {
584
+ const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
585
+ workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
586
+ childKey: options.workflowChildPermitLaunch.childKey,
587
+ agent: agent.name,
588
+ launchContractDigest,
589
+ context: options.context ?? "fresh",
590
+ runner: "pi",
549
591
  });
550
- const jsonlWriter = createJsonlWriter(shared.jsonlPath, proc.stdout);
551
- let processClosed = false;
592
+ if (permitError) {
593
+ result.exitCode = 1;
594
+ result.error = permitError;
595
+ result.finalOutput = permitError;
596
+ progress.status = "failed";
597
+ progress.error = permitError;
598
+ return result;
599
+ }
600
+ }
601
+ const childSessions = options.childSessionFactory ?? childSessionFactory();
602
+ let afterCompactionSettlement = false;
603
+ const exitCode = await new Promise<number>((resolve) => {
604
+ const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
605
+ let session: ChildSession | undefined;
606
+ let unsubscribe: (() => void) | undefined;
607
+ let sessionSettled = false;
552
608
  let lifecycleFinished = false;
553
609
  let detached = false;
554
610
  let intercomStarted = false;
@@ -557,39 +613,26 @@ async function runSingleAttempt(
557
613
  let removeInterruptListener: (() => void) | undefined;
558
614
  let activityTimer: NodeJS.Timeout | undefined;
559
615
  let timeoutTimer: NodeJS.Timeout | undefined;
560
- let timeoutTerminationTimer: NodeJS.Timeout | undefined;
561
- let timeoutHardKillTimer: NodeJS.Timeout | undefined;
562
- let turnBudgetSoftReached = false;
563
- let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
564
- let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
565
- let protocolHardKillTimer: NodeJS.Timeout | undefined;
566
- const clearTurnBudgetTimers = () => {
567
- if (turnBudgetTerminationTimer) {
568
- clearTimeout(turnBudgetTerminationTimer);
569
- turnBudgetTerminationTimer = undefined;
570
- }
571
- if (turnBudgetHardKillTimer) {
572
- clearTimeout(turnBudgetHardKillTimer);
573
- turnBudgetHardKillTimer = undefined;
574
- }
575
- };
616
+ let timeoutHardFinishTimer: NodeJS.Timeout | undefined;
576
617
  const clearTimeoutTimers = () => {
577
618
  if (timeoutTimer) {
578
619
  clearTimeout(timeoutTimer);
579
620
  timeoutTimer = undefined;
580
621
  }
581
- if (timeoutTerminationTimer) {
582
- clearTimeout(timeoutTerminationTimer);
583
- timeoutTerminationTimer = undefined;
584
- }
585
- if (timeoutHardKillTimer) {
586
- clearTimeout(timeoutHardKillTimer);
587
- timeoutHardKillTimer = undefined;
622
+ if (timeoutHardFinishTimer) {
623
+ clearTimeout(timeoutHardFinishTimer);
624
+ timeoutHardFinishTimer = undefined;
588
625
  }
589
626
  };
627
+ const abortChild = (): void => {
628
+ if (!session || sessionSettled || lifecycleFinished) return;
629
+ void session.abort().catch(() => {
630
+ // The session settles through its prompt promise; abort failures are not separately actionable.
631
+ });
632
+ };
590
633
 
591
634
  const detachForeground = (reason: string): boolean => {
592
- if (detached || processClosed || lifecycleFinished || options.signal?.aborted) return false;
635
+ if (detached || sessionSettled || lifecycleFinished || options.signal?.aborted) return false;
593
636
  const receiptProgress = snapshotProgress(progress);
594
637
  receiptProgress.status = "detached";
595
638
  receiptProgress.durationMs = Date.now() - startTime;
@@ -624,19 +667,21 @@ async function runSingleAttempt(
624
667
  }
625
668
  if (!accepted) return false;
626
669
  detached = true;
670
+ if (session) session.detached = true;
627
671
  return true;
628
672
  };
629
673
 
630
- // If the child emits a terminal assistant stop but never exits,
631
- // give it a short grace period to flush naturally, then clean it up.
674
+ // If the child emits a terminal assistant stop but its run never settles
675
+ // (a hook is stuck), abort it after a short grace period and then finish
676
+ // without it.
632
677
  const FINAL_STOP_GRACE_MS = 1000;
633
- const HARD_KILL_MS = 3000;
634
- let childExited = false;
635
- let forcedTerminationSignal = false;
678
+ const HARD_FINISH_MS = 3000;
679
+ let forcedTermination = false;
636
680
  let cleanTerminalAssistantStopReceived = false;
637
681
  let agentSettledReceived = false;
682
+ let compactionStartedReceived = false;
638
683
  let finalDrainTimer: NodeJS.Timeout | undefined;
639
- let finalHardKillTimer: NodeJS.Timeout | undefined;
684
+ let finalHardFinishTimer: NodeJS.Timeout | undefined;
640
685
  let watchdogTailTimer: NodeJS.Timeout | undefined;
641
686
  let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
642
687
  const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
@@ -655,9 +700,9 @@ async function runSingleAttempt(
655
700
  clearTimeout(finalDrainTimer);
656
701
  finalDrainTimer = undefined;
657
702
  }
658
- if (finalHardKillTimer) {
659
- clearTimeout(finalHardKillTimer);
660
- finalHardKillTimer = undefined;
703
+ if (finalHardFinishTimer) {
704
+ clearTimeout(finalHardFinishTimer);
705
+ finalHardFinishTimer = undefined;
661
706
  }
662
707
  };
663
708
  const startFinalDrain = () => {
@@ -665,32 +710,30 @@ async function runSingleAttempt(
665
710
  armWatchdogTail();
666
711
  return;
667
712
  }
668
- if (childExited || finalDrainTimer || lifecycleFinished || processClosed) return;
713
+ if (sessionSettled || finalDrainTimer || lifecycleFinished) return;
669
714
  finalDrainTimer = setTimeout(() => {
670
- if (lifecycleFinished || processClosed) return;
671
- const termSent = trySignalChild(proc, "SIGTERM");
672
- if (!termSent) return;
673
- forcedTerminationSignal = true;
715
+ if (lifecycleFinished || sessionSettled) return;
716
+ forcedTermination = true;
674
717
  if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !assistantError) {
675
- result.error = result.error ?? `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
718
+ result.error = result.error ?? `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
676
719
  }
677
- finalHardKillTimer = setTimeout(() => {
678
- if (lifecycleFinished || processClosed) return;
679
- forcedTerminationSignal = trySignalChild(proc, "SIGKILL") || forcedTerminationSignal;
680
- }, HARD_KILL_MS);
681
- finalHardKillTimer.unref?.();
720
+ abortChild();
721
+ finalHardFinishTimer = setTimeout(() => {
722
+ if (lifecycleFinished || sessionSettled) return;
723
+ settle(undefined, true);
724
+ }, HARD_FINISH_MS);
725
+ finalHardFinishTimer.unref?.();
682
726
  }, FINAL_STOP_GRACE_MS);
683
727
  finalDrainTimer.unref?.();
684
728
  };
685
729
  function armWatchdogTail(): void {
686
- if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || processClosed) return;
730
+ if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || sessionSettled) return;
687
731
  watchdogTailTimer = setTimeout(() => {
688
732
  watchdogTailTimer = undefined;
689
733
  updateChildWatchdogState({
690
734
  phase: "stale",
691
735
  seq: (childWatchdogState?.seq ?? 0) + 1,
692
736
  lastUpdate: Date.now(),
693
- followUpPending: false,
694
737
  reason: "child watchdog tail timeout",
695
738
  timedOut: true,
696
739
  });
@@ -707,9 +750,10 @@ async function runSingleAttempt(
707
750
  }
708
751
  if (action === "start-drain") startFinalDrain();
709
752
  };
753
+ const childLifecycleState: ChildLifecycleState = { compactionRetryActive: false };
710
754
 
711
755
  const unsubscribeIntercomDetach = options.intercomEvents?.on?.(INTERCOM_DETACH_REQUEST_EVENT, (payload) => {
712
- if (!options.allowIntercomDetach || processClosed) return;
756
+ if (!options.allowIntercomDetach || sessionSettled) return;
713
757
  if (!payload || typeof payload !== "object") return;
714
758
  const event = payload as { requestId?: unknown; runId?: unknown; agent?: unknown; childIndex?: unknown };
715
759
  const requestId = event.requestId;
@@ -729,14 +773,8 @@ async function runSingleAttempt(
729
773
  lifecycleFinished = true;
730
774
  clearFinalDrainTimers();
731
775
  clearWatchdogTailTimer();
732
- clearStdioGuard();
733
776
  clearTimeoutTimers();
734
777
  clearAllToolTimeouts();
735
- clearTurnBudgetTimers();
736
- if (protocolHardKillTimer) {
737
- clearTimeout(protocolHardKillTimer);
738
- protocolHardKillTimer = undefined;
739
- }
740
778
  if (activityTimer) {
741
779
  clearInterval(activityTimer);
742
780
  activityTimer = undefined;
@@ -744,7 +782,13 @@ async function runSingleAttempt(
744
782
  unsubscribeIntercomDetach?.();
745
783
  removeAbortListener?.();
746
784
  removeInterruptListener?.();
747
- resolve(code);
785
+ unsubscribe?.();
786
+ onWatchdogStatus = undefined;
787
+ void jsonlWriter.close().catch(() => {
788
+ // JSONL artifact flush is best effort.
789
+ });
790
+ // Report the run only after the child's extensions have shut down.
791
+ void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => resolve(code));
748
792
  };
749
793
 
750
794
  const drainPendingControlEvents = (): ControlEvent[] | undefined => {
@@ -875,63 +919,13 @@ async function runSingleAttempt(
875
919
  }));
876
920
  return true;
877
921
  };
878
- const requestTurnBudgetAbort = (turnCount: number) => {
879
- const budget = options.turnBudget;
880
- if (!budget || result.timedOut || result.turnBudgetExceeded || interruptedByControl || processClosed || lifecycleFinished) return;
881
- const message = turnBudgetExceededMessage(budget, turnCount);
882
- result.turnBudgetExceeded = true;
883
- result.wrapUpRequested = true;
884
- result.turnBudget = turnBudgetState(budget, turnCount, true);
885
- result.error = message;
886
- result.finalOutput = message;
887
- progress.status = "failed";
888
- progress.error = message;
889
- progress.durationMs = Date.now() - startTime;
890
- fireUpdate();
891
- trySignalChild(proc, "SIGINT");
892
- turnBudgetTerminationTimer = setTimeout(() => {
893
- if (processClosed || lifecycleFinished || result.timedOut) return;
894
- trySignalChild(proc, "SIGTERM");
895
- }, 1000);
896
- turnBudgetTerminationTimer.unref?.();
897
- turnBudgetHardKillTimer = setTimeout(() => {
898
- if (processClosed || lifecycleFinished || result.timedOut) return;
899
- trySignalChild(proc, "SIGKILL");
900
- }, 4000);
901
- turnBudgetHardKillTimer.unref?.();
902
- };
903
-
904
- const updateTurnBudget = (turnCount: number, terminalAssistantStop: boolean, toolWorkActiveOrStarting: boolean) => {
905
- const budget = options.turnBudget;
906
- if (!budget || result.timedOut || result.turnBudgetExceeded) return;
907
- if (turnCount < budget.maxTurns) {
908
- result.turnBudget = { ...budget, outcome: "within-budget", turnCount };
909
- return;
910
- }
911
- if (!turnBudgetSoftReached) {
912
- turnBudgetSoftReached = true;
913
- result.wrapUpRequested = true;
914
- appendRecentOutput(progress, [turnBudgetSoftNote(budget, turnCount)]);
915
- }
916
- const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting, options.enforceHardTurnLimit);
917
- if (decision === "defer") {
918
- result.turnBudget = turnBudgetDeferredState(
919
- budget,
920
- turnCount,
921
- result.turnBudget?.terminationDeferredAtTurn,
922
- );
923
- return;
924
- }
925
- result.turnBudget = turnBudgetState(budget, turnCount, false);
926
- if (decision === "abort") requestTurnBudgetAbort(turnCount);
927
- };
928
-
929
922
  const updateActivityState = (now: number): boolean => {
930
923
  if (!controlConfig.enabled) return false;
931
924
  const idleState = deriveActivityState({
932
925
  config: controlConfig,
933
926
  startedAt: startTime,
934
927
  lastActivityAt: progress.lastActivityAt,
928
+ turnCount: progress.turnCount,
935
929
  currentTool: progress.currentTool,
936
930
  thinking: resolvedThinking,
937
931
  now,
@@ -960,8 +954,9 @@ async function runSingleAttempt(
960
954
  };
961
955
 
962
956
 
957
+ let lastStructuredDelegationProgressState: StructuredDelegationProgressState | undefined;
963
958
  const emitUpdateSnapshot = (text: string) => {
964
- if (!options.onUpdate || processClosed) return;
959
+ if (!options.onUpdate || sessionSettled) return;
965
960
  const progressSnapshot = snapshotProgress(progress);
966
961
  const resultSnapshot = snapshotStreamResult(result, progressSnapshot);
967
962
  const controlEvents = drainPendingControlEvents();
@@ -977,19 +972,23 @@ async function runSingleAttempt(
977
972
  };
978
973
 
979
974
  const fireUpdate = () => {
980
- if (!options.onUpdate || processClosed) return;
975
+ if (!options.onUpdate || sessionSettled) return;
981
976
  progress.durationMs = Date.now() - startTime;
982
- const output = (result.timedOut || result.turnBudgetExceeded) && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
977
+ if (options.suppressUnchangedDelegationUpdates) {
978
+ if (lastStructuredDelegationProgressState && !structuredDelegationProgressChanged(lastStructuredDelegationProgressState, progress, result)) return;
979
+ lastStructuredDelegationProgressState = captureStructuredDelegationProgressState(progress, result);
980
+ }
981
+ const output = result.timedOut && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
983
982
  emitUpdateSnapshot(output || "(running...)");
984
983
  };
985
984
 
986
- const toolResultCallId = (message: Message): string | undefined => {
987
- const value = (message as { toolCallId?: unknown }).toolCallId;
988
- return typeof value === "string" && value.length > 0 ? value : undefined;
989
- };
990
-
991
- const handleToolResult = (message: Message, now: number): void => {
992
- const callId = toolResultCallId(message);
985
+ // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
986
+ // deliver the same result either as a tool_result_end event or as a
987
+ // message_end whose message role is toolResult; both funnel through here
988
+ // so one result updates budget, output, and mutating-failure state once.
989
+ const handleToolResult = (message: Message, completion: { toolCallId?: unknown }, now: number): void => {
990
+ const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
991
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
993
992
  if (callId) {
994
993
  if (handledToolResultIds.has(callId)) return;
995
994
  if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
@@ -1030,24 +1029,26 @@ async function runSingleAttempt(
1030
1029
  fireUpdate();
1031
1030
  };
1032
1031
 
1033
- const rawStdoutTail = createBoundedByteTail();
1034
- const processLine = (line: string) => {
1035
- if (!line.trim()) return;
1036
- jsonlWriter.writeLine(line);
1037
- let evt: { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
1038
- try {
1039
- evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
1040
- } catch {
1041
- rawStdoutTail.push(`${line}\n`);
1042
- shared.transcriptWriter?.writeStdoutLine(line);
1043
- shared.orcaProgressTab?.append(`${line}\n`);
1044
- // Non-JSON stdout lines are expected; only structured events are parsed.
1045
- return;
1046
- }
1032
+ const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1033
+ if (lifecycleFinished) return;
1034
+ jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
1047
1035
  shared.transcriptWriter?.writeChildEvent(evt);
1048
1036
  shared.orcaProgressTab?.event(evt);
1049
- if (evt.type === "agent_settled") agentSettledReceived = true;
1050
- applyChildLifecycle(projectChildLifecycle(evt));
1037
+ if (evt.type === "compaction_start") compactionStartedReceived = true;
1038
+ if (evt.type === "compaction_end" && evt.willRetry === true) {
1039
+ compactionStartedReceived = false;
1040
+ afterCompactionSettlement = false;
1041
+ }
1042
+ if (evt.type === "agent_start" || evt.type === "auto_retry_start") {
1043
+ compactionStartedReceived = false;
1044
+ afterCompactionSettlement = false;
1045
+ }
1046
+ const lifecycleAction = projectChildLifecycle(evt, false, childLifecycleState);
1047
+ if (evt.type === "agent_settled" && lifecycleAction === "start-drain") {
1048
+ agentSettledReceived = true;
1049
+ afterCompactionSettlement = compactionStartedReceived;
1050
+ }
1051
+ applyChildLifecycle(lifecycleAction);
1051
1052
 
1052
1053
  if (isChildWatchdogStatusEvent(evt)) {
1053
1054
  if (!childWatchdog) return;
@@ -1093,7 +1094,7 @@ async function runSingleAttempt(
1093
1094
  if (options.toolBudget) {
1094
1095
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
1095
1096
  }
1096
- const mutates = isMutatingTool(evt.toolName, toolArgs);
1097
+ const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1097
1098
  observedMutationAttempt = observedMutationAttempt || mutates;
1098
1099
  pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1099
1100
  fireUpdate();
@@ -1115,24 +1116,26 @@ async function runSingleAttempt(
1115
1116
 
1116
1117
  if (evt.type === "message_end" && evt.message) {
1117
1118
  if (evt.message.role === "toolResult") {
1118
- handleToolResult(evt.message, now);
1119
+ // Fork: hosts that deliver tool results as message_end instead of
1120
+ // tool_result_end reach the same deduplicated completion path.
1121
+ handleToolResult(evt.message, evt, now);
1119
1122
  } else {
1120
1123
  result.messages!.push(evt.message);
1124
+ if (childWatchdog) {
1125
+ const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
1126
+ if (next) updateChildWatchdogState(next);
1127
+ }
1121
1128
  if (evt.message.role === "assistant") {
1122
1129
  result.usage.turns++;
1123
1130
  progress.turnCount = result.usage.turns;
1124
- const stopReason = (evt.message as { stopReason?: string }).stopReason;
1125
1131
  const toolCalls = Array.isArray(evt.message.content)
1126
1132
  ? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
1127
1133
  : [];
1128
1134
  const hasToolCall = toolCalls.length > 0;
1129
- const terminalAssistantStop = stopReason === "stop" && !hasToolCall;
1130
- const terminalStructuredOutputCall = Boolean(options.structuredOutput)
1131
- && toolCalls.length === 1
1132
- && (toolCalls[0] as { name?: string }).name === "structured_output";
1133
- updateTurnBudget(result.usage.turns, terminalAssistantStop || terminalStructuredOutputCall, hasToolCall || Boolean(progress.currentTool));
1135
+ const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
1134
1136
  const u = evt.message.usage;
1135
1137
  if (u) {
1138
+ const window = (u.input || 0) + (u.cacheRead || 0);
1136
1139
  result.usage.input += u.input || 0;
1137
1140
  result.usage.output += u.output || 0;
1138
1141
  result.usage.cacheRead += u.cacheRead || 0;
@@ -1141,24 +1144,29 @@ async function runSingleAttempt(
1141
1144
  progress.tokens = result.usage.input + result.usage.output;
1142
1145
  progress.inputTokens = result.usage.input;
1143
1146
  progress.outputTokens = result.usage.output;
1147
+ progress.window = window;
1148
+ progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1144
1149
  }
1145
1150
  if (evt.message.model) {
1146
1151
  progress.model = evt.message.model;
1147
1152
  if (!result.model) result.model = evt.message.model;
1148
- if (expectedModelForVerification && !hasToolCall) {
1149
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
1150
- if (modelVerificationError && !result.error) result.error = modelVerificationError;
1151
- }
1153
+ if (expectedModelForVerification && !hasToolCall) {
1154
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
1155
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1156
+ }
1152
1157
  }
1153
-
1154
1158
  if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1155
1159
  const assistantText = extractTextFromContent(evt.message.content);
1156
1160
  appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1157
- // Final assistant message: start the exit drain window.
1161
+ // Final assistant message: start the settle drain window.
1158
1162
  if (terminalAssistantStop) {
1159
1163
  if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1160
1164
  cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1161
- applyChildLifecycle(projectChildLifecycle(evt, true));
1165
+ clearAllToolTimeouts();
1166
+ activeToolCalls.clear();
1167
+ activeToolKeysByName.clear();
1168
+ refreshCurrentTool();
1169
+ applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1162
1170
  }
1163
1171
  }
1164
1172
  updateActivityState(now);
@@ -1181,17 +1189,22 @@ async function runSingleAttempt(
1181
1189
  });
1182
1190
  refreshCurrentTool();
1183
1191
  }
1184
- // Fork: the shared, id-deduplicated tool-result tail (message push,
1185
- // budget, mutating-failure tracking, output) lives in handleToolResult;
1186
- // hosts may deliver the same result via message_end(role=toolResult).
1187
- handleToolResult(evt.message, now);
1192
+ // Fork: the shared, id-deduplicated tail (message push, budget,
1193
+ // mutating-failure tracking, output) lives in handleToolResult; hosts
1194
+ // may deliver the same result via message_end(role=toolResult).
1195
+ handleToolResult(evt.message, evt, now);
1188
1196
  }
1189
1197
  };
1198
+ // SAFETY: this callback is only ever invoked with child-watchdog status events
1199
+ // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1200
+ // fields `processEvent` needs, and `processEvent` re-validates the shape with
1201
+ // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1202
+ onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
1190
1203
 
1191
1204
  fireUpdate();
1192
1205
  if (controlConfig.enabled || options.onUpdate) {
1193
1206
  activityTimer = setInterval(() => {
1194
- if (processClosed || lifecycleFinished) {
1207
+ if (sessionSettled || lifecycleFinished) {
1195
1208
  return;
1196
1209
  }
1197
1210
  updateActivityState(Date.now());
@@ -1202,7 +1215,7 @@ async function runSingleAttempt(
1202
1215
 
1203
1216
  if (attemptTimeout) {
1204
1217
  timeoutTimer = setTimeout(() => {
1205
- if (processClosed || lifecycleFinished || interruptedByControl) return;
1218
+ if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1206
1219
  result.timedOut = true;
1207
1220
  clearAllToolTimeouts();
1208
1221
  result.error = attemptTimeout.message;
@@ -1211,17 +1224,12 @@ async function runSingleAttempt(
1211
1224
  progress.error = attemptTimeout.message;
1212
1225
  progress.durationMs = Date.now() - startTime;
1213
1226
  fireUpdate();
1214
- trySignalChild(proc, "SIGINT");
1215
- timeoutTerminationTimer = setTimeout(() => {
1216
- if (processClosed || lifecycleFinished) return;
1217
- trySignalChild(proc, "SIGTERM");
1218
- }, 1000);
1219
- timeoutTerminationTimer.unref?.();
1220
- timeoutHardKillTimer = setTimeout(() => {
1221
- if (processClosed || lifecycleFinished) return;
1222
- trySignalChild(proc, "SIGKILL");
1227
+ abortChild();
1228
+ timeoutHardFinishTimer = setTimeout(() => {
1229
+ if (sessionSettled || lifecycleFinished) return;
1230
+ settle(undefined, true);
1223
1231
  }, 4000);
1224
- timeoutHardKillTimer.unref?.();
1232
+ timeoutHardFinishTimer.unref?.();
1225
1233
  }, attemptTimeout.remainingMs);
1226
1234
  timeoutTimer.unref?.();
1227
1235
  }
@@ -1229,8 +1237,7 @@ async function runSingleAttempt(
1229
1237
  let toolTimeoutSequence = 0;
1230
1238
  const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
1231
1239
  const activeToolTimeoutKeysByName = new Map<string, string[]>();
1232
- let toolTimeoutTerminationTimer: ReturnType<typeof setTimeout> | undefined;
1233
- let toolTimeoutHardKillTimer: ReturnType<typeof setTimeout> | undefined;
1240
+ let toolTimeoutHardFinishTimer: ReturnType<typeof setTimeout> | undefined;
1234
1241
  const removeToolTimeoutKey = (key: string): void => {
1235
1242
  const active = activeToolTimeouts.get(key);
1236
1243
  if (!active) return;
@@ -1252,17 +1259,13 @@ async function runSingleAttempt(
1252
1259
  };
1253
1260
  const clearAllToolTimeouts = (): void => {
1254
1261
  for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
1255
- if (toolTimeoutTerminationTimer) {
1256
- clearTimeout(toolTimeoutTerminationTimer);
1257
- toolTimeoutTerminationTimer = undefined;
1258
- }
1259
- if (toolTimeoutHardKillTimer) {
1260
- clearTimeout(toolTimeoutHardKillTimer);
1261
- toolTimeoutHardKillTimer = undefined;
1262
+ if (toolTimeoutHardFinishTimer) {
1263
+ clearTimeout(toolTimeoutHardFinishTimer);
1264
+ toolTimeoutHardFinishTimer = undefined;
1262
1265
  }
1263
1266
  };
1264
1267
  const terminateForToolTimeout = (message: string): void => {
1265
- if (processClosed || lifecycleFinished || interruptedByControl) return;
1268
+ if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1266
1269
  result.timedOut = true;
1267
1270
  result.error = message;
1268
1271
  result.finalOutput = message;
@@ -1270,17 +1273,12 @@ async function runSingleAttempt(
1270
1273
  progress.error = message;
1271
1274
  progress.durationMs = Date.now() - startTime;
1272
1275
  fireUpdate();
1273
- trySignalChild(proc, "SIGINT");
1274
- toolTimeoutTerminationTimer = setTimeout(() => {
1275
- if (processClosed || lifecycleFinished) return;
1276
- trySignalChild(proc, "SIGTERM");
1277
- }, 1000);
1278
- toolTimeoutTerminationTimer.unref?.();
1279
- toolTimeoutHardKillTimer = setTimeout(() => {
1280
- if (processClosed || lifecycleFinished) return;
1281
- trySignalChild(proc, "SIGKILL");
1276
+ abortChild();
1277
+ toolTimeoutHardFinishTimer = setTimeout(() => {
1278
+ if (sessionSettled || lifecycleFinished) return;
1279
+ settle(undefined, true);
1282
1280
  }, 4000);
1283
- toolTimeoutHardKillTimer.unref?.();
1281
+ toolTimeoutHardFinishTimer.unref?.();
1284
1282
  };
1285
1283
  const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
1286
1284
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
@@ -1301,107 +1299,42 @@ async function runSingleAttempt(
1301
1299
  activeToolTimeoutKeysByName.set(toolName, keys);
1302
1300
  };
1303
1301
 
1304
- const stderrTail = createBoundedByteTail();
1305
- const failProtocol = (limit: ProtocolOutputLimit): void => {
1306
- if (result.protocolError) return;
1307
- result.protocolError = limit;
1308
- result.error = formatProtocolOutputLimit(limit);
1309
- progress.status = "failed";
1310
- progress.error = result.error;
1311
- progress.durationMs = Date.now() - startTime;
1312
- fireUpdate();
1313
- if (!childExited) {
1314
- trySignalChild(proc, "SIGTERM");
1315
- protocolHardKillTimer = setTimeout(() => {
1316
- if (!childExited) trySignalChild(proc, "SIGKILL");
1317
- }, 3000);
1318
- protocolHardKillTimer.unref?.();
1319
- }
1320
- };
1321
- const stdoutReader = createBoundedLineReader({
1322
- oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
1323
- onLine: processLine,
1324
- onLimit: failProtocol,
1325
- });
1326
- const stderrReader = createBoundedLineReader({
1327
- stream: "stderr",
1328
- maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
1329
- onLine: (line) => shared.transcriptWriter?.writeStderrLine(line),
1330
- onLimit: (limit) => shared.transcriptWriter?.writeStderrLine(formatProtocolOutputLimit(limit)),
1331
- });
1332
-
1333
- const clearStdioGuard = attachPostExitStdioGuard(proc, { idleMs: 2000, hardMs: 8000 });
1334
- proc.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
1335
- proc.stderr.on("data", (chunk: Buffer) => {
1336
- stderrTail.push(chunk);
1337
- stderrReader.push(chunk);
1338
- shared.orcaProgressTab?.append(chunk.toString("utf-8"));
1339
- });
1340
- proc.on("exit", () => {
1341
- childExited = true;
1342
- clearFinalDrainTimers();
1343
- });
1344
- proc.on("close", (code, signal) => {
1345
- if (lifecycleFinished) return;
1346
- processClosed = true;
1302
+ /** The child run ended (or was forced to end); fold in the captures and finish. */
1303
+ const settle = (promptError: unknown, forced = false): void => {
1304
+ if (lifecycleFinished || sessionSettled) return;
1305
+ sessionSettled = true;
1347
1306
  clearFinalDrainTimers();
1348
- clearStdioGuard();
1349
- void jsonlWriter.close().catch(() => {
1350
- // JSONL artifact flush is best effort.
1351
- });
1352
- const toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
1307
+ const diagnostic = capture.toolDiagnostic();
1308
+ const toolDiagnosticError = diagnostic ? formatChildToolDiagnostic(diagnostic, { host: "parent" }) : undefined;
1353
1309
  toolAvailabilityError = toolDiagnosticError;
1354
- result.runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1355
- cleanupTempDir(tempDir);
1356
- stdoutReader.end();
1357
- stderrReader.end();
1358
- const stderr = stderrTail.text();
1359
- const rawStdout = rawStdoutTail.text();
1310
+ result.runtimeAcknowledgedExtensions = capture.runtimeAcknowledgedExtensions();
1360
1311
  let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1361
- const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1362
- if (signal) result.processSignal = signal;
1363
- if (!closeError && isUnexplainedProcessSignal({
1364
- processSignal: signal,
1365
- interrupted: result.interrupted,
1366
- timedOut: result.timedOut,
1367
- stopped: result.stopped,
1368
- turnBudgetExceeded: result.turnBudgetExceeded,
1369
- forcedDrainAfterFinalSuccess,
1370
- })) {
1371
- closeError = formatProcessSignalError(signal!);
1312
+ if (!closeError && promptError !== undefined) {
1313
+ closeError = promptError instanceof Error ? promptError.message : String(promptError);
1372
1314
  }
1373
- if (code !== 0 && rawStdout.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1374
- closeError = rawStdout.trim();
1315
+ const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1316
+ const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
1317
+ if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
1318
+ closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
1375
1319
  }
1376
- if (code !== 0 && stderr.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1377
- closeError = stderr.trim();
1320
+ if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
1321
+ closeError = "Subagent session did not settle after it was aborted.";
1378
1322
  }
1379
- const finalCode = forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (code ?? 1) : (code ?? 0);
1323
+ const finalCode = forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal ? 0 : closeError || promptError !== undefined ? 1 : 0;
1380
1324
  if (!result.error && closeError) result.error = closeError;
1381
1325
  finish(finalCode);
1382
- });
1383
- proc.on("error", (error) => {
1384
- if (lifecycleFinished) return;
1385
- processClosed = true;
1386
- clearFinalDrainTimers();
1387
- clearStdioGuard();
1388
- void jsonlWriter.close().catch(() => {
1389
- // JSONL artifact flush is best effort.
1390
- });
1391
- cleanupTempDir(tempDir);
1392
- stdoutReader.end();
1393
- stderrReader.end();
1394
- if (!result.error) {
1395
- result.error = error instanceof Error ? error.message : String(error);
1396
- }
1397
- finish(1);
1398
- });
1326
+ };
1399
1327
 
1400
1328
  if (options.signal) {
1401
1329
  const kill = () => {
1402
- if (processClosed || lifecycleFinished) return;
1403
- proc.kill("SIGTERM");
1404
- setTimeout(() => !proc.killed && proc.kill("SIGKILL"), 3000);
1330
+ if (sessionSettled || lifecycleFinished) return;
1331
+ abortedBySignal = true;
1332
+ abortChild();
1333
+ const hardTimer = setTimeout(() => {
1334
+ if (sessionSettled || lifecycleFinished) return;
1335
+ settle(undefined, true);
1336
+ }, 3000);
1337
+ hardTimer.unref?.();
1405
1338
  };
1406
1339
  if (options.signal.aborted) kill();
1407
1340
  else {
@@ -1412,7 +1345,7 @@ async function runSingleAttempt(
1412
1345
 
1413
1346
  if (options.interruptSignal) {
1414
1347
  const interrupt = () => {
1415
- if (processClosed || lifecycleFinished) return;
1348
+ if (sessionSettled || lifecycleFinished) return;
1416
1349
  if (result.timedOut) return;
1417
1350
  interruptedByControl = true;
1418
1351
  clearTimeoutTimers();
@@ -1423,11 +1356,12 @@ async function runSingleAttempt(
1423
1356
  result.finalOutput = "Interrupted. Waiting for explicit next action.";
1424
1357
  progress.activityState = undefined;
1425
1358
  fireUpdate();
1426
- trySignalChild(proc, "SIGINT");
1427
- setTimeout(() => {
1428
- if (lifecycleFinished || processClosed) return;
1429
- trySignalChild(proc, "SIGTERM");
1430
- }, 1000).unref?.();
1359
+ abortChild();
1360
+ const hardTimer = setTimeout(() => {
1361
+ if (sessionSettled || lifecycleFinished) return;
1362
+ settle(undefined, true);
1363
+ }, 3000);
1364
+ hardTimer.unref?.();
1431
1365
  };
1432
1366
  if (options.interruptSignal.aborted) interrupt();
1433
1367
  else {
@@ -1442,11 +1376,40 @@ async function runSingleAttempt(
1442
1376
  options.onDetachReady?.((reason = "user request") => detachForeground(reason));
1443
1377
  } catch (error) {
1444
1378
  // A consumer callback is advisory. Keep the child attached and observable
1445
- // rather than rejecting this attempt and orphaning its live process.
1379
+ // rather than rejecting this attempt and orphaning its live session.
1446
1380
  appendRecentOutput(progress, [`Foreground detach callback failed: ${error instanceof Error ? error.message : String(error)}`]);
1447
1381
  }
1382
+
1383
+ void (async () => {
1384
+ try {
1385
+ const created = await childSessions.create({
1386
+ ...launch.session,
1387
+ onExtensionError: (error) => {
1388
+ shared.transcriptWriter?.writeStderrLine(`Extension error (${error.extensionPath}, ${error.event}): ${error.error instanceof Error ? error.error.message : String(error.error)}`);
1389
+ },
1390
+ });
1391
+ if (lifecycleFinished) {
1392
+ void created.dispose();
1393
+ return;
1394
+ }
1395
+ session = created;
1396
+ created.detached = detached;
1397
+ unsubscribe = created.subscribe((event) => processEvent(event as Parameters<typeof processEvent>[0]));
1398
+ if (abortedBySignal || interruptedByControl || result.timedOut) {
1399
+ abortChild();
1400
+ }
1401
+ options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
1402
+ await created.prompt(`Task: ${task}`);
1403
+ settle(undefined);
1404
+ } catch (error) {
1405
+ settle(error ?? new Error("Child session failed."));
1406
+ }
1407
+ })();
1448
1408
  });
1449
1409
  result.exitCode = exitCode;
1410
+ if (afterCompactionSettlement) {
1411
+ (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT] = true;
1412
+ }
1450
1413
  if (interruptedByControl) {
1451
1414
  result.exitCode = 0;
1452
1415
  result.interrupted = true;
@@ -1462,10 +1425,15 @@ async function runSingleAttempt(
1462
1425
  };
1463
1426
  return result;
1464
1427
  }
1465
- result.error = formatSubagentExtensionConflictError(result.error, {
1466
- agent: agent.name,
1467
- ambientExtensionsEnabled: !launchResolvedExtensions.disableAmbientExtensions,
1468
- });
1428
+ if (progress.currentTool
1429
+ && isOrdinaryToolForMidToolExit(progress.currentTool)
1430
+ && !abortedBySignal
1431
+ && !result.timedOut
1432
+ && !result.stopped
1433
+ && !toolAvailabilityError) {
1434
+ result.exitCode = 1;
1435
+ result.error = formatMidToolExitError({ toolName: progress.currentTool });
1436
+ }
1469
1437
  if (result.error && result.exitCode === 0) {
1470
1438
  result.exitCode = 1;
1471
1439
  }
@@ -1473,27 +1441,23 @@ async function runSingleAttempt(
1473
1441
  if (options.structuredOutput && result.exitCode === 0 && !result.error) {
1474
1442
  result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
1475
1443
  result.structuredOutputPath = options.structuredOutput.outputPath;
1476
- if (!structuredOutputToolInvoked) {
1444
+ const structured = capture.structuredOutput();
1445
+ if (!structuredOutputToolInvoked || !structured.called) {
1477
1446
  result.exitCode = 1;
1478
1447
  result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1479
1448
  result.structuredOutputFailed = true;
1480
1449
  } else {
1481
- const structured = await readStructuredOutput({
1482
- schema: options.structuredOutput.schema,
1483
- schemaPath: options.structuredOutput.schemaPath,
1484
- outputPath: options.structuredOutput.outputPath,
1485
- });
1486
- if (structured.error) {
1487
- result.exitCode = 1;
1488
- result.error = structured.error;
1489
- result.structuredOutputFailed = true;
1490
- } else {
1491
- result.structuredOutput = structured.value;
1492
- const acceptanceReport = readStructuredOutputAcceptanceReport(options.structuredOutput);
1493
- (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceReport.value;
1494
- (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReport.error;
1495
- validatedStructuredOutput = true;
1496
- }
1450
+ result.structuredOutput = structured.value;
1451
+ const acceptanceMode = options.structuredOutput.acceptanceReportPath
1452
+ ? options.structuredOutput.acceptanceReportRequired ? "required" : "optional"
1453
+ : undefined;
1454
+ const acceptanceReportError = acceptanceMode === "required" && !structured.acceptanceReportProvided
1455
+ ? MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR
1456
+ : undefined;
1457
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceMode ? structured.acceptanceReport : undefined;
1458
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReportError;
1459
+ writeStructuredOutputArtifacts(options.structuredOutput, structured.value, acceptanceMode ? structured.acceptanceReport : undefined);
1460
+ validatedStructuredOutput = true;
1497
1461
  }
1498
1462
  }
1499
1463
  if (result.exitCode === 0 && !result.error) {
@@ -1504,9 +1468,21 @@ async function runSingleAttempt(
1504
1468
  : messages;
1505
1469
  const errInfo = detectSubagentError(errorMessages);
1506
1470
  const missingOutput = !finalText?.trim() && !validatedStructuredOutput;
1507
- if (missingOutput && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1471
+ const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1472
+ && hasEmptyTerminalAssistantResponse(messages)
1473
+ && (progress.toolCount > 0 || Boolean(finalText?.trim()));
1474
+ if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1475
+ // A startup guard can block the first turn, which leaves no message to
1476
+ // inspect. Prefer the reason the blocked child published.
1477
+ const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1508
1478
  result.exitCode = 1;
1509
- result.error = "Subagent produced no output (possible model cold-start or empty response).";
1479
+ if (sandboxDiagnostic) {
1480
+ result.error = sandboxDiagnostic.reason;
1481
+ result.startupBlocked = true;
1482
+ clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1483
+ } else {
1484
+ result.error = formatEmptyTerminalAssistantResponseError(messages);
1485
+ }
1510
1486
  } else if (errInfo.hasError) {
1511
1487
  result.exitCode = errInfo.exitCode ?? 1;
1512
1488
  result.error = errInfo.details
@@ -1525,6 +1501,7 @@ async function runSingleAttempt(
1525
1501
  }
1526
1502
 
1527
1503
  result.progressSummary = {
1504
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1528
1505
  toolCount: progress.toolCount,
1529
1506
  tokens: progress.tokens,
1530
1507
  durationMs: progress.durationMs,
@@ -1537,9 +1514,17 @@ async function runSingleAttempt(
1537
1514
  result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1538
1515
  if (result.timedOut) {
1539
1516
  const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1517
+ let requiredOutputMissing: boolean | undefined;
1518
+ if (options.outputMode === "file-only" && options.outputPath) {
1519
+ const outputChanged = hasSingleOutputChangedSinceSnapshot(options.outputPath, shared.outputSnapshot);
1520
+ requiredOutputMissing = outputChanged === undefined ? undefined : !outputChanged;
1521
+ } else if (options.structuredOutput) {
1522
+ requiredOutputMissing = !capture.structuredOutput().called;
1523
+ }
1540
1524
  result.timeoutRecovery = buildTimeoutRecoverySummary({
1541
1525
  termination: "timed-out",
1542
1526
  evidence: mutationEvidence,
1527
+ requiredOutputMissing,
1543
1528
  currentTool: progress.currentTool,
1544
1529
  currentToolArgs: progress.currentToolArgs,
1545
1530
  currentPath: progress.currentPath,
@@ -1550,14 +1535,6 @@ async function runSingleAttempt(
1550
1535
  fullOutput = fullOutput.trim()
1551
1536
  ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1552
1537
  : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1553
- } else if (result.turnBudgetExceeded && result.turnBudget) {
1554
- fullOutput = formatTurnBudgetOutput(turnBudgetExceededMessage(result.turnBudget, result.turnBudget.turnCount), fullOutput);
1555
- } else if (result.turnBudget?.outcome === "termination-deferred") {
1556
- const note = turnBudgetDeferredNote(result.turnBudget, result.turnBudget.terminationDeferredAtTurn ?? result.turnBudget.turnCount);
1557
- fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1558
- } else if (result.wrapUpRequested && result.turnBudget?.outcome === "wrap-up-requested") {
1559
- const note = turnBudgetSoftNote(result.turnBudget, result.turnBudget.wrapUpRequestedAtTurn ?? result.turnBudget.turnCount);
1560
- fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1561
1538
  }
1562
1539
  const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1563
1540
  const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
@@ -1567,13 +1544,13 @@ async function runSingleAttempt(
1567
1544
  messages: result.messages ?? [],
1568
1545
  tools: contractTools,
1569
1546
  mcpDirectTools: toolPlan.effectiveMcpTools,
1547
+ mutationTools: agent.mutationTools,
1570
1548
  toolAvailabilityError,
1571
1549
  mutationEvidence,
1572
1550
  })
1573
1551
  : undefined;
1574
1552
  const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
1575
1553
  let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
1576
- const completionGuardBlocked = completionGuard?.blocked === true;
1577
1554
  // The classifier is deliberately narrow, so a read-only review task can
1578
1555
  // still be misread as implementation. Arbitrate BEFORE any failure side
1579
1556
  // effect is published (effects, exit code, progress, notifications,
@@ -1590,31 +1567,26 @@ async function runSingleAttempt(
1590
1567
  completionGuardTriggered = arbitration.triggered;
1591
1568
  arbiterRescued = arbitration.rescued;
1592
1569
  }
1593
- if (completionGuard) {
1570
+ const completionEvidence = planCompletionEvidence({
1571
+ guard: completionGuard,
1572
+ guardTriggered: completionGuardTriggered,
1573
+ completionGuardEnabled,
1574
+ mutationCapable: hasMutationToolCapability(contractTools, toolPlan.effectiveMcpTools),
1575
+ implementationMutationExpected: expectsImplementationMutation(agent.name, shared.originalTask ?? task),
1576
+ mutationAttemptObserved,
1577
+ mutationEvidence,
1578
+ arbiterRescued,
1579
+ agentContractV1: isAgentContractV1(options.agentContract),
1580
+ });
1581
+ if (completionEvidence.fileMutation) {
1594
1582
  result.effects = {
1595
1583
  ...(result.effects ?? {}),
1596
- fileMutation: {
1597
- status: completionGuardBlocked
1598
- ? "blocked"
1599
- : completionGuard.expectedMutation
1600
- ? completionGuardTriggered
1601
- ? "missing"
1602
- : arbiterRescued
1603
- ? "not-applicable"
1604
- : "observed"
1605
- : "not-applicable",
1606
- expected: completionGuard.expectedMutation,
1607
- attempted: completionGuardBlocked ? false : completionGuard.attemptedMutation || mutationAttemptObserved,
1608
- evidence: mutationEvidence,
1609
- ...(completionGuardBlocked && completionGuard.message ? { message: completionGuard.message } : {}),
1610
- ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1611
- ...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
1612
- },
1584
+ fileMutation: completionEvidence.fileMutation,
1613
1585
  };
1614
1586
  }
1615
- if (completionGuardTriggered && !isAgentContractV1(options.agentContract)) {
1587
+ if (completionEvidence.legacyFailureError) {
1616
1588
  result.exitCode = 1;
1617
- result.error = "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes.";
1589
+ result.error = completionEvidence.legacyFailureError;
1618
1590
  progress.status = "failed";
1619
1591
  progress.error = result.error;
1620
1592
  emitControlEvent(buildControlEvent({
@@ -1629,10 +1601,14 @@ async function runSingleAttempt(
1629
1601
  }));
1630
1602
  }
1631
1603
  if (options.outputPath && result.exitCode === 0) {
1632
- const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot);
1604
+ const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
1633
1605
  fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
1634
1606
  result.savedOutputPath = resolvedOutput.savedPath;
1635
1607
  result.outputSaveError = resolvedOutput.saveError;
1608
+ if (resolvedOutput.fatalError) {
1609
+ result.exitCode = 1;
1610
+ result.error = result.error ? `${result.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
1611
+ }
1636
1612
  if (resolvedOutput.savedPath) {
1637
1613
  result.outputReference = formatSavedOutputReference(resolvedOutput.savedPath, fullOutput);
1638
1614
  if (result.outputState === "absent") result.outputState = "unknown";
@@ -1662,6 +1638,20 @@ async function runSingleAttempt(
1662
1638
  return result;
1663
1639
  }
1664
1640
 
1641
+ /** Keep the structured output artifact files other consumers read by path. */
1642
+ function writeStructuredOutputArtifacts(runtime: NonNullable<RunSyncOptions["structuredOutput"]>, value: unknown, acceptanceReport: unknown): void {
1643
+ try {
1644
+ mkdirSync(path.dirname(runtime.outputPath), { recursive: true });
1645
+ writeFileSync(runtime.outputPath, JSON.stringify(value), { mode: 0o600 });
1646
+ if (runtime.acceptanceReportPath) {
1647
+ if (acceptanceReport !== undefined) writeFileSync(runtime.acceptanceReportPath, JSON.stringify(acceptanceReport), { mode: 0o600 });
1648
+ else rmSync(runtime.acceptanceReportPath, { force: true });
1649
+ }
1650
+ } catch {
1651
+ // The captured value is already on the result; the file is observability only.
1652
+ }
1653
+ }
1654
+
1665
1655
  /**
1666
1656
  * Run a subagent synchronously (blocking until complete)
1667
1657
  */
@@ -1672,12 +1662,28 @@ async function runSyncCompletionInner(
1672
1662
  task: string,
1673
1663
  options: RunSyncOptions,
1674
1664
  ): Promise<SingleResult> {
1665
+ const effectiveCwd = options.cwd ?? runtimeCwd;
1666
+ const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1667
+ if (cwdError) {
1668
+ return redactResultPrompt(withRunContext({
1669
+ index: options.index ?? 0,
1670
+ agent: agentName,
1671
+ task,
1672
+ exitCode: 1,
1673
+ messages: [],
1674
+ usage: emptyUsage(),
1675
+ error: cwdError,
1676
+ }, options.context));
1677
+ }
1675
1678
  options = {
1676
1679
  ...options,
1677
- capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])),
1680
+ capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), options.childRuntime?.capabilityCeiling),
1678
1681
  };
1682
+ const childSessionName = deriveChildSessionName({ agent: agentName, task });
1679
1683
  const agent = agents.find((a) => a.name === agentName);
1680
1684
  if (!agent) {
1685
+ const diagnosticContext = options.unknownAgentDiagnosticContext
1686
+ ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(options.cwd ?? runtimeCwd), "both"));
1681
1687
  return redactResultPrompt(withRunContext({
1682
1688
  index: options.index ?? 0,
1683
1689
  agent: agentName,
@@ -1685,7 +1691,7 @@ async function runSyncCompletionInner(
1685
1691
  exitCode: 1,
1686
1692
  messages: [],
1687
1693
  usage: emptyUsage(),
1688
- error: `Unknown agent: ${agentName}`,
1694
+ error: formatUnknownAgentError(agentName, diagnosticContext),
1689
1695
  }, options.context));
1690
1696
  }
1691
1697
  options = {
@@ -1693,7 +1699,7 @@ async function runSyncCompletionInner(
1693
1699
  thinkingCeiling: intersectThinkingCeilings(
1694
1700
  options.thinkingCeiling,
1695
1701
  agent.maxThinking,
1696
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
1702
+ options.childRuntime?.thinkingCeiling,
1697
1703
  ),
1698
1704
  };
1699
1705
  try {
@@ -1810,8 +1816,24 @@ async function runSyncCompletionInner(
1810
1816
  agent.fallbackModels,
1811
1817
  options.availableModels,
1812
1818
  agent.modelProvider ?? options.preferredModelProvider,
1813
- { scope: options.modelScope, primaryModelFromParent: options.modelOverrideFromParent },
1819
+ {
1820
+ scope: options.modelScope,
1821
+ primaryModelFromParent: options.modelOverrideFromParent,
1822
+ origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1823
+ },
1814
1824
  );
1825
+ if (options.workflowChildPermitLaunch && candidates.length > 1) {
1826
+ const error = "Workflow child permit does not support model fallback.";
1827
+ return redactResultPrompt(withRunContext({
1828
+ index: options.index ?? 0,
1829
+ agent: agent.name,
1830
+ task,
1831
+ exitCode: 1,
1832
+ messages: [],
1833
+ usage: emptyUsage(),
1834
+ error,
1835
+ }, options.context));
1836
+ }
1815
1837
  try {
1816
1838
  for (const candidate of candidates) {
1817
1839
  const model = applyThinkingSuffix(candidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
@@ -1901,15 +1923,17 @@ async function runSyncCompletionInner(
1901
1923
  };
1902
1924
  let lastResult: SingleResult | undefined;
1903
1925
  const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1904
- // Escalated to "file" after an unexplained zero-activity startup failure so
1905
- // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1906
- let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1926
+ let abortRecoveryAttempted = false;
1927
+ let nextAttemptTask = taskWithAcceptance;
1907
1928
  modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1908
1929
  const candidate = modelsToTry[modelIndex];
1909
- for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
1930
+ // The inner loop re-runs the same candidate at most once, for abort recovery.
1931
+ for (;;) {
1932
+ const recoveringAbort = abortRecoveryAttempted;
1933
+ const attemptTask = nextAttemptTask;
1910
1934
  const verifyModel = Boolean(candidate) && !(options.modelOverrideFromParent && modelIndex === 0);
1911
1935
  const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1912
- const result = await runSingleAttempt(runtimeCwd, agent, taskWithAcceptance, candidate, attemptOptions, {
1936
+ const result = await runSingleAttempt(runtimeCwd, agent, attemptTask, candidate, attemptOptions, {
1913
1937
  sessionEnabled,
1914
1938
  systemPrompt,
1915
1939
  resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
@@ -1923,13 +1947,12 @@ async function runSyncCompletionInner(
1923
1947
  .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1924
1948
  outputSnapshot,
1925
1949
  originalTask: task,
1926
- taskDelivery: taskDeliveryOverride,
1927
1950
  orcaProgressTab,
1928
1951
  launchWarnings,
1929
1952
  verifyModel,
1930
1953
  });
1931
1954
  lastResult = result;
1932
- if (startupAttemptIndex === 0) {
1955
+ if (!recoveringAbort) {
1933
1956
  if (result.model) attemptedModels.push(result.model);
1934
1957
  else if (candidate) attemptedModels.push(candidate);
1935
1958
  }
@@ -1945,79 +1968,45 @@ async function runSyncCompletionInner(
1945
1968
  usage: { ...result.usage },
1946
1969
  };
1947
1970
  modelAttempts.push(attempt);
1948
- // Preserve the legacy intercom handoff contract: once this logical run has
1949
- // been handed to a supervisor, terminating that attempt must not launch a
1950
- // startup retry or model fallback. Explicit user detach retains fallback.
1951
- if (intercomDetached || result.timedOut || result.turnBudgetExceeded) break modelAttemptsLoop;
1952
- if (attemptSucceeded) break modelAttemptsLoop;
1953
-
1954
- const startupFailure = isRetryableSubagentStartupFailure({
1955
- exitCode: result.exitCode,
1956
- error: result.error,
1957
- finalOutput: result.finalOutput,
1958
- messageCount: result.messages?.length ?? 0,
1959
- toolCount: result.progressSummary?.toolCount ?? 0,
1960
- usage: result.usage,
1961
- durationMs: result.progressSummary?.durationMs ?? Number.POSITIVE_INFINITY,
1962
- protocolError: result.protocolError,
1963
- processSignal: result.processSignal,
1964
- detached: result.detached,
1965
- interrupted: result.interrupted,
1966
- timedOut: result.timedOut,
1967
- stopped: result.stopped,
1968
- turnBudgetExceeded: result.turnBudgetExceeded,
1969
- });
1970
- const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1971
- if (startupFailure && retryDelayMs !== undefined) {
1972
- const retryNote = formatSubagentStartupRetryNote({
1973
- model: attempt.model,
1974
- attempt: startupAttemptIndex + 1,
1975
- maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1976
- delayMs: retryDelayMs,
1971
+ if (!attemptSucceeded) {
1972
+ const afterCompactionSettlement = (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT];
1973
+ const abortRecovery = planAbortRecovery({
1974
+ messages: result.messages ?? [],
1975
+ error: result.error,
1976
+ processSignal: result.processSignal,
1977
+ sessionAvailable: Boolean(options.sessionFile && existsSync(options.sessionFile)),
1978
+ alreadyResumed: abortRecoveryAttempted,
1979
+ stopped: result.stopped || result.detached || options.signal?.aborted,
1980
+ interrupted: result.interrupted || intercomDetached || options.interruptSignal?.aborted,
1981
+ timedOut: result.timedOut,
1982
+ toolBudgetExhausted: result.toolBudgetBlocked,
1983
+ usageBudgetExhausted: false,
1984
+ structuredOutputFailed: result.structuredOutputFailed,
1985
+ acceptanceFailed: false,
1986
+ currentTool: result.progress?.currentTool,
1987
+ afterCompactionSettlement,
1977
1988
  });
1978
- const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [options.signal, options.interruptSignal]);
1979
- if (!shouldRetry) {
1980
- if (options.interruptSignal?.aborted) {
1981
- result.exitCode = 0;
1982
- result.interrupted = true;
1983
- result.error = undefined;
1984
- result.finalOutput = "Interrupted. Waiting for explicit next action.";
1985
- if (result.progress) {
1986
- result.progress.status = "running";
1987
- result.progress.error = undefined;
1988
- }
1989
- } else {
1990
- const cancellationError = "Subagent startup retry cancelled before relaunch.";
1991
- result.error = cancellationError;
1992
- result.finalOutput = cancellationError;
1993
- attempt.error = cancellationError;
1994
- if (result.progress) result.progress.error = cancellationError;
1995
- }
1996
- break modelAttemptsLoop;
1989
+ if (abortRecovery.action === "resume") {
1990
+ abortRecoveryAttempted = true;
1991
+ nextAttemptTask = abortRecovery.prompt;
1992
+ attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1993
+ continue;
1997
1994
  }
1998
- if (!taskDeliveryOverride && result.processSignal === "SIGKILL") {
1999
- taskDeliveryOverride = "file";
2000
- attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1995
+ if (abortRecovery.diagnostic) {
1996
+ result.error = result.error ? `${result.error}\n${abortRecovery.diagnostic}` : abortRecovery.diagnostic;
1997
+ attempt.error = result.error;
1998
+ break modelAttemptsLoop;
2001
1999
  }
2002
- attempt.error = retryNote;
2003
- attemptNotes.push(retryNote);
2004
- continue;
2005
2000
  }
2006
- if (startupFailure) {
2007
- const startupError = formatSubagentStartupRetryExhaustedError({
2008
- model: attempt.model,
2009
- attempts: startupAttemptIndex + 1,
2010
- });
2011
- result.error = startupError;
2012
- result.finalOutput = startupError;
2013
- if (result.progress) {
2014
- result.progress.error = startupError;
2015
- result.progress.status = "failed";
2016
- }
2017
- attempt.error = startupError;
2018
- break modelAttemptsLoop;
2019
- }
2020
- const retryableModelFailure = isRetryableModelFailure(result.error);
2001
+ if (recoveringAbort && !attemptSucceeded) break modelAttemptsLoop;
2002
+ if (options.workflowChildPermitLaunch && !attemptSucceeded) break modelAttemptsLoop;
2003
+ // Preserve the legacy intercom handoff contract: once this logical run has
2004
+ // been handed to a supervisor, terminating that attempt must not launch a
2005
+ // model fallback. Explicit user detach retains fallback.
2006
+ if (intercomDetached || result.timedOut) break modelAttemptsLoop;
2007
+ if (attemptSucceeded) break modelAttemptsLoop;
2008
+
2009
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount, ...(result.startupBlocked ? { startupBlocked: true } : {}) });
2021
2010
  if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
2022
2011
  if (isContextOverflow(result.error)) {
2023
2012
  result.contextOverflow = true;
@@ -2039,11 +2028,13 @@ async function runSyncCompletionInner(
2039
2028
  usage: emptyUsage(),
2040
2029
  error: "Subagent did not produce a result.",
2041
2030
  } satisfies SingleResult, options.context);
2031
+ result.task = task;
2042
2032
 
2043
2033
  result.usage = aggregateUsage;
2044
2034
  result.attemptedModels = attemptedModels.length > 0 ? attemptedModels : undefined;
2045
2035
  result.modelAttempts = modelAttempts.length > 0 ? modelAttempts : undefined;
2046
2036
  result.progressSummary = {
2037
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
2047
2038
  toolCount: totalToolCount,
2048
2039
  tokens: aggregateUsage.input + aggregateUsage.output,
2049
2040
  durationMs: totalDurationMs,
@@ -2097,8 +2088,6 @@ async function runSyncCompletionInner(
2097
2088
  result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." });
2098
2089
  } else if (result.timedOut) {
2099
2090
  result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." });
2100
- } else if (result.turnBudgetExceeded) {
2101
- result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." });
2102
2091
  } else {
2103
2092
  result.acceptance = await evaluateAcceptance({
2104
2093
  acceptance: effectiveAcceptance,
@@ -2106,12 +2095,13 @@ async function runSyncCompletionInner(
2106
2095
  report: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReport,
2107
2096
  reportError: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError,
2108
2097
  fileOutput: childWrittenOutput !== undefined && options.outputPath
2109
- ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only" }
2098
+ ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
2110
2099
  : undefined,
2111
2100
  cwd: options.cwd ?? runtimeCwd,
2112
2101
  reportOptional: isAgentContractV1(options.agentContract),
2113
2102
  artifactsDir: options.artifactsDir,
2114
2103
  runId: options.runId,
2104
+ watchdog: result.watchdog,
2115
2105
  });
2116
2106
  }
2117
2107
  } catch (error) {