@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -357,9 +357,18 @@ export function reconcileNestedAsyncDescendants(route: NestedRoute, options: Rec
357
357
  }
358
358
  }
359
359
 
360
- export function checkPidLiveness(pid: number, kill: KillFn = process.kill): PidLiveness {
360
+ export function checkPidLiveness(pid: number, kill: KillFn = process.kill, probeZombie = false): PidLiveness {
361
361
  try {
362
362
  kill(pid, 0);
363
+ if (probeZombie && process.platform === "linux") {
364
+ try {
365
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
366
+ const closeParen = stat.lastIndexOf(") ");
367
+ if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
368
+ } catch {
369
+ // Fall back to kill(pid, 0) when procfs is unavailable or unreadable.
370
+ }
371
+ }
363
372
  return "alive";
364
373
  } catch (error) {
365
374
  const code = typeof error === "object" && error !== null && "code" in error
@@ -437,7 +446,9 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
437
446
  const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
438
447
  // An observer without a scope (macOS/Windows host sharing a container's temp root) cannot match a recorded one.
439
448
  const pidScopeMismatch = effectiveStatus.pidNamespaceScope !== undefined && effectiveStatus.pidNamespaceScope !== observedScope;
440
- const observedLiveness = checkPidLiveness(effectiveStatus.pid, options.kill);
449
+ // A local zombie is evidence about this runner only when its namespace is known to match.
450
+ const pidScopeVerified = effectiveStatus.pidNamespaceScope !== undefined && effectiveStatus.pidNamespaceScope === observedScope;
451
+ const observedLiveness = checkPidLiveness(effectiveStatus.pid, options.kill, pidScopeVerified);
441
452
  const liveness = observedLiveness === "dead" && pidScopeMismatch ? "unknown" : observedLiveness;
442
453
  if (liveness !== "dead") {
443
454
  const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
@@ -5,6 +5,7 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
5
  import { acquireSessionLease } from "../shared/session-lease.ts";
6
6
  import { readProcessTerminalCandidate, writeProcessTerminalCandidate, markProcessTerminalCandidateLeaseRelease } from "./process-terminal-candidate.ts";
7
7
  import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
8
+ import { currentPidNamespaceScope } from "./pid-namespace.ts";
8
9
  import type { DefaultChildSessionFactoryOptions } from "../shared/child-session.ts";
9
10
  import type { SubagentRunConfig } from "./subagent-runner.ts";
10
11
 
@@ -129,6 +130,8 @@ export async function runConfiguredSubagent(rawConfig: unknown, options: RunnerB
129
130
  process.once("exit", releaseOnExit);
130
131
  try {
131
132
  if (config.launchBarrierToken) {
133
+ // Behind a launcher the parent only knows the wrapper's pid; report this runner's own identity first.
134
+ if (config.launcher) writeAtomicJson(startupPath, { state: "identified", token: config.launchBarrierToken, pid: process.pid, pidNamespaceScope: currentPidNamespaceScope() });
132
135
  await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
133
136
  startupCommitted = true;
134
137
  try {
@@ -139,7 +142,7 @@ export async function runConfiguredSubagent(rawConfig: unknown, options: RunnerB
139
142
  } else if (config.revivalLease) {
140
143
  lease = acquireSessionLease(config.revivalLease);
141
144
  config.revivalLeaseToken = lease.owner.token;
142
- writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
145
+ writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner, ...(config.launcher ? { pidNamespaceScope: currentPidNamespaceScope() } : {}) });
143
146
  await waitForStartupControl(startupAckPath, lease.owner.token, "ack");
144
147
  writeAtomicJson(startupPath, { state: "acknowledged", token: lease.owner.token, pid: process.pid });
145
148
  await waitForStartupControl(startupConfirmPath, lease.owner.token, "confirm");
@@ -6,7 +6,7 @@ import { pathToFileURL } from "node:url";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
7
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
- import { writeAsyncResultFile, writePendingAsyncResultFile } from "./result-files.ts";
9
+ import { withResultRunLease, writeAsyncResultFile, writePendingAsyncResultFile } from "./result-files.ts";
10
10
  import { createFileCoalescer } from "../../shared/file-coalescer.ts";
11
11
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
12
12
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
@@ -49,6 +49,7 @@ import {
49
49
  type SubagentChildStatusEvent,
50
50
  type WorkflowLaneMetadata,
51
51
  type HerdrMachineReference,
52
+ type RunnerLauncher,
52
53
  DEFAULT_MAX_OUTPUT,
53
54
  type MaxOutputConfig,
54
55
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -99,6 +100,7 @@ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
99
100
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
100
101
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, unconsumedSteerReason, updateSteeringTarget } from "./steering.ts";
101
102
  import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getAgentDir, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
103
+ import { planBackgroundRunHistory, recordRun } from "../shared/run-history.ts";
102
104
  import { planAbortRecovery } from "../shared/abort-recovery.ts";
103
105
  import {
104
106
  createMutatingFailureState,
@@ -171,6 +173,7 @@ process.env[SUBAGENT_CHILD_ENV] = "1";
171
173
 
172
174
  export interface SubagentRunConfig {
173
175
  id: string;
176
+ toolCallId?: string;
174
177
  steps: RunnerStep[];
175
178
  resultPath: string;
176
179
  cwd: string;
@@ -230,6 +233,7 @@ export interface SubagentRunConfig {
230
233
  parentWorkflowRunId?: string;
231
234
  workflowKey?: string;
232
235
  lane?: WorkflowLaneMetadata;
236
+ launcher?: RunnerLauncher;
233
237
  }
234
238
 
235
239
  interface StepResult {
@@ -245,6 +249,7 @@ interface StepResult {
245
249
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
246
250
  output: string;
247
251
  outputState?: SubagentOutputState;
252
+ outputPartial?: boolean;
248
253
  error?: string;
249
254
  success?: boolean;
250
255
  exitCode: number | null;
@@ -911,7 +916,7 @@ export async function runSingleStepInner(
911
916
  const resolvedOutput = step.outputPath ? resolveSingleOutput(step.outputPath, output, outputSnapshot, step.outputClaimPath) : { fullOutput: output };
912
917
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
913
918
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({ fullOutput: resolvedOutput.fullOutput, outputPath: step.outputPath, outputMode: step.outputMode, exitCode: 1, preserveSavedOutput: true, savedPath: resolvedOutput.savedPath, outputReference, saveError: resolvedOutput.saveError }));
914
- const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false ? persistStepArtifacts({ artifactPaths, artifactConfig: ctx.artifactConfig, output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })), metadata: { runId: ctx.id, agent: step.agent, task: PROMPT_REDACTED, runner, placement: session.owner.identity, settlement: settled.settlement, outcome: settled.outcome, timestamp: Date.now() } }) : {};
919
+ const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false ? persistStepArtifacts({ artifactPaths, artifactConfig: ctx.artifactConfig, output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })), metadata: { runId: ctx.id, parentSessionId: step.parentSessionId, agent: step.agent, task: PROMPT_REDACTED, runner, placement: session.owner.identity, settlement: settled.settlement, outcome: settled.outcome, timestamp: Date.now() } }) : {};
915
920
  return omitUndefinedProperties({ agent: step.agent, ...(childSessionName ? { sessionName: childSessionName } : {}), context: step.context, output: finalizedOutput.displayOutput, outputState: output.trim() ? "present" : "absent", exitCode: 1, error: resolvedOutput.fatalError ? resolvedOutput.saveError : undefined, timedOut, stopped, artifactPaths, outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined, metadataSaveError: artifactErrors.metadataSaveError, runner, execution: { status: "partial", success: false, exitCode: 1 } });
916
921
  } catch (error) {
917
922
  // Any post-allocation uncertainty retains the pane; only explicit stop
@@ -926,7 +931,7 @@ export async function runSingleStepInner(
926
931
  const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
927
932
  ? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
928
933
  : step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
929
- ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
934
+ ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command, overrideArgs: step.claudeCodeOverrideArgs })
930
935
  : step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
931
936
  ? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
932
937
  : undefined;
@@ -984,7 +989,7 @@ export async function runSingleStepInner(
984
989
  artifactPaths,
985
990
  artifactConfig: ctx.artifactConfig,
986
991
  output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, error: external.error, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })),
987
- metadata: { runId: ctx.id, agent: step.agent, task: PROMPT_REDACTED, runner, externalProcess: externalProcess, exitCode: external.exitCode, error: external.error, timestamp: Date.now() },
992
+ metadata: { runId: ctx.id, parentSessionId: step.parentSessionId, agent: step.agent, task: PROMPT_REDACTED, runner, externalProcess: externalProcess, exitCode: external.exitCode, error: external.error, timestamp: Date.now() },
988
993
  })
