@selesai/code 0.1.5 → 0.1.6

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 (142) hide show
  1. package/dist/config.d.ts +21 -4
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +71 -4
  4. package/dist/config.js.map +1 -1
  5. package/dist/core/package-manager.d.ts +1 -0
  6. package/dist/core/package-manager.d.ts.map +1 -1
  7. package/dist/core/package-manager.js +6 -1
  8. package/dist/core/package-manager.js.map +1 -1
  9. package/dist/core/resource-loader.d.ts.map +1 -1
  10. package/dist/core/resource-loader.js +3 -2
  11. package/dist/core/resource-loader.js.map +1 -1
  12. package/dist/core/settings-manager.d.ts +1 -0
  13. package/dist/core/settings-manager.d.ts.map +1 -1
  14. package/dist/core/settings-manager.js.map +1 -1
  15. package/dist/extensions/pi-intercom/LICENSE +21 -0
  16. package/dist/extensions/pi-intercom/README.md +484 -0
  17. package/dist/extensions/pi-intercom/broker/broker.ts +345 -0
  18. package/dist/extensions/pi-intercom/broker/client.ts +535 -0
  19. package/dist/extensions/pi-intercom/broker/framing.ts +57 -0
  20. package/dist/extensions/pi-intercom/broker/paths.ts +20 -0
  21. package/dist/extensions/pi-intercom/broker/spawn.ts +307 -0
  22. package/dist/extensions/pi-intercom/config.ts +108 -0
  23. package/dist/extensions/pi-intercom/index.ts +1778 -0
  24. package/dist/extensions/pi-intercom/package.json +38 -0
  25. package/dist/extensions/pi-intercom/reply-tracker.ts +102 -0
  26. package/dist/extensions/pi-intercom/skills/pi-intercom/SKILL.md +512 -0
  27. package/dist/extensions/pi-intercom/types.ts +46 -0
  28. package/dist/extensions/pi-intercom/ui/compose.ts +139 -0
  29. package/dist/extensions/pi-intercom/ui/inline-message.ts +76 -0
  30. package/dist/extensions/pi-intercom/ui/session-list.ts +162 -0
  31. package/dist/extensions/pi-rewind-hook/README.md +245 -0
  32. package/dist/extensions/pi-rewind-hook/index.ts +1445 -0
  33. package/dist/extensions/pi-rewind-hook/package.json +29 -0
  34. package/dist/extensions/pi-subagents/README.md +1290 -0
  35. package/dist/extensions/pi-subagents/agents/context-builder.md +46 -0
  36. package/dist/extensions/pi-subagents/agents/delegate.md +12 -0
  37. package/dist/extensions/pi-subagents/agents/oracle.md +73 -0
  38. package/dist/extensions/pi-subagents/agents/planner.md +55 -0
  39. package/dist/extensions/pi-subagents/agents/researcher.md +52 -0
  40. package/dist/extensions/pi-subagents/agents/reviewer.md +79 -0
  41. package/dist/extensions/pi-subagents/agents/scout.md +50 -0
  42. package/dist/extensions/pi-subagents/agents/worker.md +55 -0
  43. package/dist/extensions/pi-subagents/package.json +83 -0
  44. package/dist/extensions/pi-subagents/prompts/gather-context-and-clarify.md +13 -0
  45. package/dist/extensions/pi-subagents/prompts/parallel-cleanup.md +59 -0
  46. package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +55 -0
  47. package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +61 -0
  48. package/dist/extensions/pi-subagents/prompts/parallel-research.md +50 -0
  49. package/dist/extensions/pi-subagents/prompts/parallel-review.md +54 -0
  50. package/dist/extensions/pi-subagents/prompts/review-loop.md +41 -0
  51. package/dist/extensions/pi-subagents/skills/pi-subagents/SKILL.md +855 -0
  52. package/dist/extensions/pi-subagents/src/agents/agent-management.ts +875 -0
  53. package/dist/extensions/pi-subagents/src/agents/agent-scope.ts +6 -0
  54. package/dist/extensions/pi-subagents/src/agents/agent-selection.ts +25 -0
  55. package/dist/extensions/pi-subagents/src/agents/agent-serializer.ts +110 -0
  56. package/dist/extensions/pi-subagents/src/agents/agents.ts +1379 -0
  57. package/dist/extensions/pi-subagents/src/agents/chain-serializer.ts +252 -0
  58. package/dist/extensions/pi-subagents/src/agents/frontmatter.ts +93 -0
  59. package/dist/extensions/pi-subagents/src/agents/identity.ts +30 -0
  60. package/dist/extensions/pi-subagents/src/agents/proactive-skills.ts +191 -0
  61. package/dist/extensions/pi-subagents/src/agents/skills.ts +729 -0
  62. package/dist/extensions/pi-subagents/src/extension/config.ts +16 -0
  63. package/dist/extensions/pi-subagents/src/extension/control-notices.ts +92 -0
  64. package/dist/extensions/pi-subagents/src/extension/doctor.ts +220 -0
  65. package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +171 -0
  66. package/dist/extensions/pi-subagents/src/extension/index.ts +627 -0
  67. package/dist/extensions/pi-subagents/src/extension/schemas.ts +265 -0
  68. package/dist/extensions/pi-subagents/src/intercom/intercom-bridge.ts +412 -0
  69. package/dist/extensions/pi-subagents/src/intercom/result-intercom.ts +377 -0
  70. package/dist/extensions/pi-subagents/src/profiles/profiles.ts +637 -0
  71. package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +916 -0
  72. package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +355 -0
  73. package/dist/extensions/pi-subagents/src/runs/background/async-resume.ts +391 -0
  74. package/dist/extensions/pi-subagents/src/runs/background/async-status.ts +338 -0
  75. package/dist/extensions/pi-subagents/src/runs/background/chain-append.ts +282 -0
  76. package/dist/extensions/pi-subagents/src/runs/background/chain-root-attachment.ts +161 -0
  77. package/dist/extensions/pi-subagents/src/runs/background/completion-dedupe.ts +63 -0
  78. package/dist/extensions/pi-subagents/src/runs/background/control-channel.ts +177 -0
  79. package/dist/extensions/pi-subagents/src/runs/background/notify.ts +108 -0
  80. package/dist/extensions/pi-subagents/src/runs/background/parallel-groups.ts +45 -0
  81. package/dist/extensions/pi-subagents/src/runs/background/result-watcher.ts +316 -0
  82. package/dist/extensions/pi-subagents/src/runs/background/run-id-resolver.ts +83 -0
  83. package/dist/extensions/pi-subagents/src/runs/background/run-status.ts +273 -0
  84. package/dist/extensions/pi-subagents/src/runs/background/stale-run-reconciler.ts +341 -0
  85. package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +2458 -0
  86. package/dist/extensions/pi-subagents/src/runs/background/top-level-async.ts +13 -0
  87. package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +1333 -0
  88. package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +1217 -0
  89. package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +1092 -0
  90. package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +3125 -0
  91. package/dist/extensions/pi-subagents/src/runs/shared/acceptance.ts +856 -0
  92. package/dist/extensions/pi-subagents/src/runs/shared/chain-outputs.ts +116 -0
  93. package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +147 -0
  94. package/dist/extensions/pi-subagents/src/runs/shared/dynamic-fanout.ts +295 -0
  95. package/dist/extensions/pi-subagents/src/runs/shared/long-running-guard.ts +175 -0
  96. package/dist/extensions/pi-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +365 -0
  97. package/dist/extensions/pi-subagents/src/runs/shared/model-fallback.ts +141 -0
  98. package/dist/extensions/pi-subagents/src/runs/shared/nested-events.ts +819 -0
  99. package/dist/extensions/pi-subagents/src/runs/shared/nested-path.ts +52 -0
  100. package/dist/extensions/pi-subagents/src/runs/shared/nested-render.ts +115 -0
  101. package/dist/extensions/pi-subagents/src/runs/shared/parallel-utils.ts +149 -0
  102. package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +240 -0
  103. package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +115 -0
  104. package/dist/extensions/pi-subagents/src/runs/shared/run-history.ts +60 -0
  105. package/dist/extensions/pi-subagents/src/runs/shared/single-output.ts +178 -0
  106. package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +77 -0
  107. package/dist/extensions/pi-subagents/src/runs/shared/subagent-control.ts +223 -0
  108. package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +222 -0
  109. package/dist/extensions/pi-subagents/src/runs/shared/workflow-graph.ts +206 -0
  110. package/dist/extensions/pi-subagents/src/runs/shared/worktree.ts +577 -0
  111. package/dist/extensions/pi-subagents/src/shared/artifacts.ts +98 -0
  112. package/dist/extensions/pi-subagents/src/shared/atomic-json.ts +73 -0
  113. package/dist/extensions/pi-subagents/src/shared/file-coalescer.ts +40 -0
  114. package/dist/extensions/pi-subagents/src/shared/fork-context.ts +76 -0
  115. package/dist/extensions/pi-subagents/src/shared/formatters.ts +133 -0
  116. package/dist/extensions/pi-subagents/src/shared/jsonl-writer.ts +81 -0
  117. package/dist/extensions/pi-subagents/src/shared/model-info.ts +78 -0
  118. package/dist/extensions/pi-subagents/src/shared/post-exit-stdio-guard.ts +85 -0
  119. package/dist/extensions/pi-subagents/src/shared/session-identity.ts +10 -0
  120. package/dist/extensions/pi-subagents/src/shared/session-tokens.ts +44 -0
  121. package/dist/extensions/pi-subagents/src/shared/settings.ts +448 -0
  122. package/dist/extensions/pi-subagents/src/shared/status-format.ts +49 -0
  123. package/dist/extensions/pi-subagents/src/shared/types.ts +1064 -0
  124. package/dist/extensions/pi-subagents/src/shared/utils.ts +469 -0
  125. package/dist/extensions/pi-subagents/src/slash/prompt-template-bridge.ts +420 -0
  126. package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +176 -0
  127. package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +1165 -0
  128. package/dist/extensions/pi-subagents/src/slash/slash-live-state.ts +292 -0
  129. package/dist/extensions/pi-subagents/src/tui/render-helpers.ts +80 -0
  130. package/dist/extensions/pi-subagents/src/tui/render.ts +1728 -0
  131. package/dist/extensions/quick.ts +630 -0
  132. package/dist/modes/index.d.ts +1 -1
  133. package/dist/modes/index.d.ts.map +1 -1
  134. package/dist/modes/index.js.map +1 -1
  135. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  136. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  137. package/dist/modes/rpc/rpc-mode.js +4 -3
  138. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  139. package/dist/modes/rpc/rpc-types.d.ts +3 -2
  140. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  141. package/dist/modes/rpc/rpc-types.js.map +1 -1
  142. package/package.json +1 -1
