@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -15,13 +15,14 @@ import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts"
15
15
  import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
16
16
  import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
17
17
  import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
18
- import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
18
+ import { buildChainInstructions, isCheckpointStep, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveExistingReadPaths, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
19
19
  import type { RunnerStep } from "../shared/parallel-utils.ts";
20
20
  import type { ContextMode } from "../shared/context-mode.ts";
21
21
  import { resolvePiPackageRoot } from "../shared/pi-spawn.ts";
22
+ import { resolveNodeExecutable } from "../../shared/node-executable.ts";
22
23
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
23
24
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
24
- import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, resolveChildCwd } from "../../shared/utils.ts";
25
+ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
25
26
  import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from "../shared/model-fallback.ts";
26
27
  import type { ModelScopeConfig } from "../shared/model-scope.ts";
27
28
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
@@ -30,17 +31,21 @@ import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
30
31
  import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.ts";
31
32
  import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
32
33
  import { resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
34
+ import { createRunFanoutBudget, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
33
35
  import {
34
36
  type AcceptanceInput,
35
37
  type AgentContract,
38
+ type AsyncStatus,
36
39
  type ArtifactConfig,
37
40
  type Details,
41
+ type IntercomBridgeConfig,
38
42
  type JsonSchemaObject,
39
43
  type MaxOutputConfig,
40
44
  type NestedRouteInfo,
41
45
  type ResolvedControlConfig,
42
46
  type ResolvedTurnBudget,
43
47
  type ResolvedToolBudget,
48
+ type RunFanoutBudgetDescriptor,
44
49
  type ToolBudgetConfig,
45
50
  type SubagentRunMode,
46
51
  type SteeringRecoveryDescriptor,
@@ -59,6 +64,7 @@ import { usageBudgetState } from "../shared/usage-budget.ts";
59
64
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
60
65
  import type { SessionLeaseRequest } from "../shared/session-lease.ts";
61
66
  import { finalizeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
67
+ import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
62
68
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
63
69
  import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
64
70
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
@@ -128,6 +134,8 @@ interface AsyncExecutionContext {
128
134
  interactive?: boolean;
129
135
  }
130
136
 
137
+ export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
138
+
131
139
  interface AsyncChainParams {
132
140
  chain: ChainStep[];
133
141
  task?: string;
@@ -169,8 +177,10 @@ interface AsyncChainParams {
169
177
  /** Global cap on simultaneously-running subagent tasks within the async run. */
170
178
  globalConcurrencyLimit?: number;
171
179
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
180
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
172
181
  parentWorkflowRunId?: string;
173
182
  workflowKey?: string;
183
+ activeAsyncCapacity?: ActiveAsyncCapacityHandle;
174
184
  }
175
185
 
176
186
  interface AsyncSingleParams {
@@ -179,6 +189,8 @@ interface AsyncSingleParams {
179
189
  /** Raw caller-facing goal used only by the started event. */
180
190
  goal?: string;
181
191
  agentConfig: AgentConfig;
192
+ /** Agent contract before per-run bridge injection, used only for recovery persistence. */
193
+ recoveryAgentConfig?: AgentConfig;
182
194
  ctx: AsyncExecutionContext;
183
195
  cwd?: string;
184
196
  maxOutput?: MaxOutputConfig;
@@ -206,6 +218,7 @@ interface AsyncSingleParams {
206
218
  worktreeSetupHookTimeoutMs?: number;
207
219
  worktreeBaseDir?: string;
208
220
  controlConfig?: ResolvedControlConfig;
221
+ intercomBridge?: IntercomBridgeConfig;
209
222
  controlIntercomTarget?: string;
210
223
  childIntercomTarget?: (agent: string, index: number) => string | undefined;
211
224
  nestedRoute?: NestedRouteInfo;
@@ -218,8 +231,10 @@ interface AsyncSingleParams {
218
231
  configToolBudget?: ResolvedToolBudget;
219
232
  allowZeroToolBudget?: boolean;
220
233
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
234
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
221
235
  parentWorkflowRunId?: string;
222
236
  workflowKey?: string;
237
+ activeAsyncCapacity?: ActiveAsyncCapacityHandle;
223
238
  }
224
239
 
225
240
  interface AsyncExecutionResult {
@@ -289,27 +304,6 @@ export function isAsyncAvailable(): boolean {
289
304
  return jitiCliPath !== undefined;
290
305
  }
291
306
 
292
- function isNodeExecutableName(execPath: string): boolean {
293
- const basename = path.basename(execPath).toLowerCase();
294
- return basename === "node" || basename === "node.exe" || basename === "nodejs" || basename === "nodejs.exe";
295
- }
296
-
297
- function canUseCurrentNodeExecutable(execPath: string): boolean {
298
- try {
299
- fs.accessSync(execPath, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
300
- return true;
301
- } catch {
302
- return false;
303
- }
304
- }
305
-
306
- function resolveAsyncRunnerNodeCommand(): string {
307
- if (isNodeExecutableName(process.execPath) && canUseCurrentNodeExecutable(process.execPath)) {
308
- return process.execPath;
309
- }
310
- return process.platform === "win32" ? "node.exe" : "node";
311
- }
312
-
313
307
  export function resolveAsyncRunnerLogPaths(cfg: object): { stdoutPath: string; stderrPath: string } | undefined {
314
308
  const asyncDir = typeof (cfg as { asyncDir?: unknown }).asyncDir === "string"
315
309
  ? (cfg as { asyncDir: string }).asyncDir
@@ -341,7 +335,7 @@ type RunnerStartupState = "ready" | "acknowledged";
341
335
 
342
336
  type RunnerStartupWaitResult =
343
337
  | { ok: true; token: string }
344
- | { ok: false; error: string };
338
+ | { ok: false; error: string; startupDidNotProceed?: boolean };
345
339
 
346
340
  function waitForStartupInterval(delayMs = 20): void {
347
341
  if (RUNNER_STARTUP_WAIT_VIEW) {
@@ -358,14 +352,14 @@ function readRunnerStartup(startupPath: string, expectedState: RunnerStartupStat
358
352
  if (!fs.existsSync(startupPath)) return undefined;
359
353
  try {
360
354
  const payload = JSON.parse(fs.readFileSync(startupPath, "utf-8")) as { state?: unknown; token?: unknown; error?: unknown };
361
- if (payload.state === "error" && typeof payload.error === "string") return { ok: false, error: payload.error };
355
+ if (payload.state === "error" && typeof payload.error === "string") return { ok: false, error: payload.error, startupDidNotProceed: true };
362
356
  if (payload.state !== expectedState) return undefined;
363
357
  if (typeof payload.token !== "string" || (expectedToken !== undefined && payload.token !== expectedToken)) {
364
- return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}` };
358
+ return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}`, startupDidNotProceed: true };
365
359
  }
366
360
  return { ok: true, token: payload.token };
367
361
  } catch (error) {
368
- return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}` };
362
+ return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}`, startupDidNotProceed: true };
369
363
  }
370
364
  }
371
365
 
@@ -379,7 +373,7 @@ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupS
379
373
  }
380
374
  const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
381
375
  if (finalResult) return finalResult;
382
- return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.` };
376
+ return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.`, startupDidNotProceed: true };
383
377
  }
384
378
 
385
379
  function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
@@ -400,20 +394,63 @@ function runnerIsAlive(pid: number): boolean {
400
394
  }
401
395
  }
402
396
 
403
- function terminateRunnerBeforeProceed(pid: number): void {
397
+ function terminateRunnerBeforeProceed(pid: number): boolean {
404
398
  for (const signal of ["SIGTERM", "SIGKILL"] as const) {
405
- if (!runnerIsAlive(pid)) return;
399
+ if (!runnerIsAlive(pid)) return true;
406
400
  try {
407
401
  process.kill(pid, signal);
408
402
  } catch {
409
- if (!runnerIsAlive(pid)) return;
403
+ if (!runnerIsAlive(pid)) return true;
410
404
  }
411
405
  const deadline = Date.now() + 1000;
412
406
  while (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupInterval();
413
407
  }
408
+ return !runnerIsAlive(pid);
409
+ }
410
+
411
+ function persistPreProceedStartupFailure(asyncDir: string, runId: string, runnerProcessInstanceId: string, sessionId: string | undefined, message: string): void {
412
+ const now = Date.now();
413
+ try {
414
+ const statusPath = path.join(asyncDir, "status.json");
415
+ let status: Partial<AsyncStatus> = {};
416
+ try {
417
+ status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Partial<AsyncStatus>;
418
+ } catch {}
419
+ writePrivateAtomicJson(statusPath, {
420
+ ...status,
421
+ runId,
422
+ ...(sessionId ? { sessionId } : {}),
423
+ state: "failed",
424
+ lastUpdate: now,
425
+ error: message,
426
+ processTerminal: {
427
+ version: 1,
428
+ state: "not-started",
429
+ runId,
430
+ runnerProcessInstanceId,
431
+ },
432
+ });
433
+ writePrivateAtomicJson(path.join(asyncDir, "process-terminal-candidate.json"), {
434
+ version: 1,
435
+ runId,
436
+ runnerProcessInstanceId,
437
+ writers: {},
438
+ expectedWriters: { 0: 0 },
439
+ });
440
+ } catch {
441
+ // Startup failures must still return the original launch error.
442
+ }
443
+ }
444
+
445
+ interface SpawnRunnerResult {
446
+ pid?: number;
447
+ runnerProcessInstanceId?: string;
448
+ error?: string;
449
+ terminationObserved?: boolean;
450
+ startupDidNotProceed?: boolean;
414
451
  }
415
452
 
416
- function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): { pid?: number; error?: string } {
453
+ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): SpawnRunnerResult {
417
454
  if (!jitiCliPath) {
418
455
  return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
419
456
  }
@@ -433,9 +470,11 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
433
470
  const launchConfig = { ...cfg, runnerProcessInstanceId };
434
471
  fs.writeFileSync(cfgPath, JSON.stringify(launchConfig));
435
472
  const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
436
- const nodeCommand = resolveAsyncRunnerNodeCommand();
437
- const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; revivalLease?: unknown };
473
+ const nodeCommand = resolveNodeExecutable();
474
+ const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; id?: unknown; sessionId?: unknown; revivalLease?: unknown };
438
475
  const launchAsyncDir = typeof launchForStartup.asyncDir === "string" ? launchForStartup.asyncDir : undefined;
476
+ const launchRunId = typeof launchForStartup.id === "string" ? launchForStartup.id : suffix;
477
+ const launchSessionId = typeof launchForStartup.sessionId === "string" ? launchForStartup.sessionId : undefined;
439
478
  const startupPath = typeof launchForStartup.revivalLease === "object" && launchAsyncDir
440
479
  ? path.join(launchAsyncDir, "runner-startup.json")
441
480
  : undefined;
@@ -524,27 +563,36 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
524
563
  }
525
564
  proc.unref();
526
565
  if (startupPath && startupAckPath && startupProceedPath) {
566
+ const persistStartupFailure = (message: string) => {
567
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, message);
568
+ };
527
569
  const ready = waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS);
528
570
  if (ready.ok === false) {
529
- terminateRunnerBeforeProceed(proc.pid);
530
- return { error: ready.error };
571
+ persistStartupFailure(ready.error);
572
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
573
+ return { pid: proc.pid, runnerProcessInstanceId, error: ready.error, terminationObserved, startupDidNotProceed: ready.startupDidNotProceed };
531
574
  }
532
575
  try {
533
576
  writeRunnerStartupControl(startupAckPath, { action: "ack", token: ready.token });
534
577
  } catch (error) {
535
- terminateRunnerBeforeProceed(proc.pid);
536
- return { error: `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}` };
578
+ const message = `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}`;
579
+ persistStartupFailure(message);
580
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
581
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
537
582
  }
538
583
  const acknowledged = waitForRunnerStartup(startupPath, "acknowledged", RUNNER_STARTUP_TIMEOUT_MS, ready.token);
539
584
  if (acknowledged.ok === false) {
540
- terminateRunnerBeforeProceed(proc.pid);
541
- return { error: acknowledged.error };
585
+ persistStartupFailure(acknowledged.error);
586
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
587
+ return { pid: proc.pid, runnerProcessInstanceId, error: acknowledged.error, terminationObserved, startupDidNotProceed: acknowledged.startupDidNotProceed };
542
588
  }
543
589
  try {
544
590
  writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: ready.token });
545
591
  } catch (error) {
546
- terminateRunnerBeforeProceed(proc.pid);
547
- return { error: `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}` };
592
+ const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
593
+ persistStartupFailure(message);
594
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
595
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
548
596
  }
549
597
  try {
550
598
  fs.rmSync(startupPath, { force: true });
@@ -552,7 +600,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
552
600
  // Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error.
553
601
  }
554
602
  }
