@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -4,10 +4,10 @@ import { writeAtomicJson, writePrivateAtomicJson } from "../../shared/atomic-jso
4
4
  import {
5
5
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
6
6
  type AsyncStatus,
7
- type CanonicalSessionTerminalV1,
8
- type ProcessInstanceExitV1,
7
+ type CanonicalSessionTerminal,
8
+ type ProcessInstanceExit,
9
9
  type ProcessTerminalReason,
10
- type ProcessTerminalV1,
10
+ type ProcessTerminal,
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";
@@ -16,7 +16,7 @@ export interface ProcessTerminalCandidate {
16
16
  version: 1;
17
17
  runId: string;
18
18
  runnerProcessInstanceId: string;
19
- writers: Record<string, ProcessInstanceExitV1[]>;
19
+ writers: Record<string, ProcessInstanceExit[]>;
20
20
  expectedWriters?: Record<string, number>;
21
21
  sessionFile?: string;
22
22
  revivalLeaseToken?: string;
@@ -34,7 +34,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
34
34
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
35
35
  }
36
36
 
37
- function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExitV1 {
37
+ function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExit {
38
38
  if (!isRecord(value)) return false;
39
39
  if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
40
40
  if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
@@ -56,7 +56,7 @@ function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): va
56
56
  && (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
57
57
  }
58
58
 
59
- function validInstance(value: unknown): value is ProcessInstanceExitV1 {
59
+ function validInstance(value: unknown): value is ProcessInstanceExit {
60
60
  return validProcessInstance(value, "pi-writer");
61
61
  }
62
62
 
@@ -78,7 +78,7 @@ export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalC
78
78
  if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
79
79
  throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
80
80
  }
81
- const writers: Record<string, ProcessInstanceExitV1[]> = {};
81
+ const writers: Record<string, ProcessInstanceExit[]> = {};
82
82
  for (const [index, entries] of Object.entries(raw.writers)) {
83
83
  if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
84
84
  writers[index] = entries;
@@ -137,7 +137,7 @@ export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token
137
137
  writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
138
138
  }
139
139
 
140
- function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string): ProcessTerminalV1 {
140
+ function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string): ProcessTerminal {
141
141
  return { version: 1, state: "unknown", runId, runnerProcessInstanceId, reason, ...(diagnostic ? { diagnostic } : {}) };
142
142
  }
143
143
 
@@ -147,7 +147,7 @@ function resumeDisposition(state: string | undefined, sessionFile: string | unde
147
147
  return sessionFile && fs.existsSync(sessionFile) ? "resumable" : "unavailable";
148
148
  }
149
149
 
150
- function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnType<typeof inspectSessionLease>): CanonicalSessionTerminalV1 | undefined {
150
+ function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnType<typeof inspectSessionLease>): CanonicalSessionTerminal | undefined {
151
151
  if (!candidate.sessionFile || lease.state !== "free") return undefined;
152
152
  if (candidate.revivalLeaseToken && candidate.revivalLeaseReleaseAcknowledged !== true) return undefined;
153
153
  return {
@@ -158,7 +158,7 @@ function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnTyp
158
158
  };
159
159
  }
160
160
 
161
- function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): raw is ProcessTerminalV1 {
161
+ function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): raw is ProcessTerminal {
162
162
  if (!isRecord(raw) || raw.version !== 1 || !["pending", "observed", "unknown", "not-started"].includes(String(raw.state)) || typeof raw.runId !== "string" || !raw.runId || typeof raw.runnerProcessInstanceId !== "string" || !raw.runnerProcessInstanceId) {
163
163
  throw new Error(`Invalid process-terminal proof in '${asyncDir}'.`);
164
164
  }
@@ -177,21 +177,21 @@ function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: stri
177
177
  return true;
178
178
  }
179
179
 