@@ -0,0 +1,2458 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import type { Message } from "@earendil-works/pi-ai";
6
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
7
+ import { consumeInterruptRequest, watchAsyncControlInbox } from "./control-channel.ts";
8
+ import { appendJsonl as appendRawJsonl, getArtifactPaths } from "../../shared/artifacts.ts";
9
+ import { PI_CODING_AGENT_PACKAGE, getPiSpawnCommand, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
10
+ import { captureSingleOutputSnapshot, finalizeSingleOutput, formatSavedOutputReference, resolveSingleOutput, type SingleOutputSnapshot } from "../shared/single-output.ts";
11
+ import {
12
+ type ActivityState,
13
+ type ArtifactConfig,
14
+ type ArtifactPaths,
15
+ type AsyncParallelGroupStatus,
16
+ type AsyncStatus,
17
+ type ChainOutputMap,
18
+ type ModelAttempt,
19
+ type NestedRouteInfo,
20
+ type ResolvedControlConfig,
21
+ type SubagentRunMode,
22
+ type Usage,
23
+ type WorkflowGraphSnapshot,
24
+ DEFAULT_MAX_OUTPUT,
25
+ type MaxOutputConfig,
26
+ truncateOutput,
27
+ getSubagentDepthEnv,
28
+ } from "../../shared/types.ts";
29
+ import {
30
+ DEFAULT_CONTROL_CONFIG,
31
+ buildControlEvent,
32
+ deriveActivityState,
33
+ claimControlNotification,
34
+ formatControlIntercomMessage,
35
+ formatControlNoticeMessage,
36
+ } from "../shared/subagent-control.ts";
37
+ import {
38
+ type RunnerSubagentStep as SubagentStep,
39
+ type RunnerStep,
40
+ isDynamicRunnerGroup,
41
+ isParallelGroup,
42
+ flattenSteps,
43
+ mapConcurrent,
44
+ aggregateParallelOutputs,
45
+ MAX_PARALLEL_CONCURRENCY,
46
+ } from "../shared/parallel-utils.ts";
47
+ import { buildPiArgs, cleanupTempDir } from "../shared/pi-args.ts";
48
+ import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/chain-outputs.ts";
49
+ import { createStructuredOutputRuntime, readStructuredOutput } from "../shared/structured-output.ts";
50
+ import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.ts";
51
+ import { nestedSummaryFromAsyncStatus, writeNestedEvent } from "../shared/nested-events.ts";
52
+ import { formatModelAttemptNote, isRetryableModelFailure } from "../shared/model-fallback.ts";
53
+ import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
54
+ import { detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput } from "../../shared/utils.ts";
55
+ import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
56
+ import {
57
+ createMutatingFailureState,
58
+ didMutatingToolFail,
59
+ isMutatingTool,
60
+ nextLongRunningTrigger,
61
+ recordMutatingFailure,
62
+ resetMutatingFailureState,
63
+ resolveCurrentPath,
64
+ shouldEscalateMutatingFailures,
65
+ summarizeRecentMutatingFailures,
66
+ } from "../shared/long-running-guard.ts";
67
+ import { parseSessionTokens } from "../../shared/session-tokens.ts";
68
+ import type { TokenUsage } from "../../shared/types.ts";
69
+ import {
70
+ cleanupWorktrees,
71
+ createWorktrees,
72
+ diffWorktrees,
73
+ findWorktreeTaskCwdConflict,
74
+ formatWorktreeDiffSummary,
75
+ formatWorktreeTaskCwdConflict,
76
+ type WorktreeSetup,
77
+ } from "../shared/worktree.ts";
78
+ import { resolveEffectiveThinking } from "../../shared/model-info.ts";
79
+ import { writeInitialProgressFile } from "../../shared/settings.ts";
80
+ import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
81
+ import { acceptanceFailureMessage, aggregateAcceptanceReport, evaluateAcceptance, formatAcceptancePrompt, stripAcceptanceReport } from "../shared/acceptance.ts";
82
+ import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
83
+ import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests } from "./chain-append.ts";
84
+
85
+ interface SubagentRunConfig {
86
+ id: string;
87
+ steps: RunnerStep[];
88
+ resultPath: string;
89
+ cwd: string;
90
+ placeholder: string;
91
+ taskIndex?: number;
92
+ totalTasks?: number;
93
+ maxOutput?: MaxOutputConfig;
94
+ artifactsDir?: string;
95
+ artifactConfig?: Partial<ArtifactConfig>;
96
+ share?: boolean;
97
+ sessionDir?: string;
98
+ asyncDir: string;
99
+ sessionId?: string | null;
100
+ piPackageRoot?: string;
101
+ piArgv1?: string;
102
+ worktreeSetupHook?: string;
103
+ worktreeSetupHookTimeoutMs?: number;
104
+ controlConfig?: ResolvedControlConfig;
105
+ controlIntercomTarget?: string;
106
+ childIntercomTargets?: Array<string | undefined>;
107
+ resultMode?: SubagentRunMode;
108
+ dynamicFanoutMaxItems?: number;
109
+ workflowGraph?: WorkflowGraphSnapshot;
110
+ nestedRoute?: NestedRouteInfo;
111
+ nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> };
112
+ }
113
+
114
+ interface StepResult {
115
+ agent: string;
116
+ output: string;
117
+ error?: string;
118
+ success: boolean;
119
+ exitCode?: number | null;
120
+ skipped?: boolean;
121
+ sessionFile?: string;
122
+ intercomTarget?: string;
123
+ model?: string;
124
+ attemptedModels?: string[];
125
+ modelAttempts?: ModelAttempt[];
126
+ artifactPaths?: ArtifactPaths;
127
+ truncated?: boolean;
128
+ structuredOutput?: unknown;
129
+ structuredOutputPath?: string;
130
+ structuredOutputSchemaPath?: string;
131
+ acceptance?: import("../../shared/types.ts").AcceptanceLedger;
132
+ }
133
+
134
+ const ASYNC_INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
135
+ const DEFAULT_MAX_ASYNC_EVENTS_BYTES = 50 * 1024 * 1024;
136
+ const ASYNC_EVENTS_MAX_BYTES_ENV = "PI_SUBAGENT_ASYNC_EVENTS_MAX_BYTES";
137
+ const TRUNCATED_EVENT_TYPE = "subagent.events.truncated";
138
+ const TRUNCATION_MARKER_RESERVE_BYTES = 512;
139
+
140
+ interface AsyncEventLogState {
141
+ bytes: number;
142
+ diagnosticsTruncated: boolean;
143
+ }
144
+
145
+ const asyncEventLogStates = new Map<string, AsyncEventLogState>();
146
+
147
+ function maxAsyncEventsBytes(): number {
148
+ const raw = process.env[ASYNC_EVENTS_MAX_BYTES_ENV];
149
+ if (!raw) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
150
+ const parsed = Number(raw);
151
+ if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
152
+ return Math.floor(parsed);
153
+ }
154
+
155
+ function eventLogState(filePath: string): AsyncEventLogState {
156
+ let state = asyncEventLogStates.get(filePath);
157
+ if (state) return state;
158
+ let bytes = 0;
159
+ try {
160
+ bytes = fs.statSync(filePath).size;
161
+ } catch (error) {
162
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
163
+ // Diagnostic event accounting is best-effort; writes below are also safe.
164
+ }
165
+ }
166
+ state = { bytes, diagnosticsTruncated: false };
167
+ asyncEventLogStates.set(filePath, state);
168
+ return state;
169
+ }
170
+
171
+ function appendJsonl(filePath: string, line: string): void {
172
+ try {
173
+ appendRawJsonl(filePath, line);
174
+ const state = asyncEventLogStates.get(filePath);
175
+ if (state) state.bytes += Buffer.byteLength(`${line}\n`, "utf-8");
176
+ } catch {
177
+ // Async event logging is diagnostic and must not fail the run.
178
+ }
179
+ }
180
+
181
+ function appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?: string): void {
182
+ if (!line.trim()) return;
183
+ const state = eventLogState(filePath);
184
+ if (state.diagnosticsTruncated) return;
185
+ const maxBytes = maxAsyncEventsBytes();
186
+ const chunkBytes = Buffer.byteLength(`${line}\n`, "utf-8");
187
+ const diagnosticBudget = Math.max(0, maxBytes - TRUNCATION_MARKER_RESERVE_BYTES);
188
+ if (state.bytes + chunkBytes <= diagnosticBudget) {
189
+ appendJsonl(filePath, line);
190
+ return;
191
+ }
192
+
193
+ const marker = JSON.stringify({
194
+ type: TRUNCATED_EVENT_TYPE,
195
+ ts: Date.now(),
196
+ maxBytes,
197
+ droppedEventType,
198
+ });
199
+ if (state.bytes + Buffer.byteLength(`${marker}\n`, "utf-8") <= maxBytes) {
200
+ appendJsonl(filePath, marker);
201
+ }
202
+ state.diagnosticsTruncated = true;
203
+ }
204
+
205
+ function shouldPersistChildEvent(event: Record<string, unknown>): boolean {
206
+ return event.type !== "message_update";
207
+ }
208
+
209
+ function findLatestSessionFile(sessionDir: string): string | null {
210
+ try {
211
+ const files = fs
212
+ .readdirSync(sessionDir)
213
+ .filter((f) => f.endsWith(".jsonl"))
214
+ .map((f) => path.join(sessionDir, f));
215
+ if (files.length === 0) return null;
216
+ files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
217
+ return files[0] ?? null;
218
+ } catch {
219
+ // Session lookup is optional metadata.
220
+ return null;
221
+ }
222
+ }
223
+
224
+ function emptyUsage(): Usage {
225
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
226
+ }
227
+
228
+ function tokenUsageFromAttempts(attempts: ModelAttempt[] | undefined): TokenUsage | null {
229
+ if (!attempts || attempts.length === 0) return null;
230
+ let input = 0;
231
+ let output = 0;
232
+ for (const attempt of attempts) {
233
+ input += attempt.usage?.input ?? 0;
234
+ output += attempt.usage?.output ?? 0;
235
+ }
236
+ const total = input + output;
237
+ return total > 0 ? { input, output, total } : null;
238
+ }
239
+
240
+ function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
241
+ const nonEmpty = lines.filter((line) => line.trim());
242
+ if (nonEmpty.length === 0) return;
243
+ step.recentOutput ??= [];
244
+ step.recentOutput.push(...nonEmpty);
245
+ if (step.recentOutput.length > 50) {
246
+ step.recentOutput.splice(0, step.recentOutput.length - 50);
247
+ }
248
+ }
249
+
250
+ function resetStepLiveDetail(step: RunnerStatusStep): void {
251
+ step.currentTool = undefined;
252
+ step.currentToolArgs = undefined;
253
+ step.currentToolStartedAt = undefined;
254
+ step.currentPath = undefined;
255
+ step.recentTools = [];
256
+ step.recentOutput = [];
257
+ }
258
+
259
+ interface ChildEventContext {
260
+ eventsPath: string;
261
+ runId: string;
262
+ stepIndex: number;
263
+ agent: string;
264
+ }
265
+
266
+ interface ChildUsage {
267
+ input?: number;
268
+ inputTokens?: number;
269
+ output?: number;
270
+ outputTokens?: number;
271
+ cacheRead?: number;
272
+ cacheWrite?: number;
273
+ cost?: { total?: number };
274
+ }
275
+
276
+ type ChildMessage = Message & {
277
+ model?: string;
278
+ errorMessage?: string;
279
+ usage?: ChildUsage;
280
+ };
281
+
282
+ interface ChildEvent {
283
+ type?: string;
284
+ message?: ChildMessage;
285
+ toolName?: string;
286
+ args?: Record<string, unknown>;
287
+ }
288
+
289
+ interface RunPiStreamingResult {
290
+ stderr: string;
291
+ exitCode: number | null;
292
+ messages: Message[];
293
+ usage: Usage;
294
+ model?: string;
295
+ error?: string;
296
+ finalOutput: string;
297
+ interrupted?: boolean;
298
+ observedMutationAttempt?: boolean;
299
+ }
300
+
301
+ function runPiStreaming(
302
+ args: string[],
303
+ cwd: string,
304
+ outputFile: string,
305
+ env?: Record<string, string | undefined>,
306
+ piPackageRoot?: string,
307
+ piArgv1?: string,
308
+ maxSubagentDepth?: number,
309
+ childEventContext?: ChildEventContext,
310
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void,
311
+ onChildEvent?: (event: ChildEvent) => void,
312
+ ): Promise<RunPiStreamingResult> {
313
+ return new Promise((resolve) => {
314
+ const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
315
+ const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
316
+ const spawnSpec = getPiSpawnCommand(args, {
317
+ ...(piPackageRoot ? { piPackageRoot } : {}),
318
+ ...(piArgv1 ? { argv1: piArgv1 } : {}),
319
+ });
320
+ const child = spawn(spawnSpec.command, spawnSpec.args, {
321
+ cwd,
322
+ stdio: ["ignore", "pipe", "pipe"],
323
+ env: spawnEnv,
324
+ windowsHide: true,
325
+ });
326
+ let stderr = "";
327
+ let stdoutBuf = "";
328
+ let stderrBuf = "";
329
+ const messages: Message[] = [];
330
+ const usage = emptyUsage();
331
+ let model: string | undefined;
332
+ let error: string | undefined;
333
+ let assistantError: string | undefined;
334
+ let interrupted = false;
335
+ let observedMutationAttempt = false;
336
+ const rawStdoutLines: string[] = [];
337
+
338
+ const writeOutputLine = (line: string) => {
339
+ if (!line.trim()) return;
340
+ outputStream.write(`${line}\n`);
341
+ };
342
+
343
+ const writeOutputText = (text: string) => {
344
+ for (const line of text.split("\n")) {
345
+ writeOutputLine(line);
346
+ }
347
+ };
348
+
349
+ const appendChildEvent = (event: Record<string, unknown>) => {
350
+ if (!childEventContext) return;
351
+ if (!shouldPersistChildEvent(event)) return;
352
+ appendDiagnosticJsonl(childEventContext.eventsPath, JSON.stringify({
353
+ ...event,
354
+ subagentSource: "child",
355
+ subagentRunId: childEventContext.runId,
356
+ subagentStepIndex: childEventContext.stepIndex,
357
+ subagentAgent: childEventContext.agent,
358
+ observedAt: Date.now(),
359
+ }), typeof event.type === "string" ? event.type : undefined);
360
+ };
361
+
362
+ const appendChildLine = (type: "subagent.child.stdout" | "subagent.child.stderr", line: string) => {
363
+ appendChildEvent({ type, line });
364
+ };
365
+
366
+ const processStdoutLine = (line: string) => {
367
+ if (!line.trim()) return;
368
+ let event: ChildEvent;
369
+ try {
370
+ event = JSON.parse(line) as ChildEvent;
371
+ } catch {
372
+ rawStdoutLines.push(line);
373
+ writeOutputLine(line);
374
+ appendChildLine("subagent.child.stdout", line);
375
+ return;
376
+ }
377
+
378
+ appendChildEvent(event);
379
+ onChildEvent?.(event);
380
+
381
+ if (event.type === "tool_execution_start" && event.toolName) {
382
+ observedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);
383
+ const toolArgs = extractToolArgsPreview(event.args ?? {});
384
+ writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
385
+ return;
386
+ }
387
+
388
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
389
+ messages.push(event.message);
390
+ const text = extractTextFromContent(event.message.content);
391
+ if (text) writeOutputText(text);
392
+
393
+ if (event.type !== "message_end" || event.message.role !== "assistant") return;
394
+ if (event.message.model) model = event.message.model;
395
+ if (event.message.errorMessage) assistantError = event.message.errorMessage;
396
+ const eventUsage = event.message.usage;
397
+ if (eventUsage) {
398
+ usage.turns++;
399
+ usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
400
+ usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
401
+ usage.cacheRead += eventUsage.cacheRead ?? 0;
402
+ usage.cacheWrite += eventUsage.cacheWrite ?? 0;
403
+ usage.cost += eventUsage.cost?.total ?? 0;
404
+ }
405
+ const stopReason = (event.message as { stopReason?: string }).stopReason;
406
+ const hasToolCall = Array.isArray(event.message.content)
407
+ && event.message.content.some((part) => (part as { type?: string }).type === "toolCall");
408
+ if (stopReason === "stop" && !hasToolCall) {
409
+ if (!event.message.errorMessage && extractTextFromContent(event.message.content).trim()) assistantError = undefined;
410
+ cleanTerminalAssistantStopReceived ||= !event.message.errorMessage;
411
+ startFinalDrain();
412
+ }
413
+ }
414
+ };
415
+
416
+ const processStderrText = (text: string) => {
417
+ stderr += text;
418
+ stderrBuf += text;
419
+ outputStream.write(text);
420
+ if (!childEventContext) return;
421
+ const lines = stderrBuf.split("\n");
422
+ stderrBuf = lines.pop() || "";
423
+ for (const line of lines) {
424
+ if (!line.trim()) continue;
425
+ appendChildLine("subagent.child.stderr", line);
426
+ }
427
+ };
428
+
429
+ // Guard both cases that can leave the parent waiting on `close` forever:
430
+ // a lingering stdio holder after `exit`, or a child that never exits.
431
+ const FINAL_STOP_GRACE_MS = 1000;
432
+ const HARD_KILL_MS = 3000;
433
+ let childExited = false;
434
+ let forcedTerminationSignal = false;
435
+ let cleanTerminalAssistantStopReceived = false;
436
+ let finalDrainTimer: NodeJS.Timeout | undefined;
437
+ let finalHardKillTimer: NodeJS.Timeout | undefined;
438
+ let settled = false;
439
+ const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
440
+ child.stdout.on("data", (chunk: Buffer) => {
441
+ const text = chunk.toString();
442
+ stdoutBuf += text;
443
+ const lines = stdoutBuf.split("\n");
444
+ stdoutBuf = lines.pop() || "";
445
+ for (const line of lines) processStdoutLine(line);
446
+ });
447
+
448
+ child.stderr.on("data", (chunk: Buffer) => {
449
+ processStderrText(chunk.toString());
450
+ });
451
+ registerInterrupt?.(() => {
452
+ if (settled) return;
453
+ interrupted = true;
454
+ if (!error) error = "Interrupted. Waiting for explicit next action.";
455
+ trySignalChild(child, "SIGINT");
456
+ setTimeout(() => {
457
+ if (!settled) trySignalChild(child, "SIGTERM");
458
+ }, 1000).unref?.();
459
+ });
460
+ const clearDrainTimers = () => {
461
+ if (finalDrainTimer) {
462
+ clearTimeout(finalDrainTimer);
463
+ finalDrainTimer = undefined;
464
+ }
465
+ if (finalHardKillTimer) {
466
+ clearTimeout(finalHardKillTimer);
467
+ finalHardKillTimer = undefined;
468
+ }
469
+ };
470
+ function startFinalDrain(): void {
471
+ if (childExited || finalDrainTimer || settled) return;
472
+ finalDrainTimer = setTimeout(() => {
473
+ if (settled) return;
474
+ const termSent = trySignalChild(child, "SIGTERM");
475
+ if (!termSent) return;
476
+ forcedTerminationSignal = true;
477
+ if (!cleanTerminalAssistantStopReceived && !error && !assistantError) {
478
+ error = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its final message. Forcing termination.`;
479
+ }
480
+ finalHardKillTimer = setTimeout(() => {
481
+ if (settled) return;
482
+ forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
483
+ }, HARD_KILL_MS);
484
+ finalHardKillTimer.unref?.();
485
+ }, FINAL_STOP_GRACE_MS);
486
+ finalDrainTimer.unref?.();
487
+ }
488
+ child.on("exit", () => {
489
+ childExited = true;
490
+ clearDrainTimers();
491
+ });
492
+ child.on("close", (exitCode, signal) => {
493
+ settled = true;
494
+ registerInterrupt?.(undefined);
495
+ clearDrainTimers();
496
+ clearStdioGuard();
497
+ if (stdoutBuf.trim()) processStdoutLine(stdoutBuf);
498
+ if (stderrBuf.trim()) appendChildLine("subagent.child.stderr", stderrBuf);
499
+ outputStream.end();
500
+ const finalOutput = getFinalOutput(messages) || rawStdoutLines.join("\n").trim();
501
+ const finalError = error ?? assistantError;
502
+ const forcedDrainAfterFinalSuccess = forcedTerminationSignal && cleanTerminalAssistantStopReceived && !finalError;
503
+ resolve({
504
+ stderr,
505
+ exitCode: interrupted || forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
506
+ messages,
507
+ usage,
508
+ model,
509
+ error: interrupted || forcedDrainAfterFinalSuccess ? undefined : finalError,
510
+ finalOutput,
511
+ interrupted,
512
+ observedMutationAttempt,
513
+ });
514
+ });
515
+
516
+ child.on("error", (spawnError) => {
517
+ settled = true;
518
+ registerInterrupt?.(undefined);
519
+ clearDrainTimers();
520
+ clearStdioGuard();
521
+ outputStream.end();
522
+ const finalOutput = getFinalOutput(messages) || rawStdoutLines.join("\n").trim();
523
+ const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
524
+ resolve({ stderr, exitCode: 1, messages, usage, model, error: error ?? assistantError ?? spawnErrorMessage, finalOutput, observedMutationAttempt });
525
+ });
526
+ });
527
+ }
528
+
529
+ function resolvePiPackageRootFallback(): string {
530
+ const root = resolveInstalledPiPackageRoot();
531
+ if (root) return root;
532
+ throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
533
+ }
534
+
535
+ async function exportSessionHtml(sessionFile: string, outputDir: string, piPackageRoot?: string): Promise<string> {
536
+ const pkgRoot = piPackageRoot ?? resolvePiPackageRootFallback();
537
+ const exportModulePath = path.join(pkgRoot, "dist", "core", "export-html", "index.js");
538
+ const moduleUrl = pathToFileURL(exportModulePath).href;
539
+ const mod = await import(moduleUrl);
540
+ const exportFromFile = (mod as { exportFromFile?: (inputPath: string, options?: { outputPath?: string }) => string })
541
+ .exportFromFile;
542
+ if (typeof exportFromFile !== "function") {
543
+ throw new Error("exportFromFile not available");
544
+ }
545
+ const outputPath = path.join(outputDir, `${path.basename(sessionFile, ".jsonl")}.html`);
546
+ return exportFromFile(sessionFile, { outputPath });
547
+ }
548
+
549
+ function createShareLink(htmlPath: string): { shareUrl: string; gistUrl: string } | { error: string } {
550
+ try {
551
+ const auth = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
552
+ if (auth.status !== 0) {
553
+ return { error: "GitHub CLI is not logged in. Run 'gh auth login' first." };
554
+ }
555
+ } catch {
556
+ return { error: "GitHub CLI (gh) is not installed." };
557
+ }
558
+
559
+ try {
560
+ const result = spawnSync("gh", ["gist", "create", htmlPath], { encoding: "utf-8" });
561
+ if (result.status !== 0) {
562
+ const err = (result.stderr || "").trim() || "Failed to create gist.";
563
+ return { error: err };
564
+ }
565
+ const gistUrl = (result.stdout || "").trim();
566
+ const gistId = gistUrl.split("/").pop();
567
+ if (!gistId) return { error: "Failed to parse gist ID." };
568
+ const shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;
569
+ return { shareUrl, gistUrl };
570
+ } catch (err) {
571
+ return { error: String(err) };
572
+ }
573
+ }
574
+
575
+ function formatDuration(ms: number): string {
576
+ if (ms < 1000) return `${ms}ms`;
577
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
578
+ const minutes = Math.floor(ms / 60000);
579
+ const seconds = Math.floor((ms % 60000) / 1000);
580
+ return `${minutes}m${seconds}s`;
581
+ }
582
+
583
+ function writeRunLog(
584
+ logPath: string,
585
+ input: {
586
+ id: string;
587
+ mode: SubagentRunMode;
588
+ cwd: string;
589
+ startedAt: number;
590
+ endedAt: number;
591
+ steps: Array<{
592
+ agent: string;
593
+ status: string;
594
+ durationMs?: number;
595
+ }>;
596
+ summary: string;
597
+ truncated: boolean;
598
+ artifactsDir?: string;
599
+ sessionFile?: string;
600
+ shareUrl?: string;
601
+ shareError?: string;
602
+ },
603
+ ): void {
604
+ const lines: string[] = [];
605
+ lines.push(`# Subagent run ${input.id}`);
606
+ lines.push("");
607
+ lines.push(`- **Mode:** ${input.mode}`);
608
+ lines.push(`- **CWD:** ${input.cwd}`);
609
+ lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
610
+ lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
611
+ lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
612
+ if (input.sessionFile) lines.push(`- **Session:** ${input.sessionFile}`);
613
+ if (input.shareUrl) lines.push(`- **Share:** ${input.shareUrl}`);
614
+ if (input.shareError) lines.push(`- **Share error:** ${input.shareError}`);
615
+ if (input.artifactsDir) lines.push(`- **Artifacts:** ${input.artifactsDir}`);
616
+ lines.push("");
617
+ lines.push("## Steps");
618
+ lines.push("| Step | Agent | Status | Duration |");
619
+ lines.push("| --- | --- | --- | --- |");
620
+ input.steps.forEach((step, i) => {
621
+ const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
622
+ lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
623
+ });
624
+ lines.push("");
625
+ lines.push("## Summary");
626
+ if (input.truncated) {
627
+ lines.push("_Output truncated_");
628
+ lines.push("");
629
+ }
630
+ lines.push(input.summary.trim() || "(no output)");
631
+ lines.push("");
632
+ fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
633
+ }
634
+
635
+ /** Context for running a single step */
636
+ interface SingleStepContext {
637
+ previousOutput: string;
638
+ outputs?: ChainOutputMap;
639
+ placeholder: string;
640
+ cwd: string;
641
+ sessionEnabled: boolean;
642
+ sessionDir?: string;
643
+ artifactsDir?: string;
644
+ artifactConfig?: Partial<ArtifactConfig>;
645
+ id: string;
646
+ flatIndex: number;
647
+ flatStepCount: number;
648
+ outputFile: string;
649
+ piPackageRoot?: string;
650
+ piArgv1?: string;
651
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void;
652
+ childIntercomTarget?: string;
653
+ orchestratorIntercomTarget?: string;
654
+ nestedRoute?: NestedRouteInfo;
655
+ onAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;
656
+ onChildEvent?: (event: ChildEvent) => void;
657
+ }
658
+
659
+ /** Run a single pi agent step, returning output and metadata */
660
+ async function runSingleStep(
661
+ step: SubagentStep,
662
+ ctx: SingleStepContext,
663
+ ): Promise<{
664
+ agent: string;
665
+ output: string;
666
+ exitCode: number | null;
667
+ error?: string;
668
+ model?: string;
669
+ attemptedModels?: string[];
670
+ modelAttempts?: ModelAttempt[];
671
+ artifactPaths?: ArtifactPaths;
672
+ interrupted?: boolean;
673
+ sessionFile?: string;
674
+ intercomTarget?: string;
675
+ completionGuardTriggered?: boolean;
676
+ structuredOutput?: unknown;
677
+ structuredOutputPath?: string;
678
+ structuredOutputSchemaPath?: string;
679
+ acceptance?: import("../../shared/types.ts").AcceptanceLedger;
680
+ }> {
681
+ if (step.importAsyncRoot) {
682
+ const imported = await waitForImportedAsyncRoot(step.importAsyncRoot);
683
+ try {
684
+ fs.writeFileSync(ctx.outputFile, imported.output, "utf-8");
685
+ } catch {
686
+ // Output files are observability only for imported roots.
687
+ }
688
+ return {
689
+ agent: imported.agent,
690
+ output: imported.output,
691
+ exitCode: imported.exitCode,
692
+ error: imported.error,
693
+ sessionFile: imported.sessionFile,
694
+ intercomTarget: imported.intercomTarget,
695
+ model: imported.model,
696
+ attemptedModels: imported.attemptedModels,
697
+ modelAttempts: imported.modelAttempts,
698
+ structuredOutput: imported.structuredOutput,
699
+ structuredOutputPath: imported.structuredOutputPath,
700
+ structuredOutputSchemaPath: imported.structuredOutputSchemaPath,
701
+ acceptance: imported.acceptance,
702
+ };
703
+ }
704
+
705
+ const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
706
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
707
+ : undefined);
708
+ const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
709
+ let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
710
+ task = resolveOutputReferences(task, ctx.outputs ?? {});
711
+ const taskForCompletionGuard = task;
712
+ if (step.effectiveAcceptance) {
713
+ const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance);
714
+ if (acceptancePrompt) task = `${task}\n${acceptancePrompt}`;
715
+ }
716
+ const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
717
+ const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
718
+
719
+ let artifactPaths: ArtifactPaths | undefined;
720
+ if (ctx.artifactsDir && ctx.artifactConfig?.enabled !== false) {
721
+ const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
722
+ artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
723
+ fs.mkdirSync(ctx.artifactsDir, { recursive: true });
724
+ if (ctx.artifactConfig?.includeInput !== false) {
725
+ fs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`, "utf-8");
726
+ }
727
+ }
728
+
729
+ const candidates = step.modelCandidates && step.modelCandidates.length > 0
730
+ ? step.modelCandidates
731
+ : step.model
732
+ ? [step.model]
733
+ : [undefined];
734
+ const attemptedModels: string[] = [];
735
+ const modelAttempts: ModelAttempt[] = [];
736
+ const attemptNotes: string[] = [];
737
+ const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
738
+ let finalResult: RunPiStreamingResult | undefined;
739
+ let finalOutputSnapshot: SingleOutputSnapshot | undefined;
740
+ let completionGuardTriggeredFinal = false;
741
+
742
+ for (let index = 0; index < candidates.length; index++) {
743
+ const candidate = candidates[index];
744
+ ctx.onAttemptStart?.({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) });
745
+ const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
746
+ if (effectiveStructuredOutput) {
747
+ try {
748
+ if (fs.existsSync(effectiveStructuredOutput.outputPath)) fs.unlinkSync(effectiveStructuredOutput.outputPath);
749
+ } catch {
750
+ // Missing/stale structured-output files are handled after the child exits.
751
+ }
752
+ }
753
+ const { args, env, tempDir } = buildPiArgs({
754
+ parentSessionId: step.parentSessionId,
755
+ baseArgs: ["--mode", "json", "-p"],
756
+ task,
757
+ sessionEnabled,
758
+ sessionDir,
759
+ sessionFile: step.sessionFile,
760
+ model: candidate,
761
+ inheritProjectContext: step.inheritProjectContext,
762
+ inheritSkills: step.inheritSkills,
763
+ requireReadTool: Boolean(step.skills?.length),
764
+ tools: step.tools,
765
+ extensions: step.extensions,
766
+ subagentOnlyExtensions: step.subagentOnlyExtensions,
767
+ systemPrompt: step.systemPrompt,
768
+ systemPromptMode: step.systemPromptMode,
769
+ mcpDirectTools: step.mcpDirectTools,
770
+ cwd: step.cwd ?? ctx.cwd,
771
+ promptFileStem: step.agent,
772
+ intercomSessionName: ctx.childIntercomTarget,
773
+ orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
774
+ runId: ctx.id,
775
+ childAgentName: step.agent,
776
+ childIndex: ctx.flatIndex,
777
+ parentEventSink: ctx.nestedRoute?.eventSink,
778
+ parentControlInbox: ctx.nestedRoute?.controlInbox,
779
+ parentRootRunId: ctx.nestedRoute?.rootRunId,
780
+ parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
781
+ structuredOutput: effectiveStructuredOutput,
782
+ });
783
+ const run = await runPiStreaming(
784
+ args,
785
+ step.cwd ?? ctx.cwd,
786
+ ctx.outputFile,
787
+ env,
788
+ ctx.piPackageRoot,
789
+ ctx.piArgv1,
790
+ step.maxSubagentDepth,
791
+ { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
792
+ ctx.registerInterrupt,
793
+ ctx.onChildEvent,
794
+ );
795
+ cleanupTempDir(tempDir);
796
+
797
+ const hiddenError = run.exitCode === 0 && !run.error ? detectSubagentError(run.messages) : null;
798
+ let structuredOutput: unknown;
799
+ let structuredError: string | undefined;
800
+ if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !hiddenError?.hasError) {
801
+ const structured = readStructuredOutput({
802
+ schema: effectiveStructuredOutput.schema,
803
+ schemaPath: effectiveStructuredOutput.schemaPath,
804
+ outputPath: effectiveStructuredOutput.outputPath,
805
+ });
806
+ if (structured.error) structuredError = structured.error;
807
+ else structuredOutput = structured.value;
808
+ }
809
+ const completionGuard = run.exitCode === 0 && !run.error && !hiddenError?.hasError && step.completionGuard !== false
810
+ ? evaluateCompletionMutationGuard({
811
+ agent: step.agent,
812
+ task: taskForCompletionGuard,
813
+ messages: run.messages,
814
+ tools: step.tools,
815
+ mcpDirectTools: step.mcpDirectTools,
816
+ })
817
+ : undefined;
818
+ const completionGuardTriggered = completionGuard?.triggered === true && !run.observedMutationAttempt;
819
+ const completionGuardError = completionGuardTriggered
820
+ ? "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes."
821
+ : undefined;
822
+ const effectiveExitCode = completionGuardTriggered
823
+ ? 1
824
+ : structuredError
825
+ ? 1
826
+ : hiddenError?.hasError
827
+ ? (hiddenError.exitCode ?? 1)
828
+ : run.error && run.exitCode === 0
829
+ ? 1
830
+ : run.exitCode;
831
+ const error = completionGuardError
832
+ ?? structuredError
833
+ ?? (hiddenError?.hasError
834
+ ? hiddenError.details
835
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
836
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
837
+ : run.error || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined));
838
+ const attempt: ModelAttempt = {
839
+ model: candidate ?? run.model ?? step.model ?? "default",
840
+ success: effectiveExitCode === 0 && !error,
841
+ exitCode: effectiveExitCode,
842
+ error,
843
+ usage: run.usage,
844
+ };
845
+ modelAttempts.push(attempt);
846
+ if (candidate) attemptedModels.push(candidate);
847
+ completionGuardTriggeredFinal = completionGuardTriggered;
848
+ finalOutputSnapshot = outputSnapshot;
849
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput } as RunPiStreamingResult & { structuredOutput?: unknown };
850
+ if (attempt.success || completionGuardTriggered) break;
851
+ if (!isRetryableModelFailure(error) || index === candidates.length - 1) break;
852
+ attemptNotes.push(formatModelAttemptNote(attempt, candidates[index + 1]));
853
+ }
854
+
855
+ const rawOutput = finalResult?.finalOutput ?? "";
856
+ const outputForPersistence = stripAcceptanceReport(rawOutput);
857
+ const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
858
+ ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)
859
+ : { fullOutput: outputForPersistence };
860
+ const output = resolvedOutput.fullOutput;
861
+ const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
862
+ let outputForSummary = output;
863
+ if (attemptNotes.length > 0) {
864
+ outputForSummary = `${attemptNotes.join("\n")}\n\n${outputForSummary}`.trim();
865
+ }
866
+ const outputForAcceptance = rawOutput;
867
+ const finalizedOutput = finalizeSingleOutput({
868
+ fullOutput: outputForSummary,
869
+ outputPath: step.outputPath,
870
+ outputMode: step.outputMode,
871
+ exitCode: finalResult?.exitCode ?? 1,
872
+ savedPath: resolvedOutput.savedPath,
873
+ outputReference,
874
+ saveError: resolvedOutput.saveError,
875
+ });
876
+ outputForSummary = finalizedOutput.displayOutput;
877
+ const acceptance = step.effectiveAcceptance
878
+ ? await evaluateAcceptance({
879
+ acceptance: step.effectiveAcceptance,
880
+ output: outputForAcceptance,
881
+ cwd: step.cwd ?? ctx.cwd,
882
+ })
883
+ : undefined;
884
+ const acceptanceFailure = acceptance ? acceptanceFailureMessage(acceptance) : undefined;
885
+ const acceptanceCanFailRun = acceptanceFailure && acceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted;
886
+ const effectiveFinalExitCode = acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
887
+ const effectiveFinalError = acceptanceCanFailRun
888
+ ? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
889
+ : finalResult?.error;
890
+
891
+ if (artifactPaths && ctx.artifactConfig?.enabled !== false) {
892
+ if (ctx.artifactConfig?.includeOutput !== false) {
893
+ fs.writeFileSync(artifactPaths.outputPath, output, "utf-8");
894
+ }
895
+ if (ctx.artifactConfig?.includeMetadata !== false) {
896
+ fs.writeFileSync(
897
+ artifactPaths.metadataPath,
898
+ JSON.stringify({
899
+ runId: ctx.id,
900
+ agent: step.agent,
901
+ task,
902
+ exitCode: effectiveFinalExitCode,
903
+ model: finalResult?.model,
904
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
905
+ modelAttempts,
906
+ skills: step.skills,
907
+ timestamp: Date.now(),
908
+ }, null, 2),
909
+ "utf-8",
910
+ );
911
+ }
912
+ }
913
+
914
+ return {
915
+ agent: step.agent,
916
+ output: outputForSummary,
917
+ exitCode: effectiveFinalExitCode,
918
+ error: effectiveFinalError,
919
+ sessionFile: step.sessionFile,
920
+ intercomTarget: ctx.childIntercomTarget,
921
+ model: finalResult?.model,
922
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
923
+ modelAttempts,
924
+ artifactPaths,
925
+ interrupted: finalResult?.interrupted,
926
+ completionGuardTriggered: completionGuardTriggeredFinal,
927
+ structuredOutput: (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
928
+ structuredOutputPath: effectiveStructuredOutput?.outputPath,
929
+ structuredOutputSchemaPath: effectiveStructuredOutput?.schemaPath,
930
+ acceptance,
931
+ };
932
+ }
933
+
934
+ type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
935
+ exitCode?: number | null;
936
+ };
937
+
938
+ type RunnerStatusPayload = Omit<AsyncStatus, "steps" | "parallelGroups" | "pid" | "cwd" | "currentStep" | "chainStepCount" | "lastUpdate"> & {
939
+ pid: number;
940
+ cwd: string;
941
+ currentStep: number;
942
+ chainStepCount: number;
943
+ parallelGroups: AsyncParallelGroupStatus[];
944
+ steps: RunnerStatusStep[];
945
+ lastUpdate: number;
946
+ artifactsDir?: string;
947
+ shareUrl?: string;
948
+ gistUrl?: string;
949
+ shareError?: string;
950
+ error?: string;
951
+ };
952
+
953
+ function markParallelGroupSetupFailure(input: {
954
+ statusPayload: RunnerStatusPayload;
955
+ results: StepResult[];
956
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
957
+ groupStartFlatIndex: number;
958
+ setupError: string;
959
+ failedAt: number;
960
+ statusPath: string;
961
+ eventsPath: string;
962
+ asyncDir: string;
963
+ runId: string;
964
+ stepIndex: number;
965
+ }): void {
966
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
967
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
968
+ input.statusPayload.steps[flatTaskIndex].status = "failed";
969
+ input.statusPayload.steps[flatTaskIndex].startedAt = input.failedAt;
970
+ input.statusPayload.steps[flatTaskIndex].endedAt = input.failedAt;
971
+ input.statusPayload.steps[flatTaskIndex].durationMs = 0;
972
+ input.statusPayload.steps[flatTaskIndex].exitCode = 1;
973
+ input.results.push({ agent: input.group.parallel[taskIndex].agent, output: input.setupError, success: false, exitCode: 1, sessionFile: input.group.parallel[taskIndex].sessionFile });
974
+ }
975
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
976
+ input.statusPayload.lastUpdate = input.failedAt;
977
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
978
+ writeAtomicJson(input.statusPath, input.statusPayload);
979
+ appendJsonl(input.eventsPath, JSON.stringify({
980
+ type: "subagent.parallel.completed",
981
+ ts: input.failedAt,
982
+ runId: input.runId,
983
+ stepIndex: input.stepIndex,
984
+ success: false,
985
+ }));
986
+ }
987
+
988
+ function markParallelGroupRunning(input: {
989
+ statusPayload: RunnerStatusPayload;
990
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
991
+ groupStartFlatIndex: number;
992
+ groupStartTime: number;
993
+ statusPath: string;
994
+ eventsPath: string;
995
+ asyncDir: string;
996
+ runId: string;
997
+ stepIndex: number;
998
+ }): void {
999
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
1000
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
1001
+ input.statusPayload.steps[flatTaskIndex].status = "pending";
1002
+ input.statusPayload.steps[flatTaskIndex].startedAt = undefined;
1003
+ input.statusPayload.steps[flatTaskIndex].endedAt = undefined;
1004
+ input.statusPayload.steps[flatTaskIndex].durationMs = undefined;
1005
+ input.statusPayload.steps[flatTaskIndex].lastActivityAt = undefined;
1006
+ input.statusPayload.steps[flatTaskIndex].activityState = undefined;
1007
+ input.statusPayload.steps[flatTaskIndex].error = undefined;
1008
+ }
1009
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
1010
+ input.statusPayload.activityState = undefined;
1011
+ input.statusPayload.lastActivityAt = input.groupStartTime;
1012
+ input.statusPayload.lastUpdate = input.groupStartTime;
1013
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
1014
+ writeAtomicJson(input.statusPath, input.statusPayload);
1015
+ appendJsonl(input.eventsPath, JSON.stringify({
1016
+ type: "subagent.parallel.started",
1017
+ ts: input.groupStartTime,
1018
+ runId: input.runId,
1019
+ stepIndex: input.stepIndex,
1020
+ agents: input.group.parallel.map((task) => task.agent),
1021
+ count: input.group.parallel.length,
1022
+ }));
1023
+ }
1024
+
1025
+ function prepareParallelTaskRun(
1026
+ task: SubagentStep,
1027
+ cwd: string,
1028
+ worktreeSetup: WorktreeSetup | undefined,
1029
+ taskIndex: number,
1030
+ ): { taskForRun: SubagentStep; taskCwd: string } {
1031
+ if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
1032
+ return {
1033
+ taskForRun: { ...task, cwd: undefined },
1034
+ taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
1035
+ };
1036
+ }
1037
+
1038
+ function appendParallelWorktreeSummary(
1039
+ previousOutput: string,
1040
+ worktreeSetup: WorktreeSetup | undefined,
1041
+ asyncDir: string,
1042
+ stepIndex: number,
1043
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>,
1044
+ ): string {
1045
+ if (!worktreeSetup) return previousOutput;
1046
+ const diffsDir = path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`);
1047
+ const diffs = diffWorktrees(worktreeSetup, group.parallel.map((task) => task.agent), diffsDir);
1048
+ const diffSummary = formatWorktreeDiffSummary(diffs);
1049
+ if (!diffSummary) return previousOutput;
1050
+ return `${previousOutput}\n\n${diffSummary}`;
1051
+ }
1052
+
1053
+ function ensureParallelProgressFile(cwd: string, group: Extract<RunnerStep, { parallel: SubagentStep[] }>): void {
1054
+ const progressPath = path.join(cwd, "progress.md");
1055
+ if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`))) return;
1056
+ writeInitialProgressFile(cwd);
1057
+ }
1058
+
1059
+ async function runSubagent(config: SubagentRunConfig): Promise<void> {
1060
+ const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
1061
+ config;
1062
+ let previousOutput = "";
1063
+ const outputs: ChainOutputMap = {};
1064
+ const results: StepResult[] = [];
1065
+ const overallStartTime = Date.now();
1066
+ const shareEnabled = config.share === true;
1067
+ const asyncDir = config.asyncDir;
1068
+ const statusPath = path.join(asyncDir, "status.json");
1069
+ const eventsPath = path.join(asyncDir, "events.jsonl");
1070
+ const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
1071
+ const controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;
1072
+ let activeChildInterrupt: (() => void) | undefined;
1073
+ let interrupted = false;
1074
+ let currentActivityState: ActivityState | undefined;
1075
+ let activityTimer: NodeJS.Timeout | undefined;
1076
+ let previousCumulativeTokens: TokenUsage = { input: 0, output: 0, total: 0 };
1077
+ let latestSessionFile: string | undefined;
1078
+
1079
+ const parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];
1080
+ const initialStatusSteps: RunnerStatusStep[] = [];
1081
+ let flatStepCount = 0;
1082
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
1083
+ const step = steps[stepIndex]!;
1084
+ if (isParallelGroup(step)) {
1085
+ parallelGroups.push({ start: flatStepCount, count: step.parallel.length, stepIndex });
1086
+ for (const task of step.parallel) {
1087
+ initialStatusSteps.push({
1088
+ agent: task.agent,
1089
+ phase: task.phase,
1090
+ label: task.label,
1091
+ outputName: task.outputName,
1092
+ structured: task.structured,
1093
+ status: "pending",
1094
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
1095
+ skills: task.skills,
1096
+ model: task.model,
1097
+ thinking: task.thinking,
1098
+ attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
1099
+ recentTools: [],
1100
+ recentOutput: [],
1101
+ });
1102
+ }
1103
+ flatStepCount += step.parallel.length;
1104
+ } else if (isDynamicRunnerGroup(step)) {
1105
+ parallelGroups.push({ start: flatStepCount, count: 1, stepIndex });
1106
+ initialStatusSteps.push({
1107
+ agent: `expand:${step.parallel.agent}`,
1108
+ phase: step.phase ?? step.parallel.phase,
1109
+ label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
1110
+ outputName: step.collect.as,
1111
+ structured: Boolean(step.collect.outputSchema),
1112
+ status: "pending",
1113
+ recentTools: [],
1114
+ recentOutput: [],
1115
+ });
1116
+ flatStepCount++;
1117
+ } else {
1118
+ initialStatusSteps.push({
1119
+ agent: step.agent,
1120
+ phase: step.phase,
1121
+ label: step.label,
1122
+ outputName: step.outputName,
1123
+ structured: step.structured,
1124
+ status: "pending",
1125
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1126
+ skills: step.skills,
1127
+ model: step.model,
1128
+ thinking: step.thinking,
1129
+ attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
1130
+ recentTools: [],
1131
+ recentOutput: [],
1132
+ });
1133
+ flatStepCount++;
1134
+ }
1135
+ }
1136
+ const flatSteps = flattenSteps(steps);
1137
+ const sessionEnabled = Boolean(config.sessionDir)
1138
+ || shareEnabled
1139
+ || flatSteps.some((step) => Boolean(step.sessionFile));
1140
+ const statusPayload: RunnerStatusPayload = {
1141
+ runId: id,
1142
+ ...(config.sessionId ? { sessionId: config.sessionId } : {}),
1143
+ mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
1144
+ state: "running",
1145
+ lastActivityAt: overallStartTime,
1146
+ startedAt: overallStartTime,
1147
+ lastUpdate: overallStartTime,
1148
+ pid: process.pid,
1149
+ cwd,
1150
+ currentStep: 0,
1151
+ chainStepCount: steps.length,
1152
+ parallelGroups,
1153
+ workflowGraph: config.workflowGraph,
1154
+ steps: initialStatusSteps,
1155
+ artifactsDir,
1156
+ sessionDir: config.sessionDir,
1157
+ outputFile: path.join(asyncDir, "output-0.log"),
1158
+ };
1159
+
1160
+ fs.mkdirSync(asyncDir, { recursive: true });
1161
+ writeAtomicJson(statusPath, statusPayload);
1162
+ const emitNestedSelfEvent = (type: "subagent.nested.updated" | "subagent.nested.completed"): void => {
1163
+ if (!config.nestedRoute || !config.nestedSelf) return;
1164
+ try {
1165
+ writeNestedEvent(config.nestedRoute, {
1166
+ type,
1167
+ ts: Date.now(),
1168
+ parentRunId: config.nestedSelf.parentRunId,
1169
+ parentStepIndex: config.nestedSelf.parentStepIndex,
1170
+ child: nestedSummaryFromAsyncStatus(statusPayload, asyncDir, {
1171
+ id,
1172
+ parentRunId: config.nestedSelf.parentRunId,
1173
+ parentStepIndex: config.nestedSelf.parentStepIndex,
1174
+ depth: config.nestedSelf.depth,
1175
+ path: config.nestedSelf.path,
1176
+ mode: statusPayload.mode,
1177
+ ts: Date.now(),
1178
+ }),
1179
+ });
1180
+ } catch (error) {
1181
+ console.error("Failed to emit nested async status event:", error);
1182
+ }
1183
+ };
1184
+ const refreshWorkflowGraph = (): void => {
1185
+ if (!config.workflowGraph) return;
1186
+ const graph = structuredClone(statusPayload.workflowGraph ?? config.workflowGraph);
1187
+ const normalize = (status: RunnerStatusStep["status"]): "pending" | "running" | "completed" | "failed" | "paused" | "detached" => {
1188
+ if (status === "complete" || status === "completed") return "completed";
1189
+ if (status === "running" || status === "failed" || status === "paused" || status === "pending") return status;
1190
+ return "pending";
1191
+ };
1192
+ const updateNode = (node: NonNullable<typeof graph.nodes>[number]): void => {
1193
+ if (node.flatIndex !== undefined) {
1194
+ const step = statusPayload.steps[node.flatIndex];
1195
+ if (step) {
1196
+ node.status = normalize(step.status);
1197
+ node.error = step.error;
1198
+ node.acceptanceStatus = step.acceptance?.status;
1199
+ }
1200
+ if (statusPayload.currentStep === node.flatIndex) graph.currentNodeId = node.id;
1201
+ }
1202
+ for (const child of node.children ?? []) updateNode(child);
1203
+ if (node.children?.length) {
1204
+ if (node.children.every((child) => child.status === "completed")) node.status = "completed";
1205
+ else if (node.children.some((child) => child.status === "running")) node.status = "running";
1206
+ else if (node.children.some((child) => child.status === "failed")) node.status = "failed";
1207
+ else if (node.children.some((child) => child.status === "paused")) node.status = "paused";
1208
+ }
1209
+ if (node.error) node.status = "failed";
1210
+ };
1211
+ for (const node of graph.nodes) updateNode(node);
1212
+ statusPayload.workflowGraph = graph;
1213
+ };
1214
+ const writeStatusPayload = (): void => {
1215
+ refreshWorkflowGraph();
1216
+ writeAtomicJson(statusPath, statusPayload);
1217
+ emitNestedSelfEvent(statusPayload.state === "running" || statusPayload.state === "queued" ? "subagent.nested.updated" : "subagent.nested.completed");
1218
+ };
1219
+ const consumePendingAppendRequests = (): void => {
1220
+ if (statusPayload.mode !== "chain" || statusPayload.state !== "running") return;
1221
+ const requests = consumeChainAppendRequests(asyncDir);
1222
+ if (requests.length === 0) {
1223
+ const pendingAppends = countPendingChainAppendRequests(asyncDir);
1224
+ if ((statusPayload.pendingAppends ?? 0) !== pendingAppends) {
1225
+ statusPayload.pendingAppends = pendingAppends;
1226
+ statusPayload.lastUpdate = Date.now();
1227
+ writeStatusPayload();
1228
+ }
1229
+ return;
1230
+ }
1231
+ const appendedSteps = requests.flatMap((request) => request.steps);
1232
+ steps.push(...appendedSteps);
1233
+ const now = Date.now();
1234
+ const pendingAppends = countPendingChainAppendRequests(asyncDir);
1235
+ const added = appendRunnerStepsToStatus({
1236
+ status: statusPayload,
1237
+ steps: appendedSteps,
1238
+ now,
1239
+ pendingAppends,
1240
+ });
1241
+ mutatingFailureStates.push(...Array.from({ length: added.addedFlatSteps }, () => createMutatingFailureState()));
1242
+ pendingToolResults.push(...Array.from({ length: added.addedFlatSteps }, () => undefined));
1243
+ if (config.childIntercomTargets) {
1244
+ config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => resolveSubagentIntercomTarget(id, statusStep.agent, index));
1245
+ }
1246
+ writeStatusPayload();
1247
+ for (const request of requests) {
1248
+ appendJsonl(eventsPath, JSON.stringify({
1249
+ type: "subagent.chain.append.accepted",
1250
+ ts: now,
1251
+ runId: id,
1252
+ requestId: request.id,
1253
+ stepCount: request.steps.length,
1254
+ pendingAppends,
1255
+ }));
1256
+ }
1257
+ };
1258
+ const markDynamicGraphGroup = (stepIndex: number, status: "completed" | "failed" | "running", error?: string, acceptance?: import("../../shared/types.ts").AcceptanceLedger): void => {
1259
+ const groupNode = statusPayload.workflowGraph?.nodes.find((node) => node.id === `step-${stepIndex}`);
1260
+ if (!groupNode) return;
1261
+ groupNode.status = status;
1262
+ groupNode.error = error;
1263
+ groupNode.acceptanceStatus = acceptance?.status ?? groupNode.acceptanceStatus;
1264
+ };
1265
+
1266
+ const stepOutputActivityAt = (index: number): number => {
1267
+ const step = statusPayload.steps[index];
1268
+ let lastActivityAt = step?.lastActivityAt ?? step?.startedAt ?? overallStartTime;
1269
+ const outputPath = path.join(asyncDir, `output-${index}.log`);
1270
+ try {
1271
+ lastActivityAt = Math.max(lastActivityAt, fs.statSync(outputPath).mtimeMs);
1272
+ } catch (error) {
1273
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
1274
+ console.error(`Failed to inspect async output file '${outputPath}':`, error);
1275
+ }
1276
+ }
1277
+ return lastActivityAt;
1278
+ };
1279
+ const emittedControlEventKeys = new Set<string>();
1280
+ const activeLongRunningSteps = new Set<number>();
1281
+ const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
1282
+ const pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> = initialStatusSteps.map(() => undefined);
1283
+ const mutatingFailureWindowMs = 5 * 60_000;
1284
+ const appendControlEvent = (event: ReturnType<typeof buildControlEvent>) => {
1285
+ if (!controlConfig.enabled) return;
1286
+ const childIntercomTarget = config.childIntercomTargets?.[event.index ?? statusPayload.currentStep];
1287
+ const channels = event.type === "active_long_running"
1288
+ ? controlConfig.notifyChannels.filter((channel) => channel !== "intercom")
1289
+ : controlConfig.notifyChannels;
1290
+ if (channels.length === 0 || !claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget)) return;
1291
+ appendJsonl(eventsPath, JSON.stringify({
1292
+ type: "subagent.control",
1293
+ event,
1294
+ channels,
1295
+ childIntercomTarget,
1296
+ noticeText: formatControlNoticeMessage(event, childIntercomTarget),
1297
+ ...(config.controlIntercomTarget && channels.includes("intercom") ? {
1298
+ intercom: {
1299
+ to: config.controlIntercomTarget,
1300
+ message: formatControlIntercomMessage(event, childIntercomTarget),
1301
+ },
1302
+ } : {}),
1303
+ }));
1304
+ };
1305
+ const syncTopLevelCurrentTool = (): void => {
1306
+ const activeStep = statusPayload.steps
1307
+ .filter((step) => step.status === "running" && typeof step.currentTool === "string" && step.currentTool.length > 0)
1308
+ .sort((left, right) => (right.currentToolStartedAt ?? 0) - (left.currentToolStartedAt ?? 0))[0];
1309
+ statusPayload.currentTool = activeStep?.currentTool;
1310
+ statusPayload.currentToolStartedAt = activeStep?.currentToolStartedAt;
1311
+ statusPayload.currentPath = activeStep?.currentPath;
1312
+ };
1313
+ const maybeEmitActiveLongRunning = (flatIndex: number, now: number): boolean => {
1314
+ if (!controlConfig.enabled || activeLongRunningSteps.has(flatIndex)) return false;
1315
+ const step = statusPayload.steps[flatIndex];
1316
+ if (!step || step.status !== "running" || step.activityState === "needs_attention") return false;
1317
+ const reason = nextLongRunningTrigger(controlConfig, {
1318
+ startedAt: step.startedAt ?? overallStartTime,
1319
+ now,
1320
+ turns: step.turnCount ?? 0,
1321
+ tokens: step.tokens?.total ?? 0,
1322
+ });
1323
+ if (!reason) return false;
1324
+ activeLongRunningSteps.add(flatIndex);
1325
+ const previous = step.activityState;
1326
+ step.activityState = "active_long_running";
1327
+ statusPayload.activityState = statusPayload.activityState === "needs_attention" ? "needs_attention" : "active_long_running";
1328
+ const event = buildControlEvent({
1329
+ type: "active_long_running",
1330
+ from: previous,
1331
+ to: "active_long_running",
1332
+ runId: id,
1333
+ agent: step.agent,
1334
+ index: flatIndex,
1335
+ ts: now,
1336
+ message: `${step.agent} is still active but long-running`,
1337
+ reason,
1338
+ turns: step.turnCount,
1339
+ tokens: step.tokens?.total,
1340
+ toolCount: step.toolCount,
1341
+ currentTool: step.currentTool,
1342
+ currentToolDurationMs: step.currentToolStartedAt ? Math.max(0, now - step.currentToolStartedAt) : undefined,
1343
+ currentPath: step.currentPath,
1344
+ elapsedMs: now - (step.startedAt ?? overallStartTime),
1345
+ });
1346
+ appendControlEvent(event);
1347
+ return true;
1348
+ };
1349
+ const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, now = Date.now()): void => {
1350
+ const step = statusPayload.steps[flatIndex];
1351
+ if (!step) return;
1352
+ step.model = model;
1353
+ step.thinking = thinking;
1354
+ statusPayload.lastUpdate = now;
1355
+ writeStatusPayload();
1356
+ };
1357
+ const updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {
1358
+ const step = statusPayload.steps[flatIndex];
1359
+ if (!step) return;
1360
+ const now = Date.now();
1361
+ statusPayload.currentStep = flatIndex;
1362
+ if (event.type === "tool_execution_start" && event.toolName) {
1363
+ const mutates = isMutatingTool(event.toolName, event.args);
1364
+ const currentPath = resolveCurrentPath(event.toolName, event.args);
1365
+ step.toolCount = (step.toolCount ?? 0) + 1;
1366
+ step.currentTool = event.toolName;
1367
+ step.currentToolArgs = extractToolArgsPreview(event.args ?? {});
1368
+ step.currentToolStartedAt = now;
1369
+ step.currentPath = currentPath;
1370
+ pendingToolResults[flatIndex] = { tool: event.toolName, path: currentPath, mutates, startedAt: now };
1371
+ statusPayload.toolCount = (statusPayload.toolCount ?? 0) + 1;
1372
+ syncTopLevelCurrentTool();
1373
+ } else if (event.type === "tool_execution_end") {
1374
+ if (step.currentTool) {
1375
+ step.recentTools ??= [];
1376
+ step.recentTools.push({ tool: step.currentTool, args: step.currentToolArgs || "", endMs: now });
1377
+ }
1378
+ step.currentTool = undefined;
1379
+ step.currentToolArgs = undefined;
1380
+ step.currentToolStartedAt = undefined;
1381
+ step.currentPath = undefined;
1382
+ syncTopLevelCurrentTool();
1383
+ } else if (event.type === "tool_result_end" && event.message) {
1384
+ const toolSnapshot = pendingToolResults[flatIndex];
1385
+ pendingToolResults[flatIndex] = undefined;
1386
+ const resultText = extractTextFromContent(event.message.content);
1387
+ appendRecentStepOutput(step, resultText.split("\n").slice(-10));
1388
+ if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
1389
+ const state = mutatingFailureStates[flatIndex]!;
1390
+ recordMutatingFailure(state, {
1391
+ tool: toolSnapshot.tool,
1392
+ path: toolSnapshot.path,
1393
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1394
+ ts: now,
1395
+ }, mutatingFailureWindowMs);
1396
+ if (controlConfig.enabled && shouldEscalateMutatingFailures(state, controlConfig.failedToolAttemptsBeforeAttention) && step.activityState !== "needs_attention") {
1397
+ const previous = step.activityState;
1398
+ step.activityState = "needs_attention";
1399
+ statusPayload.activityState = "needs_attention";
1400
+ appendControlEvent(buildControlEvent({
1401
+ type: "needs_attention",
1402
+ from: previous,
1403
+ to: "needs_attention",
1404
+ runId: id,
1405
+ agent: step.agent,
1406
+ index: flatIndex,
1407
+ ts: now,
1408
+ message: `${step.agent} needs attention after repeated mutating tool failures`,
1409
+ reason: "tool_failures",
1410
+ turns: step.turnCount,
1411
+ tokens: step.tokens?.total,
1412
+ toolCount: step.toolCount,
1413
+ currentTool: toolSnapshot.tool,
1414
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1415
+ currentPath: toolSnapshot.path,
1416
+ recentFailureSummary: summarizeRecentMutatingFailures(state),
1417
+ }));
1418
+ }
1419
+ } else if (toolSnapshot?.mutates) {
1420
+ resetMutatingFailureState(mutatingFailureStates[flatIndex]!);
1421
+ }
1422
+ } else if (event.type === "message_end" && event.message?.role === "assistant") {
1423
+ appendRecentStepOutput(step, stripAcceptanceReport(extractTextFromContent(event.message.content)).split("\n").slice(-10));
1424
+ step.turnCount = (step.turnCount ?? 0) + 1;
1425
+ const usage = event.message.usage;
1426
+ if (usage) {
1427
+ const input = usage.input ?? usage.inputTokens ?? 0;
1428
+ const output = usage.output ?? usage.outputTokens ?? 0;
1429
+ const previousInput = step.tokens?.input ?? 0;
1430
+ const previousOutput = step.tokens?.output ?? 0;
1431
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
1432
+ const totalInput = statusPayload.totalTokens?.input ?? 0;
1433
+ const totalOutput = statusPayload.totalTokens?.output ?? 0;
1434
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
1435
+ }
1436
+ statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
1437
+ }
1438
+ syncTopLevelCurrentTool();
1439
+ step.lastActivityAt = now;
1440
+ statusPayload.lastActivityAt = now;
1441
+ statusPayload.lastUpdate = now;
1442
+ maybeEmitActiveLongRunning(flatIndex, now);
1443
+ writeStatusPayload();
1444
+ };
1445
+ const updateRunnerActivityState = (now: number): boolean => {
1446
+ if (!controlConfig.enabled) return false;
1447
+ let changed = false;
1448
+ let runLastActivityAt = statusPayload.lastActivityAt ?? overallStartTime;
1449
+ for (let index = 0; index < statusPayload.steps.length; index++) {
1450
+ const step = statusPayload.steps[index]!;
1451
+ if (step.status !== "running") continue;
1452
+ const lastActivityAt = stepOutputActivityAt(index);
1453
+ runLastActivityAt = Math.max(runLastActivityAt, lastActivityAt);
1454
+ if (step.lastActivityAt !== lastActivityAt) {
1455
+ step.lastActivityAt = lastActivityAt;
1456
+ changed = true;
1457
+ }
1458
+ const idleState = deriveActivityState({
1459
+ config: controlConfig,
1460
+ startedAt: step.startedAt ?? overallStartTime,
1461
+ lastActivityAt,
1462
+ now,
1463
+ });
1464
+ if (idleState === "needs_attention") {
1465
+ const previous = step.activityState;
1466
+ step.activityState = "needs_attention";
1467
+ if (previous !== "needs_attention") {
1468
+ appendControlEvent(buildControlEvent({
1469
+ from: previous,
1470
+ to: "needs_attention",
1471
+ runId: id,
1472
+ agent: step.agent,
1473
+ index,
1474
+ ts: now,
1475
+ lastActivityAt,
1476
+ }));
1477
+ changed = true;
1478
+ }
1479
+ } else if (maybeEmitActiveLongRunning(index, now)) {
1480
+ changed = true;
1481
+ }
1482
+ }
1483
+ if (statusPayload.lastActivityAt !== runLastActivityAt) {
1484
+ statusPayload.lastActivityAt = runLastActivityAt;
1485
+ changed = true;
1486
+ }
1487
+ const nextRunState = statusPayload.steps.some((step) => step.activityState === "needs_attention")
1488
+ ? "needs_attention"
1489
+ : statusPayload.steps.some((step) => step.activityState === "active_long_running")
1490
+ ? "active_long_running"
1491
+ : undefined;
1492
+ if (nextRunState !== currentActivityState) {
1493
+ currentActivityState = nextRunState;
1494
+ statusPayload.activityState = nextRunState;
1495
+ changed = true;
1496
+ }
1497
+ statusPayload.lastUpdate = now;
1498
+ if (changed) writeStatusPayload();
1499
+ return changed;
1500
+ };
1501
+ if (controlConfig.enabled) {
1502
+ activityTimer = setInterval(() => {
1503
+ if (statusPayload.state !== "running") return;
1504
+ const now = Date.now();
1505
+ updateRunnerActivityState(now);
1506
+ }, 1000);
1507
+ activityTimer.unref?.();
1508
+ }
1509
+
1510
+ const interruptRunner = () => {
1511
+ consumeInterruptRequest(asyncDir);
1512
+ if (interrupted || statusPayload.state !== "running") return;
1513
+ interrupted = true;
1514
+ const now = Date.now();
1515
+ statusPayload.state = "paused";
1516
+ currentActivityState = undefined;
1517
+ statusPayload.activityState = undefined;
1518
+ statusPayload.lastUpdate = now;
1519
+ for (const step of statusPayload.steps) {
1520
+ if (step.status === "running") {
1521
+ step.status = "paused";
1522
+ step.activityState = undefined;
1523
+ step.endedAt = now;
1524
+ step.durationMs = step.startedAt ? now - step.startedAt : undefined;
1525
+ step.lastActivityAt = now;
1526
+ }
1527
+ }
1528
+ writeStatusPayload();
1529
+ appendJsonl(eventsPath, JSON.stringify({
1530
+ type: "subagent.run.paused",
1531
+ ts: now,
1532
+ runId: id,
1533
+ }));
1534
+ activeChildInterrupt?.();
1535
+ };
1536
+ process.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
1537
+ // Portable control inbox: the parent drops an interrupt request file here when
1538
+ // it cannot deliver the OS signal (e.g. ENOSYS on Windows). Routes into the
1539
+ // same graceful interruptRunner() so stop/steer work on every platform.
1540
+ const disposeControlInbox = watchAsyncControlInbox(asyncDir, { onInterrupt: interruptRunner });
1541
+ appendJsonl(
1542
+ eventsPath,
1543
+ JSON.stringify({
1544
+ type: "subagent.run.started",
1545
+ ts: overallStartTime,
1546
+ runId: id,
1547
+ mode: statusPayload.mode,
1548
+ cwd,
1549
+ pid: process.pid,
1550
+ }),
1551
+ );
1552
+
1553
+ let flatIndex = 0;
1554
+ let stepCursor = 0;
1555
+
1556
+ while (true) {
1557
+ if (interrupted) break;
1558
+ consumePendingAppendRequests();
1559
+ if (stepCursor >= steps.length) break;
1560
+ const stepIndex = stepCursor++;
1561
+ const step = steps[stepIndex]!;
1562
+
1563
+ if (isDynamicRunnerGroup(step)) {
1564
+ const groupStartFlatIndex = flatIndex;
1565
+ let materialized: ReturnType<typeof materializeDynamicParallelStep>;
1566
+ try {
1567
+ materialized = materializeDynamicParallelStep(step as Parameters<typeof materializeDynamicParallelStep>[0], outputs, stepIndex, { maxItems: config.dynamicFanoutMaxItems, allowRunnerFields: true });
1568
+ if (materialized.collectedOnEmpty) validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);
1569
+ } catch (error) {
1570
+ const now = Date.now();
1571
+ const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1572
+ statusPayload.state = "failed";
1573
+ statusPayload.error = message;
1574
+ statusPayload.currentStep = flatIndex;
1575
+ const placeholder = statusPayload.steps[groupStartFlatIndex];
1576
+ if (placeholder) {
1577
+ placeholder.status = "failed";
1578
+ placeholder.error = message;
1579
+ placeholder.startedAt = now;
1580
+ placeholder.endedAt = now;
1581
+ placeholder.durationMs = 0;
1582
+ placeholder.exitCode = 1;
1583
+ }
1584
+ statusPayload.lastUpdate = now;
1585
+ markDynamicGraphGroup(stepIndex, "failed", message);
1586
+ writeStatusPayload();
1587
+ results.push({ agent: step.parallel.agent, output: message, error: message, success: false, exitCode: 1 });
1588
+ break;
1589
+ }
1590
+
1591
+ if (materialized.parallel.length === 0) {
1592
+ const now = Date.now();
1593
+ const collection = materialized.collectedOnEmpty ?? [];
1594
+ outputs[step.collect.as] = {
1595
+ text: JSON.stringify(collection),
1596
+ structured: collection,
1597
+ agent: step.parallel.agent,
1598
+ stepIndex,
1599
+ };
1600
+ statusPayload.outputs = outputs;
1601
+ const placeholder = statusPayload.steps[groupStartFlatIndex];
1602
+ if (placeholder) {
1603
+ placeholder.status = "complete";
1604
+ placeholder.startedAt = now;
1605
+ placeholder.endedAt = now;
1606
+ placeholder.durationMs = 0;
1607
+ }
1608
+ previousOutput = "Dynamic fanout produced 0 results.";
1609
+ const groupAcceptance = step.effectiveAcceptance?.explicit
1610
+ ? await evaluateAcceptance({
1611
+ acceptance: step.effectiveAcceptance,
1612
+ output: "",
1613
+ report: aggregateAcceptanceReport({
1614
+ results: [],
1615
+ notes: "Dynamic fanout produced 0 results.",
1616
+ }),
1617
+ cwd,
1618
+ })
1619
+ : undefined;
1620
+ if (placeholder && groupAcceptance) placeholder.acceptance = groupAcceptance;
1621
+ const groupAcceptanceFailure = groupAcceptance ? acceptanceFailureMessage(groupAcceptance) : undefined;
1622
+ if (groupAcceptanceFailure) {
1623
+ statusPayload.state = "failed";
1624
+ statusPayload.error = groupAcceptanceFailure;
1625
+ if (placeholder) {
1626
+ placeholder.status = "failed";
1627
+ placeholder.error = groupAcceptanceFailure;
1628
+ placeholder.exitCode = 1;
1629
+ }
1630
+ markDynamicGraphGroup(stepIndex, "failed", groupAcceptanceFailure, groupAcceptance);
1631
+ statusPayload.lastUpdate = now;
1632
+ writeStatusPayload();
1633
+ results.push({ agent: step.parallel.agent, output: groupAcceptanceFailure, error: groupAcceptanceFailure, success: false, exitCode: 1, acceptance: groupAcceptance });
1634
+ break;
1635
+ }
1636
+ flatIndex++;
1637
+ statusPayload.lastUpdate = now;
1638
+ markDynamicGraphGroup(stepIndex, "completed", undefined, groupAcceptance);
1639
+ writeStatusPayload();
1640
+ continue;
1641
+ }
1642
+
1643
+ const dynamicSteps = materialized.parallel.map((task, itemIndex) => ({
1644
+ ...step.parallel,
1645
+ task: task.task ?? step.parallel.task,
1646
+ label: task.label ?? step.parallel.label,
1647
+ structuredOutput: undefined,
1648
+ structuredOutputSchema: step.parallel.structuredOutputSchema ?? step.parallel.structuredOutput?.schema,
1649
+ }));
1650
+ const dynamicStatusSteps: RunnerStatusStep[] = dynamicSteps.map((task) => ({
1651
+ agent: task.agent,
1652
+ phase: task.phase ?? step.phase,
1653
+ label: task.label,
1654
+ outputName: undefined,
1655
+ structured: Boolean(task.structuredOutputSchema),
1656
+ status: "pending",
1657
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
1658
+ skills: task.skills,
1659
+ model: task.model,
1660
+ thinking: task.thinking,
1661
+ attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
1662
+ recentTools: [],
1663
+ recentOutput: [],
1664
+ }));
1665
+ statusPayload.steps.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps);
1666
+ if (config.childIntercomTargets) {
1667
+ config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => resolveSubagentIntercomTarget(id, statusStep.agent, index));
1668
+ }
1669
+ mutatingFailureStates.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => createMutatingFailureState()));
1670
+ pendingToolResults.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => undefined));
1671
+ const materializedDelta = dynamicStatusSteps.length - 1;
1672
+ for (const group of statusPayload.parallelGroups) {
1673
+ if (group.stepIndex === stepIndex) {
1674
+ group.start = groupStartFlatIndex;
1675
+ group.count = dynamicStatusSteps.length;
1676
+ } else if (group.start > groupStartFlatIndex) {
1677
+ group.start += materializedDelta;
1678
+ }
1679
+ }
1680
+ if (statusPayload.workflowGraph) {
1681
+ const shiftFlatIndexes = (nodes: NonNullable<typeof statusPayload.workflowGraph>["nodes"]): void => {
1682
+ for (const node of nodes) {
1683
+ if (node.stepIndex !== undefined && node.stepIndex > stepIndex && node.flatIndex !== undefined && node.flatIndex >= groupStartFlatIndex) {
1684
+ node.flatIndex += dynamicStatusSteps.length;
1685
+ }
1686
+ if (node.children) shiftFlatIndexes(node.children);
1687
+ }
1688
+ };
1689
+ shiftFlatIndexes(statusPayload.workflowGraph.nodes);
1690
+ const groupNode = statusPayload.workflowGraph.nodes.find((node) => node.id === `step-${stepIndex}`);
1691
+ if (groupNode) {
1692
+ groupNode.children = materialized.items.map((item, itemIndex) => ({
1693
+ id: `step-${stepIndex}-item-${item.idKey}`,
1694
+ kind: "agent",
1695
+ agent: step.parallel.agent,
1696
+ phase: dynamicSteps[itemIndex]?.phase ?? step.phase,
1697
+ label: dynamicSteps[itemIndex]?.label?.trim() || `${step.parallel.agent} ${item.key}`,
1698
+ status: "pending",
1699
+ flatIndex: groupStartFlatIndex + itemIndex,
1700
+ stepIndex,
1701
+ itemKey: item.key,
1702
+ structured: Boolean(dynamicSteps[itemIndex]?.structuredOutputSchema),
1703
+ }));
1704
+ }
1705
+ }
1706
+ writeStatusPayload();
1707
+
1708
+ const concurrency = step.concurrency ?? MAX_PARALLEL_CONCURRENCY;
1709
+ const failFast = step.failFast ?? false;
1710
+ let aborted = false;
1711
+ const parallelResults = await mapConcurrent(dynamicSteps, concurrency, async (task, taskIdx) => {
1712
+ const fi = groupStartFlatIndex + taskIdx;
1713
+ if (aborted && failFast) {
1714
+ const skippedAt = Date.now();
1715
+ statusPayload.steps[fi].status = "failed";
1716
+ statusPayload.steps[fi].error = "Skipped due to fail-fast";
1717
+ statusPayload.steps[fi].startedAt = skippedAt;
1718
+ statusPayload.steps[fi].endedAt = skippedAt;
1719
+ statusPayload.steps[fi].durationMs = 0;
1720
+ statusPayload.steps[fi].exitCode = -1;
1721
+ statusPayload.lastUpdate = skippedAt;
1722
+ writeStatusPayload();
1723
+ return { agent: task.agent, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true };
1724
+ }
1725
+ const taskStartTime = Date.now();
1726
+ statusPayload.currentStep = fi;
1727
+ statusPayload.steps[fi].status = "running";
1728
+ statusPayload.steps[fi].error = undefined;
1729
+ statusPayload.steps[fi].activityState = undefined;
1730
+ resetStepLiveDetail(statusPayload.steps[fi]);
1731
+ statusPayload.steps[fi].startedAt = taskStartTime;
1732
+ statusPayload.steps[fi].lastActivityAt = taskStartTime;
1733
+ statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
1734
+ statusPayload.lastActivityAt = taskStartTime;
1735
+ statusPayload.lastUpdate = taskStartTime;
1736
+ writeStatusPayload();
1737
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent }));
1738
+ const singleResult = await runSingleStep(task, {
1739
+ previousOutput, placeholder, cwd, sessionEnabled,
1740
+ outputs,
1741
+ sessionDir: config.sessionDir ? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`) : undefined,
1742
+ artifactsDir, artifactConfig, id,
1743
+ flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
1744
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
1745
+ piPackageRoot: config.piPackageRoot,
1746
+ piArgv1: config.piArgv1,
1747
+ childIntercomTarget: config.childIntercomTargets?.[fi],
1748
+ orchestratorIntercomTarget: config.controlIntercomTarget,
1749
+ nestedRoute: config.nestedRoute,
1750
+ registerInterrupt: (interrupt) => {
1751
+ activeChildInterrupt = interrupt;
1752
+ },
1753
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
1754
+ onChildEvent: (event) => updateStepFromChildEvent(fi, event),
1755
+ });
1756
+ const taskEndTime = Date.now();
1757
+ statusPayload.steps[fi].status = singleResult.exitCode === 0 ? "complete" : "failed";
1758
+ statusPayload.steps[fi].endedAt = taskEndTime;
1759
+ statusPayload.steps[fi].durationMs = taskEndTime - taskStartTime;
1760
+ statusPayload.steps[fi].exitCode = singleResult.exitCode;
1761
+ statusPayload.steps[fi].model = singleResult.model;
1762
+ statusPayload.steps[fi].thinking = resolveEffectiveThinking(singleResult.model, statusPayload.steps[fi].thinking);
1763
+ statusPayload.steps[fi].attemptedModels = singleResult.attemptedModels;
1764
+ statusPayload.steps[fi].modelAttempts = singleResult.modelAttempts;
1765
+ statusPayload.steps[fi].error = singleResult.error;
1766
+ statusPayload.steps[fi].structuredOutput = singleResult.structuredOutput;
1767
+ statusPayload.steps[fi].structuredOutputPath = singleResult.structuredOutputPath;
1768
+ statusPayload.steps[fi].structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
1769
+ statusPayload.steps[fi].acceptance = singleResult.acceptance;
1770
+ statusPayload.lastUpdate = taskEndTime;
1771
+ writeStatusPayload();
1772
+ appendJsonl(eventsPath, JSON.stringify({
1773
+ type: singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
1774
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
1775
+ exitCode: singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
1776
+ }));
1777
+ if (singleResult.exitCode !== 0 && failFast) aborted = true;
1778
+ return { ...singleResult, skipped: false };
1779
+ });
1780
+
1781
+ flatIndex += dynamicSteps.length;
1782
+ for (const pr of parallelResults) {
1783
+ results.push({
1784
+ agent: pr.agent,
1785
+ output: pr.output,
1786
+ error: pr.error,
1787
+ success: pr.exitCode === 0,
1788
+ exitCode: pr.exitCode,
1789
+ skipped: pr.skipped,
1790
+ sessionFile: pr.sessionFile,
1791
+ intercomTarget: pr.intercomTarget,
1792
+ model: pr.model,
1793
+ attemptedModels: pr.attemptedModels,
1794
+ modelAttempts: pr.modelAttempts,
1795
+ artifactPaths: pr.artifactPaths,
1796
+ structuredOutput: pr.structuredOutput,
1797
+ structuredOutputPath: pr.structuredOutputPath,
1798
+ structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
1799
+ acceptance: pr.acceptance,
1800
+ });
1801
+ }
1802
+ const collection = collectDynamicResults(step as Parameters<typeof collectDynamicResults>[0], materialized.items, parallelResults);
1803
+ const failures = parallelResults.filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
1804
+ if (failures.length === 0) {
1805
+ try {
1806
+ validateDynamicCollection(step.collect.outputSchema, collection);
1807
+ outputs[step.collect.as] = {
1808
+ text: JSON.stringify(collection),
1809
+ structured: collection,
1810
+ agent: step.parallel.agent,
1811
+ stepIndex,
1812
+ };
1813
+ statusPayload.outputs = outputs;
1814
+ const groupAcceptance = step.effectiveAcceptance
1815
+ ? await evaluateAcceptance({
1816
+ acceptance: step.effectiveAcceptance,
1817
+ output: "",
1818
+ report: aggregateAcceptanceReport({
1819
+ results: parallelResults,
1820
+ notes: `Dynamic fanout collected ${collection.length} result(s) into ${step.collect.as}.`,
1821
+ }),
1822
+ cwd,
1823
+ })
1824
+ : undefined;
1825
+ const groupAcceptanceFailure = groupAcceptance ? acceptanceFailureMessage(groupAcceptance) : undefined;
1826
+ markDynamicGraphGroup(stepIndex, groupAcceptanceFailure ? "failed" : "completed", groupAcceptanceFailure, groupAcceptance);
1827
+ if (groupAcceptanceFailure) {
1828
+ results.push({
1829
+ agent: step.parallel.agent,
1830
+ output: groupAcceptanceFailure,
1831
+ error: groupAcceptanceFailure,
1832
+ success: false,
1833
+ exitCode: 1,
1834
+ structuredOutput: collection,
1835
+ acceptance: groupAcceptance,
1836
+ });
1837
+ statusPayload.error = groupAcceptanceFailure;
1838
+ }
1839
+ } catch (error) {
1840
+ const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1841
+ results.push({ agent: step.parallel.agent, output: message, error: message, success: false, exitCode: 1, structuredOutput: collection });
1842
+ statusPayload.error = message;
1843
+ markDynamicGraphGroup(stepIndex, "failed", message);
1844
+ }
1845
+ }
1846
+ previousOutput = aggregateParallelOutputs(
1847
+ parallelResults.map((r, i) => ({
1848
+ agent: r.agent,
1849
+ taskIndex: i,
1850
+ output: r.output,
1851
+ exitCode: r.exitCode,
1852
+ error: r.error,
1853
+ })),
1854
+ (i, agent) => `=== Dynamic Item ${i + 1} (${agent}, key ${materialized.items[i]?.key ?? i}) ===`,
1855
+ );
1856
+ appendJsonl(eventsPath, JSON.stringify({
1857
+ type: "subagent.dynamic.completed",
1858
+ ts: Date.now(),
1859
+ runId: id,
1860
+ stepIndex,
1861
+ success: failures.length === 0,
1862
+ }));
1863
+ if (failures.length > 0) markDynamicGraphGroup(stepIndex, "failed", failures[0]?.error ?? "Dynamic fanout child failed.");
1864
+ statusPayload.lastUpdate = Date.now();
1865
+ writeStatusPayload();
1866
+ if (failures.length > 0 || statusPayload.error) break;
1867
+ continue;
1868
+ }
1869
+
1870
+ if (isParallelGroup(step)) {
1871
+ const group = step;
1872
+ const concurrency = group.concurrency ?? MAX_PARALLEL_CONCURRENCY;
1873
+ const failFast = group.failFast ?? false;
1874
+ const groupStartFlatIndex = flatIndex;
1875
+ let aborted = false;
1876
+ let worktreeSetup: WorktreeSetup | undefined;
1877
+ if (group.worktree) {
1878
+ const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, cwd);
1879
+ if (worktreeTaskCwdConflict) {
1880
+ const failedAt = Date.now();
1881
+ markParallelGroupSetupFailure({
1882
+ statusPayload,
1883
+ results,
1884
+ group,
1885
+ groupStartFlatIndex,
1886
+ setupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, cwd),
1887
+ failedAt,
1888
+ statusPath,
1889
+ eventsPath,
1890
+ asyncDir,
1891
+ runId: id,
1892
+ stepIndex,
1893
+ });
1894
+ flatIndex += group.parallel.length;
1895
+ break;
1896
+ }
1897
+ try {
1898
+ worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, {
1899
+ agents: group.parallel.map((task) => task.agent),
1900
+ setupHook: config.worktreeSetupHook
1901
+ ? { hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs }
1902
+ : undefined,
1903
+ });
1904
+ } catch (error) {
1905
+ const setupError = error instanceof Error ? error.message : String(error);
1906
+ const failedAt = Date.now();
1907
+ markParallelGroupSetupFailure({
1908
+ statusPayload,
1909
+ results,
1910
+ group,
1911
+ groupStartFlatIndex,
1912
+ setupError,
1913
+ failedAt,
1914
+ statusPath,
1915
+ eventsPath,
1916
+ asyncDir,
1917
+ runId: id,
1918
+ stepIndex,
1919
+ });
1920
+ flatIndex += group.parallel.length;
1921
+ break;
1922
+ }
1923
+ }
1924
+
1925
+ try {
1926
+ if (group.worktree) ensureParallelProgressFile(cwd, group);
1927
+ const groupStartTime = Date.now();
1928
+ markParallelGroupRunning({
1929
+ statusPayload,
1930
+ group,
1931
+ groupStartFlatIndex,
1932
+ groupStartTime,
1933
+ statusPath,
1934
+ eventsPath,
1935
+ asyncDir,
1936
+ runId: id,
1937
+ stepIndex,
1938
+ });
1939
+ const parallelResults = await mapConcurrent(
1940
+ group.parallel,
1941
+ concurrency,
1942
+ async (task, taskIdx) => {
1943
+ const fi = groupStartFlatIndex + taskIdx;
1944
+ if (aborted && failFast) {
1945
+ const skippedAt = Date.now();
1946
+ statusPayload.steps[fi].status = "failed";
1947
+ statusPayload.steps[fi].error = "Skipped due to fail-fast";
1948
+ statusPayload.steps[fi].startedAt = skippedAt;
1949
+ statusPayload.steps[fi].endedAt = skippedAt;
1950
+ statusPayload.steps[fi].durationMs = 0;
1951
+ statusPayload.steps[fi].exitCode = -1;
1952
+ statusPayload.steps[fi].activityState = undefined;
1953
+ statusPayload.lastUpdate = skippedAt;
1954
+ writeStatusPayload();
1955
+ appendJsonl(eventsPath, JSON.stringify({
1956
+ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: -1, durationMs: 0,
1957
+ }));
1958
+ return { agent: task.agent, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true };
1959
+ }
1960
+
1961
+ const taskStartTime = Date.now();
1962
+ statusPayload.currentStep = fi;
1963
+ statusPayload.steps[fi].status = "running";
1964
+ statusPayload.steps[fi].error = undefined;
1965
+ statusPayload.steps[fi].activityState = undefined;
1966
+ resetStepLiveDetail(statusPayload.steps[fi]);
1967
+ statusPayload.steps[fi].startedAt = taskStartTime;
1968
+ statusPayload.steps[fi].endedAt = undefined;
1969
+ statusPayload.steps[fi].durationMs = undefined;
1970
+ statusPayload.steps[fi].lastActivityAt = taskStartTime;
1971
+ statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
1972
+ statusPayload.lastActivityAt = taskStartTime;
1973
+ statusPayload.lastUpdate = taskStartTime;
1974
+ writeStatusPayload();
1975
+
1976
+ appendJsonl(eventsPath, JSON.stringify({
1977
+ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent,
1978
+ }));
1979
+
1980
+ const taskSessionDir = config.sessionDir
1981
+ ? path.join(config.sessionDir, `parallel-${taskIdx}`)
1982
+ : undefined;
1983
+ const { taskForRun, taskCwd } = prepareParallelTaskRun(task, cwd, worktreeSetup, taskIdx);
1984
+
1985
+ const singleResult = await runSingleStep(taskForRun, {
1986
+ previousOutput, placeholder, cwd: taskCwd, sessionEnabled,
1987
+ outputs,
1988
+ sessionDir: taskSessionDir,
1989
+ artifactsDir, artifactConfig, id,
1990
+ flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
1991
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
1992
+ piPackageRoot: config.piPackageRoot,
1993
+ piArgv1: config.piArgv1,
1994
+ childIntercomTarget: config.childIntercomTargets?.[fi],
1995
+ orchestratorIntercomTarget: config.controlIntercomTarget,
1996
+ nestedRoute: config.nestedRoute,
1997
+ registerInterrupt: (interrupt) => {
1998
+ activeChildInterrupt = interrupt;
1999
+ },
2000
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
2001
+ onChildEvent: (event) => updateStepFromChildEvent(fi, event),
2002
+ });
2003
+ if (task.sessionFile) {
2004
+ latestSessionFile = task.sessionFile;
2005
+ }
2006
+
2007
+ const taskEndTime = Date.now();
2008
+ const taskDuration = taskEndTime - taskStartTime;
2009
+
2010
+ statusPayload.steps[fi].status = singleResult.exitCode === 0 ? "complete" : "failed";
2011
+ statusPayload.steps[fi].endedAt = taskEndTime;
2012
+ statusPayload.steps[fi].durationMs = taskDuration;
2013
+ statusPayload.steps[fi].exitCode = singleResult.exitCode;
2014
+ statusPayload.steps[fi].model = singleResult.model;
2015
+ statusPayload.steps[fi].thinking = resolveEffectiveThinking(singleResult.model, statusPayload.steps[fi].thinking);
2016
+ statusPayload.steps[fi].attemptedModels = singleResult.attemptedModels;
2017
+ statusPayload.steps[fi].modelAttempts = singleResult.modelAttempts;
2018
+ statusPayload.steps[fi].error = singleResult.error;
2019
+ statusPayload.steps[fi].structuredOutput = singleResult.structuredOutput;
2020
+ statusPayload.steps[fi].structuredOutputPath = singleResult.structuredOutputPath;
2021
+ statusPayload.steps[fi].structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
2022
+ statusPayload.steps[fi].acceptance = singleResult.acceptance;
2023
+ statusPayload.lastUpdate = taskEndTime;
2024
+ writeStatusPayload();
2025
+
2026
+ appendJsonl(eventsPath, JSON.stringify({
2027
+ type: singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
2028
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
2029
+ exitCode: singleResult.exitCode, durationMs: taskDuration,
2030
+ }));
2031
+ if (singleResult.completionGuardTriggered) {
2032
+ const event = buildControlEvent({
2033
+ from: statusPayload.steps[fi].activityState,
2034
+ to: "needs_attention",
2035
+ runId: id,
2036
+ agent: task.agent,
2037
+ index: fi,
2038
+ ts: taskEndTime,
2039
+ message: `${task.agent} completed without making edits for an implementation task`,
2040
+ reason: "completion_guard",
2041
+ });
2042
+ appendControlEvent(event);
2043
+ }
2044
+
2045
+ if (singleResult.exitCode !== 0 && failFast) aborted = true;
2046
+ return { ...singleResult, skipped: false };
2047
+ },
2048
+ );
2049
+
2050
+ flatIndex += group.parallel.length;
2051
+
2052
+ for (let t = 0; t < group.parallel.length; t++) {
2053
+ const fi = groupStartFlatIndex + t;
2054
+ const sessionTokens = config.sessionDir
2055
+ ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
2056
+ : null;
2057
+ const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
2058
+ if (!taskTokens) continue;
2059
+ statusPayload.steps[fi].tokens = taskTokens;
2060
+ previousCumulativeTokens = {
2061
+ input: previousCumulativeTokens.input + taskTokens.input,
2062
+ output: previousCumulativeTokens.output + taskTokens.output,
2063
+ total: previousCumulativeTokens.total + taskTokens.total,
2064
+ };
2065
+ }
2066
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
2067
+ statusPayload.lastUpdate = Date.now();
2068
+ writeStatusPayload();
2069
+
2070
+ for (const pr of parallelResults) {
2071
+ results.push({
2072
+ agent: pr.agent,
2073
+ output: pr.output,
2074
+ error: pr.error,
2075
+ success: pr.exitCode === 0,
2076
+ exitCode: pr.exitCode,
2077
+ skipped: pr.skipped,
2078
+ sessionFile: pr.sessionFile,
2079
+ intercomTarget: pr.intercomTarget,
2080
+ model: pr.model,
2081
+ attemptedModels: pr.attemptedModels,
2082
+ modelAttempts: pr.modelAttempts,
2083
+ artifactPaths: pr.artifactPaths,
2084
+ structuredOutput: pr.structuredOutput,
2085
+ structuredOutputPath: pr.structuredOutputPath,
2086
+ structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
2087
+ acceptance: pr.acceptance,
2088
+ });
2089
+ }
2090
+ for (let t = 0; t < group.parallel.length; t++) {
2091
+ const outputName = group.parallel[t]?.outputName;
2092
+ if (outputName) outputs[outputName] = outputEntryFromAsyncResult({
2093
+ agent: parallelResults[t]!.agent,
2094
+ output: parallelResults[t]!.output,
2095
+ structuredOutput: parallelResults[t]!.structuredOutput,
2096
+ }, stepIndex);
2097
+ }
2098
+ statusPayload.outputs = outputs;
2099
+
2100
+ previousOutput = aggregateParallelOutputs(
2101
+ parallelResults.map((r) => ({
2102
+ agent: r.agent,
2103
+ output: r.output,
2104
+ exitCode: r.exitCode,
2105
+ error: r.error,
2106
+ model: r.model,
2107
+ attemptedModels: r.attemptedModels,
2108
+ })),
2109
+ );
2110
+ previousOutput = appendParallelWorktreeSummary(previousOutput, worktreeSetup, asyncDir, stepIndex, group);
2111
+
2112
+ appendJsonl(eventsPath, JSON.stringify({
2113
+ type: "subagent.parallel.completed",
2114
+ ts: Date.now(),
2115
+ runId: id,
2116
+ stepIndex,
2117
+ success: parallelResults.every((r) => r.exitCode === 0 || r.exitCode === -1),
2118
+ }));
2119
+
2120
+ if (parallelResults.some((r) => r.exitCode !== 0 && r.exitCode !== -1)) {
2121
+ break;
2122
+ }
2123
+ } finally {
2124
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
2125
+ }
2126
+ } else {
2127
+ const seqStep = step as SubagentStep;
2128
+ const stepStartTime = Date.now();
2129
+ statusPayload.currentStep = flatIndex;
2130
+ statusPayload.steps[flatIndex].status = "running";
2131
+ statusPayload.steps[flatIndex].activityState = undefined;
2132
+ statusPayload.activityState = undefined;
2133
+ resetStepLiveDetail(statusPayload.steps[flatIndex]);
2134
+ statusPayload.steps[flatIndex].skills = seqStep.skills;
2135
+ statusPayload.steps[flatIndex].startedAt = stepStartTime;
2136
+ statusPayload.steps[flatIndex].lastActivityAt = stepStartTime;
2137
+ statusPayload.lastActivityAt = stepStartTime;
2138
+ statusPayload.lastUpdate = stepStartTime;
2139
+ statusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);
2140
+ writeStatusPayload();
2141
+
2142
+ appendJsonl(eventsPath, JSON.stringify({
2143
+ type: "subagent.step.started",
2144
+ ts: stepStartTime,
2145
+ runId: id,
2146
+ stepIndex: flatIndex,
2147
+ agent: seqStep.agent,
2148
+ }));
2149
+
2150
+ const singleResult = await runSingleStep(seqStep, {
2151
+ previousOutput, placeholder, cwd, sessionEnabled,
2152
+ outputs,
2153
+ sessionDir: config.sessionDir,
2154
+ artifactsDir, artifactConfig, id,
2155
+ flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
2156
+ outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
2157
+ piPackageRoot: config.piPackageRoot,
2158
+ piArgv1: config.piArgv1,
2159
+ childIntercomTarget: config.childIntercomTargets?.[flatIndex],
2160
+ orchestratorIntercomTarget: config.controlIntercomTarget,
2161
+ nestedRoute: config.nestedRoute,
2162
+ registerInterrupt: (interrupt) => {
2163
+ activeChildInterrupt = interrupt;
2164
+ },
2165
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
2166
+ onChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),
2167
+ });
2168
+ if (seqStep.sessionFile) {
2169
+ latestSessionFile = seqStep.sessionFile;
2170
+ }
2171
+
2172
+ previousOutput = singleResult.output;
2173
+ results.push({
2174
+ agent: singleResult.agent,
2175
+ output: singleResult.output,
2176
+ error: singleResult.error,
2177
+ success: singleResult.exitCode === 0,
2178
+ exitCode: singleResult.exitCode,
2179
+ sessionFile: singleResult.sessionFile,
2180
+ intercomTarget: singleResult.intercomTarget,
2181
+ model: singleResult.model,
2182
+ attemptedModels: singleResult.attemptedModels,
2183
+ modelAttempts: singleResult.modelAttempts,
2184
+ artifactPaths: singleResult.artifactPaths,
2185
+ structuredOutput: singleResult.structuredOutput,
2186
+ structuredOutputPath: singleResult.structuredOutputPath,
2187
+ structuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,
2188
+ acceptance: singleResult.acceptance,
2189
+ });
2190
+ if (seqStep.outputName) {
2191
+ outputs[seqStep.outputName] = outputEntryFromAsyncResult({
2192
+ agent: singleResult.agent,
2193
+ output: singleResult.output,
2194
+ structuredOutput: singleResult.structuredOutput,
2195
+ }, stepIndex);
2196
+ }
2197
+ statusPayload.outputs = outputs;
2198
+
2199
+ const cumulativeTokens = config.sessionDir ? parseSessionTokens(config.sessionDir) : null;
2200
+ let stepTokens: TokenUsage | null = cumulativeTokens
2201
+ ? {
2202
+ input: cumulativeTokens.input - previousCumulativeTokens.input,
2203
+ output: cumulativeTokens.output - previousCumulativeTokens.output,
2204
+ total: cumulativeTokens.total - previousCumulativeTokens.total,
2205
+ }
2206
+ : null;
2207
+ if (cumulativeTokens) {
2208
+ previousCumulativeTokens = cumulativeTokens;
2209
+ } else {
2210
+ stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
2211
+ if (stepTokens) {
2212
+ previousCumulativeTokens = {
2213
+ input: previousCumulativeTokens.input + stepTokens.input,
2214
+ output: previousCumulativeTokens.output + stepTokens.output,
2215
+ total: previousCumulativeTokens.total + stepTokens.total,
2216
+ };
2217
+ }
2218
+ }
2219
+
2220
+ const stepEndTime = Date.now();
2221
+ statusPayload.steps[flatIndex].status = singleResult.exitCode === 0 ? "complete" : "failed";
2222
+ statusPayload.steps[flatIndex].endedAt = stepEndTime;
2223
+ statusPayload.steps[flatIndex].durationMs = stepEndTime - stepStartTime;
2224
+ statusPayload.steps[flatIndex].exitCode = singleResult.exitCode;
2225
+ statusPayload.steps[flatIndex].model = singleResult.model;
2226
+ statusPayload.steps[flatIndex].thinking = resolveEffectiveThinking(singleResult.model, statusPayload.steps[flatIndex].thinking);
2227
+ statusPayload.steps[flatIndex].attemptedModels = singleResult.attemptedModels;
2228
+ statusPayload.steps[flatIndex].modelAttempts = singleResult.modelAttempts;
2229
+ statusPayload.steps[flatIndex].error = singleResult.error;
2230
+ statusPayload.steps[flatIndex].structuredOutput = singleResult.structuredOutput;
2231
+ statusPayload.steps[flatIndex].structuredOutputPath = singleResult.structuredOutputPath;
2232
+ statusPayload.steps[flatIndex].structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
2233
+ statusPayload.steps[flatIndex].acceptance = singleResult.acceptance;
2234
+ if (stepTokens) {
2235
+ statusPayload.steps[flatIndex].tokens = stepTokens;
2236
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
2237
+ }
2238
+ statusPayload.lastUpdate = stepEndTime;
2239
+ writeStatusPayload();
2240
+
2241
+ appendJsonl(eventsPath, JSON.stringify({
2242
+ type: singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
2243
+ ts: stepEndTime,
2244
+ runId: id,
2245
+ stepIndex: flatIndex,
2246
+ agent: seqStep.agent,
2247
+ exitCode: singleResult.exitCode,
2248
+ durationMs: stepEndTime - stepStartTime,
2249
+ tokens: stepTokens,
2250
+ }));
2251
+ if (singleResult.completionGuardTriggered) {
2252
+ const event = buildControlEvent({
2253
+ from: statusPayload.steps[flatIndex].activityState,
2254
+ to: "needs_attention",
2255
+ runId: id,
2256
+ agent: seqStep.agent,
2257
+ index: flatIndex,
2258
+ ts: stepEndTime,
2259
+ message: `${seqStep.agent} completed without making edits for an implementation task`,
2260
+ reason: "completion_guard",
2261
+ });
2262
+ appendControlEvent(event);
2263
+ }
2264
+
2265
+ flatIndex++;
2266
+ if (singleResult.exitCode !== 0) {
2267
+ break;
2268
+ }
2269
+ }
2270
+ }
2271
+
2272
+ let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
2273
+ let truncated = false;
2274
+
2275
+ if (maxOutput) {
2276
+ const config = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };
2277
+ const lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;
2278
+ const truncResult = truncateOutput(summary, config, lastArtifactPath);
2279
+ if (truncResult.truncated) {
2280
+ summary = truncResult.text;
2281
+ truncated = true;
2282
+ }
2283
+ }
2284
+
2285
+ const resultMode = config.resultMode ?? statusPayload.mode;
2286
+ const finalFlatAgents = statusPayload.steps.map((step) => step.agent);
2287
+ const agentName = finalFlatAgents.length === 1
2288
+ ? finalFlatAgents[0]!
2289
+ : resultMode === "parallel"
2290
+ ? `parallel:${finalFlatAgents.join("+")}`
2291
+ : `chain:${finalFlatAgents.join("->")}`;
2292
+ let sessionFile: string | undefined;
2293
+ let shareUrl: string | undefined;
2294
+ let gistUrl: string | undefined;
2295
+ let shareError: string | undefined;
2296
+
2297
+ if (shareEnabled) {
2298
+ sessionFile = config.sessionDir
2299
+ ? (findLatestSessionFile(config.sessionDir) ?? undefined)
2300
+ : undefined;
2301
+ if (!sessionFile && latestSessionFile) {
2302
+ sessionFile = latestSessionFile;
2303
+ }
2304
+ if (sessionFile) {
2305
+ try {
2306
+ const exportDir = config.sessionDir ?? path.dirname(sessionFile);
2307
+ const htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);
2308
+ const share = createShareLink(htmlPath);
2309
+ if ("error" in share) shareError = share.error;
2310
+ else {
2311
+ shareUrl = share.shareUrl;
2312
+ gistUrl = share.gistUrl;
2313
+ }
2314
+ } catch (err) {
2315
+ shareError = String(err);
2316
+ }
2317
+ } else {
2318
+ shareError = "Session file not found.";
2319
+ }
2320
+ }
2321
+
2322
+ if (activityTimer) {
2323
+ clearInterval(activityTimer);
2324
+ activityTimer = undefined;
2325
+ }
2326
+ disposeControlInbox();
2327
+ const effectiveSessionFile = sessionFile ?? latestSessionFile;
2328
+ const runEndedAt = Date.now();
2329
+ statusPayload.state = interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
2330
+ statusPayload.activityState = undefined;
2331
+ statusPayload.endedAt = runEndedAt;
2332
+ statusPayload.lastUpdate = runEndedAt;
2333
+ statusPayload.sessionFile = effectiveSessionFile;
2334
+ statusPayload.shareUrl = shareUrl;
2335
+ statusPayload.gistUrl = gistUrl;
2336
+ statusPayload.shareError = shareError;
2337
+ if (statusPayload.state === "failed" && !statusPayload.error) {
2338
+ const failedStep = statusPayload.steps.find((s) => s.status === "failed");
2339
+ if (failedStep?.agent) {
2340
+ statusPayload.error = `Step failed: ${failedStep.agent}`;
2341
+ }
2342
+ }
2343
+ writeStatusPayload();
2344
+ appendJsonl(
2345
+ eventsPath,
2346
+ JSON.stringify({
2347
+ type: "subagent.run.completed",
2348
+ ts: runEndedAt,
2349
+ runId: id,
2350
+ status: statusPayload.state,
2351
+ durationMs: runEndedAt - overallStartTime,
2352
+ }),
2353
+ );
2354
+ writeRunLog(logPath, {
2355
+ id,
2356
+ mode: statusPayload.mode,
2357
+ cwd,
2358
+ startedAt: overallStartTime,
2359
+ endedAt: runEndedAt,
2360
+ steps: statusPayload.steps.map((step) => ({
2361
+ agent: step.agent,
2362
+ status: step.status,
2363
+ durationMs: step.durationMs,
2364
+ })),
2365
+ summary,
2366
+ truncated,
2367
+ artifactsDir,
2368
+ sessionFile: effectiveSessionFile,
2369
+ shareUrl,
2370
+ shareError,
2371
+ });
2372
+
2373
+ try {
2374
+ writeAtomicJson(resultPath, {
2375
+ id,
2376
+ agent: agentName,
2377
+ mode: resultMode,
2378
+ success: !interrupted && results.every((r) => r.success),
2379
+ state: interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed",
2380
+ summary: interrupted ? "Paused after interrupt. Waiting for explicit next action." : summary,
2381
+ results: results.map((r) => ({
2382
+ agent: r.agent,
2383
+ output: r.output,
2384
+ error: r.error,
2385
+ success: r.success,
2386
+ skipped: r.skipped || undefined,
2387
+ sessionFile: r.sessionFile,
2388
+ intercomTarget: r.intercomTarget,
2389
+ model: r.model,
2390
+ attemptedModels: r.attemptedModels,
2391
+ modelAttempts: r.modelAttempts,
2392
+ artifactPaths: r.artifactPaths,
2393
+ truncated: r.truncated,
2394
+ structuredOutput: r.structuredOutput,
2395
+ structuredOutputPath: r.structuredOutputPath,
2396
+ structuredOutputSchemaPath: r.structuredOutputSchemaPath,
2397
+ acceptance: r.acceptance,
2398
+ })),
2399
+ outputs,
2400
+ workflowGraph: statusPayload.workflowGraph,
2401
+ exitCode: interrupted || results.every((r) => r.success) ? 0 : 1,
2402
+ timestamp: runEndedAt,
2403
+ durationMs: runEndedAt - overallStartTime,
2404
+ truncated,
2405
+ artifactsDir,
2406
+ cwd,
2407
+ asyncDir,
2408
+ sessionId: config.sessionId,
2409
+ sessionFile: effectiveSessionFile,
2410
+ intercomTarget: config.controlIntercomTarget,
2411
+ shareUrl,
2412
+ gistUrl,
2413
+ shareError,
2414
+ ...(taskIndex !== undefined && { taskIndex }),
2415
+ ...(totalTasks !== undefined && { totalTasks }),
2416
+ });
2417
+ } catch (err) {
2418
+ console.error(`Failed to write result file ${resultPath}:`, err);
2419
+ }
2420
+ }
2421
+
2422
+ const configArg = process.argv[2];
2423
+ if (configArg) {
2424
+ try {
2425
+ const configJson = fs.readFileSync(configArg, "utf-8");
2426
+ const config = JSON.parse(configJson) as SubagentRunConfig;
2427
+ try {
2428
+ fs.unlinkSync(configArg);
2429
+ } catch {
2430
+ // Temp config cleanup is best effort.
2431
+ }
2432
+ runSubagent(config).catch((runErr) => {
2433
+ console.error("Subagent runner error:", runErr);
2434
+ process.exit(1);
2435
+ });
2436
+ } catch (err) {
2437
+ console.error("Subagent runner error:", err);
2438
+ process.exit(1);
2439
+ }
2440
+ } else {
2441
+ let input = "";
2442
+ process.stdin.setEncoding("utf-8");
2443
+ process.stdin.on("data", (chunk) => {
2444
+ input += chunk;
2445
+ });
2446
+ process.stdin.on("end", () => {
2447
+ try {
2448
+ const config = JSON.parse(input) as SubagentRunConfig;
2449
+ runSubagent(config).catch((runErr) => {
2450
+ console.error("Subagent runner error:", runErr);
2451
+ process.exit(1);
2452
+ });
2453
+ } catch (err) {
2454
+ console.error("Subagent runner error:", err);
2455
+ process.exit(1);
2456
+ }
2457
+ });
2458
+ }