@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  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 +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. 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,35 +55,32 @@ 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 } 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";
64
65
  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";
66
+ import { applyThinkingSuffix, deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
67
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
68
+ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
68
69
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
69
- import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
70
- import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
71
- import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
72
- import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
70
+ import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
71
+ import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
72
+ import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
73
+ import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
74
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
75
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
73
76
  import {
74
77
  buildModelCandidates,
78
+ formatSubagentModelVerificationError,
75
79
  formatModelAttemptNote,
76
- isRetryableModelFailure,
80
+ isContextOverflow,
81
+ isRetryableModelFailureAttempt,
77
82
  recordRetryableModelFailure,
78
83
  } from "../shared/model-fallback.ts";
79
- import {
80
- SUBAGENT_STARTUP_RETRY_DELAYS_MS,
81
- formatSubagentExtensionConflictError,
82
- formatSubagentStartupRetryExhaustedError,
83
- formatSubagentStartupRetryNote,
84
- isRetryableSubagentStartupFailure,
85
- waitForSubagentStartupRetry,
86
- } from "../shared/subagent-startup-retry.ts";
87
84
  import {
88
85
  createMutatingFailureState,
89
86
  didMutatingToolFail,
@@ -98,18 +95,22 @@ import {
98
95
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
99
96
  import { PROMPT_REDACTED } from "../../shared/utils.ts";
100
97
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
101
- import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
102
98
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
103
99
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
104
100
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
105
- import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
101
+ import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
102
+ import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
106
103
  import {
107
104
  acceptChildWatchdogEvent,
105
+ applyChildWatchdogMessage,
108
106
  childWatchdogIsActive,
109
107
  isChildWatchdogStatusEvent,
110
108
  resolveChildWatchdogConfig,
111
109
  type ChildWatchdogStateSnapshot,
110
+ type ChildWatchdogStatusEvent,
112
111
  } from "../../watchdog/child-status.ts";
112
+ import { buildInProcessChildLaunch } from "../shared/child-launch.ts";
113
+ import { childSessionFactory, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
113
114
 
114
115
  const artifactOutputByResult = new WeakMap<SingleResult, string>();
115
116
  const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
@@ -277,8 +278,8 @@ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleRe
277
278
  /**
278
279
  * Streaming variant of snapshotResult for `onUpdate` progress events: it drops the
279
280
  * unbounded `messages` transcript in favour of compact tool-call summaries so a
280
- * single `tool_execution_update` line stays well under the child-stdout protocol
281
- * cap (`MAX_CHILD_PENDING_LINE_BYTES`). Non-streaming consumers such as
281
+ * single `tool_execution_update` event stays small; the parent records every
282
+ * one in its transcript and `events.jsonl`. Non-streaming consumers such as
282
283
  * foreground detach receipts and terminal consumers use snapshotResult directly.
283
284
  */
284
285
  function snapshotStreamResult(result: SingleResult, progress: AgentProgress): SingleResult {
@@ -288,6 +289,61 @@ function snapshotStreamResult(result: SingleResult, progress: AgentProgress): Si
288
289
  return snapshot;
289
290
  }
290
291
 
292
+ interface StructuredDelegationProgressState {
293
+ currentTool?: string;
294
+ currentToolArgs?: string;
295
+ recentOutput: string[];
296
+ recentTools: Array<{ tool: string; args: string }>;
297
+ activityState?: AgentProgress["activityState"];
298
+ model?: string;
299
+ toolCount: number;
300
+ tokens: number;
301
+ }
302
+
303
+ function captureStructuredDelegationProgressState(progress: AgentProgress, result: SingleResult): StructuredDelegationProgressState {
304
+ return {
305
+ currentTool: progress.currentTool,
306
+ currentToolArgs: progress.currentToolArgs,
307
+ recentOutput: [...progress.recentOutput],
308
+ recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
309
+ activityState: progress.activityState,
310
+ model: progress.model ?? result.model,
311
+ toolCount: progress.toolCount,
312
+ tokens: progress.tokens,
313
+ };
314
+ }
315
+
316
+ function structuredDelegationProgressChanged(
317
+ previous: StructuredDelegationProgressState,
318
+ progress: AgentProgress,
319
+ result: SingleResult,
320
+ ): boolean {
321
+ if (previous.currentTool !== progress.currentTool
322
+ || previous.currentToolArgs !== progress.currentToolArgs
323
+ || previous.activityState !== progress.activityState
324
+ || previous.model !== (progress.model ?? result.model)
325
+ || previous.toolCount !== progress.toolCount
326
+ || previous.tokens !== progress.tokens
327
+ || previous.recentOutput.length !== progress.recentOutput.length) return true;
328
+ for (let index = 0; index < progress.recentOutput.length; index++) {
329
+ if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
330
+ }
331
+ const recentToolsStart = Math.max(0, progress.recentTools.length - MAX_STREAMED_RECENT_TOOLS);
332
+ if (previous.recentTools.length !== progress.recentTools.length - recentToolsStart) return true;
333
+ for (let index = recentToolsStart; index < progress.recentTools.length; index++) {
334
+ const previousTool = previous.recentTools[index - recentToolsStart];
335
+ const currentTool = progress.recentTools[index];
336
+ if (previousTool?.tool !== currentTool?.tool || previousTool?.args !== currentTool?.args) return true;
337
+ }
338
+ return false;
339
+ }
340
+
341
+ const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
342
+ type AbortRecoverySingleResult = SingleResult & { [AFTER_COMPACTION_SETTLEMENT]?: true };
343
+
344
+ const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
345
+
346
+
291
347
  async function runSingleAttempt(
292
348
  runtimeCwd: string,
293
349
  agent: AgentConfig,
@@ -306,13 +362,20 @@ async function runSingleAttempt(
306
362
  attemptNotes: string[];
307
363
  outputSnapshot?: SingleOutputSnapshot;
308
364
  originalTask?: string;
309
- taskDelivery?: SubagentTaskDelivery;
310
365
  orcaProgressTab?: OrcaProgressTab;
366
+ launchWarnings: { emitted: boolean };
367
+ verifyModel: boolean;
311
368
  },
312
369
  ): Promise<SingleResult> {
313
370
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
314
371
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
372
+ assertThinkingWithinCeiling({ model: modelArg, configThinking: effectiveThinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
373
+ const expectedModelForVerification = shared.verifyModel ? modelArg : undefined;
315
374
  const resolvedThinking = resolveEffectiveThinking(modelArg, effectiveThinking);
375
+ // Display name for the child session: applied inside the child through its
376
+ // runtime config and echoed back on the result payload so hosts can label
377
+ // this run without reading the child's session file.
378
+ const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task });
316
379
  const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
317
380
  const childWatchdog = watchdogConfig.ok
318
381
  ? resolveChildWatchdogConfig({
@@ -326,86 +389,117 @@ async function runSingleAttempt(
326
389
  const permissionAuditPath = permissionRules && options.artifactsDir
327
390
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
328
391
  : undefined;
329
- const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit } = buildPiArgs({
330
- baseArgs: ["--mode", "json", "-p"],
331
- task,
332
- taskDelivery: shared.taskDelivery,
392
+ let onWatchdogStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined;
393
+ const launch = buildInProcessChildLaunch({
333
394
  sessionEnabled: shared.sessionEnabled,
334
395
  sessionDir: options.sessionDir,
335
396
  sessionFile: options.sessionFile,
336
397
  model: modelArg,
337
- thinking: effectiveThinking,
338
398
  systemPromptMode: agent.systemPromptMode,
339
399
  inheritProjectContext: agent.inheritProjectContext,
400
+ inheritGlobalContext: agent.inheritGlobalContext,
340
401
  inheritSkills: agent.inheritSkills,
341
402
  requireReadTool: Boolean(shared.resolvedSkillNames?.length),
342
403
  tools: agent.tools,
404
+ excludeTools: agent.excludeTools,
405
+ allowNestedSubagents: agent.allowNestedSubagents,
343
406
  extensions: agent.extensions,
344
407
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
345
- systemPrompt: appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget),
408
+ systemPrompt: shared.systemPrompt,
346
409
  mcpDirectTools: agent.mcpDirectTools,
347
410
  cwd: options.cwd ?? runtimeCwd,
348
- promptFileStem: agent.name,
349
411
  intercomSessionName: options.intercomSessionName,
412
+ sessionName: childSessionName,
350
413
  orchestratorIntercomTarget: options.orchestratorIntercomTarget,
351
414
  runId: options.runId,
352
415
  childAgentName: agent.name,
353
416
  childIndex: options.index ?? 0,
354
- parentEventSink: options.nestedRoute?.eventSink,
355
- parentControlInbox: options.nestedRoute?.controlInbox,
356
- parentRootRunId: options.nestedRoute?.rootRunId,
357
- parentCapabilityToken: options.nestedRoute?.capabilityToken,
417
+ nestedRoute: options.nestedRoute,
358
418
  runFanoutBudget: options.runFanoutBudget,
359
419
  parentSessionId: options.parentSessionId,
360
- steerInboxDir: options.steerInboxDir,
361
- steerCapabilityPath: options.steerCapabilityPath,
362
- steerAckDir: options.steerAckDir,
420
+ forkCacheKey: options.context === "fork" ? deriveForkPromptCacheKey(options.parentSessionId) : undefined,
363
421
  structuredOutput: options.structuredOutput,
422
+ fast: options.fast ?? agent.fast,
423
+ modelCandidates: shared.modelCandidates,
364
424
  toolBudget: options.toolBudget,
365
- allowZeroToolBudget: options.allowZeroToolBudget,
366
425
  permissionRules,
367
426
  permissionAuditPath,
368
427
  childWatchdog,
428
+ watchdogStatus: (event) => onWatchdogStatus?.(event),
369
429
  waitToolEnabled: options.waitToolEnabled,
430
+ waitToolDefaultTimeoutMs: options.waitToolDefaultTimeoutMs,
370
431
  capabilityCeiling: options.capabilityCeiling,
432
+ thinkingCeiling: options.thinkingCeiling,
433
+ maxSubagentDepth: options.maxSubagentDepth,
434
+ runtimeSnapshotHost: options.runtimeSnapshotHost,
435
+ inherited: options.childRuntime,
436
+ host: "parent",
371
437
  });
438
+ const { toolPlan, capabilityAudit, warnings, launchResolvedExtensions, capture } = launch;
439
+ if (!shared.launchWarnings.emitted && warnings.length > 0) {
440
+ for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
441
+ shared.launchWarnings.emitted = true;
442
+ }
372
443
 
373
- const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget);
374
- const toolPlan = resolvePiLaunchToolPlan({
375
- tools: agent.tools,
376
- extensions: agent.extensions,
377
- subagentOnlyExtensions: agent.subagentOnlyExtensions,
378
- mcpDirectTools: agent.mcpDirectTools,
379
- cwd: options.cwd ?? runtimeCwd,
380
- requireReadTool: Boolean(shared.resolvedSkillNames?.length),
381
- structuredOutput: Boolean(options.structuredOutput),
382
- capabilityCeiling: options.capabilityCeiling,
383
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
384
- agentName: agent.name,
444
+ const effectiveSystemPrompt = shared.systemPrompt;
445
+ const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
446
+ const contractError = validateImplementationToolContract({
447
+ agent: agent.name,
448
+ task: shared.originalTask ?? task,
449
+ tools: contractTools,
450
+ mcpDirectTools: toolPlan.effectiveMcpTools,
451
+ configuredExtensions: toolPlan.configuredExtensions,
452
+ requestedTools: toolPlan.requestedBuiltinTools,
453
+ acceptanceRole: agent.acceptanceRole,
454
+ completionGuard: agent.completionGuard,
385
455
  });
386
- const launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
456
+ if (contractError) {
457
+ return {
458
+ index: options.index ?? 0,
459
+ agent: agent.name,
460
+ task,
461
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
462
+ messages: [],
463
+ finalOutput: "",
464
+ exitCode: 1,
465
+ error: contractError,
466
+ usage: emptyUsage(),
467
+ model: modelArg,
468
+ modelAttempts: [],
469
+ attemptedModels: [],
470
+ progressSummary: { status: "failed", toolCount: 0, tokens: 0, durationMs: 0 },
471
+ ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
472
+ ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
473
+ };
474
+ }
387
475
  const launchContractDigest = launchBindingDigest({
388
476
  definitionDigest: agentDefinitionDigest(agent),
389
477
  task: shared.originalTask ?? task,
390
478
  ...(modelArg ? { model: modelArg } : {}),
391
479
  modelCandidates: shared.modelCandidates,
480
+ ...((options.fast ?? agent.fast) !== undefined ? { fast: options.fast ?? agent.fast } : {}),
392
481
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
482
+ ...(options.thinkingCeiling ? { thinkingCeiling: options.thinkingCeiling } : {}),
393
483
  systemPrompt: effectiveSystemPrompt,
394
484
  systemPromptMode: agent.systemPromptMode,
395
485
  inheritProjectContext: agent.inheritProjectContext,
486
+ inheritGlobalContext: agent.inheritGlobalContext,
396
487
  inheritSkills: agent.inheritSkills,
397
488
  skills: shared.resolvedSkillNames ?? [],
398
489
  tools: toolPlan.effectiveToolAllowlist,
490
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
399
491
  extensions: toolPlan.extensionArgs,
400
492
  mcpDirectTools: toolPlan.effectiveMcpTools,
401
493
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
402
494
  outputMode: options.outputMode ?? "inline",
403
495
  ...(options.structuredOutput ? { structuredOutputSchema: options.structuredOutput.schema } : {}),
496
+ ...(options.extensionBindings ? { extensionBindings: options.extensionBindings } : {}),
404
497
  });
405
498
  const result: SingleResult = withRunContext({
406
499
  index: options.index ?? 0,
407
500
  agent: agent.name,
408
501
  task: shared.originalTask ?? task,
502
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
409
503
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
410
504
  launchContractDigest,
411
505
  launchResolvedExtensions,
@@ -419,19 +513,11 @@ async function runSingleAttempt(
419
513
  transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
420
514
  skills: shared.resolvedSkillNames,
421
515
  skillsWarning: shared.skillsWarning,
422
- ...(options.turnBudget ? { turnBudget: initialTurnBudgetState(options.turnBudget) } : {}),
423
516
  ...(options.toolBudget ? { toolBudget: initialToolBudgetState(options.toolBudget) } : {}),
424
517
  ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
425
518
  ...(capabilityAudit ? { capabilityAudit } : {}),
426
519
  }, options.context);
427
520
  const startTime = Date.now();
428
- if (options.structuredOutput) {
429
- try {
430
- if (existsSync(options.structuredOutput.outputPath)) unlinkSync(options.structuredOutput.outputPath);
431
- } catch {
432
- // Missing/stale structured-output files are handled after the child exits.
433
- }
434
- }
435
521
  const controlConfig = options.controlConfig ?? DEFAULT_CONTROL_CONFIG;
436
522
  let interruptedByControl = false;
437
523
  const allControlEvents: ControlEvent[] = [];
@@ -448,6 +534,7 @@ async function runSingleAttempt(
448
534
  const progress: AgentProgress = {
449
535
  index: options.index ?? 0,
450
536
  agent: agent.name,
537
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
451
538
  status: "running",
452
539
  task,
453
540
  skills: shared.resolvedSkillNames,
@@ -465,7 +552,6 @@ async function runSingleAttempt(
465
552
  result.progress = progress;
466
553
  const attemptTimeout = resolveAttemptTimeout(options);
467
554
  if (attemptTimeout?.remainingMs === 0) {
468
- cleanupTempDir(tempDir);
469
555
  result.exitCode = 1;
470
556
  result.timedOut = true;
471
557
  result.error = attemptTimeout.message;
@@ -479,21 +565,38 @@ async function runSingleAttempt(
479
565
  };
480
566
  return result;
481
567
  }
482
- const spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) };
568
+ const mutationSnapshot = snapshotTrackedMutations(options.cwd ?? runtimeCwd);
483
569
  let observedMutationAttempt = false;
484
570
  let structuredOutputToolInvoked = false;
485
571
  let structuredOutputMessageStartIndex: number | undefined;
572
+ let toolAvailabilityError: string | undefined;
573
+ let abortedBySignal = options.signal?.aborted === true;
486
574
 
487
- const exitCode = await new Promise<number>((resolve) => {
488
- const spawnSpec = getPiSpawnCommand(args);
489
- const proc = spawn(spawnSpec.command, spawnSpec.args, {
490
- cwd: options.cwd ?? runtimeCwd,
491
- env: spawnEnv,
492
- stdio: ["ignore", "pipe", "pipe"],
493
- windowsHide: true,
575
+ if (options.workflowChildPermitLaunch) {
576
+ const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
577
+ workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
578
+ childKey: options.workflowChildPermitLaunch.childKey,
579
+ agent: agent.name,
580
+ launchContractDigest,
581
+ context: options.context ?? "fresh",
582
+ runner: "pi",
494
583
  });
495
- const jsonlWriter = createJsonlWriter(shared.jsonlPath, proc.stdout);
496
- let processClosed = false;
584
+ if (permitError) {
585
+ result.exitCode = 1;
586
+ result.error = permitError;
587
+ result.finalOutput = permitError;
588
+ progress.status = "failed";
589
+ progress.error = permitError;
590
+ return result;
591
+ }
592
+ }
593
+ const childSessions = options.childSessionFactory ?? childSessionFactory();
594
+ let afterCompactionSettlement = false;
595
+ const exitCode = await new Promise<number>((resolve) => {
596
+ const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
597
+ let session: ChildSession | undefined;
598
+ let unsubscribe: (() => void) | undefined;
599
+ let sessionSettled = false;
497
600
  let lifecycleFinished = false;
498
601
  let detached = false;
499
602
  let intercomStarted = false;
@@ -502,39 +605,26 @@ async function runSingleAttempt(
502
605
  let removeInterruptListener: (() => void) | undefined;
503
606
  let activityTimer: NodeJS.Timeout | undefined;
504
607
  let timeoutTimer: NodeJS.Timeout | undefined;
505
- let timeoutTerminationTimer: NodeJS.Timeout | undefined;
506
- let timeoutHardKillTimer: NodeJS.Timeout | undefined;
507
- let turnBudgetSoftReached = false;
508
- let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
509
- let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
510
- let protocolHardKillTimer: NodeJS.Timeout | undefined;
511
- const clearTurnBudgetTimers = () => {
512
- if (turnBudgetTerminationTimer) {
513
- clearTimeout(turnBudgetTerminationTimer);
514
- turnBudgetTerminationTimer = undefined;
515
- }
516
- if (turnBudgetHardKillTimer) {
517
- clearTimeout(turnBudgetHardKillTimer);
518
- turnBudgetHardKillTimer = undefined;
519
- }
520
- };
608
+ let timeoutHardFinishTimer: NodeJS.Timeout | undefined;
521
609
  const clearTimeoutTimers = () => {
522
610
  if (timeoutTimer) {
523
611
  clearTimeout(timeoutTimer);
524
612
  timeoutTimer = undefined;
525
613
  }
526
- if (timeoutTerminationTimer) {
527
- clearTimeout(timeoutTerminationTimer);
528
- timeoutTerminationTimer = undefined;
529
- }
530
- if (timeoutHardKillTimer) {
531
- clearTimeout(timeoutHardKillTimer);
532
- timeoutHardKillTimer = undefined;
614
+ if (timeoutHardFinishTimer) {
615
+ clearTimeout(timeoutHardFinishTimer);
616
+ timeoutHardFinishTimer = undefined;
533
617
  }
534
618
  };
619
+ const abortChild = (): void => {
620
+ if (!session || sessionSettled || lifecycleFinished) return;
621
+ void session.abort().catch(() => {
622
+ // The session settles through its prompt promise; abort failures are not separately actionable.
623
+ });
624
+ };
535
625
 
536
626
  const detachForeground = (reason: string): boolean => {
537
- if (detached || processClosed || lifecycleFinished || options.signal?.aborted) return false;
627
+ if (detached || sessionSettled || lifecycleFinished || options.signal?.aborted) return false;
538
628
  const receiptProgress = snapshotProgress(progress);
539
629
  receiptProgress.status = "detached";
540
630
  receiptProgress.durationMs = Date.now() - startTime;
@@ -569,19 +659,21 @@ async function runSingleAttempt(
569
659
  }
570
660
  if (!accepted) return false;
571
661
  detached = true;
662
+ if (session) session.detached = true;
572
663
  return true;
573
664
  };
574
665
 
575
- // If the child emits a terminal assistant stop but never exits,
576
- // give it a short grace period to flush naturally, then clean it up.
666
+ // If the child emits a terminal assistant stop but its run never settles
667
+ // (a hook is stuck), abort it after a short grace period and then finish
668
+ // without it.
577
669
  const FINAL_STOP_GRACE_MS = 1000;
578
- const HARD_KILL_MS = 3000;
579
- let childExited = false;
580
- let forcedTerminationSignal = false;
670
+ const HARD_FINISH_MS = 3000;
671
+ let forcedTermination = false;
581
672
  let cleanTerminalAssistantStopReceived = false;
582
673
  let agentSettledReceived = false;
674
+ let compactionStartedReceived = false;
583
675
  let finalDrainTimer: NodeJS.Timeout | undefined;
584
- let finalHardKillTimer: NodeJS.Timeout | undefined;
676
+ let finalHardFinishTimer: NodeJS.Timeout | undefined;
585
677
  let watchdogTailTimer: NodeJS.Timeout | undefined;
586
678
  let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
587
679
  const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
@@ -600,9 +692,9 @@ async function runSingleAttempt(
600
692
  clearTimeout(finalDrainTimer);
601
693
  finalDrainTimer = undefined;
602
694
  }
603
- if (finalHardKillTimer) {
604
- clearTimeout(finalHardKillTimer);
605
- finalHardKillTimer = undefined;
695
+ if (finalHardFinishTimer) {
696
+ clearTimeout(finalHardFinishTimer);
697
+ finalHardFinishTimer = undefined;
606
698
  }
607
699
  };
608
700
  const startFinalDrain = () => {
@@ -610,32 +702,30 @@ async function runSingleAttempt(
610
702
  armWatchdogTail();
611
703
  return;
612
704
  }
613
- if (childExited || finalDrainTimer || lifecycleFinished || processClosed) return;
705
+ if (sessionSettled || finalDrainTimer || lifecycleFinished) return;
614
706
  finalDrainTimer = setTimeout(() => {
615
- if (lifecycleFinished || processClosed) return;
616
- const termSent = trySignalChild(proc, "SIGTERM");
617
- if (!termSent) return;
618
- forcedTerminationSignal = true;
707
+ if (lifecycleFinished || sessionSettled) return;
708
+ forcedTermination = true;
619
709
  if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !assistantError) {
620
- result.error = result.error ?? `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
710
+ result.error = result.error ?? `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
621
711
  }
622
- finalHardKillTimer = setTimeout(() => {
623
- if (lifecycleFinished || processClosed) return;
624
- forcedTerminationSignal = trySignalChild(proc, "SIGKILL") || forcedTerminationSignal;
625
- }, HARD_KILL_MS);
626
- finalHardKillTimer.unref?.();
712
+ abortChild();
713
+ finalHardFinishTimer = setTimeout(() => {
714
+ if (lifecycleFinished || sessionSettled) return;
715
+ settle(undefined, true);
716
+ }, HARD_FINISH_MS);
717
+ finalHardFinishTimer.unref?.();
627
718
  }, FINAL_STOP_GRACE_MS);
628
719
  finalDrainTimer.unref?.();
629
720
  };
630
721
  function armWatchdogTail(): void {
631
- if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || processClosed) return;
722
+ if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || sessionSettled) return;
632
723
  watchdogTailTimer = setTimeout(() => {
633
724
  watchdogTailTimer = undefined;
634
725
  updateChildWatchdogState({
635
726
  phase: "stale",
636
727
  seq: (childWatchdogState?.seq ?? 0) + 1,
637
728
  lastUpdate: Date.now(),
638
- followUpPending: false,
639
729
  reason: "child watchdog tail timeout",
640
730
  timedOut: true,
641
731
  });
@@ -652,9 +742,10 @@ async function runSingleAttempt(
652
742
  }
653
743
  if (action === "start-drain") startFinalDrain();
654
744
  };
745
+ const childLifecycleState: ChildLifecycleState = { compactionRetryActive: false };
655
746
 
656
747
  const unsubscribeIntercomDetach = options.intercomEvents?.on?.(INTERCOM_DETACH_REQUEST_EVENT, (payload) => {
657
- if (!options.allowIntercomDetach || processClosed) return;
748
+ if (!options.allowIntercomDetach || sessionSettled) return;
658
749
  if (!payload || typeof payload !== "object") return;
659
750
  const event = payload as { requestId?: unknown; runId?: unknown; agent?: unknown; childIndex?: unknown };
660
751
  const requestId = event.requestId;
@@ -674,14 +765,8 @@ async function runSingleAttempt(
674
765
  lifecycleFinished = true;
675
766
  clearFinalDrainTimers();
676
767
  clearWatchdogTailTimer();
677
- clearStdioGuard();
678
768
  clearTimeoutTimers();
679
769
  clearAllToolTimeouts();
680
- clearTurnBudgetTimers();
681
- if (protocolHardKillTimer) {
682
- clearTimeout(protocolHardKillTimer);
683
- protocolHardKillTimer = undefined;
684
- }
685
770
  if (activityTimer) {
686
771
  clearInterval(activityTimer);
687
772
  activityTimer = undefined;
@@ -689,7 +774,13 @@ async function runSingleAttempt(
689
774
  unsubscribeIntercomDetach?.();
690
775
  removeAbortListener?.();
691
776
  removeInterruptListener?.();
692
- resolve(code);
777
+ unsubscribe?.();
778
+ onWatchdogStatus = undefined;
779
+ void jsonlWriter.close().catch(() => {
780
+ // JSONL artifact flush is best effort.
781
+ });
782
+ // Report the run only after the child's extensions have shut down.
783
+ void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => resolve(code));
693
784
  };
694
785
 
695
786
  const drainPendingControlEvents = (): ControlEvent[] | undefined => {
@@ -820,63 +911,13 @@ async function runSingleAttempt(
820
911
  }));
821
912
  return true;
822
913
  };
823
- const requestTurnBudgetAbort = (turnCount: number) => {
824
- const budget = options.turnBudget;
825
- if (!budget || result.timedOut || result.turnBudgetExceeded || interruptedByControl || processClosed || lifecycleFinished) return;
826
- const message = turnBudgetExceededMessage(budget, turnCount);
827
- result.turnBudgetExceeded = true;
828
- result.wrapUpRequested = true;
829
- result.turnBudget = turnBudgetState(budget, turnCount, true);
830
- result.error = message;
831
- result.finalOutput = message;
832
- progress.status = "failed";
833
- progress.error = message;
834
- progress.durationMs = Date.now() - startTime;
835
- fireUpdate();
836
- trySignalChild(proc, "SIGINT");
837
- turnBudgetTerminationTimer = setTimeout(() => {
838
- if (processClosed || lifecycleFinished || result.timedOut) return;
839
- trySignalChild(proc, "SIGTERM");
840
- }, 1000);
841
- turnBudgetTerminationTimer.unref?.();
842
- turnBudgetHardKillTimer = setTimeout(() => {
843
- if (processClosed || lifecycleFinished || result.timedOut) return;
844
- trySignalChild(proc, "SIGKILL");
845
- }, 4000);
846
- turnBudgetHardKillTimer.unref?.();
847
- };
848
-
849
- const updateTurnBudget = (turnCount: number, terminalAssistantStop: boolean, toolWorkActiveOrStarting: boolean) => {
850
- const budget = options.turnBudget;
851
- if (!budget || result.timedOut || result.turnBudgetExceeded) return;
852
- if (turnCount < budget.maxTurns) {
853
- result.turnBudget = { ...budget, outcome: "within-budget", turnCount };
854
- return;
855
- }
856
- if (!turnBudgetSoftReached) {
857
- turnBudgetSoftReached = true;
858
- result.wrapUpRequested = true;
859
- appendRecentOutput(progress, [turnBudgetSoftNote(budget, turnCount)]);
860
- }
861
- const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting, options.enforceHardTurnLimit);
862
- if (decision === "defer") {
863
- result.turnBudget = turnBudgetDeferredState(
864
- budget,
865
- turnCount,
866
- result.turnBudget?.terminationDeferredAtTurn,
867
- );
868
- return;
869
- }
870
- result.turnBudget = turnBudgetState(budget, turnCount, false);
871
- if (decision === "abort") requestTurnBudgetAbort(turnCount);
872
- };
873
-
874
914
  const updateActivityState = (now: number): boolean => {
875
915
  if (!controlConfig.enabled) return false;
876
916
  const idleState = deriveActivityState({
877
917
  config: controlConfig,
878
918
  startedAt: startTime,
879
919
  lastActivityAt: progress.lastActivityAt,
920
+ turnCount: progress.turnCount,
880
921
  currentTool: progress.currentTool,
881
922
  thinking: resolvedThinking,
882
923
  now,
@@ -905,8 +946,9 @@ async function runSingleAttempt(
905
946
  };
906
947
 
907
948
 
949
+ let lastStructuredDelegationProgressState: StructuredDelegationProgressState | undefined;
908
950
  const emitUpdateSnapshot = (text: string) => {
909
- if (!options.onUpdate || processClosed) return;
951
+ if (!options.onUpdate || sessionSettled) return;
910
952
  const progressSnapshot = snapshotProgress(progress);
911
953
  const resultSnapshot = snapshotStreamResult(result, progressSnapshot);
912
954
  const controlEvents = drainPendingControlEvents();
@@ -922,19 +964,23 @@ async function runSingleAttempt(
922
964
  };
923
965
 
924
966
  const fireUpdate = () => {
925
- if (!options.onUpdate || processClosed) return;
967
+ if (!options.onUpdate || sessionSettled) return;
926
968
  progress.durationMs = Date.now() - startTime;
927
- const output = (result.timedOut || result.turnBudgetExceeded) && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
969
+ if (options.suppressUnchangedDelegationUpdates) {
970
+ if (lastStructuredDelegationProgressState && !structuredDelegationProgressChanged(lastStructuredDelegationProgressState, progress, result)) return;
971
+ lastStructuredDelegationProgressState = captureStructuredDelegationProgressState(progress, result);
972
+ }
973
+ const output = result.timedOut && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
928
974
  emitUpdateSnapshot(output || "(running...)");
929
975
  };
930
976
 
931
- const toolResultCallId = (message: Message): string | undefined => {
932
- const value = (message as { toolCallId?: unknown }).toolCallId;
933
- return typeof value === "string" && value.length > 0 ? value : undefined;
934
- };
935
-
936
- const handleToolResult = (message: Message, now: number): void => {
937
- const callId = toolResultCallId(message);
977
+ // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
978
+ // deliver the same result either as a tool_result_end event or as a
979
+ // message_end whose message role is toolResult; both funnel through here
980
+ // so one result updates budget, output, and mutating-failure state once.
981
+ const handleToolResult = (message: Message, completion: { toolCallId?: unknown }, now: number): void => {
982
+ const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
983
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
938
984
  if (callId) {
939
985
  if (handledToolResultIds.has(callId)) return;
940
986
  if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
@@ -975,24 +1021,26 @@ async function runSingleAttempt(
975
1021
  fireUpdate();
976
1022
  };
977
1023
 
978
- const rawStdoutTail = createBoundedByteTail();
979
- const processLine = (line: string) => {
980
- if (!line.trim()) return;
981
- jsonlWriter.writeLine(line);
982
- let evt: { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
983
- try {
984
- evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
985
- } catch {
986
- rawStdoutTail.push(`${line}\n`);
987
- shared.transcriptWriter?.writeStdoutLine(line);
988
- shared.orcaProgressTab?.append(`${line}\n`);
989
- // Non-JSON stdout lines are expected; only structured events are parsed.
990
- return;
991
- }
1024
+ const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1025
+ if (lifecycleFinished) return;
1026
+ jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
992
1027
  shared.transcriptWriter?.writeChildEvent(evt);
993
1028
  shared.orcaProgressTab?.event(evt);
994
- if (evt.type === "agent_settled") agentSettledReceived = true;
995
- applyChildLifecycle(projectChildLifecycle(evt));
1029
+ if (evt.type === "compaction_start") compactionStartedReceived = true;
1030
+ if (evt.type === "compaction_end" && evt.willRetry === true) {
1031
+ compactionStartedReceived = false;
1032
+ afterCompactionSettlement = false;
1033
+ }
1034
+ if (evt.type === "agent_start" || evt.type === "auto_retry_start") {
1035
+ compactionStartedReceived = false;
1036
+ afterCompactionSettlement = false;
1037
+ }
1038
+ const lifecycleAction = projectChildLifecycle(evt, false, childLifecycleState);
1039
+ if (evt.type === "agent_settled" && lifecycleAction === "start-drain") {
1040
+ agentSettledReceived = true;
1041
+ afterCompactionSettlement = compactionStartedReceived;
1042
+ }
1043
+ applyChildLifecycle(lifecycleAction);
996
1044
 
997
1045
  if (isChildWatchdogStatusEvent(evt)) {
998
1046
  if (!childWatchdog) return;
@@ -1038,7 +1086,7 @@ async function runSingleAttempt(
1038
1086
  if (options.toolBudget) {
1039
1087
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
1040
1088
  }
1041
- const mutates = isMutatingTool(evt.toolName, toolArgs);
1089
+ const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1042
1090
  observedMutationAttempt = observedMutationAttempt || mutates;
1043
1091
  pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1044
1092
  fireUpdate();
@@ -1060,24 +1108,26 @@ async function runSingleAttempt(
1060
1108
 
1061
1109
  if (evt.type === "message_end" && evt.message) {
1062
1110
  if (evt.message.role === "toolResult") {
1063
- handleToolResult(evt.message, now);
1111
+ // Fork: hosts that deliver tool results as message_end instead of
1112
+ // tool_result_end reach the same deduplicated completion path.
1113
+ handleToolResult(evt.message, evt, now);
1064
1114
  } else {
1065
1115
  result.messages!.push(evt.message);
1116
+ if (childWatchdog) {
1117
+ const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
1118
+ if (next) updateChildWatchdogState(next);
1119
+ }
1066
1120
  if (evt.message.role === "assistant") {
1067
1121
  result.usage.turns++;
1068
1122
  progress.turnCount = result.usage.turns;
1069
- const stopReason = (evt.message as { stopReason?: string }).stopReason;
1070
1123
  const toolCalls = Array.isArray(evt.message.content)
1071
1124
  ? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
1072
1125
  : [];
1073
1126
  const hasToolCall = toolCalls.length > 0;
1074
- const terminalAssistantStop = stopReason === "stop" && !hasToolCall;
1075
- const terminalStructuredOutputCall = Boolean(options.structuredOutput)
1076
- && toolCalls.length === 1
1077
- && (toolCalls[0] as { name?: string }).name === "structured_output";
1078
- updateTurnBudget(result.usage.turns, terminalAssistantStop || terminalStructuredOutputCall, hasToolCall || Boolean(progress.currentTool));
1127
+ const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
1079
1128
  const u = evt.message.usage;
1080
1129
  if (u) {
1130
+ const window = (u.input || 0) + (u.cacheRead || 0);
1081
1131
  result.usage.input += u.input || 0;
1082
1132
  result.usage.output += u.output || 0;
1083
1133
  result.usage.cacheRead += u.cacheRead || 0;
@@ -1086,19 +1136,29 @@ async function runSingleAttempt(
1086
1136
  progress.tokens = result.usage.input + result.usage.output;
1087
1137
  progress.inputTokens = result.usage.input;
1088
1138
  progress.outputTokens = result.usage.output;
1139
+ progress.window = window;
1140
+ progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1089
1141
  }
1090
1142
  if (evt.message.model) {
1091
1143
  progress.model = evt.message.model;
1092
1144
  if (!result.model) result.model = evt.message.model;
1145
+ if (expectedModelForVerification && !hasToolCall) {
1146
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
1147
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1148
+ }
1093
1149
  }
1094
1150
  if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1095
1151
  const assistantText = extractTextFromContent(evt.message.content);
1096
1152
  appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1097
- // Final assistant message: start the exit drain window.
1153
+ // Final assistant message: start the settle drain window.
1098
1154
  if (terminalAssistantStop) {
1099
1155
  if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1100
1156
  cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1101
- applyChildLifecycle(projectChildLifecycle(evt, true));
1157
+ clearAllToolTimeouts();
1158
+ activeToolCalls.clear();
1159
+ activeToolKeysByName.clear();
1160
+ refreshCurrentTool();
1161
+ applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1102
1162
  }
1103
1163
  }
1104
1164
  updateActivityState(now);
@@ -1107,14 +1167,32 @@ async function runSingleAttempt(
1107
1167
  }
1108
1168
 
1109
1169
  if (evt.type === "tool_result_end" && evt.message) {
1110
- handleToolResult(evt.message, now);
1170
+ const toolResultCompletion = {
1171
+ toolCallId: (evt.message as { toolCallId?: unknown }).toolCallId ?? (evt as { toolCallId?: unknown }).toolCallId,
1172
+ toolName: (evt.message as { toolName?: unknown }).toolName ?? (evt as { toolName?: unknown }).toolName,
1173
+ };
1174
+ clearActiveToolTimeout(toolResultCompletion);
1175
+ const endedTool = removeActiveToolCall(toolResultCompletion);
1176
+ if (endedTool) {
1177
+ progress.recentTools.push({
1178
+ tool: endedTool.tool,
1179
+ args: endedTool.args,
1180
+ endMs: now,
1181
+ });
1182
+ refreshCurrentTool();
1183
+ }
1184
+ // Fork: the shared, id-deduplicated tail (message push, budget,
1185
+ // mutating-failure tracking, output) lives in handleToolResult; hosts
1186
+ // may deliver the same result via message_end(role=toolResult).
1187
+ handleToolResult(evt.message, evt, now);
1111
1188
  }
1112
1189
  };
1190
+ onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
1113
1191
 
1114
1192
  fireUpdate();
1115
1193
  if (controlConfig.enabled || options.onUpdate) {
1116
1194
  activityTimer = setInterval(() => {
1117
- if (processClosed || lifecycleFinished) {
1195
+ if (sessionSettled || lifecycleFinished) {
1118
1196
  return;
1119
1197
  }
1120
1198
  updateActivityState(Date.now());
@@ -1125,7 +1203,7 @@ async function runSingleAttempt(
1125
1203
 
1126
1204
  if (attemptTimeout) {
1127
1205
  timeoutTimer = setTimeout(() => {
1128
- if (processClosed || lifecycleFinished || interruptedByControl) return;
1206
+ if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1129
1207
  result.timedOut = true;
1130
1208
  clearAllToolTimeouts();
1131
1209
  result.error = attemptTimeout.message;
@@ -1134,17 +1212,12 @@ async function runSingleAttempt(
1134
1212
  progress.error = attemptTimeout.message;
1135
1213
  progress.durationMs = Date.now() - startTime;
1136
1214
  fireUpdate();
1137
- trySignalChild(proc, "SIGINT");
1138
- timeoutTerminationTimer = setTimeout(() => {
1139
- if (processClosed || lifecycleFinished) return;
1140
- trySignalChild(proc, "SIGTERM");
1141
- }, 1000);
1142
- timeoutTerminationTimer.unref?.();
1143
- timeoutHardKillTimer = setTimeout(() => {
1144
- if (processClosed || lifecycleFinished) return;
1145
- trySignalChild(proc, "SIGKILL");
1215
+ abortChild();
1216
+ timeoutHardFinishTimer = setTimeout(() => {
1217
+ if (sessionSettled || lifecycleFinished) return;
1218
+ settle(undefined, true);
1146
1219
  }, 4000);
1147
- timeoutHardKillTimer.unref?.();
1220
+ timeoutHardFinishTimer.unref?.();
1148
1221
  }, attemptTimeout.remainingMs);
1149
1222
  timeoutTimer.unref?.();
1150
1223
  }
@@ -1152,8 +1225,7 @@ async function runSingleAttempt(
1152
1225
  let toolTimeoutSequence = 0;
1153
1226
  const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
1154
1227
  const activeToolTimeoutKeysByName = new Map<string, string[]>();
1155
- let toolTimeoutTerminationTimer: ReturnType<typeof setTimeout> | undefined;
1156
- let toolTimeoutHardKillTimer: ReturnType<typeof setTimeout> | undefined;
1228
+ let toolTimeoutHardFinishTimer: ReturnType<typeof setTimeout> | undefined;
1157
1229
  const removeToolTimeoutKey = (key: string): void => {
1158
1230
  const active = activeToolTimeouts.get(key);
1159
1231
  if (!active) return;
@@ -1175,17 +1247,13 @@ async function runSingleAttempt(
1175
1247
  };
1176
1248
  const clearAllToolTimeouts = (): void => {
1177
1249
  for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
1178
- if (toolTimeoutTerminationTimer) {
1179
- clearTimeout(toolTimeoutTerminationTimer);
1180
- toolTimeoutTerminationTimer = undefined;
1181
- }
1182
- if (toolTimeoutHardKillTimer) {
1183
- clearTimeout(toolTimeoutHardKillTimer);
1184
- toolTimeoutHardKillTimer = undefined;
1250
+ if (toolTimeoutHardFinishTimer) {
1251
+ clearTimeout(toolTimeoutHardFinishTimer);
1252
+ toolTimeoutHardFinishTimer = undefined;
1185
1253
  }
1186
1254
  };
1187
1255
  const terminateForToolTimeout = (message: string): void => {
1188
- if (processClosed || lifecycleFinished || interruptedByControl) return;
1256
+ if (sessionSettled || lifecycleFinished || interruptedByControl) return;
1189
1257
  result.timedOut = true;
1190
1258
  result.error = message;
1191
1259
  result.finalOutput = message;
@@ -1193,17 +1261,12 @@ async function runSingleAttempt(
1193
1261
  progress.error = message;
1194
1262
  progress.durationMs = Date.now() - startTime;
1195
1263
  fireUpdate();
1196
- trySignalChild(proc, "SIGINT");
1197
- toolTimeoutTerminationTimer = setTimeout(() => {
1198
- if (processClosed || lifecycleFinished) return;
1199
- trySignalChild(proc, "SIGTERM");
1200
- }, 1000);
1201
- toolTimeoutTerminationTimer.unref?.();
1202
- toolTimeoutHardKillTimer = setTimeout(() => {
1203
- if (processClosed || lifecycleFinished) return;
1204
- trySignalChild(proc, "SIGKILL");
1264
+ abortChild();
1265
+ toolTimeoutHardFinishTimer = setTimeout(() => {
1266
+ if (sessionSettled || lifecycleFinished) return;
1267
+ settle(undefined, true);
1205
1268
  }, 4000);
1206
- toolTimeoutHardKillTimer.unref?.();
1269
+ toolTimeoutHardFinishTimer.unref?.();
1207
1270
  };
1208
1271
  const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
1209
1272
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
@@ -1224,106 +1287,42 @@ async function runSingleAttempt(
1224
1287
  activeToolTimeoutKeysByName.set(toolName, keys);
1225
1288
  };
1226
1289
 
1227
- const stderrTail = createBoundedByteTail();
1228
- const failProtocol = (limit: ProtocolOutputLimit): void => {
1229
- if (result.protocolError) return;
1230
- result.protocolError = limit;
1231
- result.error = formatProtocolOutputLimit(limit);
1232
- progress.status = "failed";
1233
- progress.error = result.error;
1234
- progress.durationMs = Date.now() - startTime;
1235
- fireUpdate();
1236
- if (!childExited) {
1237
- trySignalChild(proc, "SIGTERM");
1238
- protocolHardKillTimer = setTimeout(() => {
1239
- if (!childExited) trySignalChild(proc, "SIGKILL");
1240
- }, 3000);
1241
- protocolHardKillTimer.unref?.();
1242
- }
1243
- };
1244
- const stdoutReader = createBoundedLineReader({
1245
- oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
1246
- onLine: processLine,
1247
- onLimit: failProtocol,
1248
- });
1249
- const stderrReader = createBoundedLineReader({
1250
- stream: "stderr",
1251
- maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
1252
- onLine: (line) => shared.transcriptWriter?.writeStderrLine(line),
1253
- onLimit: (limit) => shared.transcriptWriter?.writeStderrLine(formatProtocolOutputLimit(limit)),
1254
- });
1255
-
1256
- const clearStdioGuard = attachPostExitStdioGuard(proc, { idleMs: 2000, hardMs: 8000 });
1257
- proc.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
1258
- proc.stderr.on("data", (chunk: Buffer) => {
1259
- stderrTail.push(chunk);
1260
- stderrReader.push(chunk);
1261
- shared.orcaProgressTab?.append(chunk.toString("utf-8"));
1262
- });
1263
- proc.on("exit", () => {
1264
- childExited = true;
1265
- clearFinalDrainTimers();
1266
- });
1267
- proc.on("close", (code, signal) => {
1268
- if (lifecycleFinished) return;
1269
- processClosed = true;
1290
+ /** The child run ended (or was forced to end); fold in the captures and finish. */
1291
+ const settle = (promptError: unknown, forced = false): void => {
1292
+ if (lifecycleFinished || sessionSettled) return;
1293
+ sessionSettled = true;
1270
1294
  clearFinalDrainTimers();
1271
- clearStdioGuard();
1272
- void jsonlWriter.close().catch(() => {
1273
- // JSONL artifact flush is best effort.
1274
- });
1275
- const toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
1276
- result.runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1277
- cleanupTempDir(tempDir);
1278
- stdoutReader.end();
1279
- stderrReader.end();
1280
- const stderr = stderrTail.text();
1281
- const rawStdout = rawStdoutTail.text();
1295
+ const diagnostic = capture.toolDiagnostic();
1296
+ const toolDiagnosticError = diagnostic ? formatChildToolDiagnostic(diagnostic, { host: "parent" }) : undefined;
1297
+ toolAvailabilityError = toolDiagnosticError;
1298
+ result.runtimeAcknowledgedExtensions = capture.runtimeAcknowledgedExtensions();
1282
1299
  let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1283
- const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1284
- if (signal) result.processSignal = signal;
1285
- if (!closeError && isUnexplainedProcessSignal({
1286
- processSignal: signal,
1287
- interrupted: result.interrupted,
1288
- timedOut: result.timedOut,
1289
- stopped: result.stopped,
1290
- turnBudgetExceeded: result.turnBudgetExceeded,
1291
- forcedDrainAfterFinalSuccess,
1292
- })) {
1293
- closeError = formatProcessSignalError(signal!);
1300
+ if (!closeError && promptError !== undefined) {
1301
+ closeError = promptError instanceof Error ? promptError.message : String(promptError);
1294
1302
  }
1295
- if (code !== 0 && rawStdout.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1296
- closeError = rawStdout.trim();
1303
+ const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1304
+ const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
1305
+ if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
1306
+ closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
1297
1307
  }
1298
- if (code !== 0 && stderr.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1299
- closeError = stderr.trim();
1308
+ if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
1309
+ closeError = "Subagent session did not settle after it was aborted.";
1300
1310
  }
1301
- const finalCode = forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (code ?? 1) : (code ?? 0);
1311
+ const finalCode = forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal ? 0 : closeError || promptError !== undefined ? 1 : 0;
1302
1312
  if (!result.error && closeError) result.error = closeError;
1303
1313
  finish(finalCode);
1304
- });
1305
- proc.on("error", (error) => {
1306
- if (lifecycleFinished) return;
1307
- processClosed = true;
1308
- clearFinalDrainTimers();
1309
- clearStdioGuard();
1310
- void jsonlWriter.close().catch(() => {
1311
- // JSONL artifact flush is best effort.
1312
- });
1313
- cleanupTempDir(tempDir);
1314
- stdoutReader.end();
1315
- stderrReader.end();
1316
- if (!result.error) {
1317
- result.error = error instanceof Error ? error.message : String(error);
1318
- }
1319
- finish(1);
1320
- });
1314
+ };
1321
1315
 
1322
1316
  if (options.signal) {
1323
1317
  const kill = () => {
1324
- if (processClosed || lifecycleFinished) return;
1325
- proc.kill("SIGTERM");
1326
- setTimeout(() => !proc.killed && proc.kill("SIGKILL"), 3000);
1318
+ if (sessionSettled || lifecycleFinished) return;
1319
+ abortedBySignal = true;
1320
+ abortChild();
1321
+ const hardTimer = setTimeout(() => {
1322
+ if (sessionSettled || lifecycleFinished) return;
1323
+ settle(undefined, true);
1324
+ }, 3000);
1325
+ hardTimer.unref?.();
1327
1326
  };
1328
1327
  if (options.signal.aborted) kill();
1329
1328
  else {
@@ -1334,7 +1333,7 @@ async function runSingleAttempt(
1334
1333
 
1335
1334
  if (options.interruptSignal) {
1336
1335
  const interrupt = () => {
1337
- if (processClosed || lifecycleFinished) return;
1336
+ if (sessionSettled || lifecycleFinished) return;
1338
1337
  if (result.timedOut) return;
1339
1338
  interruptedByControl = true;
1340
1339
  clearTimeoutTimers();
@@ -1345,11 +1344,12 @@ async function runSingleAttempt(
1345
1344
  result.finalOutput = "Interrupted. Waiting for explicit next action.";
1346
1345
  progress.activityState = undefined;
1347
1346
  fireUpdate();
1348
- trySignalChild(proc, "SIGINT");
1349
- setTimeout(() => {
1350
- if (lifecycleFinished || processClosed) return;
1351
- trySignalChild(proc, "SIGTERM");
1352
- }, 1000).unref?.();
1347
+ abortChild();
1348
+ const hardTimer = setTimeout(() => {
1349
+ if (sessionSettled || lifecycleFinished) return;
1350
+ settle(undefined, true);
1351
+ }, 3000);
1352
+ hardTimer.unref?.();
1353
1353
  };
1354
1354
  if (options.interruptSignal.aborted) interrupt();
1355
1355
  else {
@@ -1364,11 +1364,40 @@ async function runSingleAttempt(
1364
1364
  options.onDetachReady?.((reason = "user request") => detachForeground(reason));
1365
1365
  } catch (error) {
1366
1366
  // A consumer callback is advisory. Keep the child attached and observable
1367
- // rather than rejecting this attempt and orphaning its live process.
1367
+ // rather than rejecting this attempt and orphaning its live session.
1368
1368
  appendRecentOutput(progress, [`Foreground detach callback failed: ${error instanceof Error ? error.message : String(error)}`]);
1369
1369
  }
1370
+
1371
+ void (async () => {
1372
+ try {
1373
+ const created = await childSessions.create({
1374
+ ...launch.session,
1375
+ onExtensionError: (error) => {
1376
+ shared.transcriptWriter?.writeStderrLine(`Extension error (${error.extensionPath}, ${error.event}): ${error.error instanceof Error ? error.error.message : String(error.error)}`);
1377
+ },
1378
+ });
1379
+ if (lifecycleFinished) {
1380
+ void created.dispose();
1381
+ return;
1382
+ }
1383
+ session = created;
1384
+ created.detached = detached;
1385
+ unsubscribe = created.subscribe((event) => processEvent(event as Parameters<typeof processEvent>[0]));
1386
+ if (abortedBySignal || interruptedByControl || result.timedOut) {
1387
+ abortChild();
1388
+ }
1389
+ options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
1390
+ await created.prompt(`Task: ${task}`);
1391
+ settle(undefined);
1392
+ } catch (error) {
1393
+ settle(error ?? new Error("Child session failed."));
1394
+ }
1395
+ })();
1370
1396
  });
1371
1397
  result.exitCode = exitCode;
1398
+ if (afterCompactionSettlement) {
1399
+ (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT] = true;
1400
+ }
1372
1401
  if (interruptedByControl) {
1373
1402
  result.exitCode = 0;
1374
1403
  result.interrupted = true;
@@ -1384,10 +1413,15 @@ async function runSingleAttempt(
1384
1413
  };
1385
1414
  return result;
1386
1415
  }
1387
- result.error = formatSubagentExtensionConflictError(result.error, {
1388
- agent: agent.name,
1389
- ambientExtensionsEnabled: !launchResolvedExtensions.disableAmbientExtensions,
1390
- });
1416
+ if (progress.currentTool
1417
+ && isOrdinaryToolForMidToolExit(progress.currentTool)
1418
+ && !abortedBySignal
1419
+ && !result.timedOut
1420
+ && !result.stopped
1421
+ && !toolAvailabilityError) {
1422
+ result.exitCode = 1;
1423
+ result.error = formatMidToolExitError({ toolName: progress.currentTool });
1424
+ }
1391
1425
  if (result.error && result.exitCode === 0) {
1392
1426
  result.exitCode = 1;
1393
1427
  }
@@ -1395,24 +1429,23 @@ async function runSingleAttempt(
1395
1429
  if (options.structuredOutput && result.exitCode === 0 && !result.error) {
1396
1430
  result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
1397
1431
  result.structuredOutputPath = options.structuredOutput.outputPath;
1398
- if (!structuredOutputToolInvoked) {
1432
+ const structured = capture.structuredOutput();
1433
+ if (!structuredOutputToolInvoked || !structured.called) {
1399
1434
  result.exitCode = 1;
1400
1435
  result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1401
1436
  result.structuredOutputFailed = true;
1402
1437
  } else {
1403
- const structured = await readStructuredOutput({
1404
- schema: options.structuredOutput.schema,
1405
- schemaPath: options.structuredOutput.schemaPath,
1406
- outputPath: options.structuredOutput.outputPath,
1407
- });
1408
- if (structured.error) {
1409
- result.exitCode = 1;
1410
- result.error = structured.error;
1411
- result.structuredOutputFailed = true;
1412
- } else {
1413
- result.structuredOutput = structured.value;
1414
- validatedStructuredOutput = true;
1415
- }
1438
+ result.structuredOutput = structured.value;
1439
+ const acceptanceMode = options.structuredOutput.acceptanceReportPath
1440
+ ? options.structuredOutput.acceptanceReportRequired ? "required" : "optional"
1441
+ : undefined;
1442
+ const acceptanceReportError = acceptanceMode === "required" && !structured.acceptanceReportProvided
1443
+ ? MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR
1444
+ : undefined;
1445
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceMode ? structured.acceptanceReport : undefined;
1446
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReportError;
1447
+ writeStructuredOutputArtifacts(options.structuredOutput, structured.value, acceptanceMode ? structured.acceptanceReport : undefined);
1448
+ validatedStructuredOutput = true;
1416
1449
  }
1417
1450
  }
1418
1451
  if (result.exitCode === 0 && !result.error) {
@@ -1423,9 +1456,12 @@ async function runSingleAttempt(
1423
1456
  : messages;
1424
1457
  const errInfo = detectSubagentError(errorMessages);
1425
1458
  const missingOutput = !finalText?.trim() && !validatedStructuredOutput;
1426
- if (missingOutput && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1459
+ const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1460
+ && hasEmptyTerminalAssistantResponse(messages)
1461
+ && (progress.toolCount > 0 || Boolean(finalText?.trim()));
1462
+ if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1427
1463
  result.exitCode = 1;
1428
- result.error = "Subagent produced no output (possible model cold-start or empty response).";
1464
+ result.error = formatEmptyTerminalAssistantResponseError(messages);
1429
1465
  } else if (errInfo.hasError) {
1430
1466
  result.exitCode = errInfo.exitCode ?? 1;
1431
1467
  result.error = errInfo.details
@@ -1444,10 +1480,12 @@ async function runSingleAttempt(
1444
1480
  }
1445
1481
 
1446
1482
  result.progressSummary = {
1483
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1447
1484
  toolCount: progress.toolCount,
1448
1485
  tokens: progress.tokens,
1449
1486
  durationMs: progress.durationMs,
1450
1487
  };
1488
+ const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, options.cwd ?? runtimeCwd);
1451
1489
 
1452
1490
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1453
1491
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1455,29 +1493,43 @@ async function runSingleAttempt(
1455
1493
  result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1456
1494
  if (result.timedOut) {
1457
1495
  const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1496
+ let requiredOutputMissing: boolean | undefined;
1497
+ if (options.outputMode === "file-only" && options.outputPath) {
1498
+ const outputChanged = hasSingleOutputChangedSinceSnapshot(options.outputPath, shared.outputSnapshot);
1499
+ requiredOutputMissing = outputChanged === undefined ? undefined : !outputChanged;
1500
+ } else if (options.structuredOutput) {
1501
+ requiredOutputMissing = !capture.structuredOutput().called;
1502
+ }
1503
+ result.timeoutRecovery = buildTimeoutRecoverySummary({
1504
+ termination: "timed-out",
1505
+ evidence: mutationEvidence,
1506
+ requiredOutputMissing,
1507
+ currentTool: progress.currentTool,
1508
+ currentToolArgs: progress.currentToolArgs,
1509
+ currentPath: progress.currentPath,
1510
+ sessionFile: options.sessionFile,
1511
+ transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
1512
+ artifactPaths: shared.artifactPaths,
1513
+ });
1458
1514
  fullOutput = fullOutput.trim()
1459
- ? `${timeoutMessage}\n\nPartial output before timeout:\n${fullOutput}`
1460
- : timeoutMessage;
1461
- } else if (result.turnBudgetExceeded && result.turnBudget) {
1462
- fullOutput = formatTurnBudgetOutput(turnBudgetExceededMessage(result.turnBudget, result.turnBudget.turnCount), fullOutput);
1463
- } else if (result.turnBudget?.outcome === "termination-deferred") {
1464
- const note = turnBudgetDeferredNote(result.turnBudget, result.turnBudget.terminationDeferredAtTurn ?? result.turnBudget.turnCount);
1465
- fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1466
- } else if (result.wrapUpRequested && result.turnBudget?.outcome === "wrap-up-requested") {
1467
- const note = turnBudgetSoftNote(result.turnBudget, result.turnBudget.wrapUpRequestedAtTurn ?? result.turnBudget.turnCount);
1468
- fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1515
+ ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1516
+ : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1469
1517
  }
1470
1518
  const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1471
- const completionGuard = result.exitCode === 0 && !result.error && completionGuardEnabled
1519
+ const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
1472
1520
  ? evaluateCompletionMutationGuard({
1473
1521
  agent: agent.name,
1474
1522
  task: shared.originalTask ?? task,
1475
1523
  messages: result.messages ?? [],
1476
- tools: agent.tools,
1477
- mcpDirectTools: agent.mcpDirectTools,
1524
+ tools: contractTools,
1525
+ mcpDirectTools: toolPlan.effectiveMcpTools,
1526
+ mutationTools: agent.mutationTools,
1527
+ toolAvailabilityError,
1528
+ mutationEvidence,
1478
1529
  })
1479
1530
  : undefined;
1480
- let completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1531
+ const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
1532
+ let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
1481
1533
  // The classifier is deliberately narrow, so a read-only review task can
1482
1534
  // still be misread as implementation. Arbitrate BEFORE any failure side
1483
1535
  // effect is published (effects, exit code, progress, notifications,
@@ -1494,27 +1546,26 @@ async function runSingleAttempt(
1494
1546
  completionGuardTriggered = arbitration.triggered;
1495
1547
  arbiterRescued = arbitration.rescued;
1496
1548
  }
1497
- if (completionGuard) {
1549
+ const completionEvidence = planCompletionEvidence({
1550
+ guard: completionGuard,
1551
+ guardTriggered: completionGuardTriggered,
1552
+ completionGuardEnabled,
1553
+ mutationCapable: hasMutationToolCapability(contractTools, toolPlan.effectiveMcpTools),
1554
+ implementationMutationExpected: expectsImplementationMutation(agent.name, shared.originalTask ?? task),
1555
+ mutationAttemptObserved,
1556
+ mutationEvidence,
1557
+ arbiterRescued,
1558
+ agentContractV1: isAgentContractV1(options.agentContract),
1559
+ });
1560
+ if (completionEvidence.fileMutation) {
1498
1561
  result.effects = {
1499
1562
  ...(result.effects ?? {}),
1500
- fileMutation: {
1501
- status: completionGuard.expectedMutation
1502
- ? completionGuardTriggered
1503
- ? "missing"
1504
- : arbiterRescued
1505
- ? "not-applicable"
1506
- : "observed"
1507
- : "not-applicable",
1508
- expected: completionGuard.expectedMutation,
1509
- attempted: completionGuard.attemptedMutation || observedMutationAttempt,
1510
- ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1511
- ...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
1512
- },
1563
+ fileMutation: completionEvidence.fileMutation,
1513
1564
  };
1514
1565
  }
1515
- if (completionGuardTriggered && !isAgentContractV1(options.agentContract)) {
1566
+ if (completionEvidence.legacyFailureError) {
1516
1567
  result.exitCode = 1;
1517
- result.error = "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes.";
1568
+ result.error = completionEvidence.legacyFailureError;
1518
1569
  progress.status = "failed";
1519
1570
  progress.error = result.error;
1520
1571
  emitControlEvent(buildControlEvent({
@@ -1529,10 +1580,14 @@ async function runSingleAttempt(
1529
1580
  }));
1530
1581
  }
1531
1582
  if (options.outputPath && result.exitCode === 0) {
1532
- const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot);
1583
+ const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
1533
1584
  fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
1534
1585
  result.savedOutputPath = resolvedOutput.savedPath;
1535
1586
  result.outputSaveError = resolvedOutput.saveError;
1587
+ if (resolvedOutput.fatalError) {
1588
+ result.exitCode = 1;
1589
+ result.error = result.error ? `${result.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
1590
+ }
1536
1591
  if (resolvedOutput.savedPath) {
1537
1592
  result.outputReference = formatSavedOutputReference(resolvedOutput.savedPath, fullOutput);
1538
1593
  if (result.outputState === "absent") result.outputState = "unknown";
@@ -1562,6 +1617,20 @@ async function runSingleAttempt(
1562
1617
  return result;
1563
1618
  }
1564
1619
 
1620
+ /** Keep the structured output artifact files other consumers read by path. */
1621
+ function writeStructuredOutputArtifacts(runtime: NonNullable<RunSyncOptions["structuredOutput"]>, value: unknown, acceptanceReport: unknown): void {
1622
+ try {
1623
+ mkdirSync(path.dirname(runtime.outputPath), { recursive: true });
1624
+ writeFileSync(runtime.outputPath, JSON.stringify(value), { mode: 0o600 });
1625
+ if (runtime.acceptanceReportPath) {
1626
+ if (acceptanceReport !== undefined) writeFileSync(runtime.acceptanceReportPath, JSON.stringify(acceptanceReport), { mode: 0o600 });
1627
+ else rmSync(runtime.acceptanceReportPath, { force: true });
1628
+ }
1629
+ } catch {
1630
+ // The captured value is already on the result; the file is observability only.
1631
+ }
1632
+ }
1633
+
1565
1634
  /**
1566
1635
  * Run a subagent synchronously (blocking until complete)
1567
1636
  */
@@ -1572,12 +1641,28 @@ async function runSyncCompletionInner(
1572
1641
  task: string,
1573
1642
  options: RunSyncOptions,
1574
1643
  ): Promise<SingleResult> {
1644
+ const effectiveCwd = options.cwd ?? runtimeCwd;
1645
+ const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1646
+ if (cwdError) {
1647
+ return redactResultPrompt(withRunContext({
1648
+ index: options.index ?? 0,
1649
+ agent: agentName,
1650
+ task,
1651
+ exitCode: 1,
1652
+ messages: [],
1653
+ usage: emptyUsage(),
1654
+ error: cwdError,
1655
+ }, options.context));
1656
+ }
1575
1657
  options = {
1576
1658
  ...options,
1577
- capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])),
1659
+ capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), options.childRuntime?.capabilityCeiling),
1578
1660
  };
1661
+ const childSessionName = deriveChildSessionName({ agent: agentName, task });
1579
1662
  const agent = agents.find((a) => a.name === agentName);
1580
1663
  if (!agent) {
1664
+ const diagnosticContext = options.unknownAgentDiagnosticContext
1665
+ ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(options.cwd ?? runtimeCwd), "both"));
1581
1666
  return redactResultPrompt(withRunContext({
1582
1667
  index: options.index ?? 0,
1583
1668
  agent: agentName,
@@ -1585,9 +1670,17 @@ async function runSyncCompletionInner(
1585
1670
  exitCode: 1,
1586
1671
  messages: [],
1587
1672
  usage: emptyUsage(),
1588
- error: `Unknown agent: ${agentName}`,
1673
+ error: formatUnknownAgentError(agentName, diagnosticContext),
1589
1674
  }, options.context));
1590
1675
  }
1676
+ options = {
1677
+ ...options,
1678
+ thinkingCeiling: intersectThinkingCeilings(
1679
+ options.thinkingCeiling,
1680
+ agent.maxThinking,
1681
+ options.childRuntime?.thinkingCeiling,
1682
+ ),
1683
+ };
1591
1684
  try {
1592
1685
  assertAgentAllowedByCapabilityCeiling(agent.name, options.capabilityCeiling);
1593
1686
  } catch (error) {
@@ -1658,7 +1751,7 @@ async function runSyncCompletionInner(
1658
1751
  dynamicGroup: options.acceptanceContext?.dynamicGroup,
1659
1752
  agentContract: options.agentContract,
1660
1753
  });
1661
- const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1754
+ const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract), structuredOutput: Boolean(options.structuredOutput?.acceptanceReportPath) });
1662
1755
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1663
1756
  options.onEffectivePrompt?.(taskWithAcceptance);
1664
1757
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
@@ -1701,13 +1794,46 @@ async function runSyncCompletionInner(
1701
1794
  options.modelOverride ?? agent.model,
1702
1795
  agent.fallbackModels,
1703
1796
  options.availableModels,
1704
- options.preferredModelProvider,
1705
- { scope: options.modelScope, primaryModelFromParent: options.modelOverrideFromParent },
1797
+ agent.modelProvider ?? options.preferredModelProvider,
1798
+ {
1799
+ scope: options.modelScope,
1800
+ primaryModelFromParent: options.modelOverrideFromParent,
1801
+ origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1802
+ },
1706
1803
  );
1804
+ if (options.workflowChildPermitLaunch && candidates.length > 1) {
1805
+ const error = "Workflow child permit does not support model fallback.";
1806
+ return redactResultPrompt(withRunContext({
1807
+ index: options.index ?? 0,
1808
+ agent: agent.name,
1809
+ task,
1810
+ exitCode: 1,
1811
+ messages: [],
1812
+ usage: emptyUsage(),
1813
+ error,
1814
+ }, options.context));
1815
+ }
1816
+ try {
1817
+ for (const candidate of candidates) {
1818
+ const model = applyThinkingSuffix(candidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
1819
+ assertThinkingWithinCeiling({ model, configThinking: options.thinkingOverride ?? agent.thinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
1820
+ }
1821
+ } catch (error) {
1822
+ return redactResultPrompt(withRunContext({
1823
+ index: options.index ?? 0,
1824
+ agent: agent.name,
1825
+ task,
1826
+ exitCode: 1,
1827
+ messages: [],
1828
+ usage: emptyUsage(),
1829
+ error: error instanceof Error ? error.message : String(error),
1830
+ }, options.context));
1831
+ }
1707
1832
  const attemptedModels: string[] = [];
1708
1833
  const modelAttempts: ModelAttempt[] = [];
1709
1834
  const aggregateUsage = emptyUsage();
1710
1835
  const attemptNotes: string[] = [];
1836
+ const launchWarnings = { emitted: false };
1711
1837
  let totalToolCount = 0;
1712
1838
  let totalDurationMs = 0;
1713
1839
 
@@ -1776,14 +1902,17 @@ async function runSyncCompletionInner(
1776
1902
  };
1777
1903
  let lastResult: SingleResult | undefined;
1778
1904
  const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1779
- // Escalated to "file" after an unexplained zero-activity startup failure so
1780
- // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1781
- let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1905
+ let abortRecoveryAttempted = false;
1906
+ let nextAttemptTask = taskWithAcceptance;
1782
1907
  modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1783
1908
  const candidate = modelsToTry[modelIndex];
1784
- for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
1909
+ // The inner loop re-runs the same candidate at most once, for abort recovery.
1910
+ for (;;) {
1911
+ const recoveringAbort = abortRecoveryAttempted;
1912
+ const attemptTask = nextAttemptTask;
1913
+ const verifyModel = Boolean(candidate) && !(options.modelOverrideFromParent && modelIndex === 0);
1785
1914
  const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1786
- const result = await runSingleAttempt(runtimeCwd, agent, taskWithAcceptance, candidate, attemptOptions, {
1915
+ const result = await runSingleAttempt(runtimeCwd, agent, attemptTask, candidate, attemptOptions, {
1787
1916
  sessionEnabled,
1788
1917
  systemPrompt,
1789
1918
  resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
@@ -1797,11 +1926,12 @@ async function runSyncCompletionInner(
1797
1926
  .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1798
1927
  outputSnapshot,
1799
1928
  originalTask: task,
1800
- taskDelivery: taskDeliveryOverride,
1801
1929
  orcaProgressTab,
1930
+ launchWarnings,
1931
+ verifyModel,
1802
1932
  });
1803
1933
  lastResult = result;
1804
- if (startupAttemptIndex === 0) {
1934
+ if (!recoveringAbort) {
1805
1935
  if (result.model) attemptedModels.push(result.model);
1806
1936
  else if (candidate) attemptedModels.push(candidate);
1807
1937
  }
@@ -1817,80 +1947,51 @@ async function runSyncCompletionInner(
1817
1947
  usage: { ...result.usage },
1818
1948
  };
1819
1949
  modelAttempts.push(attempt);
1820
- // Preserve the legacy intercom handoff contract: once this logical run has
1821
- // been handed to a supervisor, terminating that attempt must not launch a
1822
- // startup retry or model fallback. Explicit user detach retains fallback.
1823
- if (intercomDetached || result.timedOut || result.turnBudgetExceeded) break modelAttemptsLoop;
1824
- if (attemptSucceeded) break modelAttemptsLoop;
1825
-
1826
- const startupFailure = isRetryableSubagentStartupFailure({
1827
- exitCode: result.exitCode,
1828
- error: result.error,
1829
- finalOutput: result.finalOutput,
1830
- messageCount: result.messages?.length ?? 0,
1831
- toolCount: result.progressSummary?.toolCount ?? 0,
1832
- usage: result.usage,
1833
- durationMs: result.progressSummary?.durationMs ?? Number.POSITIVE_INFINITY,
1834
- protocolError: result.protocolError,
1835
- processSignal: result.processSignal,
1836
- detached: result.detached,
1837
- interrupted: result.interrupted,
1838
- timedOut: result.timedOut,
1839
- stopped: result.stopped,
1840
- turnBudgetExceeded: result.turnBudgetExceeded,
1841
- });
1842
- const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1843
- if (startupFailure && retryDelayMs !== undefined) {
1844
- const retryNote = formatSubagentStartupRetryNote({
1845
- model: attempt.model,
1846
- attempt: startupAttemptIndex + 1,
1847
- maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1848
- delayMs: retryDelayMs,
1950
+ if (!attemptSucceeded) {
1951
+ const afterCompactionSettlement = (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT];
1952
+ const abortRecovery = planAbortRecovery({
1953
+ messages: result.messages ?? [],
1954
+ error: result.error,
1955
+ processSignal: result.processSignal,
1956
+ sessionAvailable: Boolean(options.sessionFile && existsSync(options.sessionFile)),
1957
+ alreadyResumed: abortRecoveryAttempted,
1958
+ stopped: result.stopped || result.detached || options.signal?.aborted,
1959
+ interrupted: result.interrupted || intercomDetached || options.interruptSignal?.aborted,
1960
+ timedOut: result.timedOut,
1961
+ toolBudgetExhausted: result.toolBudgetBlocked,
1962
+ usageBudgetExhausted: false,
1963
+ structuredOutputFailed: result.structuredOutputFailed,
1964
+ acceptanceFailed: false,
1965
+ currentTool: result.progress?.currentTool,
1966
+ afterCompactionSettlement,
1849
1967
  });
1850
- const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [options.signal, options.interruptSignal]);
1851
- if (!shouldRetry) {
1852
- if (options.interruptSignal?.aborted) {
1853
- result.exitCode = 0;
1854
- result.interrupted = true;
1855
- result.error = undefined;
1856
- result.finalOutput = "Interrupted. Waiting for explicit next action.";
1857
- if (result.progress) {
1858
- result.progress.status = "running";
1859
- result.progress.error = undefined;
1860
- }
1861
- } else {
1862
- const cancellationError = "Subagent startup retry cancelled before relaunch.";
1863
- result.error = cancellationError;
1864
- result.finalOutput = cancellationError;
1865
- attempt.error = cancellationError;
1866
- if (result.progress) result.progress.error = cancellationError;
1867
- }
1868
- break modelAttemptsLoop;
1968
+ if (abortRecovery.action === "resume") {
1969
+ abortRecoveryAttempted = true;
1970
+ nextAttemptTask = abortRecovery.prompt;
1971
+ attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1972
+ continue;
1869
1973
  }
1870
- if (!taskDeliveryOverride && result.processSignal === "SIGKILL") {
1871
- taskDeliveryOverride = "file";
1872
- attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1974
+ if (abortRecovery.diagnostic) {
1975
+ result.error = result.error ? `${result.error}\n${abortRecovery.diagnostic}` : abortRecovery.diagnostic;
1976
+ attempt.error = result.error;
1977
+ break modelAttemptsLoop;
1873
1978
  }
1874
- attempt.error = retryNote;
1875
- attemptNotes.push(retryNote);
1876
- continue;
1877
1979
  }
1878
- if (startupFailure) {
1879
- const startupError = formatSubagentStartupRetryExhaustedError({
1880
- model: attempt.model,
1881
- attempts: startupAttemptIndex + 1,
1882
- });
1883
- result.error = startupError;
1884
- result.finalOutput = startupError;
1885
- if (result.progress) {
1886
- result.progress.error = startupError;
1887
- result.progress.status = "failed";
1888
- }
1889
- attempt.error = startupError;
1980
+ if (recoveringAbort && !attemptSucceeded) break modelAttemptsLoop;
1981
+ if (options.workflowChildPermitLaunch && !attemptSucceeded) break modelAttemptsLoop;
1982
+ // Preserve the legacy intercom handoff contract: once this logical run has
1983
+ // been handed to a supervisor, terminating that attempt must not launch a
1984
+ // model fallback. Explicit user detach retains fallback.
1985
+ if (intercomDetached || result.timedOut) break modelAttemptsLoop;
1986
+ if (attemptSucceeded) break modelAttemptsLoop;
1987
+
1988
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount });
1989
+ if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
1990
+ if (isContextOverflow(result.error)) {
1991
+ result.contextOverflow = true;
1992
+ attemptNotes.push(`[fallback] ${attempt.model} failed: context overflow — the input exceeds this model's context window. Reduce the task input or use a model with a larger context window.`);
1890
1993
  break modelAttemptsLoop;
1891
1994
  }
1892
- const retryableModelFailure = isRetryableModelFailure(result.error);
1893
- if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
1894
1995
  if (!retryableModelFailure || modelIndex === modelsToTry.length - 1) break modelAttemptsLoop;
1895
1996
  attemptNotes.push(formatModelAttemptNote(attempt, modelsToTry[modelIndex + 1]));
1896
1997
  break;
@@ -1906,11 +2007,13 @@ async function runSyncCompletionInner(
1906
2007
  usage: emptyUsage(),
1907
2008
  error: "Subagent did not produce a result.",
1908
2009
  } satisfies SingleResult, options.context);
2010
+ result.task = task;
1909
2011
 
1910
2012
  result.usage = aggregateUsage;
1911
2013
  result.attemptedModels = attemptedModels.length > 0 ? attemptedModels : undefined;
1912
2014
  result.modelAttempts = modelAttempts.length > 0 ? modelAttempts : undefined;
1913
2015
  result.progressSummary = {
2016
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1914
2017
  toolCount: totalToolCount,
1915
2018
  tokens: aggregateUsage.input + aggregateUsage.output,
1916
2019
  durationMs: totalDurationMs,
@@ -1964,19 +2067,20 @@ async function runSyncCompletionInner(
1964
2067
  result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." });
1965
2068
  } else if (result.timedOut) {
1966
2069
  result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." });
1967
- } else if (result.turnBudgetExceeded) {
1968
- result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." });
1969
2070
  } else {
1970
2071
  result.acceptance = await evaluateAcceptance({
1971
2072
  acceptance: effectiveAcceptance,
1972
2073
  output: acceptanceOutputByResult.get(result) ?? result.finalOutput ?? "",
2074
+ report: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReport,
2075
+ reportError: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError,
1973
2076
  fileOutput: childWrittenOutput !== undefined && options.outputPath
1974
- ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only" }
2077
+ ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
1975
2078
  : undefined,
1976
2079
  cwd: options.cwd ?? runtimeCwd,
1977
2080
  reportOptional: isAgentContractV1(options.agentContract),
1978
2081
  artifactsDir: options.artifactsDir,
1979
2082
  runId: options.runId,
2083
+ watchdog: result.watchdog,
1980
2084
  });
1981
2085
  }
1982
2086
  } catch (error) {