555
- return { pid: proc.pid };
603
+ return { pid: proc.pid, runnerProcessInstanceId };
556
604
  } catch (error) {
557
605
  closeFd(stdoutFd);
558
606
  closeFd(stderrFd);
@@ -646,7 +694,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
646
694
  ...(s.model !== undefined ? { model: s.model } : {}),
647
695
  };
648
696
  };
649
- const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }) => {
697
+ const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }, runFanoutPath?: string) => {
650
698
  const a = agents.find((x) => x.name === s.agent)!;
651
699
  const externalRunner = a.runner?.type === "external-cli";
652
700
  if (externalRunner) {
@@ -668,6 +716,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
668
716
  if (resolvedToolBudget.error) throw new AsyncStartValidationError(resolvedToolBudget.error);
669
717
  const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
670
718
  const instructionCwd = behaviorCwd ?? stepCwd;
719
+ const readExistenceCwd = behaviorCwd ? stepCwd : instructionCwd;
671
720
  let behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
672
721
  const inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output);
673
722
  if (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {
@@ -698,7 +747,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
698
747
  }
699
748
  systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: stepCwd, agentName: a.name });
700
749
 
701
- const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);
750
+ const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false, undefined, readExistenceCwd);
702
751
  const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
703
752
  if (behavior.progress) progressInstructionCreated = true;
