@xzzpig/pi-subagents 0.20.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 (140) hide show
  1. package/CHANGELOG.md +154 -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 +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  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 +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -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 +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -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,
@@ -172,6 +173,7 @@ process.env[SUBAGENT_CHILD_ENV] = "1";
172
173
 
173
174
  export interface SubagentRunConfig {
174
175
  id: string;
176
+ toolCallId?: string;
175
177
  steps: RunnerStep[];
176
178
  resultPath: string;
177
179
  cwd: string;
@@ -231,6 +233,7 @@ export interface SubagentRunConfig {
231
233
  parentWorkflowRunId?: string;
232
234
  workflowKey?: string;
233
235
  lane?: WorkflowLaneMetadata;
236
+ launcher?: RunnerLauncher;
234
237
  }
235
238
 
236
239
  interface StepResult {
@@ -246,6 +249,7 @@ interface StepResult {
246
249
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
247
250
  output: string;
248
251
  outputState?: SubagentOutputState;
252
+ outputPartial?: boolean;
249
253
  error?: string;
250
254
  success?: boolean;
251
255
  exitCode: number | null;
@@ -912,7 +916,7 @@ export async function runSingleStepInner(
912
916
  const resolvedOutput = step.outputPath ? resolveSingleOutput(step.outputPath, output, outputSnapshot, step.outputClaimPath) : { fullOutput: output };
913
917
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
914
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 }));
915
- 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() } }) : {};
916
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 } });
917
921
  } catch (error) {
918
922
  // Any post-allocation uncertainty retains the pane; only explicit stop
@@ -985,7 +989,7 @@ export async function runSingleStepInner(
985
989
  artifactPaths,
986
990
  artifactConfig: ctx.artifactConfig,
987
991
  output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, error: external.error, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })),
988
- 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() },
989
993
  })
990
994
  : {};
991
995
  return omitUndefinedProperties({
@@ -1056,7 +1060,7 @@ export async function runSingleStepInner(
1056
1060
  artifactPaths,
1057
1061
  artifactConfig: ctx.artifactConfig,
1058
1062
  output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, error: external.error, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })),
1059
- 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() },
1060
1064
  })
1061
1065
  : {};
