@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,1868 @@
1
+ /**
2
+ * Core execution logic for running subagents
3
+ */
4
+
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync, unlinkSync } from "node:fs";
7
+ import * as path from "node:path";
8
+ import type { Message } from "@earendil-works/pi-ai";
9
+ import type { AgentConfig } from "../../agents/agents.ts";
10
+ import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
11
+ import {
12
+ ensureArtifactsDir,
13
+ formatOutputArtifactContent,
14
+ getArtifactPaths,
15
+ writeArtifact,
16
+ writeMetadata,
17
+ } from "../../shared/artifacts.ts";
18
+ import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
19
+ import {
20
+ type AgentProgress,
21
+ type ArtifactPaths,
22
+ type ControlEvent,
23
+ type ModelAttempt,
24
+ type RunSyncOptions,
25
+ type SingleResult,
26
+ type Usage,
27
+ DEFAULT_MAX_OUTPUT,
28
+ INTERCOM_DETACH_REQUEST_EVENT,
29
+ INTERCOM_DETACH_RESPONSE_EVENT,
30
+ type AcceptanceLedger,
31
+ type ResolvedAcceptanceConfig,
32
+ truncateOutput,
33
+ getSubagentDepthEnv,
34
+ } from "../../shared/types.ts";
35
+ import {
36
+ DEFAULT_CONTROL_CONFIG,
37
+ buildControlEvent,
38
+ claimControlNotification,
39
+ deriveActivityState,
40
+ shouldNotifyControlEvent,
41
+ } from "../shared/subagent-control.ts";
42
+ import {
43
+ getFinalOutput,
44
+ findLatestSessionFile,
45
+ detectSubagentError,
46
+ hasEmptyTerminalAssistantResponse,
47
+ extractToolArgsPreview,
48
+ extractTextFromContent,
49
+ boundStreamedRecentTools,
50
+ boundStreamedRecentOutput,
51
+ boundStreamedToolCalls,
52
+ } from "../../shared/utils.ts";
53
+ import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
54
+ import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
55
+ import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
56
+ import { getPiSpawnCommand } from "../shared/pi-spawn.ts";
57
+ import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
58
+ import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
59
+ import { resolvePermissionRules } from "../shared/permissions.ts";
60
+ import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
61
+ import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
62
+ import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV } from "../shared/capability-ceiling.ts";
63
+ import { resolveEffectiveThinking } from "../../shared/model-info.ts";
64
+ import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
65
+ import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
66
+ import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
67
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
68
+ import {
69
+ buildModelCandidates,
70
+ formatModelAttemptNote,
71
+ isRetryableModelFailure,
72
+ } from "../shared/model-fallback.ts";
73
+ import {
74
+ SUBAGENT_STARTUP_RETRY_DELAYS_MS,
75
+ formatSubagentStartupRetryExhaustedError,
76
+ formatSubagentStartupRetryNote,
77
+ isRetryableSubagentStartupFailure,
78
+ waitForSubagentStartupRetry,
79
+ } from "../shared/subagent-startup-retry.ts";
80
+ import {
81
+ createMutatingFailureState,
82
+ didMutatingToolFail,
83
+ isMutatingTool,
84
+ nextLongRunningTrigger,
85
+ recordMutatingFailure,
86
+ resetMutatingFailureState,
87
+ resolveCurrentPath,
88
+ shouldEscalateMutatingFailures,
89
+ summarizeRecentMutatingFailures,
90
+ } from "../shared/long-running-guard.ts";
91
+ import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
92
+ import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
93
+ import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
94
+ import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
95
+ import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
96
+ import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
97
+ import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
98
+ import {
99
+ acceptChildWatchdogEvent,
100
+ childWatchdogIsActive,
101
+ isChildWatchdogStatusEvent,
102
+ resolveChildWatchdogConfig,
103
+ type ChildWatchdogStateSnapshot,
104
+ } from "../../watchdog/child-status.ts";
105
+
106
+ const artifactOutputByResult = new WeakMap<SingleResult, string>();
107
+ const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
108
+
109
+ function emptyUsage(): Usage {
110
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
111
+ }
112
+
113
+ function withRunContext<T extends SingleResult>(result: T, context: RunSyncOptions["context"]): T {
114
+ if (!context) return result;
115
+ result.context = context;
116
+ return result;
117
+ }
118
+
119
+ function sumUsage(target: Usage, source: Usage): void {
120
+ target.input += source.input;
121
+ target.output += source.output;
122
+ target.cacheRead += source.cacheRead;
123
+ target.cacheWrite += source.cacheWrite;
124
+ target.cost += source.cost;
125
+ target.turns += source.turns;
126
+ }
127
+
128
+ function persistSingleResultMetadata(input: {
129
+ metadataPath?: string;
130
+ enabled: boolean;
131
+ runId?: string;
132
+ agent: string;
133
+ task: string;
134
+ result: SingleResult;
135
+ }): void {
136
+ if (!input.enabled || !input.metadataPath) return;
137
+ const target = input.result;
138
+ writeMetadata(input.metadataPath, {
139
+ runId: input.runId,
140
+ agent: input.agent,
141
+ task: input.task,
142
+ exitCode: target.exitCode,
143
+ processSignal: target.processSignal,
144
+ usage: target.usage,
145
+ model: target.model,
146
+ attemptedModels: target.attemptedModels,
147
+ modelAttempts: target.modelAttempts,
148
+ durationMs: target.progressSummary?.durationMs,
149
+ toolCount: target.progressSummary?.toolCount,
150
+ error: target.error,
151
+ agentContract: target.agentContract,
152
+ launchContractDigest: target.launchContractDigest,
153
+ launchResolvedExtensions: target.launchResolvedExtensions,
154
+ runtimeAcknowledgedExtensions: target.runtimeAcknowledgedExtensions,
155
+ execution: target.execution,
156
+ acceptance: target.acceptance,
157
+ capabilityCeiling: target.capabilityCeiling,
158
+ capabilityAudit: target.capabilityAudit,
159
+ review: target.review,
160
+ effects: target.effects,
161
+ transcriptPath: target.transcriptPath,
162
+ transcriptError: target.transcriptError,
163
+ skills: target.skills,
164
+ skillsWarning: target.skillsWarning,
165
+ timestamp: Date.now(),
166
+ });
167
+ }
168
+
169
+ function formatTimeoutMessage(timeoutMs: number): string {
170
+ return `Subagent timed out after ${timeoutMs}ms.`;
171
+ }
172
+
173
+ function resolveAttemptTimeout(options: RunSyncOptions): { timeoutMs: number; remainingMs: number; message: string } | undefined {
174
+ if (options.timeoutMs === undefined) return undefined;
175
+ const deadlineAt = options.deadlineAt ?? Date.now() + options.timeoutMs;
176
+ return {
177
+ timeoutMs: options.timeoutMs,
178
+ remainingMs: Math.max(0, deadlineAt - Date.now()),
179
+ message: formatTimeoutMessage(options.timeoutMs),
180
+ };
181
+ }
182
+
183
+ function buildPendingAcceptanceLedger(acceptance: ResolvedAcceptanceConfig): AcceptanceLedger {
184
+ return {
185
+ status: "pending",
186
+ evidenceStatus: "pending",
187
+ explicit: acceptance.explicit,
188
+ effectiveAcceptance: acceptance,
189
+ inferredReason: acceptance.inferredReason,
190
+ criteria: acceptance.criteria,
191
+ runtimeChecks: [],
192
+ verifyRuns: [],
193
+ };
194
+ }
195
+
196
+ function buildInterruptedAcceptanceLedger(acceptance: ResolvedAcceptanceConfig): AcceptanceLedger {
197
+ const pending = buildPendingAcceptanceLedger(acceptance);
198
+ if (acceptance.level === "none") {
199
+ pending.status = "not-required";
200
+ pending.evidenceStatus = "not-required";
201
+ } else {
202
+ pending.runtimeChecks = [{
203
+ id: "interrupted",
204
+ status: "not-applicable",
205
+ message: "Acceptance was not evaluated because the subagent was interrupted.",
206
+ }];
207
+ }
208
+ return pending;
209
+ }
210
+
211
+ function appendRecentOutput(progress: AgentProgress, lines: string[]): void {
212
+ if (lines.length === 0) return;
213
+ progress.recentOutput.push(...lines.filter((line) => line.trim()));
214
+ if (progress.recentOutput.length > 50) {
215
+ progress.recentOutput.splice(0, progress.recentOutput.length - 50);
216
+ }
217
+ }
218
+
219
+ function stripAcceptanceReportsFromMessages(messages: Message[] | undefined): void {
220
+ for (const message of messages ?? []) {
221
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
222
+ for (const part of message.content) {
223
+ if (part.type === "text" && "text" in part && typeof part.text === "string") {
224
+ part.text = stripAcceptanceReport(part.text);
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ function snapshotProgress(progress: AgentProgress): AgentProgress {
231
+ return {
232
+ ...progress,
233
+ skills: progress.skills ? [...progress.skills] : undefined,
234
+ recentTools: boundStreamedRecentTools(progress.recentTools),
235
+ recentOutput: boundStreamedRecentOutput(progress.recentOutput),
236
+ };
237
+ }
238
+
239
+ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleResult {
240
+ return {
241
+ ...result,
242
+ messages: result.outputMode === "file-only" && result.savedOutputPath ? undefined : result.messages ? [...result.messages] : undefined,
243
+ usage: { ...result.usage },
244
+ skills: result.skills ? [...result.skills] : undefined,
245
+ attemptedModels: result.attemptedModels ? [...result.attemptedModels] : undefined,
246
+ modelAttempts: result.modelAttempts
247
+ ? result.modelAttempts.map((attempt) => ({
248
+ ...attempt,
249
+ usage: attempt.usage ? { ...attempt.usage } : undefined,
250
+ }))
251
+ : undefined,
252
+ controlEvents: result.controlEvents ? result.controlEvents.map((event) => ({ ...event })) : undefined,
253
+ progress,
254
+ progressSummary: result.progressSummary ? { ...result.progressSummary } : undefined,
255
+ artifactPaths: result.artifactPaths ? { ...result.artifactPaths } : undefined,
256
+ truncation: result.truncation ? { ...result.truncation } : undefined,
257
+ outputReference: result.outputReference ? { ...result.outputReference } : undefined,
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Streaming variant of snapshotResult for `onUpdate` progress events: it drops the
263
+ * unbounded `messages` transcript in favour of compact tool-call summaries so a
264
+ * single `tool_execution_update` line stays well under the child-stdout protocol
265
+ * cap (`MAX_CHILD_PENDING_LINE_BYTES`). Non-streaming consumers such as
266
+ * foreground detach receipts and terminal consumers use snapshotResult directly.
267
+ */
268
+ function snapshotStreamResult(result: SingleResult, progress: AgentProgress): SingleResult {
269
+ const snapshot = snapshotResult(result, progress);
270
+ snapshot.messages = undefined;
271
+ snapshot.toolCalls = boundStreamedToolCalls(result);
272
+ return snapshot;
273
+ }
274
+
275
+ async function runSingleAttempt(
276
+ runtimeCwd: string,
277
+ agent: AgentConfig,
278
+ task: string,
279
+ model: string | undefined,
280
+ options: RunSyncOptions,
281
+ shared: {
282
+ sessionEnabled: boolean;
283
+ systemPrompt: string;
284
+ resolvedSkillNames?: string[];
285
+ modelCandidates?: string[];
286
+ skillsWarning?: string;
287
+ jsonlPath?: string;
288
+ artifactPaths?: ArtifactPaths;
289
+ transcriptWriter?: ChildTranscriptWriter;
290
+ attemptNotes: string[];
291
+ outputSnapshot?: SingleOutputSnapshot;
292
+ originalTask?: string;
293
+ },
294
+ ): Promise<SingleResult> {
295
+ const effectiveThinking = options.thinkingOverride ?? agent.thinking;
296
+ const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
297
+ const resolvedThinking = resolveEffectiveThinking(modelArg, effectiveThinking);
298
+ const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
299
+ const childWatchdog = watchdogConfig.ok
300
+ ? resolveChildWatchdogConfig({
301
+ config: watchdogConfig.config,
302
+ agent: agent.name,
303
+ runId: options.runId,
304
+ childIndex: options.index ?? 0,
305
+ })
306
+ : undefined;
307
+ const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
308
+ const permissionAuditPath = permissionRules && options.artifactsDir
309
+ ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
310
+ : undefined;
311
+ const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit } = buildPiArgs({
312
+ baseArgs: ["--mode", "json", "-p"],
313
+ task,
314
+ sessionEnabled: shared.sessionEnabled,
315
+ sessionDir: options.sessionDir,
316
+ sessionFile: options.sessionFile,
317
+ model: modelArg,
318
+ thinking: effectiveThinking,
319
+ systemPromptMode: agent.systemPromptMode,
320
+ inheritProjectContext: agent.inheritProjectContext,
321
+ inheritSkills: agent.inheritSkills,
322
+ requireReadTool: Boolean(shared.resolvedSkillNames?.length),
323
+ tools: agent.tools,
324
+ extensions: agent.extensions,
325
+ subagentOnlyExtensions: agent.subagentOnlyExtensions,
326
+ systemPrompt: appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget),
327
+ mcpDirectTools: agent.mcpDirectTools,
328
+ cwd: options.cwd ?? runtimeCwd,
329
+ promptFileStem: agent.name,
330
+ intercomSessionName: options.intercomSessionName,
331
+ orchestratorIntercomTarget: options.orchestratorIntercomTarget,
332
+ runId: options.runId,
333
+ childAgentName: agent.name,
334
+ childIndex: options.index ?? 0,
335
+ parentEventSink: options.nestedRoute?.eventSink,
336
+ parentControlInbox: options.nestedRoute?.controlInbox,
337
+ parentRootRunId: options.nestedRoute?.rootRunId,
338
+ parentCapabilityToken: options.nestedRoute?.capabilityToken,
339
+ parentSessionId: options.parentSessionId,
340
+ structuredOutput: options.structuredOutput,
341
+ toolBudget: options.toolBudget,
342
+ allowZeroToolBudget: options.allowZeroToolBudget,
343
+ permissionRules,
344
+ permissionAuditPath,
345
+ childWatchdog,
346
+ waitToolEnabled: options.waitToolEnabled,
347
+ capabilityCeiling: options.capabilityCeiling,
348
+ });
349
+
350
+ const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget);
351
+ const toolPlan = resolvePiLaunchToolPlan({
352
+ tools: agent.tools,
353
+ extensions: agent.extensions,
354
+ subagentOnlyExtensions: agent.subagentOnlyExtensions,
355
+ mcpDirectTools: agent.mcpDirectTools,
356
+ cwd: options.cwd ?? runtimeCwd,
357
+ requireReadTool: Boolean(shared.resolvedSkillNames?.length),
358
+ structuredOutput: Boolean(options.structuredOutput),
359
+ capabilityCeiling: options.capabilityCeiling,
360
+ inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
361
+ agentName: agent.name,
362
+ });
363
+ const launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
364
+ const launchContractDigest = launchBindingDigest({
365
+ definitionDigest: agentDefinitionDigest(agent),
366
+ task: shared.originalTask ?? task,
367
+ ...(modelArg ? { model: modelArg } : {}),
368
+ modelCandidates: shared.modelCandidates,
369
+ ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
370
+ systemPrompt: effectiveSystemPrompt,
371
+ systemPromptMode: agent.systemPromptMode,
372
+ inheritProjectContext: agent.inheritProjectContext,
373
+ inheritSkills: agent.inheritSkills,
374
+ skills: shared.resolvedSkillNames ?? [],
375
+ tools: toolPlan.effectiveToolAllowlist,
376
+ extensions: toolPlan.extensionArgs,
377
+ mcpDirectTools: toolPlan.effectiveMcpTools,
378
+ ...(options.outputPath ? { outputPath: options.outputPath } : {}),
379
+ outputMode: options.outputMode ?? "inline",
380
+ ...(options.structuredOutput ? { structuredOutputSchema: options.structuredOutput.schema } : {}),
381
+ });
382
+ const result: SingleResult = withRunContext({
383
+ index: options.index ?? 0,
384
+ agent: agent.name,
385
+ task: shared.originalTask ?? task,
386
+ ...(options.agentContract ? { agentContract: options.agentContract } : {}),
387
+ launchContractDigest,
388
+ launchResolvedExtensions,
389
+ exitCode: 0,
390
+ outputState: "absent",
391
+ messages: [],
392
+ usage: emptyUsage(),
393
+ model: modelArg,
394
+ ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
395
+ artifactPaths: shared.artifactPaths,
396
+ transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
397
+ skills: shared.resolvedSkillNames,
398
+ skillsWarning: shared.skillsWarning,
399
+ ...(options.turnBudget ? { turnBudget: initialTurnBudgetState(options.turnBudget) } : {}),
400
+ ...(options.toolBudget ? { toolBudget: initialToolBudgetState(options.toolBudget) } : {}),
401
+ ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
402
+ ...(capabilityAudit ? { capabilityAudit } : {}),
403
+ }, options.context);
404
+ const startTime = Date.now();
405
+ if (options.structuredOutput) {
406
+ try {
407
+ if (existsSync(options.structuredOutput.outputPath)) unlinkSync(options.structuredOutput.outputPath);
408
+ } catch {
409
+ // Missing/stale structured-output files are handled after the child exits.
410
+ }
411
+ }
412
+ const controlConfig = options.controlConfig ?? DEFAULT_CONTROL_CONFIG;
413
+ let interruptedByControl = false;
414
+ const allControlEvents: ControlEvent[] = [];
415
+ let pendingControlEvents: ControlEvent[] = [];
416
+ const emittedControlEventKeys = new Set<string>();
417
+ const emitControlEvent = (event: ControlEvent) => {
418
+ if (!shouldNotifyControlEvent(controlConfig, event)) return;
419
+ if (!claimControlNotification(controlConfig, event, emittedControlEventKeys)) return;
420
+ allControlEvents.push(event);
421
+ pendingControlEvents.push(event);
422
+ options.onControlEvent?.(event);
423
+ };
424
+
425
+ const progress: AgentProgress = {
426
+ index: options.index ?? 0,
427
+ agent: agent.name,
428
+ status: "running",
429
+ task,
430
+ skills: shared.resolvedSkillNames,
431
+ recentTools: [],
432
+ recentOutput: [...shared.attemptNotes],
433
+ toolCount: 0,
434
+ tokens: 0,
435
+ ...(modelArg ? { model: modelArg } : {}),
436
+ ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
437
+ inputTokens: 0,
438
+ outputTokens: 0,
439
+ durationMs: 0,
440
+ lastActivityAt: startTime,
441
+ };
442
+ result.progress = progress;
443
+ const attemptTimeout = resolveAttemptTimeout(options);
444
+ if (attemptTimeout?.remainingMs === 0) {
445
+ cleanupTempDir(tempDir);
446
+ result.exitCode = 1;
447
+ result.timedOut = true;
448
+ result.error = attemptTimeout.message;
449
+ result.finalOutput = attemptTimeout.message;
450
+ progress.status = "failed";
451
+ progress.error = attemptTimeout.message;
452
+ result.progressSummary = {
453
+ toolCount: progress.toolCount,
454
+ tokens: progress.tokens,
455
+ durationMs: progress.durationMs,
456
+ };
457
+ return result;
458
+ }
459
+ const spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) };
460
+ let observedMutationAttempt = false;
461
+ let structuredOutputToolInvoked = false;
462
+ let structuredOutputMessageStartIndex: number | undefined;
463
+
464
+ const exitCode = await new Promise<number>((resolve) => {
465
+ const spawnSpec = getPiSpawnCommand(args);
466
+ const proc = spawn(spawnSpec.command, spawnSpec.args, {
467
+ cwd: options.cwd ?? runtimeCwd,
468
+ env: spawnEnv,
469
+ stdio: ["ignore", "pipe", "pipe"],
470
+ windowsHide: true,
471
+ });
472
+ const jsonlWriter = createJsonlWriter(shared.jsonlPath, proc.stdout);
473
+ let processClosed = false;
474
+ let lifecycleFinished = false;
475
+ let detached = false;
476
+ let intercomStarted = false;
477
+ let assistantError: string | undefined;
478
+ let removeAbortListener: (() => void) | undefined;
479
+ let removeInterruptListener: (() => void) | undefined;
480
+ let activityTimer: NodeJS.Timeout | undefined;
481
+ let timeoutTimer: NodeJS.Timeout | undefined;
482
+ let timeoutTerminationTimer: NodeJS.Timeout | undefined;
483
+ let timeoutHardKillTimer: NodeJS.Timeout | undefined;
484
+ let turnBudgetSoftReached = false;
485
+ let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
486
+ let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
487
+ let protocolHardKillTimer: NodeJS.Timeout | undefined;
488
+ const clearTurnBudgetTimers = () => {
489
+ if (turnBudgetTerminationTimer) {
490
+ clearTimeout(turnBudgetTerminationTimer);
491
+ turnBudgetTerminationTimer = undefined;
492
+ }
493
+ if (turnBudgetHardKillTimer) {
494
+ clearTimeout(turnBudgetHardKillTimer);
495
+ turnBudgetHardKillTimer = undefined;
496
+ }
497
+ };
498
+ const clearTimeoutTimers = () => {
499
+ if (timeoutTimer) {
500
+ clearTimeout(timeoutTimer);
501
+ timeoutTimer = undefined;
502
+ }
503
+ if (timeoutTerminationTimer) {
504
+ clearTimeout(timeoutTerminationTimer);
505
+ timeoutTerminationTimer = undefined;
506
+ }
507
+ if (timeoutHardKillTimer) {
508
+ clearTimeout(timeoutHardKillTimer);
509
+ timeoutHardKillTimer = undefined;
510
+ }
511
+ };
512
+
513
+ const detachForeground = (reason: string): boolean => {
514
+ if (detached || processClosed || lifecycleFinished || options.signal?.aborted) return false;
515
+ const receiptProgress = snapshotProgress(progress);
516
+ receiptProgress.status = "detached";
517
+ receiptProgress.durationMs = Date.now() - startTime;
518
+ const receipt = snapshotResult(result, receiptProgress);
519
+ receipt.exitCode = -2;
520
+ receipt.detached = true;
521
+ receipt.detachedReason = reason;
522
+ receipt.finalOutput = reason === "intercom coordination"
523
+ ? "Detached for intercom coordination before task completion."
524
+ : reason === "user request"
525
+ ? "Detached at user request before task completion."
526
+ : `Detached for ${reason} before task completion.`;
527
+ receipt.outputMode = options.outputMode ?? "inline";
528
+ if (options.outputPath) {
529
+ receipt.outputSaveError = reason === "user request"
530
+ ? "Output file was not finalized because the subagent detached at user request."
531
+ : `Output file was not finalized because the subagent detached for ${reason}.`;
532
+ }
533
+ receipt.progressSummary = {
534
+ toolCount: receiptProgress.toolCount,
535
+ tokens: receiptProgress.tokens,
536
+ durationMs: receiptProgress.durationMs,
537
+ };
538
+ // The attempt is not detached until the outer coordinator has accepted and
539
+ // synchronously published the receipt. A persistence/callback failure must
540
+ // leave this attempt attached and abortable rather than orphaning it.
541
+ let accepted = false;
542
+ try {
543
+ accepted = options.onDetachReceipt?.(receipt) === true;
544
+ } catch {
545
+ return false;
546
+ }
547
+ if (!accepted) return false;
548
+ detached = true;
549
+ return true;
550
+ };
551
+
552
+ // If the child emits a terminal assistant stop but never exits,
553
+ // give it a short grace period to flush naturally, then clean it up.
554
+ const FINAL_STOP_GRACE_MS = 1000;
555
+ const HARD_KILL_MS = 3000;
556
+ let childExited = false;
557
+ let forcedTerminationSignal = false;
558
+ let cleanTerminalAssistantStopReceived = false;
559
+ let agentSettledReceived = false;
560
+ let finalDrainTimer: NodeJS.Timeout | undefined;
561
+ let finalHardKillTimer: NodeJS.Timeout | undefined;
562
+ let watchdogTailTimer: NodeJS.Timeout | undefined;
563
+ let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
564
+ const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
565
+ childWatchdogState = snapshot;
566
+ result.watchdog = snapshot;
567
+ progress.watchdog = snapshot;
568
+ };
569
+ const clearWatchdogTailTimer = () => {
570
+ if (watchdogTailTimer) {
571
+ clearTimeout(watchdogTailTimer);
572
+ watchdogTailTimer = undefined;
573
+ }
574
+ };
575
+ const clearFinalDrainTimers = () => {
576
+ if (finalDrainTimer) {
577
+ clearTimeout(finalDrainTimer);
578
+ finalDrainTimer = undefined;
579
+ }
580
+ if (finalHardKillTimer) {
581
+ clearTimeout(finalHardKillTimer);
582
+ finalHardKillTimer = undefined;
583
+ }
584
+ };
585
+ const startFinalDrain = () => {
586
+ if (childWatchdogIsActive(childWatchdogState)) {
587
+ armWatchdogTail();
588
+ return;
589
+ }
590
+ if (childExited || finalDrainTimer || lifecycleFinished || processClosed) return;
591
+ finalDrainTimer = setTimeout(() => {
592
+ if (lifecycleFinished || processClosed) return;
593
+ const termSent = trySignalChild(proc, "SIGTERM");
594
+ if (!termSent) return;
595
+ forcedTerminationSignal = true;
596
+ if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !assistantError) {
597
+ result.error = result.error ?? `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
598
+ }
599
+ finalHardKillTimer = setTimeout(() => {
600
+ if (lifecycleFinished || processClosed) return;
601
+ forcedTerminationSignal = trySignalChild(proc, "SIGKILL") || forcedTerminationSignal;
602
+ }, HARD_KILL_MS);
603
+ finalHardKillTimer.unref?.();
604
+ }, FINAL_STOP_GRACE_MS);
605
+ finalDrainTimer.unref?.();
606
+ };
607
+ function armWatchdogTail(): void {
608
+ if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || processClosed) return;
609
+ watchdogTailTimer = setTimeout(() => {
610
+ watchdogTailTimer = undefined;
611
+ updateChildWatchdogState({
612
+ phase: "stale",
613
+ seq: (childWatchdogState?.seq ?? 0) + 1,
614
+ lastUpdate: Date.now(),
615
+ followUpPending: false,
616
+ reason: "child watchdog tail timeout",
617
+ timedOut: true,
618
+ });
619
+ startFinalDrain();
620
+ fireUpdate();
621
+ }, childWatchdog?.watchdogTailTimeoutMs ?? 120_000);
622
+ watchdogTailTimer.unref?.();
623
+ }
624
+ const applyChildLifecycle = (action: ChildLifecycleAction): void => {
625
+ if (action === "cancel-drain") {
626
+ clearFinalDrainTimers();
627
+ clearWatchdogTailTimer();
628
+ return;
629
+ }
630
+ if (action === "start-drain") startFinalDrain();
631
+ };
632
+
633
+ const unsubscribeIntercomDetach = options.intercomEvents?.on?.(INTERCOM_DETACH_REQUEST_EVENT, (payload) => {
634
+ if (!options.allowIntercomDetach || processClosed) return;
635
+ if (!payload || typeof payload !== "object") return;
636
+ const event = payload as { requestId?: unknown; runId?: unknown; agent?: unknown; childIndex?: unknown };
637
+ const requestId = event.requestId;
638
+ if (typeof requestId !== "string" || requestId.length === 0) return;
639
+ const hasRoute = event.runId !== undefined || event.agent !== undefined || event.childIndex !== undefined;
640
+ if (hasRoute) {
641
+ if (typeof event.runId === "string" && event.runId !== options.runId) return;
642
+ if (typeof event.agent === "string" && event.agent !== agent.name) return;
643
+ if (typeof event.childIndex === "number" && event.childIndex !== (options.index ?? 0)) return;
644
+ } else if (!intercomStarted) return;
645
+ const accepted = detachForeground("intercom coordination");
646
+ options.intercomEvents?.emit(INTERCOM_DETACH_RESPONSE_EVENT, { requestId, accepted, runId: options.runId, agent: agent.name, childIndex: options.index ?? 0 });
647
+ });
648
+
649
+ const finish = (code: number) => {
650
+ if (lifecycleFinished) return;
651
+ lifecycleFinished = true;
652
+ clearFinalDrainTimers();
653
+ clearWatchdogTailTimer();
654
+ clearStdioGuard();
655
+ clearTimeoutTimers();
656
+ clearTurnBudgetTimers();
657
+ if (protocolHardKillTimer) {
658
+ clearTimeout(protocolHardKillTimer);
659
+ protocolHardKillTimer = undefined;
660
+ }
661
+ if (activityTimer) {
662
+ clearInterval(activityTimer);
663
+ activityTimer = undefined;
664
+ }
665
+ unsubscribeIntercomDetach?.();
666
+ removeAbortListener?.();
667
+ removeInterruptListener?.();
668
+ resolve(code);
669
+ };
670
+
671
+ const drainPendingControlEvents = (): ControlEvent[] | undefined => {
672
+ if (pendingControlEvents.length === 0) return undefined;
673
+ const events = pendingControlEvents;
674
+ pendingControlEvents = [];
675
+ return events;
676
+ };
677
+
678
+ let activeLongRunningNotified = false;
679
+ let pendingToolResult: { tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined;
680
+ const mutatingFailures = createMutatingFailureState();
681
+ const mutatingFailureWindowMs = 5 * 60_000;
682
+ const currentToolDurationMs = (now: number) => progress.currentToolStartedAt ? Math.max(0, now - progress.currentToolStartedAt) : undefined;
683
+ const emitNeedsAttention = (now: number, input: { message?: string; reason?: ControlEvent["reason"]; recentFailureSummary?: string; currentTool?: string; currentPath?: string; currentToolDurationMs?: number } = {}): boolean => {
684
+ if (!controlConfig.enabled) return false;
685
+ const previous = progress.activityState;
686
+ progress.activityState = "needs_attention";
687
+ const event = buildControlEvent({
688
+ type: "needs_attention",
689
+ from: previous,
690
+ to: "needs_attention",
691
+ runId: options.runId,
692
+ agent: agent.name,
693
+ index: options.index,
694
+ ts: now,
695
+ lastActivityAt: progress.lastActivityAt,
696
+ message: input.message,
697
+ reason: input.reason ?? "idle",
698
+ turns: result.usage.turns,
699
+ tokens: progress.tokens,
700
+ toolCount: progress.toolCount,
701
+ currentTool: input.currentTool ?? progress.currentTool,
702
+ currentToolDurationMs: input.currentToolDurationMs ?? currentToolDurationMs(now),
703
+ currentPath: input.currentPath ?? progress.currentPath,
704
+ recentFailureSummary: input.recentFailureSummary,
705
+ });
706
+ emitControlEvent(event);
707
+ return previous !== "needs_attention";
708
+ };
709
+ const emitActiveLongRunning = (now: number, reason: ControlEvent["reason"]): boolean => {
710
+ if (!controlConfig.enabled || activeLongRunningNotified || progress.activityState === "needs_attention") return false;
711
+ activeLongRunningNotified = true;
712
+ const previous = progress.activityState;
713
+ progress.activityState = "active_long_running";
714
+ emitControlEvent(buildControlEvent({
715
+ type: "active_long_running",
716
+ from: previous,
717
+ to: "active_long_running",
718
+ runId: options.runId,
719
+ agent: agent.name,
720
+ index: options.index,
721
+ ts: now,
722
+ message: `${agent.name} is still active but long-running`,
723
+ reason,
724
+ turns: result.usage.turns,
725
+ tokens: progress.tokens,
726
+ toolCount: progress.toolCount,
727
+ currentTool: progress.currentTool,
728
+ currentToolDurationMs: currentToolDurationMs(now),
729
+ currentPath: progress.currentPath,
730
+ elapsedMs: now - startTime,
731
+ }));
732
+ return true;
733
+ };
734
+ const requestTurnBudgetAbort = (turnCount: number) => {
735
+ const budget = options.turnBudget;
736
+ if (!budget || result.timedOut || result.turnBudgetExceeded || interruptedByControl || processClosed || lifecycleFinished) return;
737
+ const message = turnBudgetExceededMessage(budget, turnCount);
738
+ result.turnBudgetExceeded = true;
739
+ result.wrapUpRequested = true;
740
+ result.turnBudget = turnBudgetState(budget, turnCount, true);
741
+ result.error = message;
742
+ result.finalOutput = message;
743
+ progress.status = "failed";
744
+ progress.error = message;
745
+ progress.durationMs = Date.now() - startTime;
746
+ fireUpdate();
747
+ trySignalChild(proc, "SIGINT");
748
+ turnBudgetTerminationTimer = setTimeout(() => {
749
+ if (processClosed || lifecycleFinished || result.timedOut) return;
750
+ trySignalChild(proc, "SIGTERM");
751
+ }, 1000);
752
+ turnBudgetTerminationTimer.unref?.();
753
+ turnBudgetHardKillTimer = setTimeout(() => {
754
+ if (processClosed || lifecycleFinished || result.timedOut) return;
755
+ trySignalChild(proc, "SIGKILL");
756
+ }, 4000);
757
+ turnBudgetHardKillTimer.unref?.();
758
+ };
759
+
760
+ const updateTurnBudget = (turnCount: number, terminalAssistantStop: boolean, toolWorkActiveOrStarting: boolean) => {
761
+ const budget = options.turnBudget;
762
+ if (!budget || result.timedOut || result.turnBudgetExceeded) return;
763
+ if (turnCount < budget.maxTurns) {
764
+ result.turnBudget = { ...budget, outcome: "within-budget", turnCount };
765
+ return;
766
+ }
767
+ if (!turnBudgetSoftReached) {
768
+ turnBudgetSoftReached = true;
769
+ result.wrapUpRequested = true;
770
+ appendRecentOutput(progress, [turnBudgetSoftNote(budget, turnCount)]);
771
+ }
772
+ const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting, options.enforceHardTurnLimit);
773
+ if (decision === "defer") {
774
+ result.turnBudget = turnBudgetDeferredState(
775
+ budget,
776
+ turnCount,
777
+ result.turnBudget?.terminationDeferredAtTurn,
778
+ );
779
+ return;
780
+ }
781
+ result.turnBudget = turnBudgetState(budget, turnCount, false);
782
+ if (decision === "abort") requestTurnBudgetAbort(turnCount);
783
+ };
784
+
785
+ const updateActivityState = (now: number): boolean => {
786
+ if (!controlConfig.enabled) return false;
787
+ const idleState = deriveActivityState({
788
+ config: controlConfig,
789
+ startedAt: startTime,
790
+ lastActivityAt: progress.lastActivityAt,
791
+ currentTool: progress.currentTool,
792
+ now,
793
+ });
794
+ if (idleState === "needs_attention") {
795
+ return progress.activityState === "needs_attention" ? false : emitNeedsAttention(now);
796
+ }
797
+ const activeReason = nextLongRunningTrigger(controlConfig, {
798
+ startedAt: startTime,
799
+ now,
800
+ turns: result.usage.turns,
801
+ tokens: progress.tokens,
802
+ });
803
+ return activeReason ? emitActiveLongRunning(now, activeReason) : false;
804
+ };
805
+
806
+
807
+ const emitUpdateSnapshot = (text: string) => {
808
+ if (!options.onUpdate || processClosed) return;
809
+ const progressSnapshot = snapshotProgress(progress);
810
+ const resultSnapshot = snapshotStreamResult(result, progressSnapshot);
811
+ const controlEvents = drainPendingControlEvents();
812
+ options.onUpdate({
813
+ content: [{ type: "text", text }],
814
+ details: {
815
+ mode: "single",
816
+ results: [resultSnapshot],
817
+ progress: [progressSnapshot],
818
+ controlEvents,
819
+ },
820
+ });
821
+ };
822
+
823
+ const fireUpdate = () => {
824
+ if (!options.onUpdate || processClosed) return;
825
+ progress.durationMs = Date.now() - startTime;
826
+ const output = (result.timedOut || result.turnBudgetExceeded) && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
827
+ emitUpdateSnapshot(output || "(running...)");
828
+ };
829
+
830
+ const rawStdoutTail = createBoundedByteTail();
831
+ const processLine = (line: string) => {
832
+ if (!line.trim()) return;
833
+ jsonlWriter.writeLine(line);
834
+ let evt: { type?: string; message?: Message; toolName?: string; args?: unknown; willRetry?: unknown };
835
+ try {
836
+ evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; args?: unknown; willRetry?: unknown };
837
+ } catch {
838
+ rawStdoutTail.push(`${line}\n`);
839
+ shared.transcriptWriter?.writeStdoutLine(line);
840
+ // Non-JSON stdout lines are expected; only structured events are parsed.
841
+ return;
842
+ }
843
+ shared.transcriptWriter?.writeChildEvent(evt);
844
+ if (evt.type === "agent_settled") agentSettledReceived = true;
845
+ applyChildLifecycle(projectChildLifecycle(evt));
846
+
847
+ if (isChildWatchdogStatusEvent(evt)) {
848
+ if (!childWatchdog) return;
849
+ const next = acceptChildWatchdogEvent({
850
+ current: childWatchdogState,
851
+ event: evt,
852
+ runId: options.runId,
853
+ agent: agent.name,
854
+ childIndex: options.index ?? 0,
855
+ });
856
+ if (!next) return;
857
+ updateChildWatchdogState(next);
858
+ if (childWatchdogIsActive(next)) {
859
+ clearFinalDrainTimers();
860
+ armWatchdogTail();
861
+ } else {
862
+ clearWatchdogTailTimer();
863
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) startFinalDrain();
864
+ }
865
+ fireUpdate();
866
+ return;
867
+ }
868
+
869
+ const now = Date.now();
870
+ progress.durationMs = now - startTime;
871
+ progress.lastActivityAt = now;
872
+ updateActivityState(now);
873
+
874
+ if (evt.type === "tool_execution_start") {
875
+ const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args)
876
+ ? evt.args as Record<string, unknown>
877
+ : {};
878
+ if (options.structuredOutput && evt.toolName === "structured_output") {
879
+ structuredOutputToolInvoked = true;
880
+ structuredOutputMessageStartIndex = result.messages?.length ?? 0;
881
+ }
882
+ if (options.allowIntercomDetach && (evt.toolName === "intercom" || evt.toolName === "contact_supervisor")) {
883
+ intercomStarted = true;
884
+ }
885
+ progress.toolCount++;
886
+ if (options.toolBudget) {
887
+ result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
888
+ }
889
+ progress.currentTool = evt.toolName;
890
+ progress.currentToolArgs = extractToolArgsPreview(toolArgs);
891
+ progress.currentToolStartedAt = now;
892
+ progress.currentPath = resolveCurrentPath(evt.toolName, toolArgs);
893
+ const mutates = isMutatingTool(evt.toolName, toolArgs);
894
+ observedMutationAttempt = observedMutationAttempt || mutates;
895
+ pendingToolResult = { tool: evt.toolName ?? "tool", path: progress.currentPath, mutates, startedAt: now };
896
+ fireUpdate();
897
+ }
898
+
899
+ if (evt.type === "tool_execution_end") {
900
+ if (progress.currentTool) {
901
+ progress.recentTools.push({
902
+ tool: progress.currentTool,
903
+ args: progress.currentToolArgs || "",
904
+ endMs: now,
905
+ });
906
+ }
907
+ progress.currentTool = undefined;
908
+ progress.currentToolArgs = undefined;
909
+ progress.currentToolStartedAt = undefined;
910
+ progress.currentPath = undefined;
911
+ fireUpdate();
912
+ }
913
+
914
+ if (evt.type === "message_end" && evt.message) {
915
+ result.messages!.push(evt.message);
916
+ if (evt.message.role === "assistant") {
917
+ result.usage.turns++;
918
+ progress.turnCount = result.usage.turns;
919
+ const stopReason = (evt.message as { stopReason?: string }).stopReason;
920
+ const toolCalls = Array.isArray(evt.message.content)
921
+ ? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
922
+ : [];
923
+ const hasToolCall = toolCalls.length > 0;
924
+ const terminalAssistantStop = stopReason === "stop" && !hasToolCall;
925
+ const terminalStructuredOutputCall = Boolean(options.structuredOutput)
926
+ && toolCalls.length === 1
927
+ && (toolCalls[0] as { name?: string }).name === "structured_output";
928
+ updateTurnBudget(result.usage.turns, terminalAssistantStop || terminalStructuredOutputCall, hasToolCall || Boolean(progress.currentTool));
929
+ const u = evt.message.usage;
930
+ if (u) {
931
+ result.usage.input += u.input || 0;
932
+ result.usage.output += u.output || 0;
933
+ result.usage.cacheRead += u.cacheRead || 0;
934
+ result.usage.cacheWrite += u.cacheWrite || 0;
935
+ result.usage.cost += u.cost?.total || 0;
936
+ progress.tokens = result.usage.input + result.usage.output;
937
+ progress.inputTokens = result.usage.input;
938
+ progress.outputTokens = result.usage.output;
939
+ }
940
+ if (evt.message.model) {
941
+ progress.model = evt.message.model;
942
+ if (!result.model) result.model = evt.message.model;
943
+ }
944
+ if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
945
+ const assistantText = extractTextFromContent(evt.message.content);
946
+ appendRecentOutput(progress, assistantText.split("\n").slice(-10));
947
+ // Final assistant message: start the exit drain window.
948
+ if (terminalAssistantStop) {
949
+ if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
950
+ cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
951
+ applyChildLifecycle(projectChildLifecycle(evt, true));
952
+ }
953
+ }
954
+ updateActivityState(now);
955
+ fireUpdate();
956
+ }
957
+
958
+ if (evt.type === "tool_result_end" && evt.message) {
959
+ result.messages!.push(evt.message);
960
+ const resultText = extractTextFromContent(evt.message.content);
961
+ if (options.toolBudget && pendingToolResult && resultText.includes("Tool budget hard limit reached")) {
962
+ result.toolBudgetBlocked = true;
963
+ result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, pendingToolResult.tool);
964
+ }
965
+ appendRecentOutput(progress, resultText.split("\n").slice(-10));
966
+ const toolSnapshot = pendingToolResult;
967
+ pendingToolResult = undefined;
968
+ if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
969
+ recordMutatingFailure(mutatingFailures, {
970
+ tool: toolSnapshot.tool,
971
+ path: toolSnapshot.path,
972
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
973
+ ts: now,
974
+ }, mutatingFailureWindowMs);
975
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
976
+ emitNeedsAttention(now, {
977
+ message: `${agent.name} needs attention after repeated mutating tool failures`,
978
+ reason: "tool_failures",
979
+ currentTool: toolSnapshot.tool,
980
+ currentPath: toolSnapshot.path,
981
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
982
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
983
+ });
984
+ }
985
+ } else if (toolSnapshot?.mutates) {
986
+ resetMutatingFailureState(mutatingFailures);
987
+ }
988
+ fireUpdate();
989
+ }
990
+ };
991
+
992
+ fireUpdate();
993
+ if (controlConfig.enabled || options.onUpdate) {
994
+ activityTimer = setInterval(() => {
995
+ if (processClosed || lifecycleFinished) {
996
+ return;
997
+ }
998
+ updateActivityState(Date.now());
999
+ fireUpdate();
1000
+ }, 1000);
1001
+ activityTimer.unref?.();
1002
+ }
1003
+
1004
+ if (attemptTimeout) {
1005
+ timeoutTimer = setTimeout(() => {
1006
+ if (processClosed || lifecycleFinished || interruptedByControl) return;
1007
+ result.timedOut = true;
1008
+ result.error = attemptTimeout.message;
1009
+ result.finalOutput = attemptTimeout.message;
1010
+ progress.status = "failed";
1011
+ progress.error = attemptTimeout.message;
1012
+ progress.durationMs = Date.now() - startTime;
1013
+ fireUpdate();
1014
+ trySignalChild(proc, "SIGINT");
1015
+ timeoutTerminationTimer = setTimeout(() => {
1016
+ if (processClosed || lifecycleFinished) return;
1017
+ trySignalChild(proc, "SIGTERM");
1018
+ }, 1000);
1019
+ timeoutTerminationTimer.unref?.();
1020
+ timeoutHardKillTimer = setTimeout(() => {
1021
+ if (processClosed || lifecycleFinished) return;
1022
+ trySignalChild(proc, "SIGKILL");
1023
+ }, 4000);
1024
+ timeoutHardKillTimer.unref?.();
1025
+ }, attemptTimeout.remainingMs);
1026
+ timeoutTimer.unref?.();
1027
+ }
1028
+
1029
+ const stderrTail = createBoundedByteTail();
1030
+ const failProtocol = (limit: ProtocolOutputLimit): void => {
1031
+ if (result.protocolError) return;
1032
+ result.protocolError = limit;
1033
+ result.error = formatProtocolOutputLimit(limit);
1034
+ progress.status = "failed";
1035
+ progress.error = result.error;
1036
+ progress.durationMs = Date.now() - startTime;
1037
+ fireUpdate();
1038
+ if (!childExited) {
1039
+ trySignalChild(proc, "SIGTERM");
1040
+ protocolHardKillTimer = setTimeout(() => {
1041
+ if (!childExited) trySignalChild(proc, "SIGKILL");
1042
+ }, 3000);
1043
+ protocolHardKillTimer.unref?.();
1044
+ }
1045
+ };
1046
+ const stdoutReader = createBoundedLineReader({
1047
+ oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
1048
+ onLine: processLine,
1049
+ onLimit: failProtocol,
1050
+ });
1051
+ const stderrReader = createBoundedLineReader({
1052
+ stream: "stderr",
1053
+ maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
1054
+ onLine: (line) => shared.transcriptWriter?.writeStderrLine(line),
1055
+ onLimit: (limit) => shared.transcriptWriter?.writeStderrLine(formatProtocolOutputLimit(limit)),
1056
+ });
1057
+
1058
+ const clearStdioGuard = attachPostExitStdioGuard(proc, { idleMs: 2000, hardMs: 8000 });
1059
+ proc.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
1060
+ proc.stderr.on("data", (chunk: Buffer) => {
1061
+ stderrTail.push(chunk);
1062
+ stderrReader.push(chunk);
1063
+ });
1064
+ proc.on("exit", () => {
1065
+ childExited = true;
1066
+ clearFinalDrainTimers();
1067
+ });
1068
+ proc.on("close", (code, signal) => {
1069
+ if (lifecycleFinished) return;
1070
+ processClosed = true;
1071
+ clearFinalDrainTimers();
1072
+ clearStdioGuard();
1073
+ void jsonlWriter.close().catch(() => {
1074
+ // JSONL artifact flush is best effort.
1075
+ });
1076
+ const toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
1077
+ result.runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1078
+ cleanupTempDir(tempDir);
1079
+ stdoutReader.end();
1080
+ stderrReader.end();
1081
+ const stderr = stderrTail.text();
1082
+ const rawStdout = rawStdoutTail.text();
1083
+ let closeError = result.error ?? toolDiagnosticError ?? assistantError;
1084
+ const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
1085
+ if (signal) result.processSignal = signal;
1086
+ if (!closeError && isUnexplainedProcessSignal({
1087
+ processSignal: signal,
1088
+ interrupted: result.interrupted,
1089
+ timedOut: result.timedOut,
1090
+ stopped: result.stopped,
1091
+ turnBudgetExceeded: result.turnBudgetExceeded,
1092
+ forcedDrainAfterFinalSuccess,
1093
+ })) {
1094
+ closeError = formatProcessSignalError(signal!);
1095
+ }
1096
+ if (code !== 0 && rawStdout.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1097
+ closeError = rawStdout.trim();
1098
+ }
1099
+ if (code !== 0 && stderr.trim() && !closeError && !forcedDrainAfterFinalSuccess) {
1100
+ closeError = stderr.trim();
1101
+ }
1102
+ const finalCode = forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (code ?? 1) : (code ?? 0);
1103
+ if (!result.error && closeError) result.error = closeError;
1104
+ finish(finalCode);
1105
+ });
1106
+ proc.on("error", (error) => {
1107
+ if (lifecycleFinished) return;
1108
+ processClosed = true;
1109
+ clearFinalDrainTimers();
1110
+ clearStdioGuard();
1111
+ void jsonlWriter.close().catch(() => {
1112
+ // JSONL artifact flush is best effort.
1113
+ });
1114
+ cleanupTempDir(tempDir);
1115
+ stdoutReader.end();
1116
+ stderrReader.end();
1117
+ if (!result.error) {
1118
+ result.error = error instanceof Error ? error.message : String(error);
1119
+ }
1120
+ finish(1);
1121
+ });
1122
+
1123
+ if (options.signal) {
1124
+ const kill = () => {
1125
+ if (processClosed || lifecycleFinished) return;
1126
+ proc.kill("SIGTERM");
1127
+ setTimeout(() => !proc.killed && proc.kill("SIGKILL"), 3000);
1128
+ };
1129
+ if (options.signal.aborted) kill();
1130
+ else {
1131
+ options.signal.addEventListener("abort", kill, { once: true });
1132
+ removeAbortListener = () => options.signal?.removeEventListener("abort", kill);
1133
+ }
1134
+ }
1135
+
1136
+ if (options.interruptSignal) {
1137
+ const interrupt = () => {
1138
+ if (processClosed || lifecycleFinished) return;
1139
+ if (result.timedOut) return;
1140
+ interruptedByControl = true;
1141
+ clearTimeoutTimers();
1142
+ progress.status = "running";
1143
+ progress.durationMs = Date.now() - startTime;
1144
+ result.interrupted = true;
1145
+ result.finalOutput = "Interrupted. Waiting for explicit next action.";
1146
+ progress.activityState = undefined;
1147
+ fireUpdate();
1148
+ trySignalChild(proc, "SIGINT");
1149
+ setTimeout(() => {
1150
+ if (lifecycleFinished || processClosed) return;
1151
+ trySignalChild(proc, "SIGTERM");
1152
+ }, 1000).unref?.();
1153
+ };
1154
+ if (options.interruptSignal.aborted) interrupt();
1155
+ else {
1156
+ options.interruptSignal.addEventListener("abort", interrupt, { once: true });
1157
+ removeInterruptListener = () => options.interruptSignal?.removeEventListener("abort", interrupt);
1158
+ }
1159
+ }
1160
+
1161
+ // Publish only after every callback and cleanup guard captured by detach or
1162
+ // later lifecycle events has initialized. Consumers may invoke synchronously.
1163
+ try {
1164
+ options.onDetachReady?.((reason = "user request") => detachForeground(reason));
1165
+ } catch (error) {
1166
+ // A consumer callback is advisory. Keep the child attached and observable
1167
+ // rather than rejecting this attempt and orphaning its live process.
1168
+ appendRecentOutput(progress, [`Foreground detach callback failed: ${error instanceof Error ? error.message : String(error)}`]);
1169
+ }
1170
+ });
1171
+ result.exitCode = exitCode;
1172
+ if (interruptedByControl) {
1173
+ result.exitCode = 0;
1174
+ result.interrupted = true;
1175
+ result.error = undefined;
1176
+ result.finalOutput = result.finalOutput || "Interrupted. Waiting for explicit next action.";
1177
+ result.controlEvents = allControlEvents.length ? allControlEvents : undefined;
1178
+ progress.activityState = undefined;
1179
+ progress.durationMs = Date.now() - startTime;
1180
+ result.progressSummary = {
1181
+ toolCount: progress.toolCount,
1182
+ tokens: progress.tokens,
1183
+ durationMs: progress.durationMs,
1184
+ };
1185
+ return result;
1186
+ }
1187
+ if (result.error && result.exitCode === 0) {
1188
+ result.exitCode = 1;
1189
+ }
1190
+ let validatedStructuredOutput = false;
1191
+ if (options.structuredOutput && result.exitCode === 0 && !result.error) {
1192
+ result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
1193
+ result.structuredOutputPath = options.structuredOutput.outputPath;
1194
+ if (!structuredOutputToolInvoked) {
1195
+ result.exitCode = 1;
1196
+ result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1197
+ result.structuredOutputFailed = true;
1198
+ } else {
1199
+ const structured = await readStructuredOutput({
1200
+ schema: options.structuredOutput.schema,
1201
+ schemaPath: options.structuredOutput.schemaPath,
1202
+ outputPath: options.structuredOutput.outputPath,
1203
+ });
1204
+ if (structured.error) {
1205
+ result.exitCode = 1;
1206
+ result.error = structured.error;
1207
+ result.structuredOutputFailed = true;
1208
+ } else {
1209
+ result.structuredOutput = structured.value;
1210
+ validatedStructuredOutput = true;
1211
+ }
1212
+ }
1213
+ }
1214
+ if (result.exitCode === 0 && !result.error) {
1215
+ const messages = result.messages ?? [];
1216
+ const finalText = getFinalOutput(messages);
1217
+ const errorMessages = validatedStructuredOutput
1218
+ ? messages.slice(structuredOutputMessageStartIndex ?? messages.length)
1219
+ : messages;
1220
+ const errInfo = detectSubagentError(errorMessages);
1221
+ const missingOutput = !finalText?.trim() && !validatedStructuredOutput;
1222
+ if (missingOutput && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1223
+ result.exitCode = 1;
1224
+ result.error = "Subagent produced no output (possible model cold-start or empty response).";
1225
+ } else if (errInfo.hasError) {
1226
+ result.exitCode = errInfo.exitCode ?? 1;
1227
+ result.error = errInfo.details
1228
+ ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}`
1229
+ : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
1230
+ }
1231
+ }
1232
+
1233
+ progress.status = result.exitCode === 0 ? "completed" : "failed";
1234
+ progress.durationMs = Date.now() - startTime;
1235
+ if (result.error) {
1236
+ progress.error = result.error;
1237
+ if (progress.currentTool) {
1238
+ progress.failedTool = progress.currentTool;
1239
+ }
1240
+ }
1241
+
1242
+ result.progressSummary = {
1243
+ toolCount: progress.toolCount,
1244
+ tokens: progress.tokens,
1245
+ durationMs: progress.durationMs,
1246
+ };
1247
+
1248
+ const acceptanceOutput = getFinalOutput(result.messages ?? []);
1249
+ let fullOutput = stripAcceptanceReport(acceptanceOutput);
1250
+ if (!fullOutput.trim() && result.structuredOutput !== undefined) fullOutput = JSON.stringify(result.structuredOutput, null, 2);
1251
+ result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1252
+ if (result.timedOut) {
1253
+ const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1254
+ fullOutput = fullOutput.trim()
1255
+ ? `${timeoutMessage}\n\nPartial output before timeout:\n${fullOutput}`
1256
+ : timeoutMessage;
1257
+ } else if (result.turnBudgetExceeded && result.turnBudget) {
1258
+ fullOutput = formatTurnBudgetOutput(turnBudgetExceededMessage(result.turnBudget, result.turnBudget.turnCount), fullOutput);
1259
+ } else if (result.turnBudget?.outcome === "termination-deferred") {
1260
+ const note = turnBudgetDeferredNote(result.turnBudget, result.turnBudget.terminationDeferredAtTurn ?? result.turnBudget.turnCount);
1261
+ fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1262
+ } else if (result.wrapUpRequested && result.turnBudget?.outcome === "wrap-up-requested") {
1263
+ const note = turnBudgetSoftNote(result.turnBudget, result.turnBudget.wrapUpRequestedAtTurn ?? result.turnBudget.turnCount);
1264
+ fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1265
+ }
1266
+ const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1267
+ const completionGuard = result.exitCode === 0 && !result.error && completionGuardEnabled
1268
+ ? evaluateCompletionMutationGuard({
1269
+ agent: agent.name,
1270
+ task: shared.originalTask ?? task,
1271
+ messages: result.messages ?? [],
1272
+ tools: agent.tools,
1273
+ mcpDirectTools: agent.mcpDirectTools,
1274
+ })
1275
+ : undefined;
1276
+ const completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1277
+ if (completionGuard) {
1278
+ result.effects = {
1279
+ ...(result.effects ?? {}),
1280
+ fileMutation: {
1281
+ status: completionGuard.expectedMutation ? completionGuardTriggered ? "missing" : "observed" : "not-applicable",
1282
+ expected: completionGuard.expectedMutation,
1283
+ attempted: completionGuard.attemptedMutation || observedMutationAttempt,
1284
+ ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1285
+ },
1286
+ };
1287
+ }
1288
+ if (completionGuardTriggered && !isAgentContractV1(options.agentContract)) {
1289
+ result.exitCode = 1;
1290
+ result.error = "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes.";
1291
+ progress.status = "failed";
1292
+ progress.error = result.error;
1293
+ emitControlEvent(buildControlEvent({
1294
+ from: progress.activityState,
1295
+ to: "needs_attention",
1296
+ runId: options.runId ?? agent.name,
1297
+ agent: agent.name,
1298
+ index: options.index,
1299
+ ts: Date.now(),
1300
+ message: `${agent.name} completed without making edits for an implementation task`,
1301
+ reason: "completion_guard",
1302
+ }));
1303
+ }
1304
+ if (options.outputPath && result.exitCode === 0) {
1305
+ const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot);
1306
+ fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
1307
+ result.savedOutputPath = resolvedOutput.savedPath;
1308
+ result.outputSaveError = resolvedOutput.saveError;
1309
+ if (resolvedOutput.savedPath) {
1310
+ result.outputReference = formatSavedOutputReference(resolvedOutput.savedPath, fullOutput);
1311
+ if (result.outputState === "absent") result.outputState = "unknown";
1312
+ }
1313
+ }
1314
+ artifactOutputByResult.set(result, fullOutput);
1315
+ acceptanceOutputByResult.set(result, acceptanceOutput);
1316
+ result.outputMode = options.outputMode ?? "inline";
1317
+ result.finalOutput = options.outputMode === "file-only" && result.savedOutputPath && result.outputReference
1318
+ ? result.outputReference.message
1319
+ : fullOutput;
1320
+ result.controlEvents = allControlEvents.length ? allControlEvents : undefined;
1321
+ if (options.onUpdate) {
1322
+ const finalText = result.finalOutput || result.error || "(no output)";
1323
+ const progressSnapshot = snapshotProgress(progress);
1324
+ const resultSnapshot = snapshotStreamResult(result, progressSnapshot);
1325
+ options.onUpdate({
1326
+ content: [{ type: "text", text: finalText }],
1327
+ details: {
1328
+ mode: "single",
1329
+ results: [resultSnapshot],
1330
+ progress: [progressSnapshot],
1331
+ controlEvents: allControlEvents.length ? allControlEvents : undefined,
1332
+ },
1333
+ });
1334
+ }
1335
+ return result;
1336
+ }
1337
+
1338
+ /**
1339
+ * Run a subagent synchronously (blocking until complete)
1340
+ */
1341
+ async function runSyncCompletion(
1342
+ runtimeCwd: string,
1343
+ agents: AgentConfig[],
1344
+ agentName: string,
1345
+ task: string,
1346
+ options: RunSyncOptions,
1347
+ ): Promise<SingleResult> {
1348
+ options = {
1349
+ ...options,
1350
+ capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])),
1351
+ };
1352
+ const agent = agents.find((a) => a.name === agentName);
1353
+ if (!agent) {
1354
+ return withRunContext({
1355
+ index: options.index ?? 0,
1356
+ agent: agentName,
1357
+ task,
1358
+ exitCode: 1,
1359
+ messages: [],
1360
+ usage: emptyUsage(),
1361
+ error: `Unknown agent: ${agentName}`,
1362
+ }, options.context);
1363
+ }
1364
+ try {
1365
+ assertAgentAllowedByCapabilityCeiling(agent.name, options.capabilityCeiling);
1366
+ } catch (error) {
1367
+ return withRunContext({
1368
+ index: options.index ?? 0,
1369
+ agent: agent.name,
1370
+ task,
1371
+ exitCode: 1,
1372
+ messages: [],
1373
+ usage: emptyUsage(),
1374
+ error: error instanceof Error ? error.message : String(error),
1375
+ ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
1376
+ }, options.context);
1377
+ }
1378
+ const acceptanceErrors = validateAcceptanceInput(options.acceptance);
1379
+ if (acceptanceErrors.length > 0) {
1380
+ return withRunContext({
1381
+ index: options.index ?? 0,
1382
+ agent: agentName,
1383
+ task,
1384
+ exitCode: 1,
1385
+ messages: [],
1386
+ usage: emptyUsage(),
1387
+ error: acceptanceErrors.join(" "),
1388
+ }, options.context);
1389
+ }
1390
+ const outputModeValidationError = validateFileOnlyOutputMode(options.outputMode, options.outputPath, `Single run (${agentName})`);
1391
+ if (outputModeValidationError) {
1392
+ return withRunContext({
1393
+ index: options.index ?? 0,
1394
+ agent: agentName,
1395
+ task,
1396
+ exitCode: 1,
1397
+ messages: [],
1398
+ usage: emptyUsage(),
1399
+ outputMode: options.outputMode,
1400
+ error: outputModeValidationError,
1401
+ }, options.context);
1402
+ }
1403
+
1404
+ const shareEnabled = options.share === true;
1405
+ const effectiveAcceptance = resolveEffectiveAcceptance({
1406
+ explicit: options.acceptance,
1407
+ agentName,
1408
+ acceptanceRole: agent.acceptanceRole,
1409
+ task,
1410
+ mode: options.acceptanceContext?.mode ?? "single",
1411
+ async: options.acceptanceContext?.async,
1412
+ dynamic: options.acceptanceContext?.dynamic,
1413
+ dynamicGroup: options.acceptanceContext?.dynamicGroup,
1414
+ agentContract: options.agentContract,
1415
+ });
1416
+ const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1417
+ const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1418
+ const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
1419
+ const skillNames = options.skills ?? agent.skills ?? [];
1420
+ const skillCwd = options.cwd ?? runtimeCwd;
1421
+ const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
1422
+ skillNames,
1423
+ skillCwd,
1424
+ runtimeCwd,
1425
+ agent.skillPath,
1426
+ agent.filePath ? path.dirname(agent.filePath) : skillCwd,
1427
+ );
1428
+ if (skillNames.some((skill) => skill.trim() === "pi-subagents") && missingSkills.includes("pi-subagents")) {
1429
+ return withRunContext({
1430
+ index: options.index ?? 0,
1431
+ agent: agentName,
1432
+ task,
1433
+ exitCode: 1,
1434
+ messages: [],
1435
+ usage: emptyUsage(),
1436
+ error: "Skills not found: pi-subagents",
1437
+ }, options.context);
1438
+ }
1439
+ let systemPrompt = agent.systemPrompt?.trim() || "";
1440
+ if (resolvedSkills.length > 0) {
1441
+ const skillInjection = buildSkillInjection(resolvedSkills);
1442
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${skillInjection}` : skillInjection;
1443
+ }
1444
+ const memoryInjection = buildAgentMemoryInjection(agent, skillCwd);
1445
+ if (memoryInjection) {
1446
+ systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
1447
+ }
1448
+ systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: skillCwd, agentName });
1449
+ systemPrompt = injectOutputPathSystemPrompt(systemPrompt, options.outputPath, agent);
1450
+
1451
+ const candidates = buildModelCandidates(
1452
+ options.modelOverride ?? agent.model,
1453
+ agent.fallbackModels,
1454
+ options.availableModels,
1455
+ options.preferredModelProvider,
1456
+ { scope: options.modelScope },
1457
+ );
1458
+ const attemptedModels: string[] = [];
1459
+ const modelAttempts: ModelAttempt[] = [];
1460
+ const aggregateUsage = emptyUsage();
1461
+ const attemptNotes: string[] = [];
1462
+ let totalToolCount = 0;
1463
+ let totalDurationMs = 0;
1464
+
1465
+ let artifactPathsResult: ArtifactPaths | undefined;
1466
+ let jsonlPath: string | undefined;
1467
+ let transcriptWriter: ChildTranscriptWriter | undefined;
1468
+ if (options.artifactsDir && options.artifactConfig?.enabled !== false) {
1469
+ artifactPathsResult = getArtifactPaths(options.artifactsDir, options.runId, agentName, options.index);
1470
+ ensureArtifactsDir(options.artifactsDir);
1471
+ if (options.artifactConfig?.includeInput !== false) {
1472
+ writeArtifact(artifactPathsResult.inputPath, `# Task for ${agentName}\n\n${taskWithAcceptance}`);
1473
+ }
1474
+ if (options.artifactConfig?.includeJsonl !== false) {
1475
+ jsonlPath = artifactPathsResult.jsonlPath;
1476
+ }
1477
+ if (options.artifactConfig?.includeTranscript !== false) {
1478
+ transcriptWriter = createChildTranscriptWriter({
1479
+ transcriptPath: artifactPathsResult.transcriptPath,
1480
+ source: "foreground",
1481
+ runId: options.runId,
1482
+ agent: agentName,
1483
+ childIndex: options.index,
1484
+ cwd: options.cwd ?? runtimeCwd,
1485
+ });
1486
+ transcriptWriter.writeInitialUserMessage(taskWithAcceptance);
1487
+ }
1488
+ }
1489
+
1490
+ const persistResultMetadata = (target: SingleResult): void => {
1491
+ persistSingleResultMetadata({
1492
+ metadataPath: artifactPathsResult?.metadataPath,
1493
+ enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
1494
+ runId: options.runId,
1495
+ agent: agentName,
1496
+ task,
1497
+ result: target,
1498
+ });
1499
+ };
1500
+
1501
+ let intercomDetached = false;
1502
+ let detachedReason: string | undefined;
1503
+ const attemptOptions: RunSyncOptions = {
1504
+ ...options,
1505
+ onDetachReceipt: (receipt) => {
1506
+ receipt.acceptance = buildPendingAcceptanceLedger(effectiveAcceptance);
1507
+ try {
1508
+ persistResultMetadata(receipt);
1509
+ } catch (error) {
1510
+ receipt.metadataSaveError = error instanceof Error ? error.message : String(error);
1511
+ }
1512
+ const accepted = options.onDetachReceipt?.(receipt) === true;
1513
+ if (accepted) {
1514
+ detachedReason = receipt.detachedReason;
1515
+ if (receipt.detachedReason === "intercom coordination") intercomDetached = true;
1516
+ }
1517
+ return accepted;
1518
+ },
1519
+ };
1520
+ let lastResult: SingleResult | undefined;
1521
+ const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1522
+ modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1523
+ const candidate = modelsToTry[modelIndex];
1524
+ for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
1525
+ const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1526
+ const result = await runSingleAttempt(runtimeCwd, agent, taskWithAcceptance, candidate, attemptOptions, {
1527
+ sessionEnabled,
1528
+ systemPrompt,
1529
+ resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
1530
+ skillsWarning: missingSkills.length > 0 ? `Skills not found: ${missingSkills.join(", ")}` : undefined,
1531
+ jsonlPath,
1532
+ artifactPaths: artifactPathsResult,
1533
+ transcriptWriter,
1534
+ attemptNotes,
1535
+ modelCandidates: candidates
1536
+ .map((modelCandidate) => applyThinkingSuffix(modelCandidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined))
1537
+ .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1538
+ outputSnapshot,
1539
+ originalTask: task,
1540
+ });
1541
+ lastResult = result;
1542
+ if (startupAttemptIndex === 0) {
1543
+ if (result.model) attemptedModels.push(result.model);
1544
+ else if (candidate) attemptedModels.push(candidate);
1545
+ }
1546
+ sumUsage(aggregateUsage, result.usage);
1547
+ totalToolCount += result.progressSummary?.toolCount ?? 0;
1548
+ totalDurationMs += result.progressSummary?.durationMs ?? 0;
1549
+ const attemptSucceeded = result.exitCode === 0 && !result.error;
1550
+ const attempt: ModelAttempt = {
1551
+ model: result.model ?? candidate ?? agent.model ?? "default",
1552
+ success: attemptSucceeded,
1553
+ exitCode: result.exitCode,
1554
+ error: result.error,
1555
+ usage: { ...result.usage },
1556
+ };
1557
+ modelAttempts.push(attempt);
1558
+ // Preserve the legacy intercom handoff contract: once this logical run has
1559
+ // been handed to a supervisor, terminating that attempt must not launch a
1560
+ // startup retry or model fallback. Explicit user detach retains fallback.
1561
+ if (intercomDetached || result.timedOut || result.turnBudgetExceeded) break modelAttemptsLoop;
1562
+ if (attemptSucceeded) break modelAttemptsLoop;
1563
+
1564
+ const startupFailure = isRetryableSubagentStartupFailure({
1565
+ exitCode: result.exitCode,
1566
+ error: result.error,
1567
+ finalOutput: result.finalOutput,
1568
+ messageCount: result.messages?.length ?? 0,
1569
+ toolCount: result.progressSummary?.toolCount ?? 0,
1570
+ usage: result.usage,
1571
+ durationMs: result.progressSummary?.durationMs ?? Number.POSITIVE_INFINITY,
1572
+ protocolError: result.protocolError,
1573
+ processSignal: result.processSignal,
1574
+ detached: result.detached,
1575
+ interrupted: result.interrupted,
1576
+ timedOut: result.timedOut,
1577
+ stopped: result.stopped,
1578
+ turnBudgetExceeded: result.turnBudgetExceeded,
1579
+ });
1580
+ const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1581
+ if (startupFailure && retryDelayMs !== undefined) {
1582
+ const retryNote = formatSubagentStartupRetryNote({
1583
+ model: attempt.model,
1584
+ attempt: startupAttemptIndex + 1,
1585
+ maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1586
+ delayMs: retryDelayMs,
1587
+ });
1588
+ const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [options.signal, options.interruptSignal]);
1589
+ if (!shouldRetry) {
1590
+ if (options.interruptSignal?.aborted) {
1591
+ result.exitCode = 0;
1592
+ result.interrupted = true;
1593
+ result.error = undefined;
1594
+ result.finalOutput = "Interrupted. Waiting for explicit next action.";
1595
+ if (result.progress) {
1596
+ result.progress.status = "running";
1597
+ result.progress.error = undefined;
1598
+ }
1599
+ } else {
1600
+ const cancellationError = "Subagent startup retry cancelled before relaunch.";
1601
+ result.error = cancellationError;
1602
+ result.finalOutput = cancellationError;
1603
+ attempt.error = cancellationError;
1604
+ if (result.progress) result.progress.error = cancellationError;
1605
+ }
1606
+ break modelAttemptsLoop;
1607
+ }
1608
+ attempt.error = retryNote;
1609
+ attemptNotes.push(retryNote);
1610
+ continue;
1611
+ }
1612
+ if (startupFailure) {
1613
+ const startupError = formatSubagentStartupRetryExhaustedError({
1614
+ model: attempt.model,
1615
+ attempts: startupAttemptIndex + 1,
1616
+ });
1617
+ result.error = startupError;
1618
+ result.finalOutput = startupError;
1619
+ if (result.progress) {
1620
+ result.progress.error = startupError;
1621
+ result.progress.status = "failed";
1622
+ }
1623
+ attempt.error = startupError;
1624
+ break modelAttemptsLoop;
1625
+ }
1626
+ if (!isRetryableModelFailure(result.error) || modelIndex === modelsToTry.length - 1) break modelAttemptsLoop;
1627
+ attemptNotes.push(formatModelAttemptNote(attempt, modelsToTry[modelIndex + 1]));
1628
+ break;
1629
+ }
1630
+ }
1631
+
1632
+ const result = withRunContext(lastResult ?? {
1633
+ index: options.index ?? 0,
1634
+ agent: agentName,
1635
+ task,
1636
+ exitCode: 1,
1637
+ messages: [],
1638
+ usage: emptyUsage(),
1639
+ error: "Subagent did not produce a result.",
1640
+ } satisfies SingleResult, options.context);
1641
+
1642
+ result.usage = aggregateUsage;
1643
+ result.attemptedModels = attemptedModels.length > 0 ? attemptedModels : undefined;
1644
+ result.modelAttempts = modelAttempts.length > 0 ? modelAttempts : undefined;
1645
+ result.progressSummary = {
1646
+ toolCount: totalToolCount,
1647
+ tokens: aggregateUsage.input + aggregateUsage.output,
1648
+ durationMs: totalDurationMs,
1649
+ };
1650
+ if (transcriptWriter) result.transcriptPath = artifactPathsResult?.transcriptPath;
1651
+ if (transcriptWriter?.getError()) result.transcriptError = transcriptWriter.getError();
1652
+
1653
+ try {
1654
+ if (artifactPathsResult && options.artifactConfig?.enabled !== false) {
1655
+ result.artifactPaths = artifactPathsResult;
1656
+ if (options.artifactConfig?.includeOutput !== false) {
1657
+ writeArtifact(artifactPathsResult.outputPath, formatOutputArtifactContent({
1658
+ output: artifactOutputByResult.get(result) ?? result.finalOutput ?? "",
1659
+ error: result.error,
1660
+ transcriptPath: result.transcriptPath,
1661
+ metadataPath: options.artifactConfig?.includeMetadata === false ? undefined : artifactPathsResult.metadataPath,
1662
+ }));
1663
+ }
1664
+ if (options.maxOutput) {
1665
+ const config = { ...DEFAULT_MAX_OUTPUT, ...options.maxOutput };
1666
+ const truncationResult = truncateOutput(result.finalOutput ?? "", config, artifactPathsResult.outputPath);
1667
+ if (truncationResult.truncated) result.truncation = truncationResult;
1668
+ }
1669
+ } else if (options.maxOutput) {
1670
+ const config = { ...DEFAULT_MAX_OUTPUT, ...options.maxOutput };
1671
+ const truncationResult = truncateOutput(result.finalOutput ?? "", config);
1672
+ if (truncationResult.truncated) result.truncation = truncationResult;
1673
+ }
1674
+ } catch (error) {
1675
+ const message = `Artifact output post-processing failed: ${error instanceof Error ? error.message : String(error)}`;
1676
+ result.outputSaveError = result.outputSaveError ? `${result.outputSaveError}\n${message}` : message;
1677
+ }
1678
+
1679
+ if (options.sessionFile && (existsSync(options.sessionFile) || result.messages?.length)) {
1680
+ result.sessionFile = options.sessionFile;
1681
+ } else if (shareEnabled && options.sessionDir) {
1682
+ const sessionFile = findLatestSessionFile(options.sessionDir);
1683
+ if (sessionFile) result.sessionFile = sessionFile;
1684
+ }
1685
+
1686
+ const childWrittenOutput = options.outputPath
1687
+ ? extractChildWrittenOutput(result.messages, options.outputPath, options.cwd ?? runtimeCwd)
1688
+ : undefined;
1689
+ try {
1690
+ if (result.interrupted && detachedReason === "user request") {
1691
+ // Only an accepted user-detach receipt needs a non-rejecting terminal
1692
+ // ledger. Attached and background execution retain their baseline
1693
+ // acceptance behavior.
1694
+ result.acceptance = buildInterruptedAcceptanceLedger(effectiveAcceptance);
1695
+ } else if (result.stopped) {
1696
+ result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." });
1697
+ } else if (result.timedOut) {
1698
+ result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." });
1699
+ } else if (result.turnBudgetExceeded) {
1700
+ result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." });
1701
+ } else {
1702
+ result.acceptance = await evaluateAcceptance({
1703
+ acceptance: effectiveAcceptance,
1704
+ output: acceptanceOutputByResult.get(result) ?? result.finalOutput ?? "",
1705
+ fileOutput: childWrittenOutput !== undefined && options.outputPath
1706
+ ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only" }
1707
+ : undefined,
1708
+ cwd: options.cwd ?? runtimeCwd,
1709
+ reportOptional: isAgentContractV1(options.agentContract),
1710
+ artifactsDir: options.artifactsDir,
1711
+ runId: options.runId,
1712
+ });
1713
+ }
1714
+ } catch (error) {
1715
+ const message = `Acceptance evaluation failed: ${error instanceof Error ? error.message : String(error)}`;
1716
+ result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "acceptance-evaluation", message });
1717
+ }
1718
+ const acceptanceFailure = acceptanceFailureMessage(result.acceptance);
1719
+ stripAcceptanceReportsFromMessages(result.messages);
1720
+ if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContractV1(options.agentContract)) {
1721
+ result.exitCode = 1;
1722
+ result.error = result.error ? `${result.error}\n${acceptanceFailure}` : acceptanceFailure;
1723
+ if (result.progress) {
1724
+ result.progress.status = "failed";
1725
+ result.progress.error = result.error;
1726
+ }
1727
+ }
1728
+ if (isAgentContractV1(options.agentContract)) attachContractProjections(result);
1729
+ try {
1730
+ persistResultMetadata(result);
1731
+ } catch (error) {
1732
+ result.metadataSaveError = error instanceof Error ? error.message : String(error);
1733
+ }
1734
+
1735
+ return result;
1736
+ }
1737
+
1738
+ /**
1739
+ * Runs the authoritative completion pipeline independently from the foreground
1740
+ * receipt. Detachment is same-runtime only: it does not adopt or daemonize work.
1741
+ */
1742
+ export async function runSync(
1743
+ runtimeCwd: string,
1744
+ agents: AgentConfig[],
1745
+ agentName: string,
1746
+ task: string,
1747
+ options: RunSyncOptions,
1748
+ ): Promise<SingleResult> {
1749
+ // Capture the strict contract before consumer-owned objects can be mutated
1750
+ // after a detached receipt is published.
1751
+ const strictContract = isAgentContractV1(options.agentContract);
1752
+ let detachedReason: string | undefined;
1753
+ let publishedReceipt: SingleResult | undefined;
1754
+ let activeDetachAttempt: ((reason?: string) => boolean) | undefined;
1755
+ let detachReadyPublished = false;
1756
+ let resolveReceipt!: (result: SingleResult) => void;
1757
+ const receipt = new Promise<SingleResult>((resolve) => { resolveReceipt = resolve; });
1758
+ const originSignal = options.signal;
1759
+ const originController = new AbortController();
1760
+ const forwardOriginAbort = () => {
1761
+ if (!detachedReason) originController.abort(originSignal?.reason);
1762
+ };
1763
+ if (originSignal?.aborted) forwardOriginAbort();
1764
+ else originSignal?.addEventListener("abort", forwardOriginAbort, { once: true });
1765
+
1766
+ const completion = runSyncCompletion(runtimeCwd, agents, agentName, task, {
1767
+ ...options,
1768
+ signal: originController.signal,
1769
+ onDetachedExit: undefined,
1770
+ onDetachReceipt: (detachedReceipt) => {
1771
+ if (detachedReason || publishedReceipt) return false;
1772
+ // Keep the authoritative result, fallback snapshot, and caller receipt
1773
+ // separately owned while the completion pipeline remains live.
1774
+ publishedReceipt = structuredClone(detachedReceipt);
1775
+ const callerReceipt = structuredClone(detachedReceipt);
1776
+ // A strict contract was already validated before detach; normalize private
1777
+ // and caller snapshots to the only safely known version.
1778
+ publishedReceipt.agentContract = strictContract ? { version: 1 } : undefined;
1779
+ callerReceipt.agentContract = strictContract ? { version: 1 } : undefined;
1780
+ detachedReason = detachedReceipt.detachedReason ?? "user request";
1781
+ resolveReceipt(callerReceipt);
1782
+ return true;
1783
+ },
1784
+ onDetachReady: (detachAttempt) => {
1785
+ activeDetachAttempt = detachAttempt;
1786
+ if (detachReadyPublished) return;
1787
+ detachReadyPublished = true;
1788
+ options.onDetachReady?.((reason = "user request") => {
1789
+ if (detachedReason || originController.signal.aborted) return false;
1790
+ return activeDetachAttempt?.(reason) ?? false;
1791
+ });
1792
+ },
1793
+ });
1794
+
1795
+ const authoritativeCompletion = completion.catch((error: unknown) => {
1796
+ if (!publishedReceipt || !detachedReason) throw error;
1797
+ const message = error instanceof Error ? error.message : String(error);
1798
+ const failureMessage = `Detached completion pipeline failed after receipt: ${message}`;
1799
+ const failedProgress: AgentProgress = publishedReceipt.progress
1800
+ ? { ...publishedReceipt.progress, status: "failed", error: failureMessage }
1801
+ : {
1802
+ index: options.index ?? 0,
1803
+ agent: publishedReceipt.agent,
1804
+ status: "failed",
1805
+ task: publishedReceipt.task,
1806
+ recentTools: [],
1807
+ recentOutput: [],
1808
+ toolCount: publishedReceipt.progressSummary?.toolCount ?? 0,
1809
+ tokens: publishedReceipt.progressSummary?.tokens ?? 0,
1810
+ durationMs: publishedReceipt.progressSummary?.durationMs ?? 0,
1811
+ error: failureMessage,
1812
+ };
1813
+ const failedResult: SingleResult = {
1814
+ ...publishedReceipt,
1815
+ detached: undefined,
1816
+ detachedReason,
1817
+ exitCode: 1,
1818
+ error: failureMessage,
1819
+ finalOutput: failureMessage,
1820
+ progress: failedProgress,
1821
+ progressSummary: {
1822
+ toolCount: failedProgress.toolCount,
1823
+ tokens: failedProgress.tokens,
1824
+ durationMs: failedProgress.durationMs,
1825
+ },
1826
+ acceptance: publishedReceipt.acceptance
1827
+ ? buildSkippedAcceptanceLedger(publishedReceipt.acceptance.effectiveAcceptance, { id: "completion-pipeline", message: failureMessage })
1828
+ : undefined,
1829
+ };
1830
+ if (strictContract) attachContractProjections(failedResult);
1831
+ try {
1832
+ // Replace the provisional detach receipt metadata with the authoritative
1833
+ // terminal failure. Persistence remains best-effort and cannot orphan work.
1834
+ persistSingleResultMetadata({
1835
+ metadataPath: failedResult.artifactPaths?.metadataPath,
1836
+ enabled: options.artifactConfig?.enabled !== false && options.artifactConfig?.includeMetadata !== false,
1837
+ runId: options.runId,
1838
+ agent: failedResult.agent,
1839
+ task: failedResult.task,
1840
+ result: failedResult,
1841
+ });
1842
+ } catch (metadataError) {
1843
+ failedResult.metadataSaveError = metadataError instanceof Error ? metadataError.message : String(metadataError);
1844
+ }
1845
+ return failedResult;
1846
+ });
1847
+
1848
+ let terminalCallbackInvoked = false;
1849
+ void authoritativeCompletion.then((terminalResult) => {
1850
+ if (!detachedReason || terminalCallbackInvoked) return;
1851
+ terminalCallbackInvoked = true;
1852
+ terminalResult.detached = undefined;
1853
+ terminalResult.detachedReason = detachedReason;
1854
+ try {
1855
+ options.onDetachedExit?.(terminalResult);
1856
+ } catch {
1857
+ // The authoritative result has settled. Consumer callback failures are
1858
+ // contained here; each consumer owns cleanup through its own finally block.
1859
+ }
1860
+ }).catch(() => {
1861
+ // Attached completion rejection remains observable through the returned
1862
+ // promise without becoming an unhandled side-channel rejection.
1863
+ }).finally(() => {
1864
+ originSignal?.removeEventListener("abort", forwardOriginAbort);
1865
+ });
1866
+
1867
+ return Promise.race([authoritativeCompletion, receipt]);
1868
+ }