704
753
  const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
@@ -745,6 +794,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
745
794
  parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
746
795
  permissionRules,
747
796
  ...(params.capabilityCeiling ? { capabilityCeiling: params.capabilityCeiling } : {}),
797
+ ...(runFanoutPath ? { runFanoutPath } : {}),
748
798
  agent: s.agent,
749
799
  task,
750
800
  ...(a.runner ? { runner: a.runner } : {}),
@@ -776,6 +826,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
776
826
  outputMode: behavior.outputMode,
777
827
  sessionFile,
778
828
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
829
+ timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
779
830
  waitToolEnabled: params.waitToolEnabled,
780
831
  effectiveAcceptance: resolveEffectiveAcceptance({
781
832
  explicit: s.acceptance,
@@ -835,7 +886,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
835
886
  }
836
887
  }
837
888
  const staticStep = nextFlatStep();
838
- return buildSeqStep({ ...t, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex });
889
+ return buildSeqStep({ ...t, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex }, resultMode === "parallel" ? `tasks[${taskIndex}]` : `chain[${stepIndex}].parallel[${taskIndex}]`);
839
890
  }),
840
891
  concurrency: s.concurrency,
841
892
  failFast: s.failFast,
@@ -880,7 +931,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
880
931
  };
881
932
  }