1062
1066
  return omitUndefinedProperties({
@@ -1392,12 +1396,13 @@ export async function runSingleStepInner(
1392
1396
  }
1393
1397
 
1394
1398
  const rawOutput = finalResult?.finalOutput ?? "";
1395
- let outputForPersistence = stripAcceptanceReport(rawOutput);
1396
- if (!outputForPersistence.trim() && finalResult?.structuredOutput !== undefined)
1397
- 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.
1398
1403
  const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1399
- ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, step.outputClaimPath)
1400
- : { fullOutput: outputForPersistence };
1404
+ ? resolveSingleOutput(step.outputPath, structuredText ?? replyOutput, finalOutputSnapshot, step.outputClaimPath)
1405
+ : { fullOutput: replyOutput };
1401
1406
  if (resolvedOutput.fatalError) {
1402
1407
  if (finalResult) {
1403
1408
  finalResult.exitCode = 1;
@@ -1410,7 +1415,8 @@ export async function runSingleStepInner(
1410
1415
  if (finalResult?.stopped && !outputForSummary.trim()) {
1411
1416
  outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
1412
1417
  }
1413
- const outputForAcceptance = rawOutput;
1418
+ // Unfinished streamed text never stands in for the child's completed reply.
1419
+ const outputForAcceptance = finalResult?.outputPartial ? "" : rawOutput;
1414
1420
  const childWrittenOutput = step.outputPath
1415
1421
  ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1416
1422
  : undefined;
@@ -1512,6 +1518,7 @@ export async function runSingleStepInner(
1512
1518
  })),
1513
1519
  metadata: {
1514
1520
  runId: ctx.id,
1521
+ parentSessionId: step.parentSessionId,
1515
1522
  agent: step.agent,
1516
1523
  task: PROMPT_REDACTED,
1517
1524
  exitCode: effectiveFinalExitCode,
@@ -1541,6 +1548,7 @@ export async function runSingleStepInner(
1541
1548
  launchContractDigest: actualLaunchContractDigest,
1542
1549
  output: outputForSummary,
1543
1550
  outputState,
1551
+ outputPartial: finalResult?.outputPartial,
1544
1552
  exitCode: effectiveFinalExitCode,
1545
1553
  error: effectiveFinalError,
1546
1554
  sessionFile: step.sessionFile,
@@ -2058,6 +2066,7 @@ export async function runSubagent(
2058
2066
  const statusPayload: RunnerStatusPayload = omitUndefinedProperties({
2059
2067
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2060
2068
  runId: id,
2069
+ ...(config.toolCallId ? { toolCallId: config.toolCallId } : {}),
2061
2070
  ...(config.sessionId ? { sessionId: config.sessionId } : {}),
2062
2071
  ...(config.completionOwnerId ? { completionOwnerId: config.completionOwnerId } : {}),
2063
2072
  mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
@@ -2088,6 +2097,7 @@ export async function runSubagent(
2088
2097
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2089
2098
  ...(config.lane ? { lane: config.lane } : {}),
2090
2099
  ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2100
+ ...(config.launcher ? { launcher: config.launcher } : {}),
2091
2101
  steps: initialStatusSteps,
2092
2102
  artifactsDir,
2093
2103
  sessionDir: config.sessionDir,
@@ -2112,6 +2122,9 @@ export async function runSubagent(
2112
2122
  };
2113
2123
  let finalResultCommitted = false;
2114
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);
2115
2128
  const runPersistence = createCapacityResilientJsonWriter({
2116
2129
  keepAlive: true,
2117
2130
  onSuccess: (filePath, payload) => {
@@ -2268,7 +2281,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2268
2281
  sessionId: config.sessionId,
2269
2282
  completionOwnerId: config.completionOwnerId,
2270
2283
  sessionFile: statusPayload.sessionFile ?? latestSessionFile,
2271
- }), (filePath, payload) => writePendingAsyncResultFile(filePath, payload as Record<string, unknown>));
2284
+ }), (filePath, payload) => publishRunResult(filePath, () => writePendingAsyncResultFile(filePath, payload as Record<string, unknown>)));
2272
2285
  };
2273
2286
  const writeStatusPayloadNow = (): void => {
2274
2287
  if (finalResultPublication) return;
@@ -3865,6 +3878,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3865
3878
  runtimeAcknowledgedExtensions: pr.runtimeAcknowledgedExtensions,
3866
3879
  output: pr.output,
3867
3880
  outputState: pr.outputState,
3881
+ outputPartial: pr.outputPartial,
3868
3882
  error: pr.error,
3869
3883
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0 && pr.execution?.status !== "partial",
3870
3884
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
@@ -3883,6 +3897,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3883
3897
  totalCost: pr.totalCost,
3884
3898
  usage: pr.usage,
3885
3899
  artifactPaths: pr.artifactPaths,
3900
+ savedOutputPath: pr.savedOutputPath,
3886
3901
  outputSaveError: pr.outputSaveError,
3887
3902
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
3888
3903
  transcriptPath: pr.transcriptPath,
@@ -4315,6 +4330,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4315
4330
  launchResolvedExtensions: pr.launchResolvedExtensions,
4316
4331
  output: pr.output,
4317
4332
  outputState: pr.outputState,
4333
+ outputPartial: pr.outputPartial,
4318
4334
  error: pr.error,
4319
4335
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0 && pr.execution?.status !== "partial",
4320
4336
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
@@ -4333,6 +4349,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4333
4349
  totalCost: pr.totalCost,
4334
4350
  usage: pr.usage,
4335
4351
  artifactPaths: pr.artifactPaths,
4352
+ savedOutputPath: pr.savedOutputPath,
4336
4353
  outputSaveError: pr.outputSaveError,
4337
4354
  artifactOutputSaveFailed: pr.artifactOutputSaveFailed,
4338
4355
  transcriptPath: pr.transcriptPath,
@@ -4622,6 +4639,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4622
4639
  runtimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,
4623
4640
  output: stopped || childStopped ? stopMessage : timedOut ? singleResult.output || (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4624
4641
  outputState: singleResult.outputState,
4642
+ outputPartial: singleResult.outputPartial,
4625
4643
  error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4626
4644
  success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0 && singleResult.execution?.status !== "partial",
4627
4645
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
@@ -5000,6 +5018,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5000
5018
  runPersistence.write(resultPath, {
5001
5019
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
5002
5020
  id,
5021
+ ...(config.toolCallId ? { toolCallId: config.toolCallId } : {}),
5003
5022
  agent: agentName,
5004
5023
  mode: resultMode,
5005
5024
  success: statusPayload.state === "complete",
@@ -5017,6 +5036,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5017
5036
  context: r.context,
5018
5037
  output: r.output,
5019
5038
  outputState: r.outputState,
5039
+ outputPartial: r.outputPartial,
5020
5040
  error: r.error,
5021
5041
  success: r.success,
5022
5042
  skipped: r.skipped || undefined,
@@ -5092,7 +5112,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5092
5112
  shareError,
5093
5113
  ...(taskIndex !== undefined && { taskIndex }),
5094
5114
  ...(totalTasks !== undefined && { totalTasks }),
5095
- }, (filePath, payload) => { writeAsyncResultFile(filePath, payload as Record<string, unknown>); });
5115
+ }, (filePath, payload) => publishRunResult(filePath, () => { writeAsyncResultFile(filePath, payload as Record<string, unknown>); }));
5096
5116
  // Only capacity deferral releases settled sessions before terminal publication.
5097
5117
  if (!finalResultCommitted) await Promise.all([publication, disposeChildSessions()]);
5098
5118
  } catch (err) {
@@ -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
  : "";
@@ -4,11 +4,14 @@ import type { AsyncStatus } from "../../shared/types.ts";
4
4
  import { readStatus } from "../../shared/utils.ts";
5
5
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
6
6
  import { encodeIndexSegment } from "./index-segment.ts";
7
+ import { isSafeNestedPathId } from "../shared/nested-path.ts";
7
8
 
8
9
  export const TERMINAL_RUN_INDEX_DIR = ".terminal-runs";
9
10
 
10
11
  const TERMINAL_RUN_INDEX_VERSION = 1;
11
12
  const TIMESTAMP_WIDTH = 16;
13
+ // Literal @ cannot occur in an encoded session key.
14
+ const TOOL_CALL_INDEX_DIR = "@tool-calls";
12
15
 
13
16
  interface TerminalRunIndexEntry {
14
17
  version: 1;
@@ -29,6 +32,14 @@ function sessionIndexDir(asyncDirRoot: string, sessionId: string): string {
29
32
  return path.join(indexRoot(asyncDirRoot), encodeIndexSegment(sessionId));
30
33
  }
31
34
 
35
+ function toolCallIndexDir(asyncDirRoot: string, toolCallId: string): string {
36
+ return path.join(indexRoot(asyncDirRoot), TOOL_CALL_INDEX_DIR, encodeIndexSegment(toolCallId));
37
+ }
38
+
39
+ function toolCallMarkerName(runId: string): string {
40
+ return `${encodeIndexSegment(runId, 250)}.json`;
41
+ }
42
+
32
43
  function markerName(endedAt: number, runId: string): string {
33
44
  return `${Math.max(0, Math.floor(endedAt)).toString().padStart(TIMESTAMP_WIDTH, "0")}-${encodeIndexSegment(runId)}.json`;
34
45
  }
@@ -58,6 +69,14 @@ export function updateTerminalRunIndex(asyncDir: string, status: AsyncStatus): v
58
69
  endedAt,
59
70
  };
60
71
  writeAtomicJson(marker, entry);
72
+ if (status.toolCallId) {
73
+ try {
74
+ writeAtomicJson(path.join(toolCallIndexDir(path.dirname(asyncDir), status.toolCallId), toolCallMarkerName(entry.runId)), entry);
75
+ } catch (error) {
76
+ // Optional aliases must not block authoritative terminal indexing or capacity release.
77
+ console.error(`Failed to write async terminal-run tool-call index for '${asyncDir}':`, error);
78
+ }
79
+ }
61
80
  }
62
81
 
63
82
  function removeInvalidMarker(marker: string): void {
@@ -89,7 +108,7 @@ function sessionDirs(asyncDirRoot: string, sessionId: string | undefined): strin
89
108
  if (sessionId) return [sessionIndexDir(asyncDirRoot, sessionId)];
90
109
  try {
91
110
  return fs.readdirSync(indexRoot(asyncDirRoot), { withFileTypes: true })
92
- .filter((entry) => entry.isDirectory())
111
+ .filter((entry) => entry.isDirectory() && entry.name !== TOOL_CALL_INDEX_DIR)
93
112
  .map((entry) => path.join(indexRoot(asyncDirRoot), entry.name));
94
113
  } catch (error) {
95
114
  const code = (error as NodeJS.ErrnoException).code;
@@ -105,6 +124,32 @@ function recentMarkerFiles(dirs: string[], limit: number): string[] {
105
124
  .map((marker) => path.join(marker.dir, marker.name));
106
125
  }
107
126
 
127
+ export function readTerminalRunToolCallIndex(asyncDirRoot: string, toolCallId: string): string[] {
128
+ const runIds: string[] = [];
129
+ for (const file of markerFiles(toolCallIndexDir(asyncDirRoot, toolCallId))) {
130
+ const marker = path.join(file.dir, file.name);
131
+ let entry: TerminalRunIndexEntry | undefined;
132
+ try {
133
+ entry = parseEntry(JSON.parse(fs.readFileSync(marker, "utf-8")));
134
+ } catch (error) {
135
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
136
+ if (!(error instanceof SyntaxError)) throw error;
137
+ }
138
+ if (!entry || !isSafeNestedPathId(entry.runId) || file.name !== toolCallMarkerName(entry.runId)) {
139
+ removeInvalidMarker(marker);
140
+ continue;
141
+ }
142
+ const status = readStatus(path.join(asyncDirRoot, entry.runId));
143
+ if (!status || !isTerminalState(status.state) || status.runId !== entry.runId
144
+ || status.sessionId !== entry.sessionId || status.toolCallId !== toolCallId) {
145
+ removeInvalidMarker(marker);
146
+ continue;
147
+ }
148
+ runIds.push(entry.runId);
149
+ }
150
+ return runIds;
151
+ }
152
+
108
153
  export function readRecentTerminalRunIndex(asyncDirRoot: string, options: { sessionId?: string; limit?: number } = {}): string[] {
109
154
  const limit = options.limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.floor(options.limit));
110
155
  const candidates = recentMarkerFiles(sessionDirs(asyncDirRoot, options.sessionId), limit);
@@ -106,6 +106,7 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
106
106
  ...(sessionFile ? { sessionFile } : {}),
107
107
  ...(typeof child.success === "boolean" ? { success: child.success } : {}),
108
108
  ...(outputState ? { outputState } : {}),
109
+ ...(child.outputPartial === true ? { outputPartial: true } : {}),
109
110
  ...(structuredOutput !== undefined ? { structuredOutput } : {}),
110
111
  ...(structuredOutputPath ? { structuredOutputPath } : {}),
111
112
  ...(error ? { error } : {}),
@@ -4,6 +4,7 @@ import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
5
5
  import type { WaitSubscriptionManager } from "./wait-subscriptions.ts";
6
6
  import { finalizeToolResult } from "../../extension/tool-result.ts";
7
+ import { registerPinnedTool } from "../../extension/declaration-pinning.ts";
7
8
 
8
9
  export function registerWaitTool(
9
10
  pi: ExtensionAPI,
@@ -14,28 +15,37 @@ export function registerWaitTool(
14
15
  child?: { nestedRootRunId?: string },
15
16
  hasPendingSupervisorRequest?: () => boolean,
16
17
  ): void {
17
- const description = `Wait for background, provider, or detached work that has no native completion notification, then return.
18
-
19
- ${child ? "This child runtime does not install the root session's native completion notifier. Use blocking bg_wait to collect your owned descendants during this turn, then read the returned result references before synthesizing findings. Automatic draining at agent_end keeps owned work alive but does not synthesize its results." : "Ordinary async subagent runs already notify this session natively when they complete or need attention. In an interactive chat, return control instead of calling this merely to wait. Use this tool for provider jobs, remembered detached foreground runs, or other background work without a native notification path. Headless runs auto-drain current-session subagent work at agent_end; use this tool only when the current turn must receive non-notifying background work results."}
20
-
21
- • { } — return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
22
- • { all: true } — wait for every async run, provider item, and remembered detached foreground descendant that was active when the call began.
23
- • { id: "..." } — wait for one async or remembered detached foreground subagent run (id or prefix). Named async runs that already finished return their terminal result references.
24
- • { id: "...", nonBlocking: true } — resolve the prefix once, persist an exact-run wake subscription, and return immediately. Use this for detached work without native completion delivery; the originating interactive session wakes on completion, failure, attention, reconciliation failure, or timeout.
25
- • { stopOnAttention: false } — for blocking waits only, keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.
26
- • { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running. Omitted values use waitTool.defaultTimeoutMs, then 30 minutes. Window expiry returns a non-error window_elapsed result with active work identities.
27
-
28
- Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`bg_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : "\n\nConfigured behavior: bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`;
29
- const execute: ToolDefinition<typeof SubagentWaitParams, Details>["execute"] = async (_id, params, signal, onUpdate, ctx) => finalizeToolResult(await waitForSubagents(params, signal, {
30
- state,
31
- nestedRootRunId: child?.nestedRootRunId,
32
- events: pi.events,
33
- enabled,
34
- hasPendingSupervisorRequest,
35
- ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
36
- onUpdate,
37
- ...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
38
- }));
18
+ const description = `Wait for background work, then return. ${child ? "This child runtime has no native completion notifier: use blocking bg_wait to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results." : "Ordinary async subagent runs already wake this session natively; use bg_wait only for provider, detached, or other background work without native notification, when a same-turn result is needed."}
19
+ {} — first active run or provider item to finish or need attention.
20
+ {all:true} — all work active at call time.
21
+ {id} — one run; a finished async run returns its result references.
22
+ {id,nonBlocking:true} — subscribe to that run's wake and return now.
23
+ Timeout or a user message ends the wait without error; work keeps running.${enabled ? "" : "\nDisabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED: returns immediately."}`;
24
+ // Messages typed while the agent is busy (steer or follow-up) end open waits so they reach the model.
25
+ const userInputWaits = new Set<AbortController>();
26
+ pi.on("input", (event) => {
27
+ if (event.source === "extension" || !event.streamingBehavior) return;
28
+ for (const controller of userInputWaits) controller.abort();
29
+ });
30
+ const execute: ToolDefinition<typeof SubagentWaitParams, Details>["execute"] = async (_id, params, signal, onUpdate, ctx) => {
31
+ const userInput = new AbortController();
32
+ userInputWaits.add(userInput);
33
+ try {
34
+ return finalizeToolResult(await waitForSubagents(params, signal, {
35
+ state,
36
+ nestedRootRunId: child?.nestedRootRunId,
37
+ events: pi.events,
38
+ enabled,
39
+ hasPendingSupervisorRequest,
40
+ userInputSignal: userInput.signal,
41
+ ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
42
+ onUpdate,
43
+ ...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
44
+ }));
45
+ } finally {
46
+ userInputWaits.delete(userInput);
47
+ }
48
+ };
39
49
  const primaryTool: ToolDefinition<typeof SubagentWaitParams, Details> = {
40
50
  name: "bg_wait",
41
51
  label: "Background Wait",
@@ -43,5 +53,5 @@ Non-blocking subscriptions are visible in subagent status and differ from disabl
43
53
  parameters: SubagentWaitParams,
44
54
  execute,
45
55
  };
46
- pi.registerTool(primaryTool);
56
+ registerPinnedTool(pi, primaryTool);
47
57
  }
@@ -14,40 +14,57 @@ export type WorkflowChildProcessEvidence =
14
14
  | { state: "observed"; children: ProcessTerminal[] }
15
15
  | { state: "pending" | "unknown"; reason: string };
16
16
 
17
+ /** `unresolvedProof` is set only when a terminal child's status matches its roster run id and runner identity, and just its process proof is missing. */
18
+ export type WorkflowChildEvidence =
19
+ | { state: "resolved"; proof: ProcessTerminal }
20
+ | { state: "pending" | "unknown"; reason: string; unresolvedProof?: { status: AsyncStatus; proofState: string } };
21
+
17
22
  /**
18
23
  * Process evidence for a workflow's async children. Status proofs and capacity
19
24
  * release both use this so they cannot disagree about the same workflow.
20
- * Synchronous children run inside the workflow host and have no process of their own.
21
25
  */
22
26
  export function readWorkflowChildProcessEvidence(workflowAsyncDir: string, steps: AsyncStatus["steps"]): WorkflowChildProcessEvidence {
23
27
  if (!steps) return { state: "unknown", reason: "workflow child roster is missing" };
24
28
  const children: ProcessTerminal[] = [];
25
29
  for (const step of steps) {
26
- const label = step.workflowKey ?? step.agent;
27
- if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
28
- if (!step.async) continue;
29
- if (!step.runId || path.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
30
- const childDir = path.join(path.dirname(workflowAsyncDir), step.runId);
31
- if (!fs.existsSync(childDir)) return { state: "unknown", reason: `async workflow child ${label} directory is missing` };
32
- const childStatus = readStatus(childDir);
33
- if (!childStatus) return { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
34
- if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
35
- const recorded = childStatus.processTerminal;
36
- if (!recorded?.runnerProcessInstanceId) return { state: "unknown", reason: `async workflow child ${label} has no runner process identity` };
37
- // A runner startup failure records `not-started` in status and never writes a process-terminal sidecar.
38
- if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
39
- children.push(recorded);
40
- continue;
41
- }
42
- const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
43
- if (proof?.state !== "observed" || proof.runId !== step.runId) {
44
- return { state: !proof || proof.state === "pending" ? "pending" : "unknown", reason: `async workflow child ${label} process-terminal proof is ${proof?.state ?? "missing"}` };
45
- }
46
- children.push(proof);
30
+ const child = readWorkflowChildEvidence(workflowAsyncDir, step);
31
+ if (!child) continue;
32
+ if (child.state !== "resolved") return { state: child.state, reason: child.reason };
33
+ children.push(child.proof);
47
34
  }
48
35
  return { state: "observed", children };
49
36
  }
50
37
 
38
+ /** Evidence for one roster entry; undefined for synchronous children, which run inside the workflow host and have no process of their own. */
39
+ export function readWorkflowChildEvidence(workflowAsyncDir: string, step: NonNullable<AsyncStatus["steps"]>[number]): WorkflowChildEvidence | undefined {
40
+ const label = step.workflowKey ?? step.agent;
41
+ if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
42
+ if (!step.async) return undefined;
43
+ if (!step.runId || path.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
44
+ const childDir = path.join(path.dirname(workflowAsyncDir), step.runId);
45
+ if (!fs.existsSync(childDir)) return { state: "unknown", reason: `async workflow child ${label} directory is missing` };
46
+ const childStatus = readStatus(childDir);
47
+ if (!childStatus) return { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
48
+ if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
49
+ const recorded = childStatus.processTerminal;
50
+ if (!recorded?.runnerProcessInstanceId) return { state: "unknown", reason: `async workflow child ${label} has no runner process identity` };
51
+ // A runner startup failure records `not-started` in status and never writes a process-terminal sidecar.
52
+ if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
53
+ return { state: "resolved", proof: recorded };
54
+ }
55
+ const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
56
+ if (proof?.state !== "observed" || proof.runId !== step.runId) {
57
+ const proofState = proof?.state ?? "missing";
58
+ const bound = childStatus.runId === step.runId && typeof recorded.runnerProcessInstanceId === "string";
59
+ return {
60
+ state: !proof || proof.state === "pending" ? "pending" : "unknown",
61
+ reason: `async workflow child ${label} process-terminal proof is ${proofState}`,
62
+ ...(bound ? { unresolvedProof: { status: childStatus, proofState } } : {}),
63
+ };
64
+ }
65
+ return { state: "resolved", proof };
66
+ }
67
+
51
68
  function unresolved(runId: string, state: "pending" | "unknown", dispatchClosed: boolean, reason: string): WorkflowTerminalProof {
52
69
  return { version: 1, kind: "workflow", runId, state, dispatchClosed, reason };
53
70
  }