@leing2021/super-pi 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +29 -16
  2. package/extensions/subagent/agent-management.ts +595 -0
  3. package/extensions/subagent/agent-manager-chain-detail.ts +162 -0
  4. package/extensions/subagent/agent-manager-detail.ts +231 -0
  5. package/extensions/subagent/agent-manager-edit.ts +390 -0
  6. package/extensions/subagent/agent-manager-list.ts +278 -0
  7. package/extensions/subagent/agent-manager-parallel.ts +304 -0
  8. package/extensions/subagent/agent-manager.ts +705 -0
  9. package/extensions/subagent/agent-scope.ts +8 -0
  10. package/extensions/subagent/agent-selection.ts +25 -0
  11. package/extensions/subagent/agent-serializer.ts +123 -0
  12. package/extensions/subagent/agent-templates.ts +62 -0
  13. package/extensions/subagent/agents/context-builder.md +37 -0
  14. package/extensions/subagent/agents/delegate.md +9 -0
  15. package/extensions/subagent/agents/oracle.md +73 -0
  16. package/extensions/subagent/agents/planner.md +52 -0
  17. package/extensions/subagent/agents/researcher.md +50 -0
  18. package/extensions/subagent/agents/reviewer.md +38 -0
  19. package/extensions/subagent/agents/scout.md +48 -0
  20. package/extensions/subagent/agents/worker.md +52 -0
  21. package/extensions/subagent/agents.ts +761 -0
  22. package/extensions/subagent/artifacts.ts +100 -0
  23. package/extensions/subagent/async-execution.ts +520 -0
  24. package/extensions/subagent/async-job-tracker.ts +216 -0
  25. package/extensions/subagent/async-status.ts +241 -0
  26. package/extensions/subagent/chain-clarify.ts +1364 -0
  27. package/extensions/subagent/chain-execution.ts +853 -0
  28. package/extensions/subagent/chain-serializer.ts +126 -0
  29. package/extensions/subagent/completion-dedupe.ts +65 -0
  30. package/extensions/subagent/doctor.ts +200 -0
  31. package/extensions/subagent/execution.ts +738 -0
  32. package/extensions/subagent/file-coalescer.ts +42 -0
  33. package/extensions/subagent/fork-context.ts +63 -0
  34. package/extensions/subagent/formatters.ts +122 -0
  35. package/extensions/subagent/frontmatter.ts +31 -0
  36. package/extensions/subagent/index.ts +585 -0
  37. package/extensions/subagent/intercom-bridge.ts +240 -0
  38. package/extensions/subagent/jsonl-writer.ts +83 -0
  39. package/extensions/subagent/model-fallback.ts +108 -0
  40. package/extensions/subagent/notify.ts +110 -0
  41. package/extensions/subagent/parallel-utils.ts +108 -0
  42. package/extensions/subagent/pi-args.ts +138 -0
  43. package/extensions/subagent/pi-spawn.ts +100 -0
  44. package/extensions/subagent/post-exit-stdio-guard.ts +87 -0
  45. package/extensions/subagent/prompt-template-bridge.ts +399 -0
  46. package/extensions/subagent/prompts/gather-context-and-clarify.md +13 -0
  47. package/extensions/subagent/prompts/parallel-cleanup.md +42 -0
  48. package/extensions/subagent/prompts/parallel-research.md +50 -0
  49. package/extensions/subagent/prompts/parallel-review.md +40 -0
  50. package/extensions/subagent/render-helpers.ts +82 -0
  51. package/extensions/subagent/render.ts +836 -0
  52. package/extensions/subagent/result-intercom.ts +237 -0
  53. package/extensions/subagent/result-watcher.ts +171 -0
  54. package/extensions/subagent/run-history.ts +57 -0
  55. package/extensions/subagent/run-status.ts +136 -0
  56. package/extensions/subagent/schemas.ts +164 -0
  57. package/extensions/subagent/session-tokens.ts +50 -0
  58. package/extensions/subagent/settings.ts +367 -0
  59. package/extensions/subagent/single-output.ts +97 -0
  60. package/extensions/subagent/skills.ts +626 -0
  61. package/extensions/subagent/slash-bridge.ts +176 -0
  62. package/extensions/subagent/slash-commands.ts +303 -0
  63. package/extensions/subagent/slash-live-state.ts +294 -0
  64. package/extensions/subagent/subagent-control.ts +150 -0
  65. package/extensions/subagent/subagent-executor.ts +1899 -0
  66. package/extensions/subagent/subagent-prompt-runtime.ts +75 -0
  67. package/extensions/subagent/subagent-runner.ts +1470 -0
  68. package/extensions/subagent/subagents-status.ts +472 -0
  69. package/extensions/subagent/text-editor.ts +272 -0
  70. package/extensions/subagent/top-level-async.ts +15 -0
  71. package/extensions/subagent/types.ts +623 -0
  72. package/extensions/subagent/utils.ts +456 -0
  73. package/extensions/subagent/worktree.ts +579 -0
  74. package/extensions/super-pi-extension/index.ts +2 -55
  75. package/package.json +12 -6
  76. package/skills/pi-subagents/SKILL.md +566 -0