989
994
  : {};
990
995
  return omitUndefinedProperties({
@@ -1055,7 +1060,7 @@ export async function runSingleStepInner(
1055
1060
  artifactPaths,
1056
1061
  artifactConfig: ctx.artifactConfig,
1057
1062
  output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, error: external.error, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })),
1058
- metadata: { runId: ctx.id, agent: step.agent, task: PROMPT_REDACTED, runner, externalJob: external.externalJob, exitCode: external.exitCode, error: external.error, timestamp: Date.now() },
1063
+ metadata: { runId: ctx.id, parentSessionId: step.parentSessionId, agent: step.agent, task: PROMPT_REDACTED, runner, externalJob: external.externalJob, exitCode: external.exitCode, error: external.error, timestamp: Date.now() },
1059
1064
  })
1060
1065
  : {};
1061
1066
  return omitUndefinedProperties({
@@ -1391,12 +1396,13 @@ export async function runSingleStepInner(
1391
1396
  }
1392
1397
 
1393
1398
  const rawOutput = finalResult?.finalOutput ?? "";
1394
- let outputForPersistence = stripAcceptanceReport(rawOutput);
1395
- if (!outputForPersistence.trim() && finalResult?.structuredOutput !== undefined)
1396
- outputForPersistence = JSON.stringify(finalResult.structuredOutput, null, 2);
1399
+ const structuredText = finalResult?.structuredOutput === undefined ? undefined : JSON.stringify(finalResult.structuredOutput, null, 2);
1400
+ let replyOutput = stripAcceptanceReport(rawOutput);
1401
+ if (!replyOutput.trim() && structuredText !== undefined) replyOutput = structuredText;
1402
+ // The schema is the caller's contract: a bound output file holds the structured result, not closing prose.
1397
1403
  const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1398
- ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, step.outputClaimPath)
1399
- : { fullOutput: outputForPersistence };
1404
+ ? resolveSingleOutput(step.outputPath, structuredText ?? replyOutput, finalOutputSnapshot, step.outputClaimPath)
1405
+ : { fullOutput: replyOutput };
1400
1406
  if (resolvedOutput.fatalError) {
1401
1407
  if (finalResult) {
1402
1408
  finalResult.exitCode = 1;
@@ -1409,7 +1415,8 @@ export async function runSingleStepInner(
1409
1415
  if (finalResult?.stopped && !outputForSummary.trim()) {
1410
1416
  outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
1411
1417
  }
1412
- const outputForAcceptance = rawOutput;
1418
+ // Unfinished streamed text never stands in for the child's completed reply.
1419
+ const outputForAcceptance = finalResult?.outputPartial ? "" : rawOutput;
1413
1420
  const childWrittenOutput = step.outputPath
1414
1421
  ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1415
1422
  : undefined;
@@ -1511,6 +1518,7 @@ export async function runSingleStepInner(
1511
1518
  })),
1512
1519
  metadata: {
1513
1520
  runId: ctx.id,
1521
+ parentSessionId: step.parentSessionId,
1514
1522
  agent: step.agent,
1515
1523
  task: PROMPT_REDACTED,
1516
1524
  exitCode: effectiveFinalExitCode,
@@ -1540,6 +1548,7 @@ export async function runSingleStepInner(
1540
1548
  launchContractDigest: actualLaunchContractDigest,
1541
1549
  output: outputForSummary,
1542
1550
  outputState,
1551
+ outputPartial: finalResult?.outputPartial,
1543
1552
  exitCode: effectiveFinalExitCode,
1544
1553
  error: effectiveFinalError,
1545
1554
  sessionFile: step.sessionFile,
@@ -1668,7 +1677,12 @@ function markParallelGroupSetupFailure(input: {
1668
1677
  if (!task) throw new Error(`Missing parallel task at index ${taskIndex}`);
1669
1678
  const stopped = statusStep.stopped || statusStep.stopRequested || input.statusPayload.stopped;
1670
1679
  const paused = !stopped && input.statusPayload.state === "paused";
1680
+ const timedOut = !stopped && !paused && input.statusPayload.timedOut === true;
1671
1681
  statusStep.status = stopped ? "stopped" : paused ? "paused" : "failed";
1682
+ // Mirror the run-level timeout onto the step so consumers (status readers,
1683
+ // run-history recording) see timed_out rather than a bare failure — the
1684
+ // StepResult below already carries it, the status step must too.
1685
+ if (timedOut) statusStep.timedOut = true;
1672
1686
  statusStep.startedAt = input.failedAt;
1673
1687
  statusStep.endedAt = input.failedAt;
1674
1688
  statusStep.durationMs = 0;
@@ -1885,6 +1899,11 @@ export async function runSubagent(
1885
1899
  let previousOutput = "";
1886
1900
  const outputs: ChainOutputMap = {};
1887
1901
  const results: StepResult[] = [];
1902
+ // Flat indices of steps a child session was actually dispatched for — the
1903
+ // ground truth for run-history: stopRunner/timeoutRunner/fail-fast/budget
1904
+ // skips relabel never-launched steps to terminal statuses, so status alone
1905
+ // cannot distinguish them from steps that really ran.
1906
+ const launchedFlatIndices = new Set<number>();
1888
1907
  const overallStartTime = Date.now();
1889
1908
  const shareEnabled = config.share === true;
1890
1909
  const asyncDir = config.asyncDir;
@@ -2047,6 +2066,7 @@ export async function runSubagent(
2047
2066
  const statusPayload: RunnerStatusPayload = omitUndefinedProperties({
2048
2067
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2049
2068
  runId: id,
2069
+ ...(config.toolCallId ? { toolCallId: config.toolCallId } : {}),
2050
2070
  ...(config.sessionId ? { sessionId: config.sessionId } : {}),
2051
2071
  ...(config.completionOwnerId ? { completionOwnerId: config.completionOwnerId } : {}),
2052
2072
  mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
@@ -2077,6 +2097,7 @@ export async function runSubagent(
2077
2097
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2078
2098
  ...(config.lane ? { lane: config.lane } : {}),
2079
2099
  ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2100
+ ...(config.launcher ? { launcher: config.launcher } : {}),
2080
2101
  steps: initialStatusSteps,
2081
2102
  artifactsDir,
2082
2103
  sessionDir: config.sessionDir,
@@ -2101,6 +2122,9 @@ export async function runSubagent(
2101
2122
  };
2102
2123
  let finalResultCommitted = false;
2103
2124
  let finalResultPublication: { resolve(): void; reject(error: unknown): void } | undefined;
2125
+ // The paused and final results replace each other under one run id; the lease keeps a consumer
2126
+ // of the older one from retiring the newer one. A lease timeout fails the publication.
2127
+ const publishRunResult = (filePath: string, write: () => void): void => withResultRunLease(path.dirname(filePath), id, write);
2104
2128
  const runPersistence = createCapacityResilientJsonWriter({
2105
2129
  keepAlive: true,
2106
2130
  onSuccess: (filePath, payload) => {
@@ -2257,7 +2281,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2257
2281
  sessionId: config.sessionId,
2258
2282
  completionOwnerId: config.completionOwnerId,
2259
2283
  sessionFile: statusPayload.sessionFile ?? latestSessionFile,
2260
- }), (filePath, payload) => writePendingAsyncResultFile(filePath, payload as Record<string, unknown>));
2284
+ }), (filePath, payload) => publishRunResult(filePath, () => writePendingAsyncResultFile(filePath, payload as Record<string, unknown>)));
2261
2285
  };
2262
2286
  const writeStatusPayloadNow = (): void => {
2263
2287
  if (finalResultPublication) return;
@@ -2654,7 +2678,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2654
2678
  const activeLongRunningSteps = new Set<number>();
2655
2679
  const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
2656
2680
  const pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> = initialStatusSteps.map(() => undefined);
2657
- type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string; blocksSupervisor: boolean };
2681
+ type ActiveToolCall = { attentionEmitted?: boolean; key: string; tool: string; args: string; startedAt: number; path?: string; blocksSupervisor: boolean };
2658
2682
  const activeToolCalls = initialStatusSteps.map(() => new Map<string, ActiveToolCall>());
2659
2683
  const activeToolKeysByName = initialStatusSteps.map(() => new Map<string, string[]>());
2660
2684
  const activeToolSequences = initialStatusSteps.map(() => 0);
@@ -2718,7 +2742,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2718
2742
  return key ? removeActiveToolCallKey(flatIndex, key) : undefined;
2719
2743
  };
2720
2744
  const openToolAttentionTarget = (flatIndex: number, now: number): ActiveToolCall | undefined => [...(activeToolCalls[flatIndex]?.values() ?? [])]
2721
- .filter((active) => shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
2745
+ .filter((active) => !active.attentionEmitted && shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
2722
2746
  .sort((left, right) => left.startedAt - right.startedAt)[0];
2723
2747
  const supervisorAttentionSteps = new Map<number, ActivityState | undefined>();
2724
2748
  const mutatingFailureWindowMs = 5 * 60_000;
@@ -2770,9 +2794,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2770
2794
  };
2771
2795
  const maybeEmitOpenToolAttention = (flatIndex: number, now: number): boolean => {
2772
2796
  const step = statusPayload.steps[flatIndex];
2773
- if (!step || step.status !== "running" || step.activityState === "needs_attention") return false;
2797
+ if (!step || step.status !== "running") return false;
2774
2798
  const target = openToolAttentionTarget(flatIndex, now);
2775
2799
  if (!target) return false;
2800
+ target.attentionEmitted = true;
2801
+ // Keep this attention when a concurrent supervisor request ends and restores its saved state.
2802
+ if (supervisorAttentionSteps.has(flatIndex)) supervisorAttentionSteps.set(flatIndex, "needs_attention");
2776
2803
  const previous = step.activityState;
2777
2804
  step.activityState = "needs_attention";
2778
2805
  statusPayload.activityState = "needs_attention";
@@ -2791,6 +2818,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2791
2818
  tokens: step.tokens?.total,
2792
2819
  toolCount: step.toolCount,
2793
2820
  currentTool: target.tool,
2821
+ toolCallId: target.key.startsWith("id:") ? target.key.slice(3) : undefined,
2794
2822
  currentToolDurationMs: toolDurationMs,
2795
2823
  currentPath: target.path,
2796
2824
  })));
@@ -3622,6 +3650,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3622
3650
  return omitUndefinedProperties({
3623
3651
  agent: task.agent,
3624
3652
  ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3653
+ ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
3625
3654
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3626
3655
  ...(task.context ? { context: task.context } : {}),
3627
3656
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -3724,6 +3753,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3724
3753
  return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3725
3754
  }
3726
3755
  const taskStartTime = Date.now();
3756
+ launchedFlatIndices.add(fi);
3727
3757
  statusPayload.currentStep = fi;
3728
3758
  requiredStatusStep(statusPayload, fi).status = "running";
3729
3759
  delete requiredStatusStep(statusPayload, fi).error;
@@ -3848,6 +3878,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3848
3878
  runtimeAcknowledgedExtensions: pr.runtimeAcknowledgedExtensions,
3849
3879
  output: pr.output,
3850
3880
  outputState: pr.outputState,
3881
+ outputPartial: pr.outputPartial,
3851
3882
  error: pr.error,
3852
3883
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0 && pr.execution?.status !== "partial",
3853
3884
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
@@ -3866,6 +3897,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3866
3897
  totalCost: pr.totalCost,
3867
3898
  usage: pr.usage,
3868
3899
  artifactPaths: pr.artifactPaths,
3900
+ savedOutputPath: pr.savedOutputPath,
3869
3901
  outputSaveError: pr.outputSaveError,
3870
3902
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
3871
3903
  transcriptPath: pr.transcriptPath,
@@ -4129,6 +4161,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4129
4161
  }
4130
4162
 
4131
4163
  const taskStartTime = Date.now();
4164
+ launchedFlatIndices.add(fi);
4132
4165
  statusPayload.currentStep = fi;
4133
4166
  requiredStatusStep(statusPayload, fi).status = "running";
4134
4167
  delete requiredStatusStep(statusPayload, fi).error;
@@ -4297,6 +4330,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4297
4330
  launchResolvedExtensions: pr.launchResolvedExtensions,
4298
4331
  output: pr.output,
4299
4332
  outputState: pr.outputState,
4333
+ outputPartial: pr.outputPartial,
4300
4334
  error: pr.error,
4301
4335
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0 && pr.execution?.status !== "partial",
4302
4336
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
@@ -4315,6 +4349,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4315
4349
  totalCost: pr.totalCost,
4316
4350
  usage: pr.usage,
4317
4351
  artifactPaths: pr.artifactPaths,
4352
+ savedOutputPath: pr.savedOutputPath,
4318
4353
  outputSaveError: pr.outputSaveError,
4319
4354
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
4320
4355
  transcriptPath: pr.transcriptPath,
@@ -4518,6 +4553,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4518
4553
  }
4519
4554
  const singleCwd = singleWorktreeSetup?.worktrees[0]?.agentCwd ?? cwd;
4520
4555
  const stepStartTime = Date.now();
4556
+ launchedFlatIndices.add(flatIndex);
4521
4557
  statusPayload.currentStep = flatIndex;
4522
4558
  requiredStatusStep(statusPayload, flatIndex).status = "running";
4523
4559
  delete requiredStatusStep(statusPayload, flatIndex).activityState;
@@ -4603,6 +4639,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4603
4639
  runtimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,
4604
4640
  output: stopped || childStopped ? stopMessage : timedOut ? singleResult.output || (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4605
4641
  outputState: singleResult.outputState,
4642
+ outputPartial: singleResult.outputPartial,
4606
4643
  error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4607
4644
  success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0 && singleResult.execution?.status !== "partial",
4608
4645
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
@@ -4981,6 +5018,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4981
5018
  runPersistence.write(resultPath, {
4982
5019
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
4983
5020
  id,
5021
+ ...(config.toolCallId ? { toolCallId: config.toolCallId } : {}),
4984
5022
  agent: agentName,
4985
5023
  mode: resultMode,
4986
5024
  success: statusPayload.state === "complete",
@@ -4998,6 +5036,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4998
5036
  context: r.context,
4999
5037
  output: r.output,
5000
5038
  outputState: r.outputState,
5039
+ outputPartial: r.outputPartial,
5001
5040
  error: r.error,
5002
5041
  success: r.success,
5003
5042
  skipped: r.skipped || undefined,
@@ -5073,7 +5112,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5073
5112
  shareError,
5074
5113
  ...(taskIndex !== undefined && { taskIndex }),
5075
5114
  ...(totalTasks !== undefined && { totalTasks }),
5076
- }, (filePath, payload) => { writeAsyncResultFile(filePath, payload as Record<string, unknown>); });
5115
+ }, (filePath, payload) => publishRunResult(filePath, () => { writeAsyncResultFile(filePath, payload as Record<string, unknown>); }));
5077
5116
  // Only capacity deferral releases settled sessions before terminal publication.
5078
5117
  if (!finalResultCommitted) await Promise.all([publication, disposeChildSessions()]);
5079
5118
  } catch (err) {
@@ -5101,6 +5140,26 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5101
5140
  usageBudget: statusPayload.usageBudget,
5102
5141
  }),
