@xzzpig/pi-subagents 0.15.1 → 0.18.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 (135) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
@@ -0,0 +1,98 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
4
+ import type { ProcessInstanceExit } from "../../shared/types.ts";
5
+
6
+ export interface ProcessTerminalCandidate {
7
+ version: 1;
8
+ runId: string;
9
+ runnerProcessInstanceId: string;
10
+ writers: Record<string, ProcessInstanceExit[]>;
11
+ expectedWriters?: Record<string, number>;
12
+ sessionFile?: string;
13
+ revivalLeaseToken?: string;
14
+ revivalLeaseReleaseAcknowledged?: boolean;
15
+ }
16
+
17
+ export function isRecord(value: unknown): value is Record<string, unknown> {
18
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19
+ }
20
+
21
+ export function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExit {
22
+ if (!isRecord(value)) return false;
23
+ if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
24
+ if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
25
+ if (typeof value.closeObservedAt !== "number" || !Number.isFinite(value.closeObservedAt)) return false;
26
+ if (typeof value.exitCode !== "number" && value.exitCode !== null) return false;
27
+ if (typeof value.signal !== "string" && value.signal !== null) return false;
28
+ if (value.kind === "runner") return value.attempt === undefined;
29
+ if (typeof value.attempt !== "number" || !Number.isInteger(value.attempt) || value.attempt < 0 || !isRecord(value.processTree)) return false;
30
+ if (value.processTree.state === "observed") {
31
+ return value.processTree.mechanism === "posix-process-group"
32
+ && typeof value.processTree.processGroupId === "number"
33
+ && Number.isInteger(value.processTree.processGroupId)
34
+ && value.processTree.processGroupId > 0
35
+ && typeof value.processTree.verifiedAt === "number"
36
+ && Number.isFinite(value.processTree.verifiedAt);
37
+ }
38
+ return value.processTree.state === "unknown"
39
+ && ["unsupported-platform", "signal-failed", "verification-failed"].includes(String(value.processTree.reason))
40
+ && (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
41
+ }
42
+
43
+ function validInstance(value: unknown): value is ProcessInstanceExit {
44
+ return validProcessInstance(value, "pi-writer");
45
+ }
46
+
47
+ export function processTerminalCandidatePath(asyncDir: string): string {
48
+ return path.join(asyncDir, "process-terminal-candidate.json");
49
+ }
50
+
51
+ export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalCandidate | undefined {
52
+ try {
53
+ const raw = JSON.parse(fs.readFileSync(processTerminalCandidatePath(asyncDir), "utf-8")) as unknown;
54
+ if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
55
+ throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
56
+ }
57
+ const writers: Record<string, ProcessInstanceExit[]> = {};
58
+ for (const [index, entries] of Object.entries(raw.writers)) {
59
+ if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
60
+ writers[index] = entries;
61
+ }
62
+ let expectedWriters: Record<string, number> | undefined;
63
+ if (raw.expectedWriters !== undefined) {
64
+ if (!isRecord(raw.expectedWriters)) throw new Error("Invalid expected writer process records.");
65
+ expectedWriters = {};
66
+ for (const [index, count] of Object.entries(raw.expectedWriters)) {
67
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 0) throw new Error(`Invalid expected writer count for child '${index}'.`);
68
+ expectedWriters[index] = count;
69
+ }
70
+ }
71
+ if (raw.sessionFile !== undefined && typeof raw.sessionFile !== "string") throw new Error("Invalid process-terminal candidate sessionFile.");
72
+ if (raw.revivalLeaseToken !== undefined && typeof raw.revivalLeaseToken !== "string") throw new Error("Invalid process-terminal candidate lease token.");
73
+ if (raw.revivalLeaseReleaseAcknowledged !== undefined && typeof raw.revivalLeaseReleaseAcknowledged !== "boolean") throw new Error("Invalid process-terminal lease release acknowledgement.");
74
+ return {
75
+ version: 1,
76
+ runId: raw.runId,
77
+ runnerProcessInstanceId: raw.runnerProcessInstanceId,
78
+ writers,
79
+ ...(expectedWriters ? { expectedWriters } : {}),
80
+ ...(typeof raw.sessionFile === "string" && raw.sessionFile ? { sessionFile: raw.sessionFile } : {}),
81
+ ...(typeof raw.revivalLeaseToken === "string" && raw.revivalLeaseToken ? { revivalLeaseToken: raw.revivalLeaseToken } : {}),
82
+ ...(typeof raw.revivalLeaseReleaseAcknowledged === "boolean" ? { revivalLeaseReleaseAcknowledged: raw.revivalLeaseReleaseAcknowledged } : {}),
83
+ };
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ export function writeProcessTerminalCandidate(asyncDir: string, candidate: ProcessTerminalCandidate): void {
91
+ writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
92
+ }
93
+
94
+ export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
95
+ const candidate = readProcessTerminalCandidate(asyncDir);
96
+ if (!candidate || candidate.revivalLeaseToken !== token) return;
97
+ writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
98
+ }
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { writeAtomicJson, writePrivateAtomicJson } from "../../shared/atomic-json.ts";
3
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
4
4
  import {
5
5
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
6
6
  type AsyncStatus,
@@ -11,17 +11,9 @@ import {
11
11
  } from "../../shared/types.ts";
12
12
  import { canonicalSessionId, inspectSessionLease } from "../shared/session-lease.ts";
13
13
  import { releaseActiveRunIndex } from "./active-run-index.ts";
14
-
15
- export interface ProcessTerminalCandidate {
16
- version: 1;
17
- runId: string;
18
- runnerProcessInstanceId: string;
19
- writers: Record<string, ProcessInstanceExit[]>;
20
- expectedWriters?: Record<string, number>;
21
- sessionFile?: string;
22
- revivalLeaseToken?: string;
23
- revivalLeaseReleaseAcknowledged?: boolean;
24
- }
14
+ import { isRecord, validProcessInstance, readProcessTerminalCandidate, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal-candidate.ts";
15
+ export { processTerminalCandidatePath, readProcessTerminalCandidate, writeProcessTerminalCandidate, markProcessTerminalCandidateLeaseRelease } from "./process-terminal-candidate.ts";
16
+ export type { ProcessTerminalCandidate } from "./process-terminal-candidate.ts";
25
17
 
26
18
  export interface RunnerCloseObservation {
27
19
  processInstanceId: string;
@@ -30,40 +22,6 @@ export interface RunnerCloseObservation {
30
22
  signal: string | null;
31
23
  }
32
24
 
33
- function isRecord(value: unknown): value is Record<string, unknown> {
34
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
35
- }
36
-
37
- function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExit {
38
- if (!isRecord(value)) return false;
39
- if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
40
- if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
41
- if (typeof value.closeObservedAt !== "number" || !Number.isFinite(value.closeObservedAt)) return false;
42
- if (typeof value.exitCode !== "number" && value.exitCode !== null) return false;
43
- if (typeof value.signal !== "string" && value.signal !== null) return false;
44
- if (value.kind === "runner") return value.attempt === undefined;
45
- if (typeof value.attempt !== "number" || !Number.isInteger(value.attempt) || value.attempt < 0 || !isRecord(value.processTree)) return false;
46
- if (value.processTree.state === "observed") {
47
- return value.processTree.mechanism === "posix-process-group"
48
- && typeof value.processTree.processGroupId === "number"
49
- && Number.isInteger(value.processTree.processGroupId)
50
- && value.processTree.processGroupId > 0
51
- && typeof value.processTree.verifiedAt === "number"
52
- && Number.isFinite(value.processTree.verifiedAt);
53
- }
54
- return value.processTree.state === "unknown"
55
- && ["unsupported-platform", "signal-failed", "verification-failed"].includes(String(value.processTree.reason))
56
- && (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
57
- }
58
-
59
- function validInstance(value: unknown): value is ProcessInstanceExit {
60
- return validProcessInstance(value, "pi-writer");
61
- }
62
-
63
- export function processTerminalCandidatePath(asyncDir: string): string {
64
- return path.join(asyncDir, "process-terminal-candidate.json");
65
- }
66
-
67
25
  export function processTerminalPath(asyncDir: string): string {
68
26
  return path.join(asyncDir, "process-terminal.json");
69
27
  }
@@ -72,49 +30,6 @@ function errorMessage(error: unknown): string {
72
30
  return error instanceof Error ? error.message : String(error);
73
31
  }
74
32
 
75
- export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalCandidate | undefined {
76
- try {
77
- const raw = JSON.parse(fs.readFileSync(processTerminalCandidatePath(asyncDir), "utf-8")) as unknown;
78
- if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
79
- throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
80
- }
81
- const writers: Record<string, ProcessInstanceExit[]> = {};
82
- for (const [index, entries] of Object.entries(raw.writers)) {
83
- if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
84
- writers[index] = entries;
85
- }
86
- let expectedWriters: Record<string, number> | undefined;
87
- if (raw.expectedWriters !== undefined) {
88
- if (!isRecord(raw.expectedWriters)) throw new Error("Invalid expected writer process records.");
89
- expectedWriters = {};
90
- for (const [index, count] of Object.entries(raw.expectedWriters)) {
91
- if (typeof count !== "number" || !Number.isInteger(count) || count < 0) throw new Error(`Invalid expected writer count for child '${index}'.`);
92
- expectedWriters[index] = count;
93
- }
94
- }
95
- if (raw.sessionFile !== undefined && typeof raw.sessionFile !== "string") throw new Error("Invalid process-terminal candidate sessionFile.");
96
- if (raw.revivalLeaseToken !== undefined && typeof raw.revivalLeaseToken !== "string") throw new Error("Invalid process-terminal candidate lease token.");
97
- if (raw.revivalLeaseReleaseAcknowledged !== undefined && typeof raw.revivalLeaseReleaseAcknowledged !== "boolean") throw new Error("Invalid process-terminal lease release acknowledgement.");
98
- return {
99
- version: 1,
100
- runId: raw.runId,
101
- runnerProcessInstanceId: raw.runnerProcessInstanceId,
102
- writers,
103
- ...(expectedWriters ? { expectedWriters } : {}),
104
- ...(typeof raw.sessionFile === "string" && raw.sessionFile ? { sessionFile: raw.sessionFile } : {}),
105
- ...(typeof raw.revivalLeaseToken === "string" && raw.revivalLeaseToken ? { revivalLeaseToken: raw.revivalLeaseToken } : {}),
106
- ...(typeof raw.revivalLeaseReleaseAcknowledged === "boolean" ? { revivalLeaseReleaseAcknowledged: raw.revivalLeaseReleaseAcknowledged } : {}),
107
- };
108
- } catch (error) {
109
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
110
- throw error;
111
- }
112
- }
113
-
114
- export function writeProcessTerminalCandidate(asyncDir: string, candidate: ProcessTerminalCandidate): void {
115
- writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
116
- }
117
-
118
33
  /** Establish ownership before authorizing a runner to start any child session. */
119
34
  export function initializeProcessTerminal(asyncDir: string, runId: string, runnerProcessInstanceId: string): void {
120
35
  writeProcessTerminalCandidate(asyncDir, {
@@ -131,12 +46,6 @@ export function initializeProcessTerminal(asyncDir: string, runId: string, runne
131
46
  });
132
47
  }
133
48
 
134
- export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
135
- const candidate = readProcessTerminalCandidate(asyncDir);
136
- if (!candidate || candidate.revivalLeaseToken !== token) return;
137
- writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
138
- }
139
-
140
49
  function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string): ProcessTerminal {
141
50
  return { version: 1, state: "unknown", runId, runnerProcessInstanceId, reason, ...(diagnostic ? { diagnostic } : {}) };
142
51
  }
@@ -248,7 +157,17 @@ export function finalizeProcessTerminal(
248
157
  const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
249
158
  if (existing && fs.existsSync(processTerminalPath(asyncDir))) {
250
159
  if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
251
- if (existing.state === "unknown") return existing;
160
+ if (existing.state === "unknown") {
161
+ // A sticky runner-published unknown proof keeps its reason; only add the observed exit. Unreadable or mismatched sidecars read back as proof-write-failed and stay untouched.
162
+ if (existing.instances?.length || existing.reason === "proof-write-failed") return existing;
163
+ const withExit: ProcessTerminal = { ...existing, instances: [{ kind: "runner", ...runnerClose }] };
164
+ try {
165
+ writeAtomicJson(processTerminalPath(asyncDir), withExit);
166
+ return withExit;
167
+ } catch {
168
+ return existing;
169
+ }
170
+ }
252
171
  }
253
172
  let proof: ProcessTerminal;
254
173
  let candidateForOverlay: ProcessTerminalCandidate | undefined;
@@ -296,6 +215,8 @@ export function finalizeProcessTerminal(
296
215
  } catch (error) {
297
216
  proof = unknownProof(runId, runnerClose.processInstanceId, "proof-write-failed", errorMessage(error));
298
217
  }
218
+ // An unverified process tree still has a directly observed runner exit; keep it for failure reports.
219
+ if (proof.state === "unknown") proof = { ...proof, instances: [{ kind: "runner", ...runnerClose }] };
299
220
  let durable = false;
300
221
  try {
301
222
  writeAtomicJson(processTerminalPath(asyncDir), proof);
@@ -483,7 +483,7 @@ export function createResultWatcher(
483
483
  : output;
484
484
  const sessionPath = result.sessionFile ?? (resultChildren.length === 1 ? data.sessionFile : undefined);
485
485
  const childNestedChildren = sanitizeNestedResultChildren(result.children, resultPath, `results[${index}].children`);
486
- const childState = result.state === "paused" || result.state === "stopped"
486
+ const childState = result.state === "running" || result.state === "queued" || result.state === "paused" || result.state === "stopped"
487
487
  ? result.state
488
488
  : result.stopped === true
489
489
  ? "stopped"
@@ -108,7 +108,8 @@ export function listRetainedChildren(asyncDirRoot: string, sessionId: string): R
108
108
  }
109
109
 
110
110
  export function formatRetainedChildren(children: RetainedChild[]): string {
111
- if (children.length === 0) return "No retained workflow children in the active parent session. If a retained-writer challenge is required, launch a same-role fallback challenge and label it as fallback.";
111
+ const noKnownEligibleTargetGuidance = 'children.list is workflow-only and is not an exhaustive list of direct native children. If the exact run id of the intended child is known, inspect it with subagent({ action: "status", id: "..." }); if status identifies the candidate, attempt subagent({ action: "resume", id: "...", message: "..." }), which authoritatively checks eligibility and may reject it. Launch a same-role fallback challenge, labeled as fallback, only when there is no known candidate or resume rejects eligibility.';
112
+ if (children.length === 0) return `No retained workflow children in the active parent session. ${noKnownEligibleTargetGuidance}`;
112
113
  const retained = children.slice(0, MAX_RETAINED_CHILDREN);
113
114
  if (!retained.some((child) => child.resumability.state === "resumable")) {
114
115
  const resumable = children.slice(MAX_RETAINED_CHILDREN).find((child) => child.resumability.state === "resumable");
@@ -130,6 +131,6 @@ export function formatRetainedChildren(children: RetainedChild[]): string {
130
131
  ] : []),
131
132
  ...(child.tokenTotals ? [` tokens: input ${child.tokenTotals.input}, output ${child.tokenTotals.output}, total ${child.tokenTotals.total}`] : []),
132
133
  ]),
133
- ...(hasResumableChild ? [] : ["No resumable retained child is listed. Launch a same-role fallback challenge and label it as fallback."]),
134
+ ...(hasResumableChild ? [] : [`No resumable retained workflow child is listed. ${noKnownEligibleTargetGuidance}`]),
134
135
  ].join("\n");
135
136
  }
@@ -25,6 +25,7 @@ import { isMutatingTool, resolveCurrentPath } from "../shared/long-running-guard
25
25
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
26
26
  import { createReportedChildSessionInput, type InProcessChildLaunch } from "../shared/child-launch.ts";
27
27
  import { childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
28
+ import { reconcileAttemptUsage } from "../shared/usage-reconciliation.ts";
28
29
  import { formatSteerMessage } from "../shared/subagent-prompt-runtime.ts";
29
30
  import type { SteerDeliveryStatus, SteerRequest } from "./control-channel.ts";
30
31
  import { takeMatchingAcceptedSteer, unconsumedSteerReason } from "./steering.ts";
@@ -92,6 +93,7 @@ export interface RunChildSessionInput {
92
93
  timeoutMessage?: string;
93
94
  stopMessage?: string;
94
95
  onChildEvent?: (event: ChildEvent) => void;
96
+ onContextWindow?: (contextWindow: number) => void;
95
97
  transcriptWriter?: ChildTranscriptWriter;
96
98
  toolTimeoutMs?: number;
97
99
  runDeadlineAt?: number;
@@ -118,6 +120,7 @@ export interface RunChildSessionResult {
118
120
  observedMutationAttempt?: boolean;
119
121
  structuredOutputToolInvoked?: boolean;
120
122
  structuredOutputMessageStartIndex?: number;
123
+ structuredOutputFailed?: boolean;
121
124
  watchdog?: ChildWatchdogStateSnapshot;
122
125
  sessionFile?: string;
123
126
  currentTool?: string;
@@ -181,6 +184,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
181
184
  let currentPath: string | undefined;
182
185
  let toolCount = 0;
183
186
  let session: ChildSession | undefined;
187
+ let messageBaseline: number | undefined;
184
188
  const acceptedSteers: Array<{ request: SteerRequest; text: string }> = [];
185
189
  let unsubscribe: (() => void) | undefined;
186
190
  let settled = false;
@@ -243,8 +247,10 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
243
247
  };
244
248
 
245
249
  const abortChild = (): void => {
246
- if (!session || settled || promptSettled) return;
247
- void session.abort().catch(() => {
250
+ if (settled || promptSettled) return;
251
+ // A hung session creation has no session to abort yet; the settle timer below is the only
252
+ // thing that ends the run, and a session created afterwards is disposed by the launch block.
253
+ void session?.abort().catch(() => {
248
254
  // The run settles through its prompt promise; abort failures are not separately actionable.
249
255
  });
250
256
  if (!abortSettleTimer) {
@@ -563,6 +569,9 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
563
569
  if (settled) return;
564
570
  settled = true;
565
571
  failUnconsumedSteers();
572
+ const terminalUsage = session && messageBaseline !== undefined
573
+ ? reconcileAttemptUsage(usage, session.messages, messageBaseline)
574
+ : usage;
566
575
  const closed = finish();
567
576
  const finalOutput = getFinalOutput(messages);
568
577
  let finalError = error ?? assistantError;
@@ -578,7 +587,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
578
587
  && finalError === promptErrorMessage
579
588
  && isChildModelResolutionFailure(promptErrorMessage)
580
589
  && messages.length === 0
581
- && usage.turns === 0
590
+ && terminalUsage.turns === 0
582
591
  && !input.launch.session.ambientExtensions) {
583
592
  finalError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: input.launch.config.agent, model: input.launch.session.model, host: "runner", capabilityCeiling: input.launch.toolPlan.capabilityCeiling })}`;
584
593
  }
@@ -596,7 +605,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
596
605
  const result: RunChildSessionResult = omitUndefined({
597
606
  exitCode,
598
607
  messages,
599
- usage,
608
+ usage: terminalUsage,
600
609
  toolCount,
601
610
  durationMs: Date.now() - startedAt,
602
611
  model,
@@ -641,10 +650,11 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
641
650
  const createInput = createReportedChildSessionInput(input.launch, input.transcriptWriter);
642
651
  const created = await input.factory.create(createInput);
643
652
  if (settled) {
644
- void created.dispose();
653
+ await created.dispose().catch(() => undefined);
645
654
  return;
646
655
  }
647
656
  session = created;
657
+ if (created.contextWindow !== undefined) input.onContextWindow?.(created.contextWindow);
648
658
  const steer = created.steer.bind(created);
649
659
  const followUp = created.followUp.bind(created);
650
660
  created.steer = async (text) => {
@@ -678,6 +688,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
678
688
  return queued;
679
689
  });
680
690
  if (interrupted || timedOut || stopped) abortChild();
691
+ messageBaseline = created.messages.length;
681
692
  await created.prompt(input.prompt);
682
693
  promptSettled = true;
683
694
  settle(undefined);
@@ -21,11 +21,11 @@ export interface ResolveSubagentRunIdDeps {
21
21
 
22
22
  function exactAsyncLocation(id: string, asyncDirRoot: string, resultsDir: string): AsyncRunLocation | undefined {
23
23
  const asyncDir = path.join(asyncDirRoot, id);
24
- const asyncDirExists = fs.existsSync(asyncDir);
24
+ const hasStatus = fs.existsSync(path.join(asyncDir, "status.json"));
25
25
  const resultPath = resultPathFor(resultsDir, id);
26
- if (!asyncDirExists && !resultPath) return undefined;
26
+ if (!hasStatus && !resultPath) return undefined;
27
27
  return {
28
- asyncDir: asyncDirExists ? asyncDir : null,
28
+ asyncDir: hasStatus ? asyncDir : null,
29
29
  resultPath,
30
30
  resolvedId: id,
31
31
  };
@@ -131,11 +131,16 @@ function nestedScopeFromState(state: SubagentState | undefined): NestedRunResolu
131
131
  };
132
132
  for (const control of state.foregroundControls.values()) add(control.nestedRoute as NestedRoute | undefined);
133
133
  for (const job of state.asyncJobs.values()) add(job.nestedRoute as NestedRoute | undefined);
134
+ if (state.retainedNestedLookupRoutes?.sessionId === state.currentSessionId) {
135
+ for (const route of state.retainedNestedLookupRoutes.routes.values()) add(route);
136
+ }
134
137
  return { routes };
135
138
  }
136
139
 
137
140
  function asyncPrefixMatches(prefix: string, asyncDirRoot: string, resultsDir: string): Array<{ id: string; location: AsyncRunLocation }> {
138
- return findAsyncRunPrefixMatches(prefix, asyncDirRoot, resultsDir);
141
+ return findAsyncRunPrefixMatches(prefix, asyncDirRoot, resultsDir).filter((match) =>
142
+ match.location.resultPath || (match.location.asyncDir && fs.existsSync(path.join(match.location.asyncDir, "status.json")))
143
+ );
139
144
  }
140
145
 
141
146
  export function resolveSubagentRunId(id: string, deps: ResolveSubagentRunIdDeps = {}): ResolvedSubagentRunId | undefined {
@@ -143,7 +148,6 @@ export function resolveSubagentRunId(id: string, deps: ResolveSubagentRunIdDeps
143
148
  const asyncDirRoot = deps.asyncDirRoot ?? DIRS.async;
144
149
  const resultsDir = deps.resultsDir ?? DIRS.results;
145
150
 
146
- const nestedScope = deps.nested ?? nestedScopeFromState(deps.state);
147
151
  if (hasExactForegroundId(deps.state, id)) return { kind: "foreground", id };
148
152
  const exactAsync = exactAsyncLocation(id, asyncDirRoot, resultsDir);
149
153
  if (exactAsync) return { kind: "async", id, location: exactAsync };
@@ -152,6 +156,7 @@ export function resolveSubagentRunId(id: string, deps: ResolveSubagentRunIdDeps
152
156
  const exactToolCallIdMatches = indexedToolCallIdAsyncLocations(id, asyncDirRoot, resultsDir);
153
157
  if (exactToolCallIdMatches.length > 1) throw new Error(`Subagent tool-call id '${id}' is ambiguous across async runs. Use the returned asyncId instead.`);
154
158
  if (exactToolCallIdMatches[0]) return { kind: "async", id: exactToolCallIdMatches[0].id, location: exactToolCallIdMatches[0].location };
159
+ const nestedScope = deps.nested ?? nestedScopeFromState(deps.state);
155
160
  const exactNested = findNestedRunMatchesById(id, nestedScope ? { scope: nestedScope } : {});
156
161
  if (exactNested.length > 1) throw new Error(`Nested run id '${id}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);
157
162
  if (exactNested[0]) return { kind: "nested", id, match: exactNested[0] };
@@ -16,6 +16,7 @@ import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts
16
16
  import { normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
17
17
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
18
18
  import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
19
+ import { readWorkflowTerminalProof } from "./workflow-terminal-proof.ts";
19
20
  import { formatWaitSubscriptions } from "./wait-subscriptions.ts";
20
21
  import { resolveAsyncRunLocation } from "./async-resume.ts";
21
22
  import { resolveSubagentRunId } from "./run-id-resolver.ts";
@@ -570,6 +571,12 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
570
571
 
571
572
  const workflowReturnPreview = status.workflow?.value !== undefined ? formatWorkflowJsonPreview(status.workflow.value, 240) : undefined;
572
573
  const workflowEmitPreview = status.workflow?.emits.length ? formatWorkflowJsonPreview(status.workflow.emits.at(-1), 240) : undefined;
574
+ const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
575
+ if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
576
+ const workflowTerminalProof = workflowChildren
577
+ ? readWorkflowTerminalProof(asyncDir, status.steps, workflowChildren, validHostStepNodes(status.workflowGraph).length, status.endedAt ?? status.lastUpdate ?? status.startedAt)
578
+ : undefined;
579
+ const workflowChildrenByKey = new Map(workflowChildren?.children.map((child) => [child.childId, child]));
573
580
  const lines = [
574
581
  `Run: ${status.runId}`,
575
582
  status.toolCallId ? `Tool call: ${status.toolCallId}` : undefined,
@@ -615,7 +622,8 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
615
622
  let hasExternalJobFollowUpHint = false;
616
623
  for (const [index, step] of (status.steps ?? []).entries()) {
617
624
  const stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
618
- const modelThinking = formatModelThinking(step.model, step.thinking);
625
+ const workflowChild = step.workflowKey ? workflowChildrenByKey.get(step.workflowKey) : undefined;
626
+ const modelThinking = formatModelThinking(step.model ?? workflowChild?.model, step.thinking ?? workflowChild?.thinking);
619
627
  const modelText = modelThinking ? ` (${modelThinking})` : "";
620
628
  const steeringText = formatSteeringSummary(step);
621
629
  const steeringSuffix = steeringText ? `, steering: ${steeringText}` : "";
@@ -705,9 +713,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
705
713
  if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
706
714
  if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
707
715
 
708
- const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
709
- if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
710
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(status.workflowReceiptPath ? { workflowReceiptPath: status.workflowReceiptPath } : {}), ...(status.preflight ? { preflight: status.preflight } : {}), ...(status.workflow?.preflightWarnings?.length ? { preflightWarnings: status.workflow.preflightWarnings } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
716
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(status.workflowReceiptPath ? { workflowReceiptPath: status.workflowReceiptPath } : {}), ...(status.preflight ? { preflight: status.preflight } : {}), ...(status.workflow?.preflightWarnings?.length ? { preflightWarnings: status.workflow.preflightWarnings } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(workflowTerminalProof ? { workflowTerminalProof } : {}), ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
711
717
  }
712
718
  }
713
719
 
@@ -50,21 +50,26 @@ function readManifest(packageDir: string): PackageManifest | undefined {
50
50
  }
51
51
  }
52
52
 
53
+ const BLOCKED_EXPORT = Symbol("blocked export");
54
+
53
55
  /** Pick the import target of one exports entry (string, conditions object, or array of those). */
54
- function exportTarget(entry: unknown): string | undefined {
56
+ function exportTarget(entry: unknown): string | typeof BLOCKED_EXPORT | undefined {
55
57
  if (typeof entry === "string") return entry;
58
+ if (entry === null) return BLOCKED_EXPORT;
56
59
  if (Array.isArray(entry)) {
60
+ let blocked = entry.length === 0;
57
61
  for (const candidate of entry) {
58
62
  const target = exportTarget(candidate);
59
- if (target) return target;
63
+ if (typeof target === "string") return target;
64
+ if (target === BLOCKED_EXPORT) blocked = true;
60
65
  }
61
- return undefined;
66
+ return blocked ? BLOCKED_EXPORT : undefined;
62
67
  }
63
68
  if (entry && typeof entry === "object") {
64
69
  const conditions = entry as Record<string, unknown>;
65
- for (const condition of ["import", "node", "default"]) {
66
- if (condition in conditions) {
67
- const target = exportTarget(conditions[condition]);
70
+ for (const [condition, value] of Object.entries(conditions)) {
71
+ if (condition === "default" || condition === "import" || condition === "node" || condition === "node-addons" || condition === "module-sync") {
72
+ const target = exportTarget(value);
68
73
  if (target) return target;
69
74
  }
70
75
  }
@@ -77,24 +82,28 @@ export function resolvePackageSubpath(packageDir: string, subpath: string): stri
77
82
  const manifest = readManifest(packageDir);
78
83
  if (!manifest) return undefined;
79
84
  const exportsField = manifest.exports;
80
- if (exportsField !== undefined) {
85
+ if (exportsField !== undefined && exportsField !== null) {
81
86
  const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
82
87
  ? { ".": exportsField }
83
88
  : exportsField as Record<string, unknown>;
84
- const exact = exportTarget(map[subpath]);
85
- if (exact) return path.resolve(packageDir, exact);
89
+ if (subpath in map) {
90
+ const exact = exportTarget(map[subpath]);
91
+ return typeof exact === "string" ? path.resolve(packageDir, exact) : undefined;
92
+ }
93
+ let best: { entry: unknown; prefix: string; suffix: string } | undefined;
86
94
  for (const [pattern, entry] of Object.entries(map)) {
87
95
  const star = pattern.indexOf("*");
88
96
  if (star === -1) continue;
89
97
  const prefix = pattern.slice(0, star);
90
98
  const suffix = pattern.slice(star + 1);
91
99
  if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix) || subpath.length < prefix.length + suffix.length) continue;
92
- const target = exportTarget(entry);
93
- if (!target) continue;
94
- const wildcard = subpath.slice(prefix.length, subpath.length - suffix.length);
95
- return path.resolve(packageDir, target.replace("*", wildcard));
100
+ if (!best || prefix.length > best.prefix.length || (prefix.length === best.prefix.length && suffix.length > best.suffix.length)) best = { entry, prefix, suffix };
96
101
  }
97
- return undefined;
102
+ if (!best) return undefined;
103
+ const target = exportTarget(best.entry);
104
+ if (typeof target !== "string") return undefined;
105
+ const wildcard = subpath.slice(best.prefix.length, subpath.length - best.suffix.length);
106
+ return path.resolve(packageDir, target.replaceAll("*", () => wildcard));
98
107
  }
99
108
  if (subpath !== ".") return undefined;
100
109
  return path.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
@@ -135,7 +144,8 @@ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record
135
144
  for (const { specifier, pkg, subpath } of required) {
136
145
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
137
146
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
138
- if (target && fs.existsSync(target)) aliases[specifier] = target;
147
+ // Native loaders short-circuit resolution, so aliases must retain the real package's dependency scope.
148
+ if (target && fs.existsSync(target)) aliases[specifier] = fs.realpathSync(target);
139
149
  else missing.push(specifier);
140
150
  }
141
151
  return { aliases, missing };
@@ -18,7 +18,6 @@ export interface RunnerChildLaunchContext {
18
18
  runFanoutBudget?: BuildInProcessChildLaunchInput["runFanoutBudget"];
19
19
  capabilityCeiling?: BuildInProcessChildLaunchInput["capabilityCeiling"];
20
20
  inheritedChildRuntime?: InheritedChildRuntime;
21
- hostAvailableBuiltins?: readonly string[];
22
21
  }
23
22
 
24
23
  export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChildLaunchContext, attempt: {
@@ -51,6 +50,7 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
51
50
  tools: step.tools,
52
51
  excludeTools: step.excludeTools,
53
52
  allowNestedSubagents: step.allowNestedSubagents,
53
+ descendantAllowedAgents: step.allowedAgents,
54
54
  extensions: step.extensions,
55
55
  subagentOnlyExtensions: step.subagentOnlyExtensions,
56
56
  requiredExtensions: step.requiredExtensions,
@@ -87,7 +87,6 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
87
87
  thinkingCeiling: step.thinkingCeiling,
88
88
  maxSubagentDepth: step.maxSubagentDepth,
89
89
  inherited: ctx.inheritedChildRuntime,
90
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
91
90
  host: "runner",
92
91
  });
93
92
  }
@@ -0,0 +1,56 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
4
+ import type { AsyncStatus } from "../../shared/types.ts";
5
+ import { readProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal-candidate.ts";
6
+
7
+ interface RunnerStartupFailureInput {
8
+ asyncDir: string;
9
+ runId: string;
10
+ runnerProcessInstanceId: string;
11
+ message: string;
12
+ sessionId?: string;
13
+ completionOwnerId?: string;
14
+ candidate?: Partial<Pick<ProcessTerminalCandidate, "sessionFile" | "revivalLeaseToken">>;
15
+ }
16
+
17
+ /** Persist a runner failure that occurred before any child writer could start. */
18
+ export function persistRunnerStartupFailure(input: RunnerStartupFailureInput): void {
19
+ const now = Date.now();
20
+ const statusPath = path.join(input.asyncDir, "status.json");
21
+ let status: Partial<AsyncStatus> = {};
22
+ try {
23
+ status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Partial<AsyncStatus>;
24
+ } catch (error) {
25
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
26
+ }
27
+ const existingProcessTerminal = status.processTerminal?.state === "observed" || status.processTerminal?.state === "unknown"
28
+ ? status.processTerminal : undefined;
29
+ writePrivateAtomicJson(statusPath, {
30
+ ...status,
31
+ runId: input.runId,
32
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
33
+ ...(input.completionOwnerId ? { completionOwnerId: input.completionOwnerId } : {}),
34
+ state: "failed",
35
+ lastUpdate: now,
36
+ error: input.message,
37
+ processTerminal: existingProcessTerminal ?? {
38
+ version: 1,
39
+ state: "not-started",
40
+ runId: input.runId,
41
+ runnerProcessInstanceId: input.runnerProcessInstanceId,
42
+ },
43
+ });
44
+ const existingCandidate = readProcessTerminalCandidate(input.asyncDir);
45
+ const stepCount = Math.max(1, status.steps?.length ?? 0);
46
+ writePrivateAtomicJson(path.join(input.asyncDir, "process-terminal-candidate.json"), {
47
+ ...existingCandidate,
48
+ version: 1,
49
+ runId: input.runId,
50
+ runnerProcessInstanceId: input.runnerProcessInstanceId,
51
+ writers: {},
52
+ expectedWriters: Object.fromEntries(Array.from({ length: stepCount }, (_, index) => [String(index), 0])),
53
+ ...(input.candidate?.sessionFile ? { sessionFile: input.candidate.sessionFile } : {}),
54
+ ...(input.candidate?.revivalLeaseToken ? { revivalLeaseToken: input.candidate.revivalLeaseToken } : {}),
55
+ });
56
+ }