@xzzpig/pi-subagents 0.18.0 → 0.20.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 (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -1,4 +1,4 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
@@ -6,7 +6,10 @@ import { randomUUID } from "node:crypto";
6
6
  import { Worker } from "node:worker_threads";
7
7
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
8
8
  import type { AsyncStatus } from "../../shared/types.ts";
9
- import { MISSION_BINDING_FILE } from "../../missions/lifecycle.ts";
9
+ import { readMissionBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
10
+ import { MissionNotFoundError, readMission } from "../../missions/store.ts";
11
+ import type { MissionStatus } from "../../missions/types.ts";
12
+ import { REVIVAL_ORIGIN_FILE } from "../../workflows/workflow-revival.ts";
10
13
  import { ACTIVE_RUN_INDEX_DIR } from "./active-run-index.ts";
11
14
  import { encodeIndexSegment } from "./index-segment.ts";
12
15
  import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
@@ -26,6 +29,8 @@ const RUN_TOMBSTONE_MARKERS_DIR = "async-retention-run-tombstones";
26
29
  const LOCK_STALE_MS = 24 * 60 * 60 * 1000;
27
30
  const RUN_MODES = new Set<AsyncStatus["mode"]>(["single", "parallel", "chain", "workflow"]);
28
31
  const TERMINAL_STATES = new Set<AsyncStatus["state"]>(["complete", "failed", "stopped", "rejected"]);
32
+ // Mirrors TERMINAL_MISSION_STATUSES in src/missions/store.ts, which keeps it private.
33
+ const TERMINAL_MISSION_STATUSES = new Set<MissionStatus>(["completed", "failed", "cancelled"]);
29
34
  const RESULT_TIMESTAMP_FIELDS = ["endedAt", "completedAt", "createdAt", "writtenAt", "expiresAt", "timestamp"] as const;
30
35
 
31
36
  interface RetentionCursor {
@@ -93,7 +98,7 @@ export interface AsyncRetentionOptions {
93
98
  hostname?: string;
94
99
  processStartIdentity?: string;
95
100
  isProcessAlive?: (pid: number) => boolean | undefined;
96
- getProcessStartIdentity?: (pid: number) => string | undefined;
101
+ getProcessStartIdentity?: (pid: number) => Promise<string | undefined>;
97
102
  lstatSync?: typeof fs.lstatSync;
98
103
  signal?: AbortSignal;
99
104
  discoveryWorkerUrl?: URL;
@@ -212,6 +217,25 @@ function missionObserverIndexExists(resultsDir: string, runId: string): boolean
212
217
  return fs.existsSync(path.join(resultsDir, "result-index", "observers", "mission", `${encodeIndexSegment(runId)}.json`));
213
218
  }
214
219
 
220
+ // The retention window doubles as a terminal mission's grace period. Unreadable references and
221
+ // pending syncs are kept because the watcher needs the run's binding to retry.
222
+ function missionReferenceBlocksReclaim(runDir: string, resultsDir: string, runId: string): boolean {
223
+ if (missionObserverIndexExists(resultsDir, runId)) return true;
224
+ let binding: MissionLaunchBinding | undefined;
225
+ try {
226
+ binding = readMissionBinding(runDir);
227
+ } catch {
228
+ return true;
229
+ }
230
+ if (!binding) return false;
231
+ try {
232
+ const mission = readMission(binding.location, binding.missionId);
233
+ return !TERMINAL_MISSION_STATUSES.has(mission.status);
234
+ } catch (error) {
235
+ return !(error instanceof MissionNotFoundError);
236
+ }
237
+ }
238
+
215
239
  function runTombstoneMarkerPath(maintenanceRoot: string, runId: string): string {
216
240
  return path.join(maintenanceRoot, RUN_TOMBSTONE_MARKERS_DIR, `${encodeIndexSegment(runId)}.json`);
217
241
  }
@@ -296,8 +320,10 @@ function runSkipReason(input: {
296
320
  if (activeMarkerExists(input.asyncDirRoot, status.runId)) return "active-index";
297
321
  if (!TERMINAL_STATES.has(status.state)) return "non-terminal";
298
322
  if (status.mode === "workflow" || status.parentWorkflowRunId || status.workflowKey) return "workflow-reference";
323
+ // A revived workflow child is a link in its key's revival chain; deleting it would cut off later revivals.
324
+ if (fs.existsSync(path.join(runDir, REVIVAL_ORIGIN_FILE))) return "workflow-reference";
299
325
  if (hasNestedReferences(status)) return "nested-reference";
300
- if (fs.existsSync(path.join(runDir, MISSION_BINDING_FILE)) || missionObserverIndexExists(input.resultsDir, status.runId)) return "mission-reference";
326
+ if (missionReferenceBlocksReclaim(runDir, input.resultsDir, status.runId)) return "mission-reference";
301
327
  if (hasUnresolvedRunHandoff(runDir, status)) return "handoff-reference";
302
328
  if (hasResumableContract(runDir, status)) return "resumable";
303
329
  const timestamp = statusTimestamp(status, runDir);
@@ -324,16 +350,16 @@ function readCursor(root: string): RetentionCursor {
324
350
  return value?.version === 1 ? value as unknown as RetentionCursor : { version: 1 };
325
351
  }
326
352
 
327
- let currentProcessStartIdentity: string | undefined | null = null;
353
+ let currentProcessStartIdentity: Promise<string | undefined> | undefined;
328
354
 
329
- function processStartIdentity(pid: number): string | undefined {
355
+ function processStartIdentity(pid: number): Promise<string | undefined> {
330
356
  // Foreign PIDs can be reused while this process lives, so resolve them afresh.
331
357
  if (pid !== process.pid) return computeProcessStartIdentity(pid);
332
- if (currentProcessStartIdentity === null) currentProcessStartIdentity = computeProcessStartIdentity(pid);
358
+ currentProcessStartIdentity ??= computeProcessStartIdentity(pid);
333
359
  return currentProcessStartIdentity;
334
360
  }
335
361
 
336
- function computeProcessStartIdentity(pid: number): string | undefined {
362
+ async function computeProcessStartIdentity(pid: number): Promise<string | undefined> {
337
363
  if (process.platform === "linux") {
338
364
  try {
339
365
  const stat = fs.readFileSync(`/proc/${pid}/stat`).toString("utf8");
@@ -346,8 +372,12 @@ function computeProcessStartIdentity(pid: number): string | undefined {
346
372
  }
347
373
  }
348
374
  if (process.platform === "win32") {
349
- const result = spawnSync("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate`], { encoding: "utf-8", windowsHide: true });
350
- const started = result.status === 0 ? result.stdout.trim() : "";
375
+ // PowerShell takes ~0.5 s to start; a synchronous spawn would freeze the TUI.
376
+ const started = await new Promise<string>((resolve) => {
377
+ execFile("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate`], { encoding: "utf-8", windowsHide: true, timeout: 5_000 }, (error, stdout) => {
378
+ resolve(error ? "" : stdout.trim());
379
+ });
380
+ });
351
381
  return started ? `win:${started}` : undefined;
352
382
  }
353
383
  return undefined;
@@ -381,7 +411,7 @@ function parseLockOwner(lockDir: string): RetentionLockOwner | undefined {
381
411
  return owner as unknown as RetentionLockOwner;
382
412
  }
383
413
 
384
- function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): { stale: boolean; token?: string } {
414
+ async function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): Promise<{ stale: boolean; token?: string }> {
385
415
  const owner = parseLockOwner(lockDir);
386
416
  if (!owner) {
387
417
  try {
@@ -394,7 +424,7 @@ function staleLock(lockDir: string, now: number, options: Required<Pick<AsyncRet
394
424
  const alive = options.isProcessAlive(owner.pid);
395
425
  if (alive === false) return { stale: true, token: owner.token };
396
426
  if (alive === true && owner.processStartIdentity) {
397
- const currentIdentity = options.getProcessStartIdentity(owner.pid);
427
+ const currentIdentity = await options.getProcessStartIdentity(owner.pid);
398
428
  if (currentIdentity !== undefined && currentIdentity !== owner.processStartIdentity) return { stale: true, token: owner.token };
399
429
  }
400
430
  return { stale: now - owner.startedAt >= LOCK_STALE_MS, token: owner.token };
@@ -416,10 +446,10 @@ function createLockDirectory(lockDir: string, owner: RetentionLockOwner): boolea
416
446
  }
417
447
  }
418
448
 
419
- function acquireRetentionLock(lockDir: string, owner: RetentionLockOwner, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): boolean {
449
+ async function acquireRetentionLock(lockDir: string, owner: RetentionLockOwner, options: Required<Pick<AsyncRetentionOptions, "hostname" | "isProcessAlive" | "getProcessStartIdentity">>): Promise<boolean> {
420
450
  for (let attempt = 0; attempt < 4; attempt += 1) {
421
451
  if (createLockDirectory(lockDir, owner)) return true;
422
- const stale = staleLock(lockDir, owner.startedAt, options);
452
+ const stale = await staleLock(lockDir, owner.startedAt, options);
423
453
  if (!stale.stale) return false;
424
454
  const staleKey = (stale.token ?? owner.token).replace(/[^A-Za-z0-9._-]/g, "-");
425
455
  const tombstone = `${lockDir}.stale-${staleKey}`;
@@ -672,7 +702,7 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
672
702
  const pid = options.pid ?? process.pid;
673
703
  const hostname = options.hostname ?? os.hostname();
674
704
  const getProcessStartIdentity = options.getProcessStartIdentity ?? processStartIdentity;
675
- const currentProcessStartIdentity = options.processStartIdentity ?? getProcessStartIdentity(pid) ?? (pid === process.pid ? `runtime:${Math.round(Date.now() - process.uptime() * 1000)}` : undefined);
705
+ const currentProcessStartIdentity = options.processStartIdentity ?? await getProcessStartIdentity(pid) ?? (pid === process.pid ? `runtime:${Math.round(Date.now() - process.uptime() * 1000)}` : undefined);
676
706
  const lockOwner: RetentionLockOwner = { version: 1, token: lockToken, pid, hostname, startedAt: currentTime, ...(currentProcessStartIdentity ? { processStartIdentity: currentProcessStartIdentity } : {}) };
677
707
  const lockOptions = { hostname, isProcessAlive: options.isProcessAlive ?? processIsAlive, getProcessStartIdentity };
678
708
  const result: AsyncRetentionResult = {
@@ -709,7 +739,7 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
709
739
  return true;
710
740
  };
711
741
  fs.mkdirSync(maintenanceRoot, { recursive: true });
712
- if (!acquireRetentionLock(lockDir, lockOwner, lockOptions)) {
742
+ if (!await acquireRetentionLock(lockDir, lockOwner, lockOptions)) {
713
743
  increment(result.skipped, "lock-busy");
714
744
  return finish();
715
745
  }
@@ -0,0 +1,78 @@
1
+ import * as fs from "node:fs";
2
+ import { readStatus } from "../../shared/utils.ts";
3
+ import { workflowAwaitedAsyncResultPath } from "./async-execution.ts";
4
+ import { waitForImportedAsyncRoot, type ImportedAsyncRootResult } from "./chain-root-attachment.ts";
5
+ import { currentPidNamespaceScope } from "./pid-namespace.ts";
6
+ import { resultPayloadPathForSessionRun } from "./result-files.ts";
7
+ import { checkPidLiveness } from "./stale-run-reconciler.ts";
8
+
9
+ type ExistingAsyncRunOutcome =
10
+ | { status: "settled"; result: ImportedAsyncRootResult }
11
+ | { status: "unavailable"; reason: string };
12
+
13
+ function errorMessage(error: unknown): string {
14
+ return error instanceof Error ? error.message : String(error);
15
+ }
16
+
17
+ /** Read-only probe: the runner is gone while status still says it is active and no result was published. */
18
+ function runnerExitedWithoutResult(asyncDir: string, runId: string, resultPath: string): boolean {
19
+ const status = readStatus(asyncDir);
20
+ if (!status || (status.state !== "running" && status.state !== "queued") || typeof status.pid !== "number") return false;
21
+ const observedScope = currentPidNamespaceScope();
22
+ if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== observedScope) return false;
23
+ const pidScopeVerified = status.pidNamespaceScope !== undefined && status.pidNamespaceScope === observedScope;
24
+ if (checkPidLiveness(status.pid, undefined, pidScopeVerified) !== "dead") return false;
25
+ return !fs.existsSync(resultPath) && !(status.sessionId && resultPayloadPathForSessionRun(asyncDir, status.sessionId, runId));
26
+ }
27
+
28
+ /**
29
+ * Waits for an existing workflow-awaited async child, identified by its async
30
+ * directory and exact run id, and returns its published result without
31
+ * launching, consuming, or rewriting anything. Anything short of a published
32
+ * result file for that exact run is `unavailable`. Rejects with the signal's
33
+ * reason when aborted.
34
+ */
35
+ export async function awaitExistingAsyncRun(asyncDir: string, runId: string, signal: AbortSignal): Promise<ExistingAsyncRunOutcome> {
36
+ signal.throwIfAborted();
37
+ let status: ReturnType<typeof readStatus>;
38
+ try {
39
+ status = readStatus(asyncDir);
40
+ } catch (error) {
41
+ return { status: "unavailable", reason: `Async status for run '${runId}' is unreadable: ${errorMessage(error)}` };
42
+ }
43
+ if (!status) return { status: "unavailable", reason: `No async status exists for run '${runId}' at ${asyncDir}.` };
44
+ if (status.runId !== runId) return { status: "unavailable", reason: `Async status at ${asyncDir} belongs to run '${status.runId}', not '${runId}'.` };
45
+ // The launcher's initial status has no workflow identity until the runner starts, so only the
46
+ // mode is checked here; a run that does not publish to the workflow result path stays unavailable.
47
+ if (status.mode !== "single") return { status: "unavailable", reason: `Async run '${runId}' is not a single-agent run.` };
48
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
49
+ let runnerExited = false;
50
+ let completed: ImportedAsyncRootResult;
51
+ try {
52
+ completed = await waitForImportedAsyncRoot({ runId, asyncDir, resultPath, index: 0 }, {
53
+ shouldAbort: () => signal.aborted || (runnerExited = runnerExitedWithoutResult(asyncDir, runId, resultPath)),
54
+ });
55
+ } catch (error) {
56
+ signal.throwIfAborted();
57
+ return { status: "unavailable", reason: `Could not await async run '${runId}': ${errorMessage(error)}` };
58
+ }
59
+ signal.throwIfAborted();
60
+ if (runnerExited) return { status: "unavailable", reason: `Async runner for run '${runId}' exited without publishing a result.` };
61
+ // Only a parsed result file carries importedPublication; status-derived fallbacks do not.
62
+ if (!completed.importedPublication) return { status: "unavailable", reason: `Async run '${runId}' ended without a result file at ${resultPath}.` };
63
+ return { status: "settled", result: completed };
64
+ }
65
+
66
+ /**
67
+ * Renames the published result to a file owned by `claimant`. Only one of several
68
+ * concurrent importers can win the rename; the others get undefined and launch fresh.
69
+ */
70
+ export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string): string | undefined {
71
+ const claimedPath = `${workflowAwaitedAsyncResultPath(asyncDir)}.${claimant}.claimed`;
72
+ try {
73
+ fs.renameSync(workflowAwaitedAsyncResultPath(asyncDir), claimedPath);
74
+ return claimedPath;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
@@ -161,7 +161,7 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
161
161
  };
162
162
  }
163
163
 
164
- function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
164
+ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string, stopped = false): ImportedAsyncRootResult {
165
165
  const step = selectedStatusStep(status, root.index);
166
166
  return {
167
167
  agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
@@ -169,7 +169,7 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
169
169
  success: false,
170
170
  exitCode: 1,
171
171
  error: message,
172
- timedOut: true,
172
+ ...(stopped ? { stopped: true } : { timedOut: true }),
173
173
  ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
174
174
  ...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
175
175
  ...(step?.model ? { model: step.model } : {}),
@@ -228,7 +228,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
228
228
 
229
229
  export async function waitForImportedAsyncRoot(
230
230
  root: ImportedAsyncRoot,
231
- options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string } = {},
231
+ options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number; shouldAbort?: () => boolean; timeoutMessage?: string; abortedAsStopped?: boolean } = {},
232
232
  ): Promise<ImportedAsyncRootResult> {
233
233
  const pollIntervalMs = options.pollIntervalMs ?? 500;
234
234
  const terminalResultGraceMs = options.terminalResultGraceMs ?? 1_000;
@@ -236,7 +236,7 @@ export async function waitForImportedAsyncRoot(
236
236
  let terminalSince: number | undefined;
237
237
  for (;;) {
238
238
  const status = readStatus(root.asyncDir);
239
- if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.");
239
+ if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.", options.abortedAsStopped === true);
240
240
  const result = readImportedResultFile(root, status);
241
241
  if (result) return buildImportedResult(root, status, result);
242
242
  if (isTerminalStatus(status, root.index)) {
@@ -74,11 +74,51 @@ export interface SteerRequest {
74
74
  source?: string;
75
75
  }
76
76
 
77
+ export interface CommandRequest {
78
+ type: "command";
79
+ id: string;
80
+ ownerId: string;
81
+ operation: "status" | "yield" | "cancel";
82
+ toolCallId?: string;
83
+ deadlineAt: number;
84
+ }
85
+
86
+ function validCommandRequest(raw: unknown): raw is CommandRequest {
87
+ if (!raw || typeof raw !== "object") return false;
88
+ const value = raw as Partial<CommandRequest>;
89
+ return value.type === "command" && typeof value.id === "string" && /^[a-f0-9-]{36}$/.test(value.id)
90
+ && typeof value.ownerId === "string" && /^[a-f0-9-]{36}$/.test(value.ownerId)
91
+ && (value.operation === "status" || value.operation === "yield" || value.operation === "cancel")
92
+ && Number.isSafeInteger(value.deadlineAt) && value.deadlineAt! > 0
93
+ && (value.toolCallId === undefined ? value.operation === "status" : typeof value.toolCallId === "string" && value.toolCallId.length > 0 && value.toolCallId.length <= 256);
94
+ }
95
+
96
+ function commandRequestsDir(dir: string): string { return path.join(controlInboxDir(dir), "command-requests"); }
97
+ export function requestAsyncCommand(dir: string, request: CommandRequest): void {
98
+ if (!validCommandRequest(request)) throw new Error("Malformed command request.");
99
+ writeAtomicJson(path.join(commandRequestsDir(dir), `${request.id}.json`), request);
100
+ }
101
+ function consumeCommandRequests(dir: string, fsImpl: ControlChannelFs): CommandRequest[] {
102
+ const requests: CommandRequest[] = [];
103
+ for (const name of fsImpl.readdirSync(commandRequestsDir(dir)).filter((entry) => entry.endsWith(".json")).sort()) {
104
+ const file = path.join(commandRequestsDir(dir), name);
105
+ let value: unknown;
106
+ try { value = JSON.parse(fsImpl.readFileSync(file, "utf8")); }
107
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; }
108
+ try { fsImpl.rmSync(file); }
109
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
110
+ if (validCommandRequest(value)) requests.push(value);
111
+ }
112
+ return requests;
113
+ }
114
+
77
115
  const STEER_REQUESTS_DIR = "steer-requests";
78
116
  const STOP_REQUESTS_DIR = "stop-requests";
79
117
  const REVIVAL_BRIEFS_DIR = "revival-briefs";
80
118
  export const MAX_STEER_QUEUE_SIZE = 20;
81
119
  const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
120
+ const STOP_INBOX_CLOSED_FILE = "stop-inbox-closed.json";
121
+ const STOP_INBOX_CLOSED_MESSAGE = "Runner stop inbox is closed. Retry stop after runner shutdown is observed.";
82
122
  const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
83
123
  const MAX_STEER_REQUEST_ID_LENGTH = 256;
84
124
 
@@ -116,6 +156,14 @@ export function steerInboxClosedPath(asyncDir: string): string {
116
156
  return path.join(controlInboxDir(asyncDir), STEER_INBOX_CLOSED_FILE);
117
157
  }
118
158
 
159
+ export function stopInboxClosedPath(asyncDir: string): string {
160
+ return path.join(controlInboxDir(asyncDir), STOP_INBOX_CLOSED_FILE);
161
+ }
162
+
163
+ export function closeStopInbox(asyncDir: string): void {
164
+ writeAtomicJson(stopInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now() });
165
+ }
166
+
119
167
  export function closeSteerInbox(asyncDir: string, state: string, write: (filePath: string, payload: object) => void = writeAtomicJson): void {
120
168
  write(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
121
169
  }
@@ -206,15 +254,21 @@ export function requestAsyncTimeout(
206
254
  export function requestAsyncStop(
207
255
  asyncDir: string,
208
256
  payload: Omit<StopRequest, "type"> = {},
209
- deps: { now?: () => number } = {},
257
+ deps: { now?: () => number; write?: typeof writeAtomicJson } = {},
210
258
  ): string {
211
259
  if (payload.targetIndex !== undefined) assertChildIndex(payload.targetIndex);
212
260
  if (payload.childId !== undefined && !validStopChildId(payload.childId)) {
213
261
  throw new Error("stop childId must be a non-empty string without newlines and at most 256 characters.");
214
262
  }
263
+ const closedPath = stopInboxClosedPath(asyncDir);
264
+ if (fs.existsSync(closedPath)) throw new Error(STOP_INBOX_CLOSED_MESSAGE);
215
265
  const request: StopRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "stop" };
216
266
  const requestPath = path.join(stopRequestsDir(asyncDir), stopRequestFileName(request));
217
- writeAtomicJson(requestPath, request);
267
+ (deps.write ?? writeAtomicJson)(requestPath, request);
268
+ if (fs.existsSync(closedPath)) {
269
+ fs.rmSync(requestPath, { force: true });
270
+ throw new Error(STOP_INBOX_CLOSED_MESSAGE);
271
+ }
218
272
  return requestPath;
219
273
  }
220
274
 
@@ -503,6 +557,7 @@ export function watchAsyncControlInbox(
503
557
  onTimeout?: () => void;
504
558
  onStop?: (request: StopRequest) => void;
505
559
  onSteer?: (request: SteerRequest) => void;
560
+ onCommand?: (request: CommandRequest) => void;
506
561
  onError?: (error: unknown, phase: "install" | "scan" | "callback", request?: SteerRequest) => void;
507
562
  pollIntervalMs?: number;
508
563
  safetyPollIntervalMs?: number;
@@ -526,6 +581,7 @@ export function watchAsyncControlInbox(
526
581
  ...(opts.onInterrupt || opts.onTimeout || opts.onStop ? [dir] : []),
527
582
  ...(opts.onStop ? [stopRequestsDir(asyncDir)] : []),
528
583
  ...(opts.onSteer ? [steerRequestsDir(asyncDir)] : []),
584
+ ...(opts.onCommand ? [commandRequestsDir(asyncDir)] : []),
529
585
  ];
530
586
  if (dirs.length === 0) return () => {};
531
587
  try {
@@ -538,6 +594,9 @@ export function watchAsyncControlInbox(
538
594
  const check = (): void => {
539
595
  if (disposed) return;
540
596
  try {
597
+ if (opts.onCommand) for (const request of consumeCommandRequests(asyncDir, fsImpl)) {
598
+ try { opts.onCommand(request); } catch (error) { report(error, "callback"); }
599
+ }
541
600
  if (opts.onStop) for (const request of consumeStopRequestPayloads(asyncDir, fsImpl, (error) => report(error, "scan"))) {
542
601
  try { opts.onStop(request); } catch (error) { report(error, "callback"); }
543
602
  }
@@ -27,6 +27,8 @@ export interface SubagentNotifyChildOutput {
27
27
  runId?: string;
28
28
  agent?: string;
29
29
  status: string;
30
+ /** Latest detached revival of this failed child, e.g. `Revived → <run>: completed`. */
31
+ revival?: string;
30
32
  savedOutputPath?: string;
31
33
  outputArtifactPath?: string;
32
34
  structuredOutputPath?: string;
@@ -93,6 +95,7 @@ export interface CompletionNotification {
93
95
  agent?: string;
94
96
  status?: string;
95
97
  state?: string;
98
+ revival?: string;
96
99
  success?: boolean;
97
100
  output?: string;
98
101
  structuredOutput?: unknown;
@@ -269,6 +272,7 @@ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefine
269
272
  const runId = child.runId ? boundedSafeText(child.runId) : "unavailable";
270
273
  const status = boundedSafeText(child.status) || "unavailable";
271
274
  lines.push(`- key=${key} run=${runId} status=${status}`);
275
+ if (child.revival) lines.push(` ${boundedSafeText(child.revival)}`);
272
276
  lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
273
277
  if (child.outputArtifactPath) lines.push(` Output artifact (retention-managed): ${boundedSafeText(child.outputArtifactPath)}`);
274
278
  if (child.structuredOutputPath) lines.push(` Structured output (retention-managed): ${boundedSafeText(child.structuredOutputPath)}`);
@@ -696,6 +700,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
696
700
  ...(runId ? { runId } : {}),
697
701
  ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
698
702
  status: childStatus(child, result.state),
703
+ ...(typeof child.revival === "string" && child.revival ? { revival: child.revival } : {}),
699
704
  ...(savedOutputPath ? { savedOutputPath } : {}),
700
705
  ...(outputArtifact.status === "verified" ? { outputArtifactPath: outputArtifact.path } : {}),
701
706
  ...(structuredOutput.status === "verified" ? { structuredOutputPath: structuredOutput.path } : {}),
@@ -414,7 +414,10 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
414
414
  const event = raw as ChildSessionEvent & ChildEvent;
415
415
  appendChildEvent(projectChildSessionEventForJson(raw) as Record<string, unknown>);
416
416
  input.transcriptWriter?.writeChildEvent(projectChildSessionEventForJson(raw) as ChildEvent);
417
- if (event.type === "compaction_start") compactionStartedReceived = true;
417
+ if (event.type === "compaction_start") {
418
+ compactionStartedReceived = true;
419
+ if (agentSettledReceived) afterCompactionSettlement = true;
420
+ }
418
421
  if (event.type === "compaction_end" && event.willRetry === true) {
419
422
  compactionStartedReceived = false;
420
423
  afterCompactionSettlement = false;
@@ -511,7 +514,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
511
514
  if (event.message.model) {
512
515
  model = event.message.model;
513
516
  if (input.expectedModelForVerification && !hasToolCall) {
514
- const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases);
517
+ const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases, session?.virtualModelId);
515
518
  if (modelVerificationError && !error) error = modelVerificationError;
516
519
  }
517
520
  }
@@ -542,7 +545,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
542
545
  };
543
546
 
544
547
  /** Stops observing the child and returns when its extensions have shut down. */
545
- const finish = (): Promise<void> => {
548
+ const finish = async (): Promise<string | undefined> => {
546
549
  clearFinalDrainTimers();
547
550
  clearWatchdogTailTimer();
548
551
  clearAllToolTimeouts();
@@ -556,7 +559,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
556
559
  input.registerSteer?.(undefined);
557
560
  input.registerWatchdogStatus?.(undefined);
558
561
  unsubscribe?.();
559
- return Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
562
+ let commandError: string | undefined;
563
+ if (!interrupted && !timedOut && !stopped) {
564
+ try { await session?.finishCommands?.(); }
565
+ catch (error) { commandError = error instanceof Error ? error.message : String(error); }
566
+ }
567
+ await Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
568
+ return commandError;
560
569
  };
561
570
 
562
571
  /** The child run ended (or was forced to end); fold in the outcome once the child's shutdown work is done. */
@@ -596,12 +605,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
596
605
  if (!finalError && forced && !forcedDrainAfterFinalSuccess && !interrupted && !timedOut && !stopped) {
597
606
  finalError = "Subagent session did not settle after it was aborted.";
598
607
  }
599
- const exitCode = timedOut || stopped
608
+ let exitCode = timedOut || stopped
600
609
  ? 1
601
610
  : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal)
602
611
  ? 0
603
612
  : finalError || promptError !== undefined ? 1 : 0;
604
- void closed.then(() => {
613
+ void closed.then((commandError) => {
614
+ if (commandError) { finalError ??= commandError; exitCode = 1; }
605
615
  const result: RunChildSessionResult = omitUndefined({
606
616
  exitCode,
607
617
  messages,
@@ -610,7 +620,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
610
620
  durationMs: Date.now() - startedAt,
611
621
  model,
612
622
  nativeMachine: session?.machineEvidence ? { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) } : undefined,
613
- error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
623
+ error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal && !commandError) ? undefined : finalError,
614
624
  finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
615
625
  outputState: finalOutput.trim() ? "present" : "absent",
616
626
  interrupted: interrupted || undefined,
@@ -34,6 +34,7 @@ import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
34
34
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
35
35
  import { validHostStepNodes } from "../shared/host-step-status.ts";
36
36
  import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.ts";
37
+ import { formatWorkflowKeyRevival, projectWorkflowKeyRevival } from "../../workflows/workflow-revival.ts";
37
38
 
38
39
  interface RunStatusParams {
39
40
  action?: string;
@@ -595,6 +596,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
595
596
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
596
597
  status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
597
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,
598
600
  `Progress: ${progressLabel}`,
599
601
  ...(status.mode === "workflow" ? formatWorkflowChecklistText(projectWorkflowChecklist({
600
602
  graph: status.workflowGraph,
@@ -634,6 +636,10 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
634
636
  const phase = step.phase ? `[${step.phase}] ` : "";
635
637
  lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
636
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
+ }
637
643
  const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
638
644
  if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
639
645
  if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
@@ -15,10 +15,11 @@ import * as path from "node:path";
15
15
  export const JITI_ALIAS_ENV = "JITI_ALIAS";
16
16
 
17
17
  /** Specifiers the runner's import graph may use, with the package and export subpath each resolves to. */
18
- export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string }> = [
18
+ export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string; optional?: boolean }> = [
19
19
  { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
20
20
  { specifier: "@earendil-works/pi-agent-core", pkg: "@earendil-works/pi-agent-core", subpath: "." },
21
- { specifier: "@earendil-works/pi-agent-core/node", pkg: "@earendil-works/pi-agent-core", subpath: "./node" },
21
+ // Optional: hosts whose pi-agent-core declares no "./node" export cannot import it, so no alias is needed.
22
+ { specifier: "@earendil-works/pi-agent-core/node", pkg: "@earendil-works/pi-agent-core", subpath: "./node", optional: true },
22
23
  { specifier: "@earendil-works/pi-tui", pkg: "@earendil-works/pi-tui", subpath: "." },
23
24
  { specifier: "@earendil-works/pi-ai", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
24
25
  { specifier: "@earendil-works/pi-ai/compat", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
@@ -131,6 +132,26 @@ function findPeerPackageDir(piPackageRoot: string, pkg: string, hostName: unknow
131
132
  return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
132
133
  }
133
134
 
135
+ /** Whether the package's `exports` map (or `main`) declares `subpath`, even if the target file is missing. */
136
+ function exportsDeclareSubpath(packageDir: string, subpath: string): boolean {
137
+ const manifest = readManifest(packageDir);
138
+ if (!manifest) return false;
139
+ const exportsField = manifest.exports;
140
+ if (exportsField === undefined || exportsField === null) return subpath === ".";
141
+ const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
142
+ ? { ".": exportsField }
143
+ : exportsField as Record<string, unknown>;
144
+ if (subpath in map) return true;
145
+ for (const pattern of Object.keys(map)) {
146
+ const star = pattern.indexOf("*");
147
+ if (star === -1) continue;
148
+ const prefix = pattern.slice(0, star);
149
+ const suffix = pattern.slice(star + 1);
150
+ if (subpath.startsWith(prefix) && subpath.endsWith(suffix) && subpath.length >= prefix.length + suffix.length) return true;
151
+ }
152
+ return false;
153
+ }
154
+
134
155
  /** The alias map the runner needs, or the specifiers that could not be resolved. */
135
156
  export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
136
157
  const aliases: Record<string, string> = {};
@@ -140,13 +161,23 @@ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record
140
161
  // hosts retain the required aliases, rather than hiding a broken install.
141
162
  const stableVersion = typeof hostManifest?.version === "string" ? /^0\.(\d+)\.\d+$/.exec(hostManifest.version) : null;
142
163
  const isPreChord = stableVersion !== null && Number(stableVersion[1]) < 85;
143
- const required = [...HOST_PEER_ALIASES, ...(isPreChord ? [] : CHORD_PEER_ALIASES)];
144
- for (const { specifier, pkg, subpath } of required) {
164
+ const required: ReadonlyArray<(typeof HOST_PEER_ALIASES)[number]> = [...HOST_PEER_ALIASES, ...(isPreChord ? [] : CHORD_PEER_ALIASES)];
165
+ for (const { specifier, pkg, subpath, optional } of required) {
145
166
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
146
167
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
168
+ // An optional subpath the package does not declare is unreachable, so skip it; a declared but missing file still fails.
169
+ if (optional && packageDir && target === undefined) continue;
147
170
  // Native loaders short-circuit resolution, so aliases must retain the real package's dependency scope.
148
- if (target && fs.existsSync(target)) aliases[specifier] = fs.realpathSync(target);
149
- else missing.push(specifier);
171
+ if (target && fs.existsSync(target)) {
172
+ aliases[specifier] = fs.realpathSync(target);
173
+ continue;
174
+ }
175
+ // Host API drift: the installed peer no longer exports the subpath at all
176
+ // (pi 1.0.0's pi-agent-core dropped ./node), so the runner cannot import
177
+ // it on this host either — the alias is best-effort. A subpath that is
178
+ // declared but missing on disk stays a broken install.
179
+ if (packageDir && subpath !== "." && !exportsDeclareSubpath(packageDir, subpath)) continue;
180
+ missing.push(specifier);
150
181
  }
151
182
  return { aliases, missing };
152
183
  }
@@ -18,6 +18,7 @@ export interface RunnerChildLaunchContext {
18
18
  runFanoutBudget?: BuildInProcessChildLaunchInput["runFanoutBudget"];
19
19
  capabilityCeiling?: BuildInProcessChildLaunchInput["capabilityCeiling"];
20
20
  inheritedChildRuntime?: InheritedChildRuntime;
21
+ projectTrusted?: boolean;
21
22
  }
22
23
 
23
24
  export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChildLaunchContext, attempt: {
@@ -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,