5103
5142
  );
5143
+ // Paused runs record an interrupted attempt; a later resume records another.
5144
+ for (const historyEntry of planBackgroundRunHistory({
5145
+ steps,
5146
+ resultMode,
5147
+ statusSteps: statusPayload.steps.map((step, index) => ({
5148
+ agent: step.agent,
5149
+ status: step.status,
5150
+ durationMs: step.durationMs,
5151
+ timedOut: step.timedOut,
5152
+ stopped: step.stopped,
5153
+ launched: launchedFlatIndices.has(index),
5154
+ })),
5155
+ stepResults: results,
5156
+ runDurationMs: runEndedAt - overallStartTime,
5157
+ stopped,
5158
+ interrupted,
5159
+ timedOut,
5160
+ })) {
5161
+ recordRun(historyEntry.agent, historyEntry.task, historyEntry.exitCode, historyEntry.durationMs, historyEntry.terminal);
5162
+ }
5104
5163
  writeRunLog(logPath, omitUndefinedProperties({
5105
5164
  id,
5106
5165
  mode: statusPayload.mode,
@@ -124,6 +124,8 @@ export interface SubagentWaitDeps {
124
124
  failOnAttention?: boolean;
125
125
  /** Durable owned supervisor-request barrier used by headless auto-drain. */
126
126
  hasPendingSupervisorRequest?: () => boolean;
127
+ /** Aborted when the user sends a message; the wait then yields without an error. */
128
+ userInputSignal?: AbortSignal;
127
129
  /** Arm a durable exact-target wait subscription in a long-lived interactive runtime. */
128
130
  subscribe?: (input: { targetKind: "async" | "foreground"; runId: string; requestedId: string; timeoutMs: number }) => { token: string; expiresAt: number };
129
131
  /** Injectable provider protocol surfaces for deterministic tests. */
@@ -215,6 +217,12 @@ function waitForWake(ms: number, signal: AbortSignal | undefined, deps: Subagent
215
217
  });
216
218
  }
217
219
 
220
+ /** Signal that wakes the poll sleep on turn abort or a user message. */
221
+ function wakeSignal(signal: AbortSignal | undefined, deps: SubagentWaitDeps): AbortSignal | undefined {
222
+ if (!deps.userInputSignal) return signal;
223
+ return signal ? AbortSignal.any([signal, deps.userInputSignal]) : deps.userInputSignal;
224
+ }
225
+
218
226
  function matchesId(run: AsyncRunSummary, id: string): boolean {
219
227
  return run.id === id || run.id.startsWith(id);
220
228
  }
@@ -398,17 +406,25 @@ function windowElapsedResult(
398
406
  };
399
407
  }
400
408
 
401
- function supervisorYieldResult(
409
+ type WaitYieldReason = "supervisor_request" | "user_input";
410
+
411
+ const WAIT_YIELD_TEXT: Record<WaitYieldReason, string> = {
412
+ supervisor_request: "Wait yielded for a pending supervisor request. Background work remains active and will continue after the supervisor reply.",
413
+ user_input: "Wait yielded because the user sent a message. Background work remains active; read the message before waiting again.",
414
+ };
415
+
416
+ function yieldResult(
417
+ reason: WaitYieldReason,
402
418
  activeRunIds: string[],
403
419
  activeProviderItems: readonly RegisteredBackgroundWorkItem[] = [],
404
420
  ): AgentToolResult<Details> {
405
421
  return {
406
- content: [{ type: "text", text: "Wait yielded for a pending supervisor request. Background work remains active and will continue after the supervisor reply." }],
422
+ content: [{ type: "text", text: WAIT_YIELD_TEXT[reason] }],
407
423
  details: {
408
424
  mode: "management",
409
425
  results: [],
410
426
  wait: {
411
- reason: "supervisor_request",
427
+ reason,
412
428
  timedOut: false,
413
429
  activeRunIds,
414
430
  activeProviderItems: activeProviderItems.map(({ provider, id }) => ({ provider, id })),
@@ -423,7 +439,7 @@ interface InitialWaitScope {
423
439
  providerIds: Set<string>;
424
440
  }
425
441
 
426
- function supervisorYieldForScope(scope: InitialWaitScope, params: SubagentWaitParams, deps: SubagentWaitDeps, nowMs: number): AgentToolResult<Details> {
442
+ function yieldForScope(reason: WaitYieldReason, scope: InitialWaitScope, params: SubagentWaitParams, deps: SubagentWaitDeps, nowMs: number): AgentToolResult<Details> {
427
443
  try {
428
444
  const activeAsyncIds = new Set(activeRunsForSession(params.id ? { id: params.id } : {}, deps).map((run) => run.id));
429
445
  const activeRunIds = new Set([...scope.asyncRunIds].filter((id) => activeAsyncIds.has(id)));
@@ -435,7 +451,7 @@ function supervisorYieldForScope(scope: InitialWaitScope, params: SubagentWaitPa
435
451
  const activeProviderItems = scope.providerIds.size > 0
436
452
  ? backgroundWorkForSession(deps, nowMs).items.filter((item) => scope.providerIds.has(backgroundWorkIdentity(item)))
437
453
  : [];
438
- return supervisorYieldResult([...activeRunIds], activeProviderItems);
454
+ return yieldResult(reason, [...activeRunIds], activeProviderItems);
439
455
  } catch (error) {
440
456
  return result(error instanceof Error ? error.message : String(error), true);
441
457
  }
@@ -563,8 +579,9 @@ async function waitForDetachedForegroundRun(
563
579
  now: () => number,
564
580
  pollIntervalMs: number,
565
581
  timeoutMs: number,
566
- supervisorYield: () => AgentToolResult<Details>,
582
+ yieldWait: (reason: WaitYieldReason) => AgentToolResult<Details>,
567
583
  ): Promise<AgentToolResult<Details>> {
584
+ const wake = wakeSignal(signal, deps);
568
585
  const initialDetachedIndices = new Set(run.children.filter((child) => child.status === "detached").map((child) => child.index));
569
586
  while (true) {
570
587
  if (deps.state.currentSessionId !== run.sessionId) {
@@ -574,7 +591,8 @@ async function waitForDetachedForegroundRun(
574
591
  if (!current || current.sessionId !== run.sessionId) {
575
592
  return result(`Remembered foreground run "${run.runId}" disappeared before a terminal child result was recorded. Completion cannot be confirmed; do not launch a replacement without checking the originating child session.`, true);
576
593
  }
577
- if (deps.hasPendingSupervisorRequest?.()) return supervisorYield();
594
+ if (deps.hasPendingSupervisorRequest?.()) return yieldWait("supervisor_request");
595
+ if (deps.userInputSignal?.aborted) return yieldWait("user_input");
578
596
  const pending = current.children.filter((child) => initialDetachedIndices.has(child.index) && child.status === "detached");
579
597
  const attention = foregroundChildrenNeedingAttention(current, initialDetachedIndices);
580
598
  if (attention.length > 0) return formatForegroundAttention(current, attention, now() - startedAt);
@@ -595,7 +613,7 @@ async function waitForDetachedForegroundRun(
595
613
  [run.runId],
596
614
  );
597
615
  }
598
- await waitForWake(pollIntervalMs, signal, deps);
616
+ await waitForWake(pollIntervalMs, wake, deps);
599
617
  }
600
618
  }
601
619
 
@@ -607,13 +625,13 @@ async function waitForSessionDetachedForegroundRuns(
607
625
  now: () => number,
608
626
  pollIntervalMs: number,
609
627
  timeoutMs: number,
610
- supervisorYield: () => AgentToolResult<Details>,
628
+ yieldWait: (reason: WaitYieldReason) => AgentToolResult<Details>,
611
629
  ): Promise<AgentToolResult<Details>> {
612
630
  const texts: string[] = [];
613
631
  for (const run of runs) {
614
- const one = await waitForDetachedForegroundRun(run, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, supervisorYield);
632
+ const one = await waitForDetachedForegroundRun(run, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, yieldWait);
615
633
  if (one.isError) return one;
616
- if (one.details.wait?.reason === "supervisor_request") return one;
634
+ if (one.details.wait && one.details.wait.reason !== "window_elapsed") return one;
617
635
  if (one.details.wait?.reason === "window_elapsed") {
618
636
  const activeRunIds = runs.filter((initial) => {
619
637
  const current = deps.state.foregroundRuns?.get(initial.runId);
@@ -729,13 +747,14 @@ export async function waitForSubagents(
729
747
  })),
730
748
  providerIds: initialProviderIds,
731
749
  };
732
- const supervisorYield = () => supervisorYieldForScope(initialScope, params, deps, now());
750
+ const yieldWait = (reason: WaitYieldReason) => yieldForScope(reason, initialScope, params, deps, now());
751
+ const wake = wakeSignal(signal, deps);
733
752
  if (selectedForeground) {
734
- return waitForDetachedForegroundRun(selectedForeground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, supervisorYield);
753
+ return waitForDetachedForegroundRun(selectedForeground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, yieldWait);
735
754
  }
736
755
  if (active.length === 0 && providerActive.length === 0) {
737
756
  if (waitForAll && !params.id && foreground.length > 0) {
738
- return waitForSessionDetachedForegroundRuns(foreground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, supervisorYield);
757
+ return waitForSessionDetachedForegroundRuns(foreground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, yieldWait);
739
758
  }
740
759
  return result(params.id
741
760
  ? `No active run matched "${params.id}". Nothing to wait for.`
@@ -772,6 +791,7 @@ export async function waitForSubagents(
772
791
  ...activeInitialProviderItems.map((item) => `${item.provider}/${item.id}`),
773
792
  ].join(", ");
774
793
  deps.onUpdate?.(asyncWaitUpdate(activeInitialRuns, activeInitialProviderItems.length, now() - startedAt));
794
+ if (deps.userInputSignal?.aborted) return yieldWait("user_input");
775
795
  if (signal?.aborted) {
776
796
  return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Still active: ${stillActive}.`, true);
777
797
  }
@@ -783,7 +803,7 @@ export async function waitForSubagents(
783
803
  );
784
804
  }
785
805
  try {
786
- await waitForWake(pollIntervalMs, signal, deps);
806
+ await waitForWake(pollIntervalMs, wake, deps);
787
807
  if (deps.state.currentSessionId !== sessionId) return result("Wait stopped because the active session changed.", true);
788
808
  active = activeRunsForSession(waitParams, deps);
789
809
  attention = attentionRunsForSession(waitParams, deps, initialAsyncIds);
@@ -799,7 +819,7 @@ export async function waitForSubagents(
799
819
  }
800
820
  }
801
821
  if (supervisorBarrier) {
802
- return supervisorYield();
822
+ return yieldWait("supervisor_request");
803
823
  }
804
824
 
805
825
  let terminalSummary: string;
@@ -837,11 +857,10 @@ export async function waitForSubagents(
837
857
 
838
858
  if (waitForAll) {
839
859
  const foregroundResult = !params.id && foreground.length > 0 && relevantAttention.length === 0
840
- ? await waitForSessionDetachedForegroundRuns(foreground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, supervisorYield)
860
+ ? await waitForSessionDetachedForegroundRuns(foreground, signal, deps, startedAt, now, pollIntervalMs, timeoutMs, yieldWait)
841
861
  : undefined;
842
862
  if (foregroundResult?.isError) return foregroundResult;
843
- if (foregroundResult?.details.wait?.reason === "supervisor_request") return foregroundResult;
844
- if (foregroundResult?.details.wait?.reason === "window_elapsed") return foregroundResult;
863
+ if (foregroundResult?.details.wait) return foregroundResult;
845
864
  const foregroundNote = foregroundResult
846
865
  ? `\n${foregroundResult.content.map((part) => part.type === "text" ? part.text : "").join("\n")}`
847
866
  : "";