882
933
  const staticStep = nextFlatStep();
883
- return buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index);
934
+ return buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index, undefined, `chain[${stepIndex}]`);
884
935
  });
885
936
  const steps = params.attachRoot
886
937
  ? [{
@@ -962,8 +1013,11 @@ export function executeAsyncChain(
962
1013
  const asyncDir = inheritedNestedRoute
963
1014
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
964
1015
  : path.join(DIRS.async, id);
1016
+ let runFanoutBudget: RunFanoutBudgetDescriptor;
965
1017
  try {
1018
+ runFanoutBudget = params.runFanoutBudget ?? createRunFanoutBudget(id, 64);
966
1019
  fs.mkdirSync(asyncDir, { recursive: true });
1020
+ writeRunFanoutBudgetDescriptor(asyncDir, runFanoutBudget);
967
1021
  } catch (error) {
968
1022
  const message = error instanceof Error ? error.message : String(error);
969
1023
  return {
@@ -1026,7 +1080,7 @@ export function executeAsyncChain(
1026
1080
  return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
1027
1081
  }) : undefined;
1028
1082
 
1029
- let spawnResult: { pid?: number; error?: string } = {};
1083
+ let spawnResult: SpawnRunnerResult = {};
1030
1084
  try {
1031
1085
  spawnResult = spawnRunner(
1032
1086
  {
@@ -1059,6 +1113,7 @@ export function executeAsyncChain(
1059
1113
  timeoutMs: params.timeoutMs,
1060
1114
  deadlineAt,
1061
1115
  globalConcurrencyLimit: params.globalConcurrencyLimit,
1116
+ runFanoutBudget,
1062
1117
  workflowGraph,
1063
1118
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1064
1119
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
@@ -1075,13 +1130,21 @@ export function executeAsyncChain(
1075
1130
  (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1076
1131
  );
1077
1132
  } catch (error) {
1133
+ params.activeAsyncCapacity?.rollback();
1078
1134
  const message = error instanceof Error ? error.message : String(error);
1079
1135
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
1080
1136
  }
1081
1137
 
1082
1138
  if (spawnResult.error) {
1139
+ if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
1140
+ else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1083
1141
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
1084
1142
  }
1143
+ if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) {
1144
+ params.activeAsyncCapacity?.rollback();
1145
+ return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': runner identity unavailable`);
1146
+ }
1147
+ params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1085
1148
 
1086
1149
  if (spawnResult.pid) {
1087
1150
  const eventFirstStep = eventChain[0];
@@ -1162,8 +1225,8 @@ export function executeAsyncChain(
1162
1225
  mode: resultMode,
1163
1226
  agent: firstAgents[0],
1164
1227
  agents: flatAgents,
1165
- task: firstTask?.slice(0, 50),
1166
- goal: workflowGoal?.slice(0, 120),
1228
+ task: firstTask?.trim() ? PROMPT_REDACTED : undefined,
1229
+ goal: workflowGoal?.trim() ? PROMPT_REDACTED : undefined,
1167
1230
  chain: eventChain.map((s) =>
1168
1231
  isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : (s as SequentialStep).agent,
1169
1232
  ),
@@ -1172,6 +1235,7 @@ export function executeAsyncChain(
1172
1235
  workflowGraph,
1173
1236
  cwd: runnerCwd,
1174
1237
  asyncDir,
1238
+ ...(sessionRoot ? { sessionRoot } : {}),
1175
1239
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1176
1240
  ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1177
1241
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
@@ -1197,6 +1261,10 @@ export function executeAsyncChain(
1197
1261
  /**
1198
1262
  * Execute a single agent asynchronously
1199
1263
  */
1264
+ export function workflowAwaitedAsyncResultPath(asyncDir: string): string {
1265
+ return path.join(asyncDir, "workflow-result.json");
1266
+ }
1267
+
1200
1268
  export function executeAsyncSingle(
1201
1269
  id: string,
1202
1270
  params: AsyncSingleParams,
@@ -1271,8 +1339,11 @@ export function executeAsyncSingle(
1271
1339
  const asyncDir = inheritedNestedRoute
1272
1340
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1273
1341
  : path.join(DIRS.async, id);
1342
+ let runFanoutBudget: RunFanoutBudgetDescriptor;
1274
1343
  try {
1344
+ runFanoutBudget = params.runFanoutBudget ?? createRunFanoutBudget(id, 64);
1275
1345
  fs.mkdirSync(asyncDir, { recursive: true });
1346
+ writeRunFanoutBudgetDescriptor(asyncDir, runFanoutBudget);
1276
1347
  } catch (error) {
1277
1348
  const message = error instanceof Error ? error.message : String(error);
1278
1349
  return {
@@ -1292,8 +1363,9 @@ export function executeAsyncSingle(
1292
1363
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1293
1364
  // absolute paths pass through; relative paths resolve against the child cwd.
1294
1365
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1295
- const readsInstruction = Array.isArray(reads) && reads.length > 0
1296
- ? `[Read from: ${reads.map((f) => resolveChainPath(f, runnerCwd)).join(", ")}]\n\n`
1366
+ const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, runnerCwd) : [];
1367
+ const readsInstruction = readPaths.length > 0
1368
+ ? `[Read from: ${readPaths.join(", ")}]\n\n`
1297
1369
  : "";
1298
1370
  const taskText = readsInstruction + taskWithOutputInstruction;
1299
1371
  const primaryModel = externalRunner ? undefined : resolveSubagentModelOverride(
@@ -1364,9 +1436,11 @@ export function executeAsyncSingle(
1364
1436
  async: true,
1365
1437
  agentContract: params.agentContract,
1366
1438
  });
1439
+ const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1367
1440
  const recoveryDescriptor: SteeringRecoveryDescriptor = {
1368
1441
  version: 1,
1369
1442
  launchContractDigest,
1443
+ runFanoutBudget,
1370
1444
  sourceRunId: id,
1371
1445
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1372
1446
  agent,
@@ -1374,30 +1448,31 @@ export function executeAsyncSingle(
1374
1448
  ...(sessionFile ? { sessionFile } : {}),
1375
1449
  cwd: runnerCwd,
1376
1450
  ...(model ? { model } : {}),
1377
- ...(agentConfig.fallbackModels ? { fallbackModels: [...agentConfig.fallbackModels] } : {}),
1451
+ ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1378
1452
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1379
- ...(agentConfig.tools ? { tools: [...agentConfig.tools] } : {}),
1380
- ...(agentConfig.extensions ? { extensions: [...agentConfig.extensions] } : {}),
1381
- ...(agentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agentConfig.subagentOnlyExtensions] } : {}),
1382
- ...(agentConfig.mcpDirectTools ? { mcpDirectTools: [...agentConfig.mcpDirectTools] } : {}),
1383
- ...(agentConfig.systemPrompt ? { systemPrompt: agentConfig.systemPrompt } : {}),
1384
- systemPromptMode: agentConfig.systemPromptMode,
1385
- inheritProjectContext: agentConfig.inheritProjectContext,
1386
- inheritSkills: agentConfig.inheritSkills,
1453
+ ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
1454
+ ...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
1455
+ ...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
1456
+ ...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
1457
+ ...(recoveryAgentConfig.systemPrompt ? { systemPrompt: recoveryAgentConfig.systemPrompt } : {}),
1458
+ systemPromptMode: recoveryAgentConfig.systemPromptMode,
1459
+ inheritProjectContext: recoveryAgentConfig.inheritProjectContext,
1460
+ inheritSkills: recoveryAgentConfig.inheritSkills,
1387
1461
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
1388
- ...(agentConfig.skillPath ? { skillPath: [...agentConfig.skillPath] } : {}),
1389
- ...(agentConfig.filePath ? { agentFilePath: agentConfig.filePath } : {}),
1390
- ...(agentConfig.completionGuard !== undefined ? { completionGuard: agentConfig.completionGuard } : {}),
1391
- ...(agentConfig.memory ? { memory: { ...agentConfig.memory } } : {}),
1462
+ ...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
1463
+ ...(recoveryAgentConfig.filePath ? { agentFilePath: recoveryAgentConfig.filePath } : {}),
1464
+ ...(recoveryAgentConfig.completionGuard !== undefined ? { completionGuard: recoveryAgentConfig.completionGuard } : {}),
1465
+ ...(recoveryAgentConfig.memory ? { memory: { ...recoveryAgentConfig.memory } } : {}),
1392
1466
  ...(outputPath ? { outputPath } : {}),
1393
1467
  outputMode,
1394
1468
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1395
1469
  ...(params.acceptance !== undefined ? { acceptance: params.acceptance } : {}),
1396
1470
  ...(controlConfig ? { controlConfig } : {}),
1471
+ ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1397
1472
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1398
- ...(initialTurnBudget ? { initialTurnBudget } : {}),
1473
+ ...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
1399
1474
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1400
- maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1475
+ maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
1401
1476
  ...(maxOutput ? { maxOutput } : {}),
1402
1477
  share: shareEnabled,
1403
1478
  ...(resolvedSessionDir ? { sessionDir: resolvedSessionDir } : {}),
@@ -1412,7 +1487,7 @@ export function executeAsyncSingle(
1412
1487
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
1413
1488
  }
1414
1489
  }
1415
- let spawnResult: { pid?: number; error?: string } = {};
1490
+ let spawnResult: SpawnRunnerResult = {};
1416
1491
  try {
1417
1492
  spawnResult = spawnRunner(
1418
1493
  {
@@ -1456,7 +1531,9 @@ export function executeAsyncSingle(
1456
1531
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1457
1532
  },
1458
1533
  ],
1459
- resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(DIRS.results, `${id}.json`),
1534
+ resultPath: params.parentWorkflowRunId !== undefined && params.revivalLease !== undefined
1535
+ ? workflowAwaitedAsyncResultPath(asyncDir)
1536
+ : inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(DIRS.results, `${id}.json`),
1460
1537
  cwd: runnerCwd,
1461
1538
  placeholder: "{previous}",
1462
1539
  maxOutput,
@@ -1483,6 +1560,7 @@ export function executeAsyncSingle(
1483
1560
  resultMode: "single",
1484
1561
  launchContractDigest,
1485
1562
  launchResolvedExtensions,
1563
+ runFanoutBudget,
1486
1564
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1487
1565
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1488
1566
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
@@ -1499,13 +1577,21 @@ export function executeAsyncSingle(
1499
1577
  (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1500
1578
  );
1501
1579
  } catch (error) {
1580
+ params.activeAsyncCapacity?.rollback();
1502
1581
  const message = error instanceof Error ? error.message : String(error);
1503
1582
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${message}`);
1504
1583
  }
1505
1584
 
1506
1585
  if (spawnResult.error) {
1586
+ if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
1587
+ else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1507
1588
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
1508
1589
  }
1590
+ if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) {
1591
+ params.activeAsyncCapacity?.rollback();
1592
+ return formatAsyncStartError("single", `Failed to start async run '${id}': runner identity unavailable`);
1593
+ }
1594
+ params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1509
1595
 
1510
1596
  if (spawnResult.pid) {
1511
1597
  if (inheritedNestedRoute && nestedAddress) {
@@ -1551,10 +1637,11 @@ export function executeAsyncSingle(
1551
1637
  sessionId: ctx.currentSessionId,
1552
1638
  mode: "single",
1553
1639
  agent,
1554
- task: task?.slice(0, 50),
1555
- goal: (params.goal ?? task).slice(0, 120),
1640
+ task: task?.trim() ? PROMPT_REDACTED : undefined,
1641
+ goal: (params.goal ?? task).trim() ? PROMPT_REDACTED : undefined,
1556
1642
  cwd: runnerCwd,
1557
1643
  asyncDir,
1644
+ ...(sessionRoot ? { sessionRoot } : {}),
1558
1645
  launchContractDigest,
1559
1646
  launchResolvedExtensions,
1560
1647
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),