@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -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) {
@@ -408,7 +414,10 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
408
414
  const event = raw as ChildSessionEvent & ChildEvent;
409
415
  appendChildEvent(projectChildSessionEventForJson(raw) as Record<string, unknown>);
410
416
  input.transcriptWriter?.writeChildEvent(projectChildSessionEventForJson(raw) as ChildEvent);
411
- if (event.type === "compaction_start") compactionStartedReceived = true;
417
+ if (event.type === "compaction_start") {
418
+ compactionStartedReceived = true;
419
+ if (agentSettledReceived) afterCompactionSettlement = true;
420
+ }
412
421
  if (event.type === "compaction_end" && event.willRetry === true) {
413
422
  compactionStartedReceived = false;
414
423
  afterCompactionSettlement = false;
@@ -563,6 +572,9 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
563
572
  if (settled) return;
564
573
  settled = true;
565
574
  failUnconsumedSteers();
575
+ const terminalUsage = session && messageBaseline !== undefined
576
+ ? reconcileAttemptUsage(usage, session.messages, messageBaseline)
577
+ : usage;
566
578
  const closed = finish();
567
579
  const finalOutput = getFinalOutput(messages);
568
580
  let finalError = error ?? assistantError;
@@ -578,7 +590,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
578
590
  && finalError === promptErrorMessage
579
591
  && isChildModelResolutionFailure(promptErrorMessage)
580
592
  && messages.length === 0
581
- && usage.turns === 0
593
+ && terminalUsage.turns === 0
582
594
  && !input.launch.session.ambientExtensions) {
583
595
  finalError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: input.launch.config.agent, model: input.launch.session.model, host: "runner", capabilityCeiling: input.launch.toolPlan.capabilityCeiling })}`;
584
596
  }
@@ -596,7 +608,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
596
608
  const result: RunChildSessionResult = omitUndefined({
597
609
  exitCode,
598
610
  messages,
599
- usage,
611
+ usage: terminalUsage,
600
612
  toolCount,
601
613
  durationMs: Date.now() - startedAt,
602
614
  model,
@@ -641,10 +653,11 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
641
653
  const createInput = createReportedChildSessionInput(input.launch, input.transcriptWriter);
642
654
  const created = await input.factory.create(createInput);
643
655
  if (settled) {
644
- void created.dispose();
656
+ await created.dispose().catch(() => undefined);
645
657
  return;
646
658
  }
647
659
  session = created;
660
+ if (created.contextWindow !== undefined) input.onContextWindow?.(created.contextWindow);
648
661
  const steer = created.steer.bind(created);
649
662
  const followUp = created.followUp.bind(created);
650
663
  created.steer = async (text) => {
@@ -678,6 +691,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
678
691
  return queued;
679
692
  });
680
693
  if (interrupted || timedOut || stopped) abortChild();
694
+ messageBaseline = created.messages.length;
681
695
  await created.prompt(input.prompt);
682
696
  promptSettled = true;
683
697
  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";
@@ -33,6 +34,7 @@ import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
33
34
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
34
35
  import { validHostStepNodes } from "../shared/host-step-status.ts";
35
36
  import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.ts";
37
+ import { formatWorkflowKeyRevival, projectWorkflowKeyRevival } from "../../workflows/workflow-revival.ts";
36
38
 
37
39
  interface RunStatusParams {
38
40
  action?: string;
@@ -570,6 +572,12 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
570
572
 
571
573
  const workflowReturnPreview = status.workflow?.value !== undefined ? formatWorkflowJsonPreview(status.workflow.value, 240) : undefined;
572
574
  const workflowEmitPreview = status.workflow?.emits.length ? formatWorkflowJsonPreview(status.workflow.emits.at(-1), 240) : undefined;
575
+ const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
576
+ if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
577
+ const workflowTerminalProof = workflowChildren
578
+ ? readWorkflowTerminalProof(asyncDir, status.steps, workflowChildren, validHostStepNodes(status.workflowGraph).length, status.endedAt ?? status.lastUpdate ?? status.startedAt)
579
+ : undefined;
580
+ const workflowChildrenByKey = new Map(workflowChildren?.children.map((child) => [child.childId, child]));
573
581
  const lines = [
574
582
  `Run: ${status.runId}`,
575
583
  status.toolCallId ? `Tool call: ${status.toolCallId}` : undefined,
@@ -588,6 +596,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
588
596
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
589
597
  status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
590
598
  status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
599
+ status.mode === "workflow" && (workflowReturnPreview?.endsWith("…") || workflowEmitPreview?.endsWith("…")) ? `Full return value and emits: ${path.join(asyncDir, "status.json")} (workflow.value, workflow.emits)` : undefined,
591
600
  `Progress: ${progressLabel}`,
592
601
  ...(status.mode === "workflow" ? formatWorkflowChecklistText(projectWorkflowChecklist({
593
602
  graph: status.workflowGraph,
@@ -615,7 +624,8 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
615
624
  let hasExternalJobFollowUpHint = false;
616
625
  for (const [index, step] of (status.steps ?? []).entries()) {
617
626
  const stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
618
- const modelThinking = formatModelThinking(step.model, step.thinking);
627
+ const workflowChild = step.workflowKey ? workflowChildrenByKey.get(step.workflowKey) : undefined;
628
+ const modelThinking = formatModelThinking(step.model ?? workflowChild?.model, step.thinking ?? workflowChild?.thinking);
619
629
  const modelText = modelThinking ? ` (${modelThinking})` : "";
620
630
  const steeringText = formatSteeringSummary(step);
621
631
  const steeringSuffix = steeringText ? `, steering: ${steeringText}` : "";
@@ -626,6 +636,10 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
626
636
  const phase = step.phase ? `[${step.phase}] ` : "";
627
637
  lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
628
638
  if (status.mode === "workflow" && step.runId) lines.push(` Child run: ${step.runId}`);
639
+ if (status.mode === "workflow" && step.runId && step.workflowKey && step.status === "failed") {
640
+ const revival = projectWorkflowKeyRevival(asyncDirRoot, status.runId, step.workflowKey, step.runId);
641
+ if (revival) lines.push(` ${formatWorkflowKeyRevival(revival)}`);
642
+ }
629
643
  const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
630
644
  if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
631
645
  if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
@@ -705,9 +719,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
705
719
  if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
706
720
  if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
707
721
 
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 } } : {}) } };
722
+ 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
723
  }
712
724
  }
713
725
 
@@ -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");
@@ -122,6 +131,26 @@ function findPeerPackageDir(piPackageRoot: string, pkg: string, hostName: unknow
122
131
  return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
123
132
  }
124
133
 
134
+ /** Whether the package's `exports` map (or `main`) declares `subpath`, even if the target file is missing. */
135
+ function exportsDeclareSubpath(packageDir: string, subpath: string): boolean {
136
+ const manifest = readManifest(packageDir);
137
+ if (!manifest) return false;
138
+ const exportsField = manifest.exports;
139
+ if (exportsField === undefined || exportsField === null) return subpath === ".";
140
+ const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
141
+ ? { ".": exportsField }
142
+ : exportsField as Record<string, unknown>;
143
+ if (subpath in map) return true;
144
+ for (const pattern of Object.keys(map)) {
145
+ const star = pattern.indexOf("*");
146
+ if (star === -1) continue;
147
+ const prefix = pattern.slice(0, star);
148
+ const suffix = pattern.slice(star + 1);
149
+ if (subpath.startsWith(prefix) && subpath.endsWith(suffix) && subpath.length >= prefix.length + suffix.length) return true;
150
+ }
151
+ return false;
152
+ }
153
+
125
154
  /** The alias map the runner needs, or the specifiers that could not be resolved. */
126
155
  export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
127
156
  const aliases: Record<string, string> = {};
@@ -135,8 +164,17 @@ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record
135
164
  for (const { specifier, pkg, subpath } of required) {
136
165
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
137
166
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
138
- if (target && fs.existsSync(target)) aliases[specifier] = target;
139
- else missing.push(specifier);
167
+ // Native loaders short-circuit resolution, so aliases must retain the real package's dependency scope.
168
+ if (target && fs.existsSync(target)) {
169
+ aliases[specifier] = fs.realpathSync(target);
170
+ continue;
171
+ }
172
+ // Host API drift: the installed peer no longer exports the subpath at all
173
+ // (pi 1.0.0's pi-agent-core dropped ./node), so the runner cannot import
174
+ // it on this host either — the alias is best-effort. A subpath that is
175
+ // declared but missing on disk stays a broken install.
176
+ if (packageDir && subpath !== "." && !exportsDeclareSubpath(packageDir, subpath)) continue;
177
+ missing.push(specifier);
140
178
  }
141
179
  return { aliases, missing };
142
180
  }
@@ -18,7 +18,7 @@ export interface RunnerChildLaunchContext {
18
18
  runFanoutBudget?: BuildInProcessChildLaunchInput["runFanoutBudget"];
19
19
  capabilityCeiling?: BuildInProcessChildLaunchInput["capabilityCeiling"];
20
20
  inheritedChildRuntime?: InheritedChildRuntime;
21
- hostAvailableBuiltins?: readonly string[];
21
+ projectTrusted?: boolean;
22
22
  }
23
23
 
24
24
  export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChildLaunchContext, attempt: {
@@ -51,6 +51,7 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
51
51
  tools: step.tools,
52
52
  excludeTools: step.excludeTools,
53
53
  allowNestedSubagents: step.allowNestedSubagents,
54
+ descendantAllowedAgents: step.allowedAgents,
54
55
  extensions: step.extensions,
55
56
  subagentOnlyExtensions: step.subagentOnlyExtensions,
56
57
  requiredExtensions: step.requiredExtensions,
@@ -58,10 +59,12 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
58
59
  systemPrompt: acceptancePrompt ? `${step.systemPrompt ?? ""}\n${acceptancePrompt}` : step.systemPrompt ?? "",
59
60
  systemPromptMode: step.systemPromptMode,
60
61
  mcpDirectTools: step.mcpDirectTools,
62
+ builtinMcpTools: step.builtinMcpTools,
61
63
  extensionBindings: normalizeExtensionBindings(step.extensionBindings)?.value,
62
64
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
63
65
  cwd: step.cwd ?? ctx.cwd,
64
66
  intercomSessionName: ctx.childIntercomTarget,
67
+ projectTrusted: ctx.projectTrusted,
65
68
  sessionName: attempt.sessionName,
66
69
  orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
67
70
  runId: ctx.id,
@@ -87,7 +90,6 @@ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChil
87
90
  thinkingCeiling: step.thinkingCeiling,
88
91
  maxSubagentDepth: step.maxSubagentDepth,
89
92
  inherited: ctx.inheritedChildRuntime,
90
- hostAvailableBuiltins: ctx.hostAvailableBuiltins,
91
93
  host: "runner",
92
94
  });
93
95
  }
@@ -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
+ }