180
- export function sanitizeProcessTerminal(value: unknown, fallback: { runId?: string; runnerProcessInstanceId?: string }, label = "status"): ProcessTerminalV1 | undefined {
180
+ export function sanitizeProcessTerminal(value: unknown, fallback: { runId?: string; runnerProcessInstanceId?: string }, label = "status"): ProcessTerminal | undefined {
181
181
  if (value === undefined) return undefined;
182
182
  try {
183
183
  validateProof(value, label, fallback);
184
- return value as ProcessTerminalV1;
184
+ return value as ProcessTerminal;
185
185
  } catch (error) {
186
186
  return unknownProof(fallback.runId ?? label, fallback.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
187
187
  }
188
188
  }
189
189
 
190
- export function readProcessTerminal(asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): ProcessTerminalV1 | undefined {
190
+ export function readProcessTerminal(asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): ProcessTerminal | undefined {
191
191
  try {
192
192
  const raw = JSON.parse(fs.readFileSync(processTerminalPath(asyncDir), "utf-8")) as unknown;
193
193
  validateProof(raw, asyncDir, fallback);
194
- return raw as ProcessTerminalV1;
194
+ return raw as ProcessTerminal;
195
195
  } catch (error) {
196
196
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
197
197
  return unknownProof(fallback?.runId ?? path.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
@@ -199,12 +199,12 @@ export function readProcessTerminal(asyncDir: string, fallback?: { runId?: strin
199
199
  }
200
200
 
201
201
  function stepProcessTerminalProof(
202
- proof: ProcessTerminalV1,
202
+ proof: ProcessTerminal,
203
203
  childIndex: number,
204
- state: ProcessTerminalV1["state"],
205
- records: ProcessInstanceExitV1[],
206
- resumeDispositionValue: ProcessTerminalV1["resumeDisposition"],
207
- ): ProcessTerminalV1 {
204
+ state: ProcessTerminal["state"],
205
+ records: ProcessInstanceExit[],
206
+ resumeDispositionValue: ProcessTerminal["resumeDisposition"],
207
+ ): ProcessTerminal {
208
208
  const base = {
209
209
  version: 1 as const,
210
210
  runId: proof.runId,
@@ -221,7 +221,7 @@ function stepProcessTerminalProof(
221
221
  return { ...base, state };
222
222
  }
223
223
 
224
- function overlayStatus(asyncDir: string, proof: ProcessTerminalV1, candidate?: ProcessTerminalCandidate): void {
224
+ function overlayStatus(asyncDir: string, proof: ProcessTerminal, candidate?: ProcessTerminalCandidate): void {
225
225
  const statusPath = path.join(asyncDir, "status.json");
226
226
  try {
227
227
  const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as AsyncStatus;
@@ -244,13 +244,13 @@ export function finalizeProcessTerminal(
244
244
  asyncDir: string,
245
245
  runId: string,
246
246
  runnerClose: RunnerCloseObservation,
247
- ): ProcessTerminalV1 {
247
+ ): ProcessTerminal {
248
248
  const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
249
249
  if (existing && fs.existsSync(processTerminalPath(asyncDir))) {
250
250
  if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
251
251
  if (existing.state === "unknown") return existing;
252
252
  }
253
- let proof: ProcessTerminalV1;
253
+ let proof: ProcessTerminal;
254
254
  let candidateForOverlay: ProcessTerminalCandidate | undefined;
255
255
  try {
256
256
  const candidate = readProcessTerminalCandidate(asyncDir);
@@ -279,7 +279,7 @@ export function finalizeProcessTerminal(
279
279
  } else if (allWriters.some((writer) => writer.kind === "pi-writer" && writer.processTree.state !== "observed")) {
280
280
  proof = unknownProof(runId, runnerClose.processInstanceId, "process-tree-unverified");
281
281
  } else {
282
- const runner: ProcessInstanceExitV1 = { kind: "runner", ...runnerClose };
282
+ const runner: ProcessInstanceExit = { kind: "runner", ...runnerClose };
283
283
  const canonicalSession = session && sessionProjection(candidate, session);
284
284
  proof = {
285
285
  version: 1,
@@ -241,10 +241,15 @@ function pendingResultExists(resultsDir: string, sessionId: string, runId: strin
241
241
  return firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId)) !== undefined;
242
242
  }
243
243
 
244
+ export function resultPayloadMatchesSessionRun(data: unknown, sessionId: string, runId: string): boolean {
245
+ if (!data || typeof data !== "object" || Array.isArray(data)) return false;
246
+ const record = data as Record<string, unknown>;
247
+ return (nonEmptyString(record.runId) ?? nonEmptyString(record.id)) === runId && nonEmptyString(record.sessionId) === sessionId;
248
+ }
249
+
244
250
  function pendingResultPayloadMatches(filePath: string, sessionId: string, runId: string): boolean {
245
251
  try {
246
- const data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
247
- return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
252
+ return resultPayloadMatchesSessionRun(JSON.parse(fs.readFileSync(filePath, "utf-8")), sessionId, runId);
248
253
  } catch (error) {
249
254
  if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
250
255
  return false;
@@ -252,8 +257,7 @@ function pendingResultPayloadMatches(filePath: string, sessionId: string, runId:
252
257
  }
253
258
 
254
259
  function assertPendingResultPayloadMatches(filePath: string, sessionId: string, runId: string): boolean {
255
- const data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
256
- return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
260
+ return resultPayloadMatchesSessionRun(JSON.parse(fs.readFileSync(filePath, "utf-8")), sessionId, runId);
257
261
  }
258
262
 
259
263
  export function promotePendingResultFile(resultsDir: string, sessionId: string, runId: string, file = resultFileName(runId), options: { logFailure?: boolean } = {}): "none" | "promoted" | "pending" {
@@ -70,6 +70,7 @@ type ResultFileChild = {
70
70
  sessionName?: string;
71
71
  output?: string;
72
72
  structuredOutput?: unknown;
73
+ structuredOutputPath?: string;
73
74
  outputState?: SubagentOutputState;
74
75
  error?: string;
75
76
  success?: boolean;
@@ -81,6 +82,8 @@ type ResultFileChild = {
81
82
  processSignal?: string | null;
82
83
  sessionFile?: string;
83
84
  artifactPaths?: { outputPath?: string };
85
+ outputSaveError?: string;
86
+ artifactOutputSaveFailed?: true;
84
87
  intercomTarget?: string;
85
88
  children?: unknown;
86
89
  };
@@ -408,7 +411,9 @@ export function createResultWatcher(
408
411
  if (typeof data.sessionId !== "string" || !data.sessionId) return;
409
412
  const sessionId = data.sessionId;
410
413
  const completionOwnerId = data.completionOwnerId;
411
- const runId = data.runId ?? data.id ?? file.replace(/\.json$/i, "");
414
+ const runId = typeof data.runId === "string" && data.runId
415
+ ? data.runId
416
+ : typeof data.id === "string" && data.id ? data.id : file.replace(/\.json$/i, "");
412
417
  const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : undefined;
413
418
  let observerSucceeded = true;
414
419
  try {
@@ -428,7 +433,7 @@ export function createResultWatcher(
428
433
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
429
434
  // Recorded before dedupe and before the unlink below so bg_wait can
430
435
  // use the in-memory record or its bounded durable replay after cleanup.
431
- recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
436
+ const completionPersisted = recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
432
437
  resultsDir,
433
438
  sessionId,
434
439
  });
@@ -456,6 +461,10 @@ export function createResultWatcher(
456
461
  }
457
462
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
458
463
  if (markReplacedPayload()) return;
464
+ if (!completionPersisted) {
465
+ scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
466
+ return;
467
+ }
459
468
  if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
460
469
  return;
461
470
  }
@@ -513,6 +522,10 @@ export function createResultWatcher(
513
522
  }
514
523
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
515
524
  if (markReplacedPayload()) return;
525
+ if (!completionPersisted) {
526
+ scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
527
+ return;
528
+ }
516
529
  if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
517
530
  return;
518
531
  }
@@ -600,6 +613,10 @@ export function createResultWatcher(
600
613
  return;
601
614
  }
602
615
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
616
+ if (!completionPersisted) {
617
+ scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
618
+ return;
619
+ }
603
620
  if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
604
621
  } catch (error) {
605
622
  if (isAccessDenied(error)) {
@@ -0,0 +1,96 @@
1
+ import * as fs from "node:fs";
2
+ import type { SubagentState } from "../../shared/types.ts";
3
+ import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
4
+ import { hasLiveNestedDescendants, projectNestedEvents } from "../shared/nested-events.ts";
5
+
6
+ interface RetainedNestedRouteTrackerOptions {
7
+ pollIntervalMs?: number;
8
+ platform?: NodeJS.Platform;
9
+ watch?: typeof fs.watch;
10
+ }
11
+
12
+ const DEFAULT_POLL_INTERVAL_MS = 5000;
13
+ const REFRESH_DEBOUNCE_MS = 25;
14
+
15
+ export function createRetainedNestedRouteTracker(
16
+ state: Pick<SubagentState, "retainedForegroundNestedRoutes">,
17
+ options: RetainedNestedRouteTrackerOptions = {},
18
+ ): { track: (rootRunId: string) => void; clear: () => void } {
19
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
20
+ const watch = options.watch ?? fs.watch;
21
+ const watchers = new Map<string, fs.FSWatcher>();
22
+ const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
23
+ let poller: ReturnType<typeof setInterval> | undefined;
24
+
25
+ const close = (rootRunId: string): void => {
26
+ watchers.get(rootRunId)?.close();
27
+ watchers.delete(rootRunId);
28
+ const timer = refreshTimers.get(rootRunId);
29
+ if (timer) clearTimeout(timer);
30
+ refreshTimers.delete(rootRunId);
31
+ };
32
+
33
+ const refresh = (rootRunId: string): void => {
34
+ const retained = state.retainedForegroundNestedRoutes?.get(rootRunId);
35
+ if (!retained) {
36
+ close(rootRunId);
37
+ return;
38
+ }
39
+ try {
40
+ if (hasLiveNestedDescendants(projectNestedEvents(retained).children)) return;
41
+ state.retainedForegroundNestedRoutes?.delete(rootRunId);
42
+ close(rootRunId);
43
+ } catch (error) {
44
+ console.error(`Failed to refresh retained nested descendants for foreground run '${rootRunId}':`, error);
45
+ }
46
+ };
47
+
48
+ const scheduleRefresh = (rootRunId: string): void => {
49
+ if (refreshTimers.has(rootRunId)) return;
50
+ const timer = setTimeout(() => {
51
+ refreshTimers.delete(rootRunId);
52
+ refresh(rootRunId);
53
+ }, REFRESH_DEBOUNCE_MS);
54
+ timer.unref?.();
55
+ refreshTimers.set(rootRunId, timer);
56
+ };
57
+
58
+ const ensurePoller = (): void => {
59
+ if (poller || (state.retainedForegroundNestedRoutes?.size ?? 0) === 0) return;
60
+ poller = setInterval(() => {
61
+ for (const rootRunId of state.retainedForegroundNestedRoutes?.keys() ?? []) refresh(rootRunId);
62
+ if ((state.retainedForegroundNestedRoutes?.size ?? 0) > 0) return;
63
+ if (poller) clearInterval(poller);
64
+ poller = undefined;
65
+ }, pollIntervalMs);
66
+ poller.unref?.();
67
+ };
68
+
69
+ const track = (rootRunId: string): void => {
70
+ const retained = state.retainedForegroundNestedRoutes?.get(rootRunId);
71
+ if (!retained) return;
72
+ if (shouldUseNativeFsWatch("retained-nested-route-tracker", options.platform) && !watchers.has(rootRunId)) {
73
+ try {
74
+ const watcher = watch(retained.eventSink, () => scheduleRefresh(rootRunId));
75
+ watcher.on("error", () => close(rootRunId));
76
+ watcher.unref?.();
77
+ watchers.set(rootRunId, watcher);
78
+ } catch {
79
+ // The bounded safety poll below covers unsupported or failed watchers.
80
+ }
81
+ }
82
+ scheduleRefresh(rootRunId);
83
+ ensurePoller();
84
+ };
85
+
86
+ const clear = (): void => {
87
+ if (poller) clearInterval(poller);
88
+ poller = undefined;
89
+ for (const rootRunId of watchers.keys()) close(rootRunId);
90
+ for (const timer of refreshTimers.values()) clearTimeout(timer);
91
+ refreshTimers.clear();
92
+ state.retainedForegroundNestedRoutes?.clear();
93
+ };
94
+
95
+ return { track, clear };
96
+ }
@@ -8,7 +8,7 @@
8
8
  import type { Message } from "@earendil-works/pi-ai";
9
9
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
10
10
  import { extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse } from "../../shared/utils.ts";
11
- import type { EffectsProjection, RuntimeAcknowledgedChildExtensionsV1, SubagentOutputState, ToolBudgetState, Usage } from "../../shared/types.ts";
11
+ import type { EffectsProjection, RuntimeAcknowledgedChildExtensions, SubagentOutputState, ToolBudgetState, Usage } from "../../shared/types.ts";
12
12
  import {
13
13
  acceptChildWatchdogEvent,
14
14
  applyChildWatchdogMessage,
@@ -19,13 +19,15 @@ import {
19
19
  type ChildWatchdogStatusEvent,
20
20
  } from "../../watchdog/child-status.ts";
21
21
  import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
22
- import { formatSubagentModelVerificationError } from "../shared/model-fallback.ts";
22
+ import { formatSubagentModelVerificationError } from "../shared/model-resolution.ts";
23
+ import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
23
24
  import { isMutatingTool, resolveCurrentPath } from "../shared/long-running-guard.ts";
24
25
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
25
- import type { InProcessChildLaunch } from "../shared/child-launch.ts";
26
- import { projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
26
+ import { createReportedChildSessionInput, type InProcessChildLaunch } from "../shared/child-launch.ts";
27
+ import { childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
27
28
  import { formatSteerMessage } from "../shared/subagent-prompt-runtime.ts";
28
29
  import type { SteerDeliveryStatus, SteerRequest } from "./control-channel.ts";
30
+ import { takeMatchingAcceptedSteer, unconsumedSteerReason } from "./steering.ts";
29
31
 
30
32
  export interface ChildEventContext {
31
33
  runId: string;
@@ -83,6 +85,8 @@ export interface RunChildSessionInput {
83
85
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
84
86
  registerStop?: (stop: (() => void) | undefined) => void;
85
87
  registerSteer?: (steer: StepSteerHandler | undefined) => void;
88
+ /** Consumption (or unconsumed settlement) after the child accepted a steer or follow-up. */
89
+ onSteerOutcome?: (request: SteerRequest, delivery: SteerDelivery) => void;
86
90
  /** Receives the sink the child's watchdog hook reports status through; the launch's `watchdogStatus` must forward to it. */
87
91
  registerWatchdogStatus?: (sink: ((event: ChildWatchdogStatusEvent) => void) | undefined) => void;
88
92
  timeoutMessage?: string;
@@ -93,6 +97,7 @@ export interface RunChildSessionInput {
93
97
  runDeadlineAt?: number;
94
98
  expectedModelForVerification?: string;
95
99
  modelVerificationRegistry?: Array<{ provider: string; id: string; fullId: string }>;
100
+ modelResponseAliases?: Record<string, string[]>;
96
101
  mutationTools?: readonly string[];
97
102
  }
98
103
 
@@ -103,6 +108,7 @@ export interface RunChildSessionResult {
103
108
  toolCount: number;
104
109
  durationMs: number;
105
110
  model?: string;
111
+ nativeMachine?: { provider: "herdr"; machineId: string; initialGit?: import("../../shared/types.ts").HerdrRemoteGitStatus; finalGit?: import("../../shared/types.ts").HerdrRemoteGitStatus };
106
112
  error?: string;
107
113
  finalOutput: string;
108
114
  outputState: SubagentOutputState;
@@ -118,12 +124,12 @@ export interface RunChildSessionResult {
118
124
  currentToolArgs?: string;
119
125
  currentPath?: string;
120
126
  afterCompactionSettlement?: boolean;
127
+ abortRecoveryDiagnostic?: string;
121
128
  /** Set by the runner while it finalizes the attempt. */
122
129
  toolBudget?: ToolBudgetState;
123
130
  toolBudgetBlocked?: boolean;
124
131
  structuredOutput?: unknown;
125
- runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
126
- abortRecoveryDiagnostic?: string;
132
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
127
133
  effects?: EffectsProjection;
128
134
  }
129
135
 
@@ -175,12 +181,14 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
175
181
  let currentPath: string | undefined;
176
182
  let toolCount = 0;
177
183
  let session: ChildSession | undefined;
184
+ const acceptedSteers: Array<{ request: SteerRequest; text: string }> = [];
178
185
  let unsubscribe: (() => void) | undefined;
179
186
  let settled = false;
180
187
  let promptSettled = false;
181
188
  let forcedTermination = false;
182
189
  let cleanTerminalAssistantStopReceived = false;
183
190
  let agentSettledReceived = false;
191
+ let queuedDrainHold = false;
184
192
  let compactionStartedReceived = false;
185
193
  let afterCompactionSettlement = false;
186
194
  let finalDrainTimer: NodeJS.Timeout | undefined;
@@ -299,14 +307,28 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
299
307
  }
300
308
  // If the child emits its terminal event but its run never settles (a hook
301
309
  // is stuck), abort it after a short grace period and then finish without it.
310
+ const observeQueuedDrainHold = (): boolean => {
311
+ if (childSessionHasQueuedMessages(session)) queuedDrainHold = true;
312
+ return queuedDrainHold;
313
+ };
302
314
  function startFinalDrain(): void {
303
315
  if (childWatchdogIsActive(childWatchdogState)) {
304
316
  armWatchdogTail();
305
317
  return;
306
318
  }
319
+ if (promptSettled || finalDrainTimer || settled) return;
320
+ if (observeQueuedDrainHold()) return;
321
+ armFinalDrainTimer();
322
+ }
323
+ function armFinalDrainTimer(): void {
307
324
  if (promptSettled || finalDrainTimer || settled) return;
308
325
  finalDrainTimer = setTimeout(() => {
309
326
  if (settled || promptSettled) return;
327
+ if (input.launch.capture.finalDrainHeld() || observeQueuedDrainHold()) {
328
+ finalDrainTimer = undefined;
329
+ armFinalDrainTimer();
330
+ return;
331
+ }
310
332
  forcedTermination = true;
311
333
  if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
312
334
  error = `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
@@ -322,6 +344,8 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
322
344
  }
323
345
  const applyChildLifecycle = (action: ChildLifecycleAction): void => {
324
346
  if (action === "cancel-drain") {
347
+ cleanTerminalAssistantStopReceived = false;
348
+ agentSettledReceived = false;
325
349
  clearFinalDrainTimers();
326
350
  clearWatchdogTailTimer();
327
351
  return;
@@ -389,6 +413,9 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
389
413
  compactionStartedReceived = false;
390
414
  afterCompactionSettlement = false;
391
415
  }
416
+ if (event.type === "turn_start" || event.type === "agent_start" || event.type === "auto_retry_start") {
417
+ queuedDrainHold = false;
418
+ }
392
419
  if (event.type === "agent_start" || event.type === "auto_retry_start") {
393
420
  compactionStartedReceived = false;
394
421
  afterCompactionSettlement = false;
@@ -458,6 +485,16 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
458
485
  messages.push(event.message);
459
486
  const text = extractTextFromContent(event.message.content);
460
487
  if (text) writeOutputText(text);
488
+ if (event.type === "message_end" && event.message.role === "user" && text) {
489
+ const matched = takeMatchingAcceptedSteer(acceptedSteers, text);
490
+ if (matched) {
491
+ input.onSteerOutcome?.(matched.request, {
492
+ state: "delivered",
493
+ deliveryStatus: "delivered",
494
+ message: "Child consumed the steering input.",
495
+ });
496
+ }
497
+ }
461
498
 
462
499
  if (input.childWatchdog && event.type === "message_end") {
463
500
  const next = applyChildWatchdogMessage(childWatchdogState, event.message);
@@ -468,11 +505,15 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
468
505
  if (event.message.model) {
469
506
  model = event.message.model;
470
507
  if (input.expectedModelForVerification && !hasToolCall) {
471
- const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry);
508
+ const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases);
472
509
  if (modelVerificationError && !error) error = modelVerificationError;
473
510
  }
474
511
  }
475
512
  if (event.message.errorMessage) assistantError = event.message.errorMessage;
513
+ else if (hasToolCall && event.message.stopReason === "toolUse") {
514
+ // A recovered request can finish via a terminating tool, without a text stop.
515
+ assistantError = undefined;
516
+ }
476
517
  const eventUsage = event.message.usage;
477
518
  if (eventUsage) {
478
519
  usage.turns++;
@@ -513,14 +554,33 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
513
554
  };
514
555
 
515
556
  /** The child run ended (or was forced to end); fold in the outcome once the child's shutdown work is done. */
557
+ const failUnconsumedSteers = (): void => {
558
+ for (const entry of acceptedSteers.splice(0)) {
559
+ input.onSteerOutcome?.(entry.request, { state: "failed", message: unconsumedSteerReason(entry.request.mode) });
560
+ }
561
+ };
516
562
  const settle = (promptError: unknown, forced = false): void => {
517
563
  if (settled) return;
518
564
  settled = true;
565
+ failUnconsumedSteers();
519
566
  const closed = finish();
520
567
  const finalOutput = getFinalOutput(messages);
521
568
  let finalError = error ?? assistantError;
522
- if (!finalError && promptError !== undefined) {
523
- finalError = promptError instanceof Error ? promptError.message : String(promptError);
569
+ const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
570
+ if (!finalError && promptErrorMessage !== undefined) {
571
+ finalError = promptErrorMessage;
572
+ }
573
+ // A child launched without the ambient extensions resolves a provider
574
+ // extension's model as "not found". Annotate only a creation/prompt failure
575
+ // that produced no turn; keep the core error and add the rule and the
576
+ // remedies that load the extension for this child.
577
+ if (promptErrorMessage !== undefined
578
+ && finalError === promptErrorMessage
579
+ && isChildModelResolutionFailure(promptErrorMessage)
580
+ && messages.length === 0
581
+ && usage.turns === 0
582
+ && !input.launch.session.ambientExtensions) {
583
+ finalError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: input.launch.config.agent, model: input.launch.session.model, host: "runner", capabilityCeiling: input.launch.toolPlan.capabilityCeiling })}`;
524
584
  }
525
585
  const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
526
586
  const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(messages);
@@ -532,29 +592,33 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
532
592
  : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal)
533
593
  ? 0
534
594
  : finalError || promptError !== undefined ? 1 : 0;
535
- void closed.then(() => resolve(omitUndefined({
536
- exitCode,
537
- messages,
538
- usage,
539
- toolCount,
540
- durationMs: Date.now() - startedAt,
541
- model,
542
- error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
543
- finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
544
- outputState: finalOutput.trim() ? "present" : "absent",
545
- interrupted: interrupted || undefined,
546
- timedOut: timedOut || undefined,
547
- stopped: stopped || undefined,
548
- observedMutationAttempt,
549
- structuredOutputToolInvoked,
550
- structuredOutputMessageStartIndex,
551
- watchdog: childWatchdogState,
552
- sessionFile: session?.sessionFile,
553
- currentTool,
554
- currentToolArgs,
555
- currentPath,
556
- afterCompactionSettlement: afterCompactionSettlement || undefined,
557
- })));
595
+ void closed.then(() => {
596
+ const result: RunChildSessionResult = omitUndefined({
597
+ exitCode,
598
+ messages,
599
+ usage,
600
+ toolCount,
601
+ durationMs: Date.now() - startedAt,
602
+ model,
603
+ nativeMachine: session?.machineEvidence ? { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) } : undefined,
604
+ error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
605
+ finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
606
+ outputState: finalOutput.trim() ? "present" : "absent",
607
+ interrupted: interrupted || undefined,
608
+ timedOut: timedOut || undefined,
609
+ stopped: stopped || undefined,
610
+ observedMutationAttempt,
611
+ structuredOutputToolInvoked,
612
+ structuredOutputMessageStartIndex,
613
+ watchdog: childWatchdogState,
614
+ sessionFile: session?.sessionFile,
615
+ currentTool,
616
+ currentToolArgs,
617
+ currentPath,
618
+ afterCompactionSettlement: afterCompactionSettlement || undefined,
619
+ });
620
+ resolve(result);
621
+ });
558
622
  };
559
623
 
560
624
  input.registerInterrupt?.(() => {
@@ -574,31 +638,44 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
574
638
 
575
639
  void (async () => {
576
640
  try {
577
- const created = await input.factory.create({
578
- ...input.launch.session,
579
- onExtensionError: (extensionError) => {
580
- input.transcriptWriter?.writeStderrLine(`Extension error (${extensionError.extensionPath}, ${extensionError.event}): ${extensionError.error instanceof Error ? extensionError.error.message : String(extensionError.error)}`);
581
- },
582
- });
641
+ const createInput = createReportedChildSessionInput(input.launch, input.transcriptWriter);
642
+ const created = await input.factory.create(createInput);
583
643
  if (settled) {
584
644
  void created.dispose();
585
645
  return;
586
646
  }
587
647
  session = created;
648
+ const steer = created.steer.bind(created);
649
+ const followUp = created.followUp.bind(created);
650
+ created.steer = async (text) => {
651
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
652
+ return steer(text);
653
+ };
654
+ created.followUp = async (text) => {
655
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
656
+ return followUp(text);
657
+ };
588
658
  unsubscribe = created.subscribe(processEvent);
589
659
  input.registerWatchdogStatus?.((event) => processEvent(event as unknown as ChildSessionEvent));
590
660
  input.registerSteer?.(async (request) => {
591
661
  const text = formatSteerMessage(request);
592
662
  const followUp = request.mode === "follow_up";
663
+ const accepted = { request, text };
664
+ acceptedSteers.push(accepted);
665
+ const queued: SteerDelivery = {
666
+ state: "queued",
667
+ deliveryStatus: "queued",
668
+ message: followUp ? "Pi queued the follow-up input." : "Pi accepted the steering input.",
669
+ };
593
670
  try {
594
671
  if (followUp) await created.followUp(text);
595
672
  else await created.steer(text);
596
673
  } catch (steerError) {
674
+ const index = acceptedSteers.indexOf(accepted);
675
+ if (index >= 0) acceptedSteers.splice(index, 1);
597
676
  return { state: "failed", message: steerError instanceof Error ? steerError.message : String(steerError) };
598
677
  }
599
- return followUp
600
- ? { state: "queued", deliveryStatus: "queued", message: "Pi queued the follow-up input." }
601
- : { state: "delivered", deliveryStatus: "delivered", message: "Pi accepted the steering input." };
678
+ return queued;
602
679
  });
603
680
  if (interrupted || timedOut || stopped) abortChild();
604
681
  await created.prompt(input.prompt);