@@ -0,0 +1,1470 @@
1
+ // Based on pi-subagents by Nico Bailon (https://github.com/nicobailon/pi-subagents)
2
+ // MIT License
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import * as fs from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import * as path from "node:path";
7
+ import { pathToFileURL } from "node:url";
8
+ import type { Message } from "@mariozechner/pi-ai";
9
+ import { appendJsonl, getArtifactPaths } from "./artifacts.ts";
10
+ import { getPiSpawnCommand } from "./pi-spawn.ts";
11
+ import { captureSingleOutputSnapshot, resolveSingleOutput } from "./single-output.ts";
12
+ import {
13
+ type ActivityState,
14
+ type ArtifactConfig,
15
+ type ArtifactPaths,
16
+ type ModelAttempt,
17
+ type ResolvedControlConfig,
18
+ type Usage,
19
+ DEFAULT_MAX_OUTPUT,
20
+ type MaxOutputConfig,
21
+ truncateOutput,
22
+ getSubagentDepthEnv,
23
+ } from "./types.ts";
24
+ import {
25
+ DEFAULT_CONTROL_CONFIG,
26
+ buildControlEvent,
27
+ deriveActivityState,
28
+ claimControlNotification,
29
+ formatControlIntercomMessage,
30
+ formatControlNoticeMessage,
31
+ shouldEmitControlEvent,
32
+ } from "./subagent-control.ts";
33
+ import {
34
+ type RunnerSubagentStep as SubagentStep,
35
+ type RunnerStep,
36
+ isParallelGroup,
37
+ flattenSteps,
38
+ mapConcurrent,
39
+ aggregateParallelOutputs,
40
+ MAX_PARALLEL_CONCURRENCY,
41
+ } from "./parallel-utils.ts";
42
+ import { buildPiArgs, cleanupTempDir } from "./pi-args.ts";
43
+ import { formatModelAttemptNote, isRetryableModelFailure } from "./model-fallback.ts";
44
+ import { attachPostExitStdioGuard, trySignalChild } from "./post-exit-stdio-guard.ts";
45
+ import { detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput } from "./utils.ts";
46
+ import { parseSessionTokens, type TokenUsage } from "./session-tokens.ts";
47
+ import {
48
+ cleanupWorktrees,
49
+ createWorktrees,
50
+ diffWorktrees,
51
+ findWorktreeTaskCwdConflict,
52
+ formatWorktreeDiffSummary,
53
+ formatWorktreeTaskCwdConflict,
54
+ type WorktreeSetup,
55
+ } from "./worktree.ts";
56
+ import { writeInitialProgressFile } from "./settings.ts";
57
+
58
+ interface SubagentRunConfig {
59
+ id: string;
60
+ steps: RunnerStep[];
61
+ resultPath: string;
62
+ cwd: string;
63
+ placeholder: string;
64
+ taskIndex?: number;
65
+ totalTasks?: number;
66
+ maxOutput?: MaxOutputConfig;
67
+ artifactsDir?: string;
68
+ artifactConfig?: Partial<ArtifactConfig>;
69
+ share?: boolean;
70
+ sessionDir?: string;
71
+ asyncDir: string;
72
+ sessionId?: string | null;
73
+ piPackageRoot?: string;
74
+ piArgv1?: string;
75
+ worktreeSetupHook?: string;
76
+ worktreeSetupHookTimeoutMs?: number;
77
+ controlConfig?: ResolvedControlConfig;
78
+ controlIntercomTarget?: string;
79
+ childIntercomTargets?: Array<string | undefined>;
80
+ resultMode?: "single" | "parallel" | "chain";
81
+ }
82
+
83
+ interface StepResult {
84
+ agent: string;
85
+ output: string;
86
+ success: boolean;
87
+ skipped?: boolean;
88
+ intercomTarget?: string;
89
+ model?: string;
90
+ attemptedModels?: string[];
91
+ modelAttempts?: ModelAttempt[];
92
+ artifactPaths?: ArtifactPaths;
93
+ truncated?: boolean;
94
+ }
95
+
96
+ const require = createRequire(import.meta.url);
97
+ const ASYNC_INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
98
+
99
+ function findLatestSessionFile(sessionDir: string): string | null {
100
+ try {
101
+ const files = fs
102
+ .readdirSync(sessionDir)
103
+ .filter((f) => f.endsWith(".jsonl"))
104
+ .map((f) => path.join(sessionDir, f));
105
+ if (files.length === 0) return null;
106
+ files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
107
+ return files[0] ?? null;
108
+ } catch {
109
+ // Session lookup is optional metadata.
110
+ return null;
111
+ }
112
+ }
113
+
114
+ function emptyUsage(): Usage {
115
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
116
+ }
117
+
118
+ function tokenUsageFromAttempts(attempts: ModelAttempt[] | undefined): TokenUsage | null {
119
+ if (!attempts || attempts.length === 0) return null;
120
+ let input = 0;
121
+ let output = 0;
122
+ for (const attempt of attempts) {
123
+ input += attempt.usage?.input ?? 0;
124
+ output += attempt.usage?.output ?? 0;
125
+ }
126
+ const total = input + output;
127
+ return total > 0 ? { input, output, total } : null;
128
+ }
129
+
130
+ interface ChildEventContext {
131
+ eventsPath: string;
132
+ runId: string;
133
+ stepIndex: number;
134
+ agent: string;
135
+ }
136
+
137
+ interface ChildUsage {
138
+ input?: number;
139
+ inputTokens?: number;
140
+ output?: number;
141
+ outputTokens?: number;
142
+ cacheRead?: number;
143
+ cacheWrite?: number;
144
+ cost?: { total?: number };
145
+ }
146
+
147
+ type ChildMessage = Message & {
148
+ model?: string;
149
+ errorMessage?: string;
150
+ usage?: ChildUsage;
151
+ };
152
+
153
+ interface ChildEvent {
154
+ type?: string;
155
+ message?: ChildMessage;
156
+ toolName?: string;
157
+ args?: Record<string, unknown>;
158
+ }
159
+
160
+ interface RunPiStreamingResult {
161
+ stderr: string;
162
+ exitCode: number | null;
163
+ messages: Message[];
164
+ usage: Usage;
165
+ model?: string;
166
+ error?: string;
167
+ finalOutput: string;
168
+ interrupted?: boolean;
169
+ }
170
+
171
+ function runPiStreaming(
172
+ args: string[],
173
+ cwd: string,
174
+ outputFile: string,
175
+ env?: Record<string, string | undefined>,
176
+ piPackageRoot?: string,
177
+ piArgv1?: string,
178
+ maxSubagentDepth?: number,
179
+ childEventContext?: ChildEventContext,
180
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void,
181
+ ): Promise<RunPiStreamingResult> {
182
+ return new Promise((resolve) => {
183
+ const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
184
+ const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
185
+ const spawnSpec = getPiSpawnCommand(args, {
186
+ ...(piPackageRoot ? { piPackageRoot } : {}),
187
+ ...(piArgv1 ? { argv1: piArgv1 } : {}),
188
+ });
189
+ const child = spawn(spawnSpec.command, spawnSpec.args, { cwd, stdio: ["ignore", "pipe", "pipe"], env: spawnEnv });
190
+ let stderr = "";
191
+ let stdoutBuf = "";
192
+ let stderrBuf = "";
193
+ const messages: Message[] = [];
194
+ const usage = emptyUsage();
195
+ let model: string | undefined;
196
+ let error: string | undefined;
197
+ let interrupted = false;
198
+ const rawStdoutLines: string[] = [];
199
+
200
+ const writeOutputLine = (line: string) => {
201
+ if (!line.trim()) return;
202
+ outputStream.write(`${line}\n`);
203
+ };
204
+
205
+ const writeOutputText = (text: string) => {
206
+ for (const line of text.split("\n")) {
207
+ writeOutputLine(line);
208
+ }
209
+ };
210
+
211
+ const appendChildEvent = (event: Record<string, unknown>) => {
212
+ if (!childEventContext) return;
213
+ appendJsonl(childEventContext.eventsPath, JSON.stringify({
214
+ ...event,
215
+ subagentSource: "child",
216
+ subagentRunId: childEventContext.runId,
217
+ subagentStepIndex: childEventContext.stepIndex,
218
+ subagentAgent: childEventContext.agent,
219
+ observedAt: Date.now(),
220
+ }));
221
+ };
222
+
223
+ const appendChildLine = (type: "subagent.child.stdout" | "subagent.child.stderr", line: string) => {
224
+ appendChildEvent({ type, line });
225
+ };
226
+
227
+ const processStdoutLine = (line: string) => {
228
+ if (!line.trim()) return;
229
+ let event: ChildEvent;
230
+ try {
231
+ event = JSON.parse(line) as ChildEvent;
232
+ } catch {
233
+ rawStdoutLines.push(line);
234
+ writeOutputLine(line);
235
+ appendChildLine("subagent.child.stdout", line);
236
+ return;
237
+ }
238
+
239
+ appendChildEvent(event);
240
+
241
+ if (event.type === "tool_execution_start" && event.toolName) {
242
+ const toolArgs = extractToolArgsPreview(event.args ?? {});
243
+ writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
244
+ return;
245
+ }
246
+
247
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
248
+ messages.push(event.message);
249
+ const text = extractTextFromContent(event.message.content);
250
+ if (text) writeOutputText(text);
251
+
252
+ if (event.type !== "message_end" || event.message.role !== "assistant") return;
253
+ if (event.message.model) model = event.message.model;
254
+ if (event.message.errorMessage) error = event.message.errorMessage;
255
+ const eventUsage = event.message.usage;
256
+ if (eventUsage) {
257
+ usage.turns++;
258
+ usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
259
+ usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
260
+ usage.cacheRead += eventUsage.cacheRead ?? 0;
261
+ usage.cacheWrite += eventUsage.cacheWrite ?? 0;
262
+ usage.cost += eventUsage.cost?.total ?? 0;
263
+ }
264
+ const stopReason = (event.message as { stopReason?: string }).stopReason;
265
+ const hasToolCall = Array.isArray(event.message.content)
266
+ && event.message.content.some((part) => (part as { type?: string }).type === "toolCall");
267
+ if (stopReason === "stop" && !hasToolCall) startFinalDrain();
268
+ }
269
+ };
270
+
271
+ const processStderrText = (text: string) => {
272
+ stderr += text;
273
+ stderrBuf += text;
274
+ outputStream.write(text);
275
+ if (!childEventContext) return;
276
+ const lines = stderrBuf.split("\n");
277
+ stderrBuf = lines.pop() || "";
278
+ for (const line of lines) {
279
+ if (!line.trim()) continue;
280
+ appendChildLine("subagent.child.stderr", line);
281
+ }
282
+ };
283
+
284
+ // Guard both cases that can leave the parent waiting on `close` forever:
285
+ // a lingering stdio holder after `exit`, or a child that never exits.
286
+ const FINAL_DRAIN_MS = 5000;
287
+ const HARD_KILL_MS = 3000;
288
+ let childExited = false;
289
+ let forcedTerminationSignal = false;
290
+ let finalDrainTimer: NodeJS.Timeout | undefined;
291
+ let finalHardKillTimer: NodeJS.Timeout | undefined;
292
+ let settled = false;
293
+ const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
294
+ child.stdout.on("data", (chunk: Buffer) => {
295
+ const text = chunk.toString();
296
+ stdoutBuf += text;
297
+ const lines = stdoutBuf.split("\n");
298
+ stdoutBuf = lines.pop() || "";
299
+ for (const line of lines) processStdoutLine(line);
300
+ });
301
+
302
+ child.stderr.on("data", (chunk: Buffer) => {
303
+ processStderrText(chunk.toString());
304
+ });
305
+ registerInterrupt?.(() => {
306
+ if (settled) return;
307
+ interrupted = true;
308
+ if (!error) error = "Interrupted. Waiting for explicit next action.";
309
+ trySignalChild(child, "SIGINT");
310
+ setTimeout(() => {
311
+ if (!settled) trySignalChild(child, "SIGTERM");
312
+ }, 1000).unref?.();
313
+ });
314
+ const clearDrainTimers = () => {
315
+ if (finalDrainTimer) {
316
+ clearTimeout(finalDrainTimer);
317
+ finalDrainTimer = undefined;
318
+ }
319
+ if (finalHardKillTimer) {
320
+ clearTimeout(finalHardKillTimer);
321
+ finalHardKillTimer = undefined;
322
+ }
323
+ };
324
+ function startFinalDrain(): void {
325
+ if (childExited || finalDrainTimer || settled) return;
326
+ finalDrainTimer = setTimeout(() => {
327
+ if (settled) return;
328
+ const termSent = trySignalChild(child, "SIGTERM");
329
+ if (!termSent) return;
330
+ forcedTerminationSignal = true;
331
+ if (!error) {
332
+ error = `Subagent process did not exit within ${FINAL_DRAIN_MS}ms after its final message. Forcing termination.`;
333
+ }
334
+ finalHardKillTimer = setTimeout(() => {
335
+ if (settled) return;
336
+ forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
337
+ }, HARD_KILL_MS);
338
+ finalHardKillTimer.unref?.();
339
+ }, FINAL_DRAIN_MS);
340
+ finalDrainTimer.unref?.();
341
+ }
342
+ child.on("exit", () => {
343
+ childExited = true;
344
+ clearDrainTimers();
345
+ });
346
+ child.on("close", (exitCode, signal) => {
347
+ settled = true;
348
+ registerInterrupt?.(undefined);
349
+ clearDrainTimers();
350
+ clearStdioGuard();
351
+ if (stdoutBuf.trim()) processStdoutLine(stdoutBuf);
352
+ if (stderrBuf.trim()) appendChildLine("subagent.child.stderr", stderrBuf);
353
+ outputStream.end();
354
+ const finalOutput = getFinalOutput(messages) || rawStdoutLines.join("\n").trim();
355
+ resolve({
356
+ stderr,
357
+ exitCode: interrupted ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
358
+ messages,
359
+ usage,
360
+ model,
361
+ error: interrupted ? undefined : error,
362
+ finalOutput,
363
+ interrupted,
364
+ });
365
+ });
366
+
367
+ child.on("error", (spawnError) => {
368
+ settled = true;
369
+ registerInterrupt?.(undefined);
370
+ clearDrainTimers();
371
+ clearStdioGuard();
372
+ outputStream.end();
373
+ const finalOutput = getFinalOutput(messages) || rawStdoutLines.join("\n").trim();
374
+ const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
375
+ resolve({ stderr, exitCode: 1, messages, usage, model, error: error ?? spawnErrorMessage, finalOutput });
376
+ });
377
+ });
378
+ }
379
+
380
+ function resolvePiPackageRootFallback(): string {
381
+ // Try to resolve the main entry point and walk up to find the package root
382
+ const entryPoint = require.resolve("@mariozechner/pi-coding-agent");
383
+ // Entry point is typically /path/to/dist/index.js, so go up to find package root
384
+ let dir = path.dirname(entryPoint);
385
+ while (dir !== path.dirname(dir)) {
386
+ const pkgJsonPath = path.join(dir, "package.json");
387
+ try {
388
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
389
+ if (pkg.name === "@mariozechner/pi-coding-agent") return dir;
390
+ } catch {
391
+ // Keep walking up until a readable package.json is found.
392
+ }
393
+ dir = path.dirname(dir);
394
+ }
395
+ throw new Error("Could not resolve @mariozechner/pi-coding-agent package root");
396
+ }
397
+
398
+ async function exportSessionHtml(sessionFile: string, outputDir: string, piPackageRoot?: string): Promise<string> {
399
+ const pkgRoot = piPackageRoot ?? resolvePiPackageRootFallback();
400
+ const exportModulePath = path.join(pkgRoot, "dist", "core", "export-html", "index.js");
401
+ const moduleUrl = pathToFileURL(exportModulePath).href;
402
+ const mod = await import(moduleUrl);
403
+ const exportFromFile = (mod as { exportFromFile?: (inputPath: string, options?: { outputPath?: string }) => string })
404
+ .exportFromFile;
405
+ if (typeof exportFromFile !== "function") {
406
+ throw new Error("exportFromFile not available");
407
+ }
408
+ const outputPath = path.join(outputDir, `${path.basename(sessionFile, ".jsonl")}.html`);
409
+ return exportFromFile(sessionFile, { outputPath });
410
+ }
411
+
412
+ function createShareLink(htmlPath: string): { shareUrl: string; gistUrl: string } | { error: string } {
413
+ try {
414
+ const auth = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
415
+ if (auth.status !== 0) {
416
+ return { error: "GitHub CLI is not logged in. Run 'gh auth login' first." };
417
+ }
418
+ } catch {
419
+ return { error: "GitHub CLI (gh) is not installed." };
420
+ }
421
+
422
+ try {
423
+ const result = spawnSync("gh", ["gist", "create", htmlPath], { encoding: "utf-8" });
424
+ if (result.status !== 0) {
425
+ const err = (result.stderr || "").trim() || "Failed to create gist.";
426
+ return { error: err };
427
+ }
428
+ const gistUrl = (result.stdout || "").trim();
429
+ const gistId = gistUrl.split("/").pop();
430
+ if (!gistId) return { error: "Failed to parse gist ID." };
431
+ const shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;
432
+ return { shareUrl, gistUrl };
433
+ } catch (err) {
434
+ return { error: String(err) };
435
+ }
436
+ }
437
+
438
+ function writeJson(filePath: string, payload: object): void {
439
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
440
+ const tempPath = path.join(
441
+ path.dirname(filePath),
442
+ `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`,
443
+ );
444
+ try {
445
+ fs.writeFileSync(tempPath, JSON.stringify(payload, null, 2), "utf-8");
446
+ fs.renameSync(tempPath, filePath);
447
+ } finally {
448
+ if (fs.existsSync(tempPath)) {
449
+ try {
450
+ fs.unlinkSync(tempPath);
451
+ } catch {}
452
+ }
453
+ }
454
+ }
455
+
456
+ function formatDuration(ms: number): string {
457
+ if (ms < 1000) return `${ms}ms`;
458
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
459
+ const minutes = Math.floor(ms / 60000);
460
+ const seconds = Math.floor((ms % 60000) / 1000);
461
+ return `${minutes}m${seconds}s`;
462
+ }
463
+
464
+ function writeRunLog(
465
+ logPath: string,
466
+ input: {
467
+ id: string;
468
+ mode: "single" | "chain";
469
+ cwd: string;
470
+ startedAt: number;
471
+ endedAt: number;
472
+ steps: Array<{
473
+ agent: string;
474
+ status: string;
475
+ durationMs?: number;
476
+ }>;
477
+ summary: string;
478
+ truncated: boolean;
479
+ artifactsDir?: string;
480
+ sessionFile?: string;
481
+ shareUrl?: string;
482
+ shareError?: string;
483
+ },
484
+ ): void {
485
+ const lines: string[] = [];
486
+ lines.push(`# Subagent run ${input.id}`);
487
+ lines.push("");
488
+ lines.push(`- **Mode:** ${input.mode}`);
489
+ lines.push(`- **CWD:** ${input.cwd}`);
490
+ lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
491
+ lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
492
+ lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
493
+ if (input.sessionFile) lines.push(`- **Session:** ${input.sessionFile}`);
494
+ if (input.shareUrl) lines.push(`- **Share:** ${input.shareUrl}`);
495
+ if (input.shareError) lines.push(`- **Share error:** ${input.shareError}`);
496
+ if (input.artifactsDir) lines.push(`- **Artifacts:** ${input.artifactsDir}`);
497
+ lines.push("");
498
+ lines.push("## Steps");
499
+ lines.push("| Step | Agent | Status | Duration |");
500
+ lines.push("| --- | --- | --- | --- |");
501
+ input.steps.forEach((step, i) => {
502
+ const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
503
+ lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
504
+ });
505
+ lines.push("");
506
+ lines.push("## Summary");
507
+ if (input.truncated) {
508
+ lines.push("_Output truncated_");
509
+ lines.push("");
510
+ }
511
+ lines.push(input.summary.trim() || "(no output)");
512
+ lines.push("");
513
+ fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
514
+ }
515
+
516
+ /** Context for running a single step */
517
+ interface SingleStepContext {
518
+ previousOutput: string;
519
+ placeholder: string;
520
+ cwd: string;
521
+ sessionEnabled: boolean;
522
+ sessionDir?: string;
523
+ artifactsDir?: string;
524
+ artifactConfig?: Partial<ArtifactConfig>;
525
+ id: string;
526
+ flatIndex: number;
527
+ flatStepCount: number;
528
+ outputFile: string;
529
+ piPackageRoot?: string;
530
+ piArgv1?: string;
531
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void;
532
+ childIntercomTarget?: string;
533
+ }
534
+
535
+ /** Run a single pi agent step, returning output and metadata */
536
+ async function runSingleStep(
537
+ step: SubagentStep,
538
+ ctx: SingleStepContext,
539
+ ): Promise<{
540
+ agent: string;
541
+ output: string;
542
+ exitCode: number | null;
543
+ error?: string;
544
+ model?: string;
545
+ attemptedModels?: string[];
546
+ modelAttempts?: ModelAttempt[];
547
+ artifactPaths?: ArtifactPaths;
548
+ interrupted?: boolean;
549
+ intercomTarget?: string;
550
+ }> {
551
+ const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
552
+ const task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
553
+ const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
554
+ const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
555
+ const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
556
+
557
+ let artifactPaths: ArtifactPaths | undefined;
558
+ if (ctx.artifactsDir && ctx.artifactConfig?.enabled !== false) {
559
+ const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
560
+ artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
561
+ fs.mkdirSync(ctx.artifactsDir, { recursive: true });
562
+ if (ctx.artifactConfig?.includeInput !== false) {
563
+ fs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`, "utf-8");
564
+ }
565
+ }
566
+
567
+ const candidates = step.modelCandidates && step.modelCandidates.length > 0
568
+ ? step.modelCandidates
569
+ : step.model
570
+ ? [step.model]
571
+ : [undefined];
572
+ const attemptedModels: string[] = [];
573
+ const modelAttempts: ModelAttempt[] = [];
574
+ const attemptNotes: string[] = [];
575
+ const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
576
+ let finalResult: RunPiStreamingResult | undefined;
577
+
578
+ for (let index = 0; index < candidates.length; index++) {
579
+ const candidate = candidates[index];
580
+ const { args, env, tempDir } = buildPiArgs({
581
+ baseArgs: ["--mode", "json", "-p"],
582
+ task,
583
+ sessionEnabled,
584
+ sessionDir,
585
+ sessionFile: step.sessionFile,
586
+ model: candidate,
587
+ inheritProjectContext: step.inheritProjectContext,
588
+ inheritSkills: step.inheritSkills,
589
+ tools: step.tools,
590
+ extensions: step.extensions,
591
+ systemPrompt: step.systemPrompt,
592
+ systemPromptMode: step.systemPromptMode,
593
+ mcpDirectTools: step.mcpDirectTools,
594
+ promptFileStem: step.agent,
595
+ intercomSessionName: ctx.childIntercomTarget,
596
+ });
597
+ const run = await runPiStreaming(
598
+ args,
599
+ step.cwd ?? ctx.cwd,
600
+ ctx.outputFile,
601
+ env,
602
+ ctx.piPackageRoot,
603
+ ctx.piArgv1,
604
+ step.maxSubagentDepth,
605
+ { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
606
+ ctx.registerInterrupt,
607
+ );
608
+ cleanupTempDir(tempDir);
609
+
610
+ const hiddenError = run.exitCode === 0 && !run.error ? detectSubagentError(run.messages) : null;
611
+ const effectiveExitCode = hiddenError?.hasError ? (hiddenError.exitCode ?? 1) : run.exitCode;
612
+ const error = hiddenError?.hasError
613
+ ? hiddenError.details
614
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
615
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
616
+ : run.error || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined);
617
+ const attempt: ModelAttempt = {
618
+ model: candidate ?? run.model ?? step.model ?? "default",
619
+ success: effectiveExitCode === 0 && !error,
620
+ exitCode: effectiveExitCode,
621
+ error,
622
+ usage: run.usage,
623
+ };
624
+ modelAttempts.push(attempt);
625
+ if (candidate) attemptedModels.push(candidate);
626
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error };
627
+ if (attempt.success) break;
628
+ if (!isRetryableModelFailure(error) || index === candidates.length - 1) break;
629
+ attemptNotes.push(formatModelAttemptNote(attempt, candidates[index + 1]));
630
+ }
631
+
632
+ const rawOutput = finalResult?.finalOutput ?? "";
633
+ const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
634
+ ? resolveSingleOutput(step.outputPath, rawOutput, outputSnapshot)
635
+ : { fullOutput: rawOutput };
636
+ const output = resolvedOutput.fullOutput;
637
+ let outputForSummary = output;
638
+ if (attemptNotes.length > 0) {
639
+ outputForSummary = `${attemptNotes.join("\n")}\n\n${outputForSummary}`.trim();
640
+ }
641
+ if (resolvedOutput.savedPath) {
642
+ outputForSummary = outputForSummary
643
+ ? `${outputForSummary}\n\nOutput saved to: ${resolvedOutput.savedPath}`
644
+ : `Output saved to: ${resolvedOutput.savedPath}`;
645
+ } else if (resolvedOutput.saveError && step.outputPath && finalResult?.exitCode === 0) {
646
+ outputForSummary = outputForSummary
647
+ ? `${outputForSummary}\n\nFailed to save output to: ${step.outputPath}\n${resolvedOutput.saveError}`
648
+ : `Failed to save output to: ${step.outputPath}\n${resolvedOutput.saveError}`;
649
+ }
650
+
651
+ if (artifactPaths && ctx.artifactConfig?.enabled !== false) {
652
+ if (ctx.artifactConfig?.includeOutput !== false) {
653
+ fs.writeFileSync(artifactPaths.outputPath, output, "utf-8");
654
+ }
655
+ if (ctx.artifactConfig?.includeMetadata !== false) {
656
+ fs.writeFileSync(
657
+ artifactPaths.metadataPath,
658
+ JSON.stringify({
659
+ runId: ctx.id,
660
+ agent: step.agent,
661
+ task,
662
+ exitCode: finalResult?.exitCode,
663
+ model: finalResult?.model,
664
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
665
+ modelAttempts,
666
+ skills: step.skills,
667
+ timestamp: Date.now(),
668
+ }, null, 2),
669
+ "utf-8",
670
+ );
671
+ }
672
+ }
673
+
674
+ return {
675
+ agent: step.agent,
676
+ output: outputForSummary,
677
+ exitCode: finalResult?.exitCode ?? 1,
678
+ error: finalResult?.error,
679
+ intercomTarget: ctx.childIntercomTarget,
680
+ model: finalResult?.model,
681
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
682
+ modelAttempts,
683
+ artifactPaths,
684
+ interrupted: finalResult?.interrupted,
685
+ };
686
+ }
687
+
688
+ type RunnerStatusPayload = {
689
+ runId: string;
690
+ mode: "single" | "chain";
691
+ state: "queued" | "running" | "complete" | "failed" | "paused";
692
+ activityState?: ActivityState;
693
+ lastActivityAt?: number;
694
+ currentTool?: string;
695
+ currentToolStartedAt?: number;
696
+ startedAt: number;
697
+ endedAt?: number;
698
+ lastUpdate: number;
699
+ pid: number;
700
+ cwd: string;
701
+ currentStep: number;
702
+ steps: Array<{
703
+ agent: string;
704
+ status: "pending" | "running" | "complete" | "failed";
705
+ activityState?: ActivityState;
706
+ lastActivityAt?: number;
707
+ currentTool?: string;
708
+ currentToolStartedAt?: number;
709
+ startedAt?: number;
710
+ endedAt?: number;
711
+ durationMs?: number;
712
+ exitCode?: number | null;
713
+ tokens?: TokenUsage;
714
+ skills?: string[];
715
+ model?: string;
716
+ attemptedModels?: string[];
717
+ modelAttempts?: ModelAttempt[];
718
+ error?: string;
719
+ }>;
720
+ artifactsDir?: string;
721
+ sessionDir?: string;
722
+ outputFile?: string;
723
+ totalTokens?: TokenUsage;
724
+ sessionFile?: string;
725
+ shareUrl?: string;
726
+ gistUrl?: string;
727
+ shareError?: string;
728
+ error?: string;
729
+ };
730
+
731
+ function markParallelGroupSetupFailure(input: {
732
+ statusPayload: RunnerStatusPayload;
733
+ results: StepResult[];
734
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
735
+ groupStartFlatIndex: number;
736
+ setupError: string;
737
+ failedAt: number;
738
+ statusPath: string;
739
+ eventsPath: string;
740
+ asyncDir: string;
741
+ runId: string;
742
+ stepIndex: number;
743
+ }): void {
744
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
745
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
746
+ input.statusPayload.steps[flatTaskIndex].status = "failed";
747
+ input.statusPayload.steps[flatTaskIndex].startedAt = input.failedAt;
748
+ input.statusPayload.steps[flatTaskIndex].endedAt = input.failedAt;
749
+ input.statusPayload.steps[flatTaskIndex].durationMs = 0;
750
+ input.statusPayload.steps[flatTaskIndex].exitCode = 1;
751
+ input.results.push({ agent: input.group.parallel[taskIndex].agent, output: input.setupError, success: false });
752
+ }
753
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
754
+ input.statusPayload.lastUpdate = input.failedAt;
755
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
756
+ writeJson(input.statusPath, input.statusPayload);
757
+ appendJsonl(input.eventsPath, JSON.stringify({
758
+ type: "subagent.parallel.completed",
759
+ ts: input.failedAt,
760
+ runId: input.runId,
761
+ stepIndex: input.stepIndex,
762
+ success: false,
763
+ }));
764
+ }
765
+
766
+ function markParallelGroupRunning(input: {
767
+ statusPayload: RunnerStatusPayload;
768
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
769
+ groupStartFlatIndex: number;
770
+ groupStartTime: number;
771
+ statusPath: string;
772
+ eventsPath: string;
773
+ asyncDir: string;
774
+ runId: string;
775
+ stepIndex: number;
776
+ }): void {
777
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
778
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
779
+ input.statusPayload.steps[flatTaskIndex].status = "running";
780
+ input.statusPayload.steps[flatTaskIndex].startedAt = input.groupStartTime;
781
+ input.statusPayload.steps[flatTaskIndex].lastActivityAt = input.groupStartTime;
782
+ }
783
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
784
+ input.statusPayload.activityState = undefined;
785
+ input.statusPayload.lastActivityAt = input.groupStartTime;
786
+ input.statusPayload.lastUpdate = input.groupStartTime;
787
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
788
+ writeJson(input.statusPath, input.statusPayload);
789
+ appendJsonl(input.eventsPath, JSON.stringify({
790
+ type: "subagent.parallel.started",
791
+ ts: input.groupStartTime,
792
+ runId: input.runId,
793
+ stepIndex: input.stepIndex,
794
+ agents: input.group.parallel.map((task) => task.agent),
795
+ count: input.group.parallel.length,
796
+ }));
797
+ }
798
+
799
+ function prepareParallelTaskRun(
800
+ task: SubagentStep,
801
+ cwd: string,
802
+ worktreeSetup: WorktreeSetup | undefined,
803
+ taskIndex: number,
804
+ ): { taskForRun: SubagentStep; taskCwd: string } {
805
+ if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
806
+ return {
807
+ taskForRun: { ...task, cwd: undefined },
808
+ taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
809
+ };
810
+ }
811
+
812
+ function appendParallelWorktreeSummary(
813
+ previousOutput: string,
814
+ worktreeSetup: WorktreeSetup | undefined,
815
+ asyncDir: string,
816
+ stepIndex: number,
817
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>,
818
+ ): string {
819
+ if (!worktreeSetup) return previousOutput;
820
+ const diffsDir = path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`);
821
+ const diffs = diffWorktrees(worktreeSetup, group.parallel.map((task) => task.agent), diffsDir);
822
+ const diffSummary = formatWorktreeDiffSummary(diffs);
823
+ if (!diffSummary) return previousOutput;
824
+ return `${previousOutput}\n\n${diffSummary}`;
825
+ }
826
+
827
+ function ensureParallelProgressFile(cwd: string, group: Extract<RunnerStep, { parallel: SubagentStep[] }>): void {
828
+ const progressPath = path.join(cwd, "progress.md");
829
+ if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`))) return;
830
+ writeInitialProgressFile(cwd);
831
+ }
832
+
833
+ async function runSubagent(config: SubagentRunConfig): Promise<void> {
834
+ const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
835
+ config;
836
+ let previousOutput = "";
837
+ const results: StepResult[] = [];
838
+ const overallStartTime = Date.now();
839
+ const shareEnabled = config.share === true;
840
+ const asyncDir = config.asyncDir;
841
+ const statusPath = path.join(asyncDir, "status.json");
842
+ const eventsPath = path.join(asyncDir, "events.jsonl");
843
+ const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
844
+ const controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;
845
+ let activeChildInterrupt: (() => void) | undefined;
846
+ let interrupted = false;
847
+ let currentActivityState: ActivityState | undefined;
848
+ let activityTimer: NodeJS.Timeout | undefined;
849
+ let previousCumulativeTokens: TokenUsage = { input: 0, output: 0, total: 0 };
850
+ let latestSessionFile: string | undefined;
851
+
852
+ const flatSteps = flattenSteps(steps);
853
+ const sessionEnabled = Boolean(config.sessionDir)
854
+ || shareEnabled
855
+ || flatSteps.some((step) => Boolean(step.sessionFile));
856
+ const statusPayload: RunnerStatusPayload = {
857
+ runId: id,
858
+ mode: flatSteps.length > 1 ? "chain" : "single",
859
+ state: "running",
860
+ lastActivityAt: overallStartTime,
861
+ startedAt: overallStartTime,
862
+ lastUpdate: overallStartTime,
863
+ pid: process.pid,
864
+ cwd,
865
+ currentStep: 0,
866
+ steps: flatSteps.map((step) => ({
867
+ agent: step.agent,
868
+ status: "pending",
869
+ skills: step.skills,
870
+ model: step.model,
871
+ attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
872
+ })),
873
+ artifactsDir,
874
+ sessionDir: config.sessionDir,
875
+ outputFile: path.join(asyncDir, "output-0.log"),
876
+ };
877
+
878
+ fs.mkdirSync(asyncDir, { recursive: true });
879
+ writeJson(statusPath, statusPayload);
880
+
881
+ const currentStepAgent = () => statusPayload.steps[statusPayload.currentStep]?.agent ?? flatSteps[statusPayload.currentStep]?.agent ?? "subagent";
882
+ const currentOutputActivityAt = (): number => {
883
+ const runningIndexes = statusPayload.steps
884
+ .map((step, index) => step.status === "running" ? index : -1)
885
+ .filter((index) => index >= 0);
886
+ let lastActivityAt = statusPayload.steps[statusPayload.currentStep]?.startedAt ?? overallStartTime;
887
+ for (const index of runningIndexes.length > 0 ? runningIndexes : [statusPayload.currentStep]) {
888
+ try {
889
+ lastActivityAt = Math.max(lastActivityAt, fs.statSync(path.join(asyncDir, `output-${index}.log`)).mtimeMs);
890
+ } catch {
891
+ // Missing output files are normal before a child writes its first line.
892
+ }
893
+ }
894
+ return lastActivityAt;
895
+ };
896
+ const emittedControlEventKeys = new Set<string>();
897
+ const appendControlEvent = (event: ReturnType<typeof buildControlEvent>) => {
898
+ const childIntercomTarget = config.childIntercomTargets?.[statusPayload.currentStep];
899
+ if (controlConfig.notifyChannels.length === 0 || !claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget)) return;
900
+ appendJsonl(eventsPath, JSON.stringify({
901
+ type: "subagent.control",
902
+ event,
903
+ channels: controlConfig.notifyChannels,
904
+ childIntercomTarget,
905
+ noticeText: formatControlNoticeMessage(event, childIntercomTarget),
906
+ ...(config.controlIntercomTarget && controlConfig.notifyChannels.includes("intercom") ? {
907
+ intercom: {
908
+ to: config.controlIntercomTarget,
909
+ message: formatControlIntercomMessage(event, childIntercomTarget),
910
+ },
911
+ } : {}),
912
+ }));
913
+ };
914
+ const updateRunnerActivityState = (now: number): boolean => {
915
+ const lastActivityAt = currentOutputActivityAt();
916
+ const next = deriveActivityState({
917
+ config: controlConfig,
918
+ startedAt: overallStartTime,
919
+ lastActivityAt,
920
+ now,
921
+ });
922
+ if (next === currentActivityState && statusPayload.lastActivityAt === lastActivityAt) return false;
923
+ const previous = currentActivityState;
924
+ currentActivityState = next;
925
+ statusPayload.activityState = next;
926
+ statusPayload.lastActivityAt = lastActivityAt;
927
+ for (const step of statusPayload.steps) {
928
+ if (step.status === "running") {
929
+ step.activityState = next;
930
+ step.lastActivityAt = lastActivityAt;
931
+ }
932
+ }
933
+ statusPayload.lastUpdate = now;
934
+ if (shouldEmitControlEvent(controlConfig, previous, next)) {
935
+ const event = buildControlEvent({
936
+ from: previous,
937
+ to: next,
938
+ runId: id,
939
+ agent: currentStepAgent(),
940
+ index: statusPayload.currentStep,
941
+ ts: now,
942
+ lastActivityAt,
943
+ });
944
+ appendControlEvent(event);
945
+ }
946
+ writeJson(statusPath, statusPayload);
947
+ return true;
948
+ };
949
+ if (controlConfig.enabled) {
950
+ activityTimer = setInterval(() => {
951
+ if (statusPayload.state !== "running") return;
952
+ const now = Date.now();
953
+ updateRunnerActivityState(now);
954
+ }, 1000);
955
+ activityTimer.unref?.();
956
+ }
957
+
958
+ const interruptRunner = () => {
959
+ if (interrupted || statusPayload.state !== "running") return;
960
+ interrupted = true;
961
+ const now = Date.now();
962
+ statusPayload.state = "paused";
963
+ currentActivityState = undefined;
964
+ statusPayload.activityState = undefined;
965
+ statusPayload.lastUpdate = now;
966
+ const current = statusPayload.steps[statusPayload.currentStep];
967
+ if (current?.status === "running") {
968
+ current.activityState = undefined;
969
+ current.endedAt = now;
970
+ current.durationMs = current.startedAt ? now - current.startedAt : undefined;
971
+ }
972
+ writeJson(statusPath, statusPayload);
973
+ appendJsonl(eventsPath, JSON.stringify({
974
+ type: "subagent.run.paused",
975
+ ts: now,
976
+ runId: id,
977
+ }));
978
+ activeChildInterrupt?.();
979
+ };
980
+ process.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
981
+ appendJsonl(
982
+ eventsPath,
983
+ JSON.stringify({
984
+ type: "subagent.run.started",
985
+ ts: overallStartTime,
986
+ runId: id,
987
+ mode: statusPayload.mode,
988
+ cwd,
989
+ pid: process.pid,
990
+ }),
991
+ );
992
+
993
+ let flatIndex = 0;
994
+
995
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
996
+ if (interrupted) break;
997
+ const step = steps[stepIndex];
998
+
999
+ if (isParallelGroup(step)) {
1000
+ const group = step;
1001
+ const concurrency = group.concurrency ?? MAX_PARALLEL_CONCURRENCY;
1002
+ const failFast = group.failFast ?? false;
1003
+ const groupStartFlatIndex = flatIndex;
1004
+ let aborted = false;
1005
+ let worktreeSetup: WorktreeSetup | undefined;
1006
+ if (group.worktree) {
1007
+ const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, cwd);
1008
+ if (worktreeTaskCwdConflict) {
1009
+ const failedAt = Date.now();
1010
+ markParallelGroupSetupFailure({
1011
+ statusPayload,
1012
+ results,
1013
+ group,
1014
+ groupStartFlatIndex,
1015
+ setupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, cwd),
1016
+ failedAt,
1017
+ statusPath,
1018
+ eventsPath,
1019
+ asyncDir,
1020
+ runId: id,
1021
+ stepIndex,
1022
+ });
1023
+ flatIndex += group.parallel.length;
1024
+ break;
1025
+ }
1026
+ try {
1027
+ worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, {
1028
+ agents: group.parallel.map((task) => task.agent),
1029
+ setupHook: config.worktreeSetupHook
1030
+ ? { hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs }
1031
+ : undefined,
1032
+ });
1033
+ } catch (error) {
1034
+ const setupError = error instanceof Error ? error.message : String(error);
1035
+ const failedAt = Date.now();
1036
+ markParallelGroupSetupFailure({
1037
+ statusPayload,
1038
+ results,
1039
+ group,
1040
+ groupStartFlatIndex,
1041
+ setupError,
1042
+ failedAt,
1043
+ statusPath,
1044
+ eventsPath,
1045
+ asyncDir,
1046
+ runId: id,
1047
+ stepIndex,
1048
+ });
1049
+ flatIndex += group.parallel.length;
1050
+ break;
1051
+ }
1052
+ }
1053
+
1054
+ try {
1055
+ if (group.worktree) ensureParallelProgressFile(cwd, group);
1056
+ const groupStartTime = Date.now();
1057
+ markParallelGroupRunning({
1058
+ statusPayload,
1059
+ group,
1060
+ groupStartFlatIndex,
1061
+ groupStartTime,
1062
+ statusPath,
1063
+ eventsPath,
1064
+ asyncDir,
1065
+ runId: id,
1066
+ stepIndex,
1067
+ });
1068
+ const parallelResults = await mapConcurrent(
1069
+ group.parallel,
1070
+ concurrency,
1071
+ async (task, taskIdx) => {
1072
+ if (aborted && failFast) {
1073
+ return { agent: task.agent, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true };
1074
+ }
1075
+
1076
+ const fi = groupStartFlatIndex + taskIdx;
1077
+ const taskStartTime = Date.now();
1078
+
1079
+ appendJsonl(eventsPath, JSON.stringify({
1080
+ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent,
1081
+ }));
1082
+
1083
+ const taskSessionDir = config.sessionDir
1084
+ ? path.join(config.sessionDir, `parallel-${taskIdx}`)
1085
+ : undefined;
1086
+ const { taskForRun, taskCwd } = prepareParallelTaskRun(task, cwd, worktreeSetup, taskIdx);
1087
+
1088
+ const singleResult = await runSingleStep(taskForRun, {
1089
+ previousOutput, placeholder, cwd: taskCwd, sessionEnabled,
1090
+ sessionDir: taskSessionDir,
1091
+ artifactsDir, artifactConfig, id,
1092
+ flatIndex: fi, flatStepCount: flatSteps.length,
1093
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
1094
+ piPackageRoot: config.piPackageRoot,
1095
+ piArgv1: config.piArgv1,
1096
+ childIntercomTarget: config.childIntercomTargets?.[fi],
1097
+ registerInterrupt: (interrupt) => {
1098
+ activeChildInterrupt = interrupt;
1099
+ },
1100
+ });
1101
+ if (task.sessionFile) {
1102
+ latestSessionFile = task.sessionFile;
1103
+ }
1104
+
1105
+ const taskEndTime = Date.now();
1106
+ const taskDuration = taskEndTime - taskStartTime;
1107
+
1108
+ statusPayload.steps[fi].status = singleResult.exitCode === 0 ? "complete" : "failed";
1109
+ statusPayload.steps[fi].endedAt = taskEndTime;
1110
+ statusPayload.steps[fi].durationMs = taskDuration;
1111
+ statusPayload.steps[fi].exitCode = singleResult.exitCode;
1112
+ statusPayload.steps[fi].model = singleResult.model;
1113
+ statusPayload.steps[fi].attemptedModels = singleResult.attemptedModels;
1114
+ statusPayload.steps[fi].modelAttempts = singleResult.modelAttempts;
1115
+ statusPayload.steps[fi].error = singleResult.error;
1116
+ statusPayload.lastUpdate = taskEndTime;
1117
+ writeJson(statusPath, statusPayload);
1118
+
1119
+ appendJsonl(eventsPath, JSON.stringify({
1120
+ type: singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
1121
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
1122
+ exitCode: singleResult.exitCode, durationMs: taskDuration,
1123
+ }));
1124
+
1125
+ if (singleResult.exitCode !== 0 && failFast) aborted = true;
1126
+ return { ...singleResult, skipped: false };
1127
+ },
1128
+ );
1129
+
1130
+ flatIndex += group.parallel.length;
1131
+
1132
+ for (let t = 0; t < group.parallel.length; t++) {
1133
+ const fi = groupStartFlatIndex + t;
1134
+ const sessionTokens = config.sessionDir
1135
+ ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
1136
+ : null;
1137
+ const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
1138
+ if (!taskTokens) continue;
1139
+ statusPayload.steps[fi].tokens = taskTokens;
1140
+ previousCumulativeTokens = {
1141
+ input: previousCumulativeTokens.input + taskTokens.input,
1142
+ output: previousCumulativeTokens.output + taskTokens.output,
1143
+ total: previousCumulativeTokens.total + taskTokens.total,
1144
+ };
1145
+ }
1146
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
1147
+ statusPayload.lastUpdate = Date.now();
1148
+ writeJson(statusPath, statusPayload);
1149
+
1150
+ for (const pr of parallelResults) {
1151
+ results.push({
1152
+ agent: pr.agent,
1153
+ output: pr.output,
1154
+ success: pr.exitCode === 0,
1155
+ skipped: pr.skipped,
1156
+ intercomTarget: pr.intercomTarget,
1157
+ model: pr.model,
1158
+ attemptedModels: pr.attemptedModels,
1159
+ modelAttempts: pr.modelAttempts,
1160
+ artifactPaths: pr.artifactPaths,
1161
+ });
1162
+ }
1163
+
1164
+ previousOutput = aggregateParallelOutputs(
1165
+ parallelResults.map((r) => ({
1166
+ agent: r.agent,
1167
+ output: r.output,
1168
+ exitCode: r.exitCode,
1169
+ error: r.error,
1170
+ model: r.model,
1171
+ attemptedModels: r.attemptedModels,
1172
+ })),
1173
+ );
1174
+ previousOutput = appendParallelWorktreeSummary(previousOutput, worktreeSetup, asyncDir, stepIndex, group);
1175
+
1176
+ appendJsonl(eventsPath, JSON.stringify({
1177
+ type: "subagent.parallel.completed",
1178
+ ts: Date.now(),
1179
+ runId: id,
1180
+ stepIndex,
1181
+ success: parallelResults.every((r) => r.exitCode === 0 || r.exitCode === -1),
1182
+ }));
1183
+
1184
+ if (parallelResults.some((r) => r.exitCode !== 0 && r.exitCode !== -1)) {
1185
+ break;
1186
+ }
1187
+ } finally {
1188
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
1189
+ }
1190
+ } else {
1191
+ const seqStep = step as SubagentStep;
1192
+ const stepStartTime = Date.now();
1193
+ statusPayload.currentStep = flatIndex;
1194
+ statusPayload.steps[flatIndex].status = "running";
1195
+ statusPayload.steps[flatIndex].activityState = undefined;
1196
+ statusPayload.activityState = undefined;
1197
+ statusPayload.steps[flatIndex].skills = seqStep.skills;
1198
+ statusPayload.steps[flatIndex].startedAt = stepStartTime;
1199
+ statusPayload.steps[flatIndex].lastActivityAt = stepStartTime;
1200
+ statusPayload.lastActivityAt = stepStartTime;
1201
+ statusPayload.lastUpdate = stepStartTime;
1202
+ statusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);
1203
+ writeJson(statusPath, statusPayload);
1204
+
1205
+ appendJsonl(eventsPath, JSON.stringify({
1206
+ type: "subagent.step.started",
1207
+ ts: stepStartTime,
1208
+ runId: id,
1209
+ stepIndex: flatIndex,
1210
+ agent: seqStep.agent,
1211
+ }));
1212
+
1213
+ const singleResult = await runSingleStep(seqStep, {
1214
+ previousOutput, placeholder, cwd, sessionEnabled,
1215
+ sessionDir: config.sessionDir,
1216
+ artifactsDir, artifactConfig, id,
1217
+ flatIndex, flatStepCount: flatSteps.length,
1218
+ outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
1219
+ piPackageRoot: config.piPackageRoot,
1220
+ piArgv1: config.piArgv1,
1221
+ childIntercomTarget: config.childIntercomTargets?.[flatIndex],
1222
+ registerInterrupt: (interrupt) => {
1223
+ activeChildInterrupt = interrupt;
1224
+ },
1225
+ });
1226
+ if (seqStep.sessionFile) {
1227
+ latestSessionFile = seqStep.sessionFile;
1228
+ }
1229
+
1230
+ previousOutput = singleResult.output;
1231
+ results.push({
1232
+ agent: singleResult.agent,
1233
+ output: singleResult.output,
1234
+ success: singleResult.exitCode === 0,
1235
+ intercomTarget: singleResult.intercomTarget,
1236
+ model: singleResult.model,
1237
+ attemptedModels: singleResult.attemptedModels,
1238
+ modelAttempts: singleResult.modelAttempts,
1239
+ artifactPaths: singleResult.artifactPaths,
1240
+ });
1241
+
1242
+ const cumulativeTokens = config.sessionDir ? parseSessionTokens(config.sessionDir) : null;
1243
+ let stepTokens: TokenUsage | null = cumulativeTokens
1244
+ ? {
1245
+ input: cumulativeTokens.input - previousCumulativeTokens.input,
1246
+ output: cumulativeTokens.output - previousCumulativeTokens.output,
1247
+ total: cumulativeTokens.total - previousCumulativeTokens.total,
1248
+ }
1249
+ : null;
1250
+ if (cumulativeTokens) {
1251
+ previousCumulativeTokens = cumulativeTokens;
1252
+ } else {
1253
+ stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
1254
+ if (stepTokens) {
1255
+ previousCumulativeTokens = {
1256
+ input: previousCumulativeTokens.input + stepTokens.input,
1257
+ output: previousCumulativeTokens.output + stepTokens.output,
1258
+ total: previousCumulativeTokens.total + stepTokens.total,
1259
+ };
1260
+ }
1261
+ }
1262
+
1263
+ const stepEndTime = Date.now();
1264
+ statusPayload.steps[flatIndex].status = singleResult.exitCode === 0 ? "complete" : "failed";
1265
+ statusPayload.steps[flatIndex].endedAt = stepEndTime;
1266
+ statusPayload.steps[flatIndex].durationMs = stepEndTime - stepStartTime;
1267
+ statusPayload.steps[flatIndex].exitCode = singleResult.exitCode;
1268
+ statusPayload.steps[flatIndex].model = singleResult.model;
1269
+ statusPayload.steps[flatIndex].attemptedModels = singleResult.attemptedModels;
1270
+ statusPayload.steps[flatIndex].modelAttempts = singleResult.modelAttempts;
1271
+ statusPayload.steps[flatIndex].error = singleResult.error;
1272
+ if (stepTokens) {
1273
+ statusPayload.steps[flatIndex].tokens = stepTokens;
1274
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
1275
+ }
1276
+ statusPayload.lastUpdate = stepEndTime;
1277
+ writeJson(statusPath, statusPayload);
1278
+
1279
+ appendJsonl(eventsPath, JSON.stringify({
1280
+ type: singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
1281
+ ts: stepEndTime,
1282
+ runId: id,
1283
+ stepIndex: flatIndex,
1284
+ agent: seqStep.agent,
1285
+ exitCode: singleResult.exitCode,
1286
+ durationMs: stepEndTime - stepStartTime,
1287
+ tokens: stepTokens,
1288
+ }));
1289
+
1290
+ flatIndex++;
1291
+ if (singleResult.exitCode !== 0) {
1292
+ break;
1293
+ }
1294
+ }
1295
+ }
1296
+
1297
+ let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
1298
+ let truncated = false;
1299
+
1300
+ if (maxOutput) {
1301
+ const config = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };
1302
+ const lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;
1303
+ const truncResult = truncateOutput(summary, config, lastArtifactPath);
1304
+ if (truncResult.truncated) {
1305
+ summary = truncResult.text;
1306
+ truncated = true;
1307
+ }
1308
+ }
1309
+
1310
+ const agentName = flatSteps.length === 1
1311
+ ? flatSteps[0].agent
1312
+ : `chain:${flatSteps.map((s) => s.agent).join("->")}`;
1313
+ let sessionFile: string | undefined;
1314
+ let shareUrl: string | undefined;
1315
+ let gistUrl: string | undefined;
1316
+ let shareError: string | undefined;
1317
+
1318
+ if (shareEnabled) {
1319
+ sessionFile = config.sessionDir
1320
+ ? (findLatestSessionFile(config.sessionDir) ?? undefined)
1321
+ : undefined;
1322
+ if (!sessionFile && latestSessionFile) {
1323
+ sessionFile = latestSessionFile;
1324
+ }
1325
+ if (sessionFile) {
1326
+ try {
1327
+ const exportDir = config.sessionDir ?? path.dirname(sessionFile);
1328
+ const htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);
1329
+ const share = createShareLink(htmlPath);
1330
+ if ("error" in share) shareError = share.error;
1331
+ else {
1332
+ shareUrl = share.shareUrl;
1333
+ gistUrl = share.gistUrl;
1334
+ }
1335
+ } catch (err) {
1336
+ shareError = String(err);
1337
+ }
1338
+ } else {
1339
+ shareError = "Session file not found.";
1340
+ }
1341
+ }
1342
+
1343
+ if (activityTimer) {
1344
+ clearInterval(activityTimer);
1345
+ activityTimer = undefined;
1346
+ }
1347
+ const effectiveSessionFile = sessionFile ?? latestSessionFile;
1348
+ const runEndedAt = Date.now();
1349
+ statusPayload.state = interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
1350
+ statusPayload.activityState = undefined;
1351
+ statusPayload.endedAt = runEndedAt;
1352
+ statusPayload.lastUpdate = runEndedAt;
1353
+ statusPayload.sessionFile = effectiveSessionFile;
1354
+ statusPayload.shareUrl = shareUrl;
1355
+ statusPayload.gistUrl = gistUrl;
1356
+ statusPayload.shareError = shareError;
1357
+ if (statusPayload.state === "failed") {
1358
+ const failedStep = statusPayload.steps.find((s) => s.status === "failed");
1359
+ if (failedStep?.agent) {
1360
+ statusPayload.error = `Step failed: ${failedStep.agent}`;
1361
+ }
1362
+ }
1363
+ writeJson(statusPath, statusPayload);
1364
+ appendJsonl(
1365
+ eventsPath,
1366
+ JSON.stringify({
1367
+ type: "subagent.run.completed",
1368
+ ts: runEndedAt,
1369
+ runId: id,
1370
+ status: statusPayload.state,
1371
+ durationMs: runEndedAt - overallStartTime,
1372
+ }),
1373
+ );
1374
+ writeRunLog(logPath, {
1375
+ id,
1376
+ mode: statusPayload.mode,
1377
+ cwd,
1378
+ startedAt: overallStartTime,
1379
+ endedAt: runEndedAt,
1380
+ steps: statusPayload.steps.map((step) => ({
1381
+ agent: step.agent,
1382
+ status: step.status,
1383
+ durationMs: step.durationMs,
1384
+ })),
1385
+ summary,
1386
+ truncated,
1387
+ artifactsDir,
1388
+ sessionFile: effectiveSessionFile,
1389
+ shareUrl,
1390
+ shareError,
1391
+ });
1392
+
1393
+ try {
1394
+ writeJson(resultPath, {
1395
+ id,
1396
+ agent: agentName,
1397
+ mode: config.resultMode ?? statusPayload.mode,
1398
+ success: !interrupted && results.every((r) => r.success),
1399
+ state: interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed",
1400
+ summary: interrupted ? "Paused after interrupt. Waiting for explicit next action." : summary,
1401
+ results: results.map((r) => ({
1402
+ agent: r.agent,
1403
+ output: r.output,
1404
+ success: r.success,
1405
+ skipped: r.skipped || undefined,
1406
+ intercomTarget: r.intercomTarget,
1407
+ model: r.model,
1408
+ attemptedModels: r.attemptedModels,
1409
+ modelAttempts: r.modelAttempts,
1410
+ artifactPaths: r.artifactPaths,
1411
+ truncated: r.truncated,
1412
+ })),
1413
+ exitCode: interrupted || results.every((r) => r.success) ? 0 : 1,
1414
+ timestamp: runEndedAt,
1415
+ durationMs: runEndedAt - overallStartTime,
1416
+ truncated,
1417
+ artifactsDir,
1418
+ cwd,
1419
+ asyncDir,
1420
+ sessionId: config.sessionId,
1421
+ sessionFile: effectiveSessionFile,
1422
+ intercomTarget: config.controlIntercomTarget,
1423
+ shareUrl,
1424
+ gistUrl,
1425
+ shareError,
1426
+ ...(taskIndex !== undefined && { taskIndex }),
1427
+ ...(totalTasks !== undefined && { totalTasks }),
1428
+ });
1429
+ } catch (err) {
1430
+ console.error(`Failed to write result file ${resultPath}:`, err);
1431
+ }
1432
+ }
1433
+
1434
+ const configArg = process.argv[2];
1435
+ if (configArg) {
1436
+ try {
1437
+ const configJson = fs.readFileSync(configArg, "utf-8");
1438
+ const config = JSON.parse(configJson) as SubagentRunConfig;
1439
+ try {
1440
+ fs.unlinkSync(configArg);
1441
+ } catch {
1442
+ // Temp config cleanup is best effort.
1443
+ }
1444
+ runSubagent(config).catch((runErr) => {
1445
+ console.error("Subagent runner error:", runErr);
1446
+ process.exit(1);
1447
+ });
1448
+ } catch (err) {
1449
+ console.error("Subagent runner error:", err);
1450
+ process.exit(1);
1451
+ }
1452
+ } else {
1453
+ let input = "";
1454
+ process.stdin.setEncoding("utf-8");
1455
+ process.stdin.on("data", (chunk) => {
1456
+ input += chunk;
1457
+ });
1458
+ process.stdin.on("end", () => {
1459
+ try {
1460
+ const config = JSON.parse(input) as SubagentRunConfig;
1461
+ runSubagent(config).catch((runErr) => {
1462
+ console.error("Subagent runner error:", runErr);
1463
+ process.exit(1);
1464
+ });
1465
+ } catch (err) {
1466
+ console.error("Subagent runner error:", err);
1467
+ process.exit(1);
1468
+ }
1469
+ });
1470
+ }