pi-subagents 0.88.1 → 0.89.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 (93) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  5. package/bundle/{chunk-5EMPFFO4.js → chunk-4FFKVLBG.js} +4 -4
  6. package/bundle/{chunk-L4YY2TOE.js → chunk-5TXWZB73.js} +1 -1
  7. package/bundle/{chunk-ZJ2BT5TI.js → chunk-6D54VW3E.js} +56 -34
  8. package/bundle/{chunk-YDZ7BZD5.js → chunk-77VQEATI.js} +1 -1
  9. package/bundle/{chunk-7OX6O7DQ.js → chunk-BERAWSQQ.js} +5 -5
  10. package/bundle/{chunk-LV3CPYXJ.js → chunk-C22YEYFZ.js} +4 -4
  11. package/bundle/{chunk-VTUUOLM4.js → chunk-CASL47ST.js} +34 -5
  12. package/bundle/{chunk-YQSTGPEU.js → chunk-F6PTAPQ3.js} +75 -32
  13. package/bundle/{chunk-FLNDHNPE.js → chunk-IGZTXGPG.js} +98 -29
  14. package/bundle/{chunk-CPSUJHZE.js → chunk-KCDPTXHT.js} +39 -10
  15. package/bundle/{chunk-PCZEQQAQ.js → chunk-LUNVS6KP.js} +26 -15
  16. package/bundle/{chunk-4MVDMA5C.js → chunk-LWH7IGI3.js} +21 -7
  17. package/bundle/{chunk-DSHQWGHO.js → chunk-MIX3MCIF.js} +96 -96
  18. package/bundle/{chunk-2DIEL4WG.js → chunk-OUM6SEVD.js} +2 -2
  19. package/bundle/{chunk-XIA5GSEU.js → chunk-Q4VH72JI.js} +2 -2
  20. package/bundle/{chunk-D32H53HM.js → chunk-R3NH5XAL.js} +1 -1
  21. package/bundle/{chunk-6OWNDN7R.js → chunk-ROJH7KPK.js} +2 -2
  22. package/bundle/{chunk-4ZQBZDF3.js → chunk-SG3NCWZW.js} +86 -20
  23. package/bundle/{chunk-KXW62VBU.js → chunk-SWGB2P5J.js} +1 -1
  24. package/bundle/{chunk-N6TAAIB3.js → chunk-TDXVQPZW.js} +5 -5
  25. package/bundle/{chunk-6CG2VAG4.js → chunk-TRN65L4F.js} +1 -1
  26. package/bundle/{chunk-GDR2ILWY.js → chunk-TXC7WIPL.js} +51 -22
  27. package/bundle/{chunk-PYKBTBY6.js → chunk-URKQZHVH.js} +9 -9
  28. package/bundle/{chunk-W6HIYD2Z.js → chunk-UUW7P6KJ.js} +1 -1
  29. package/bundle/{chunk-CYKNHFXB.js → chunk-VEEUXJDO.js} +1 -1
  30. package/bundle/{chunk-47ZN7NKR.js → chunk-YJIU5WF4.js} +1 -1
  31. package/bundle/{chunk-RMZAAXIR.js → chunk-YLU5JFW2.js} +2 -2
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +2 -2
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +10 -4
  38. package/docs/configuration.md +2 -0
  39. package/docs/extension-api.md +1 -1
  40. package/docs/tool-reference.md +1 -1
  41. package/docs/workflows.md +5 -3
  42. package/package.json +1 -1
  43. package/src/extension/herdr-pi-bridge.js +79 -23
  44. package/src/extension/schemas.js +1 -1
  45. package/src/extension/subagent-options.js +5 -0
  46. package/src/intercom/result-intercom.js +3 -2
  47. package/src/runs/background/async-job-tracker.js +85 -9
  48. package/src/runs/background/async-status.d.ts +2 -0
  49. package/src/runs/background/async-status.js +8 -3
  50. package/src/runs/background/notify.d.ts +3 -0
  51. package/src/runs/background/notify.js +7 -2
  52. package/src/runs/background/run-status.js +3 -2
  53. package/src/runs/background/runner-child-launch.js +1 -0
  54. package/src/runs/background/subagent-runner.js +11 -8
  55. package/src/runs/foreground/execution.js +8 -7
  56. package/src/runs/foreground/subagent-executor.js +31 -5
  57. package/src/runs/shared/child-launch.d.ts +2 -0
  58. package/src/runs/shared/child-launch.js +1 -1
  59. package/src/runs/shared/child-session.d.ts +2 -1
  60. package/src/runs/shared/herdr-connection.d.ts +6 -0
  61. package/src/runs/shared/herdr-connection.js +11 -1
  62. package/src/runs/shared/herdr-machine.d.ts +2 -2
  63. package/src/runs/shared/herdr-machine.js +49 -22
  64. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  65. package/src/runs/shared/herdr-pane-host.js +48 -33
  66. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  67. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  68. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  69. package/src/runs/shared/herdr-placed-run.js +10 -8
  70. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  71. package/src/runs/shared/kept-branch-text.js +24 -0
  72. package/src/runs/shared/local-machine-access.d.ts +4 -1
  73. package/src/runs/shared/local-machine-access.js +6 -3
  74. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  75. package/src/runs/shared/mutation-evidence.js +18 -2
  76. package/src/runs/shared/parallel-handoff.js +19 -7
  77. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  78. package/src/runs/shared/placed-run-owner.js +15 -7
  79. package/src/runs/shared/rex-machine.d.ts +7 -3
  80. package/src/runs/shared/rex-machine.js +12 -9
  81. package/src/runs/shared/rex-pane-host.js +7 -27
  82. package/src/runs/shared/single-output.js +2 -2
  83. package/src/runs/shared/subagent-prompt-runtime.js +34 -0
  84. package/src/runs/shared/tool-availability.d.ts +4 -0
  85. package/src/runs/shared/tool-availability.js +7 -0
  86. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  87. package/src/runs/shared/worktree.d.ts +4 -14
  88. package/src/runs/shared/worktree.js +38 -8
  89. package/src/shared/types.d.ts +26 -2
  90. package/src/shared/utils.d.ts +2 -0
  91. package/src/shared/utils.js +9 -0
  92. package/src/workflows/workflow-child-summary.d.ts +2 -1
  93. package/src/workflows/workflow-child-summary.js +14 -6
@@ -3,11 +3,11 @@ import * as path from "node:path";
3
3
  import { renderWidget, widgetRenderKey } from "../../tui/render.js";
4
4
  import { formatControlNoticeMessage } from "../shared/subagent-control.js";
5
5
  import { DIRS, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_JOBS_CHANGED_EVENT, SUBAGENT_STEERING_NOTICE_EVENT, WIDGET_ANIMATION_INTERVAL_MS, } from "../../shared/types.js";
6
- import { readStatus, resolveWatchPath } from "../../shared/utils.js";
6
+ import { isStatusAccessError, readStatus, resolveWatchPath } from "../../shared/utils.js";
7
7
  import { normalizeParallelGroups } from "./parallel-groups.js";
8
8
  import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.js";
9
9
  import { findNestedRouteForRootId, hasLiveNestedDescendants, retainNestedLookupRoute, updateAsyncJobNestedProjection } from "../shared/nested-events.js";
10
- import { listAsyncRuns } from "./async-status.js";
10
+ import { listAsyncRuns, summarizeAsyncStatus } from "./async-status.js";
11
11
  import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, externalJobBridgeEligibility, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.js";
12
12
  import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.js";
13
13
  import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.js";
@@ -49,6 +49,12 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
49
49
  // Early native failure is visible before its publisher finishes. Retain only
50
50
  // that scoped observation, using the existing liveness sweep to renew delivery.
51
51
  const terminalPublications = new Map();
52
+ // Runs whose status.json this process may not read. An unreadable file says nothing about the
53
+ // runner, so the job keeps its last known state rather than reading as finished (#3295).
54
+ const unreadableStatusRuns = new Set();
55
+ // Restored runs whose status.json was unreadable, so their owner is unknown. Each is counted as
56
+ // this session's until a read shows otherwise; nothing writes to it before then.
57
+ const unverifiedRuns = new Set();
52
58
  const supervisorNoticeTimers = new Map();
53
59
  let rootWatcher;
54
60
  let nextLivenessAt = Date.now() + livenessIntervalMs;
@@ -424,9 +430,53 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
424
430
  runningJobIds.delete(asyncId);
425
431
  externalJobBridgeRuns.delete(asyncId);
426
432
  terminalPublications.delete(asyncId);
433
+ unreadableStatusRuns.delete(asyncId);
434
+ unverifiedRuns.delete(asyncId);
427
435
  clearSupervisorNotices(asyncId);
428
436
  };
437
+ const forgetJob = (asyncId) => {
438
+ cancelCleanup(asyncId);
439
+ closeJobWatcher(asyncId);
440
+ state.asyncJobs.delete(asyncId);
441
+ state.fleetJobs?.delete(asyncId);
442
+ options.onJobCleanup?.(asyncId);
443
+ };
429
444
  const refreshJob = (job) => {
445
+ if (unverifiedRuns.has(job.asyncId)) {
446
+ let stored = null;
447
+ let summary;
448
+ try {
449
+ stored = readStatus(job.asyncDir);
450
+ if (stored)
451
+ summary = summarizeAsyncStatus(job.asyncDir, stored);
452
+ }
453
+ catch (error) {
454
+ if (isStatusAccessError(error, job.asyncDir))
455
+ return false;
456
+ console.error(`[pi-subagents] Dropping restored async run '${job.asyncId}' at '${path.join(job.asyncDir, "status.json")}': ${error instanceof Error ? error.message : String(error)}.`);
457
+ }
458
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
459
+ if (!stored || !summary || (owners && !owners.has(stored.sessionId))) {
460
+ forgetJob(job.asyncId);
461
+ return true;
462
+ }
463
+ let restored;
464
+ try {
465
+ restored = summaryToJob(summary);
466
+ }
467
+ catch (error) {
468
+ if (!unreadableStatusRuns.has(job.asyncId)) {
469
+ unreadableStatusRuns.add(job.asyncId);
470
+ console.error(`Cannot read async control events for '${job.asyncDir}'; keeping it as running until they are readable:`, error);
471
+ }
472
+ return false;
473
+ }
474
+ // Become the job a normal restore would have made, but keep the placeholder's state so the
475
+ // refresh below sees any transition, and its cursor when restore could read events.jsonl.
476
+ Object.assign(job, restored, { status: job.status, controlEventCursor: job.controlEventCursor ?? restored.controlEventCursor });
477
+ rememberFleetJob(state, job);
478
+ unverifiedRuns.delete(job.asyncId);
479
+ }
430
480
  const widgetExpanded = withLastUiContext((ctx) => ctx.ui.getToolsExpanded?.() ?? false) ?? false;
431
481
  const widgetStateBefore = widgetRenderKey(job, widgetExpanded);
432
482
  let nestedRefreshFailed = false;
@@ -475,6 +525,7 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
475
525
  },
476
526
  });
477
527
  const status = reconciliation.status ?? readStatus(job.asyncDir);
528
+ unreadableStatusRuns.delete(job.asyncId);
478
529
  if (!bridgeAlreadyRequired) {
479
530
  const bridgeEligibility = externalJobBridgeEligibility(status?.steps);
480
531
  if (bridgeEligibility === "required")
@@ -612,6 +663,13 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
612
663
  console.error(`Failed to service external job bridge for '${job.asyncDir}':`, bridgeError);
613
664
  }
614
665
  }
666
+ if (isStatusAccessError(error, job.asyncDir)) {
667
+ if (!unreadableStatusRuns.has(job.asyncId)) {
668
+ unreadableStatusRuns.add(job.asyncId);
669
+ console.error(`Cannot read async status for '${job.asyncDir}'; keeping its last known state until it is readable:`, error);
670
+ }
671
+ return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
672
+ }
615
673
  if (job.status !== "failed") {
616
674
  console.error(`Failed to read async status for '${job.asyncDir}':`, error);
617
675
  job.status = "failed";
@@ -751,11 +809,7 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
751
809
  const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
752
810
  for (const job of state.asyncJobs.values()) {
753
811
  if (owners && job.sessionId !== undefined && !owners.has(job.sessionId)) {
754
- cancelCleanup(job.asyncId);
755
- closeJobWatcher(job.asyncId);
756
- state.asyncJobs.delete(job.asyncId);
757
- state.fleetJobs?.delete(job.asyncId);
758
- options.onJobCleanup?.(job.asyncId);
812
+ forgetJob(job.asyncId);
759
813
  widgetChanged = true;
760
814
  continue;
761
815
  }
@@ -881,6 +935,8 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
881
935
  runningJobIds.clear();
882
936
  externalJobBridgeRuns.clear();
883
937
  terminalPublications.clear();
938
+ unreadableStatusRuns.clear();
939
+ unverifiedRuns.clear();
884
940
  clearSupervisorNotices();
885
941
  };
886
942
  const resetJobs = (ctx) => {
@@ -907,9 +963,13 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
907
963
  if (!state.currentSessionId)
908
964
  return;
909
965
  let runs;
966
+ const unreadable = [];
910
967
  try {
911
968
  // A workflow whose Pi exited is repaired here, in the session that owns it, which then delivers its notice.
912
- runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now, adoptCompletionOwnerId: state.completionOwnerId }, observeStatus);
969
+ runs = listAsyncRuns(asyncDirRoot, {
970
+ states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now, adoptCompletionOwnerId: state.completionOwnerId,
971
+ onUnreadableActiveRun: (runId, asyncDir) => unreadable.push({ runId, asyncDir }),
972
+ }, observeStatus);
913
973
  }
914
974
  catch (error) {
915
975
  console.error(`Failed to restore active async jobs from '${asyncDirRoot}':`, error);
@@ -923,8 +983,24 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
923
983
  rememberFleetJob(state, job);
924
984
  watchJob(job);
925
985
  }
986
+ // An unreadable run may still be working: idle must not be reported until a read settles it.
987
+ for (const { runId, asyncDir } of unreadable) {
988
+ if (state.asyncJobs.has(runId))
989
+ continue;
990
+ const job = { asyncId: runId, asyncDir, status: "running", sessionId: state.currentSessionId, updatedAt: Date.now() };
991
+ try {
992
+ job.controlEventCursor = restoredControlEventCursor(asyncDir);
993
+ }
994
+ catch {
995
+ // An unsearchable run directory: refreshJob reads the cursor once the run is verified.
996
+ }
997
+ state.asyncJobs.set(runId, job);
998
+ runningJobIds.add(runId);
999
+ unverifiedRuns.add(runId);
1000
+ watchJob(job);
1001
+ }
926
1002
  state.statusProjectionSessionId = state.currentSessionId;
927
- if (runs.length === 0)
1003
+ if (runs.length === 0 && unreadable.length === 0)
928
1004
  return;
929
1005
  ensurePoller();
930
1006
  rerenderLastWidget();
@@ -148,6 +148,8 @@ interface AsyncRunListOptions {
148
148
  adoptCompletionOwnerId?: string;
149
149
  /** Receives the warning for a skipped corrupt terminal status, so an open TUI can show it as a notice instead of console output. */
150
150
  onCorruptStatus?: (warning: string) => void;
151
+ /** Receives an active run kept in the index whose status.json this process may not read. */
152
+ onUnreadableActiveRun?: (runId: string, asyncDir: string) => void;
151
153
  }
152
154
  type TargetedAsyncRunResolution = {
153
155
  kind: "exact";
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.js";
4
4
  import { previewDisplayText } from "../../shared/display-text.js";
5
5
  import { formatActivityLabel, formatParallelOutcome } from "../../shared/status-format.js";
6
- import { readStatus } from "../../shared/utils.js";
6
+ import { isStatusAccessError, readStatus } from "../../shared/utils.js";
7
7
  import { attachRootChildrenToSteps, buildNestedRouteIndex, findNestedRouteForRootId, projectNestedEvents } from "../shared/nested-events.js";
8
8
  import { formatNestedRunStatusLines } from "../shared/nested-render.js";
9
9
  import { formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.js";
@@ -40,6 +40,7 @@ function isAsyncStatusIsolationError(asyncDir, error) {
40
40
  // Status path -> last logged signature. A corrupt run is re-scanned on every
41
41
  // status poll, so the line repeats only when the file or the outcome changes.
42
42
  const reportedCorruptStatus = new Map();
43
+ /** Returns whether the active-run marker is still in place. */
43
44
  function isolateCorruptActiveRun(asyncDir, runId, error, now) {
44
45
  const statusPath = path.join(asyncDir, "status.json");
45
46
  const processTerminal = readProcessTerminal(asyncDir, { runId });
@@ -53,9 +54,11 @@ function isolateCorruptActiveRun(asyncDir, runId, error, now) {
53
54
  const markerCanBeReleased = processTerminal?.state === "observed"
54
55
  || (markerAge !== undefined && markerAge > DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS);
55
56
  let markerAction = "active marker retained because runner liveness is unknown";
57
+ let retained = true;
56
58
  if (markerCanBeReleased) {
57
59
  try {
58
60
  releaseActiveRunIndex(asyncDir);
61
+ retained = false;
59
62
  markerAction = processTerminal?.state === "observed"
60
63
  ? "active marker released after observed process-terminal proof"
61
64
  : "stale active marker released";
@@ -75,9 +78,10 @@ function isolateCorruptActiveRun(asyncDir, runId, error, now) {
75
78
  }
76
79
  const signature = `${fileSignature}\n${line}`;
77
80
  if (reportedCorruptStatus.get(statusPath) === signature)
78
- return;
81
+ return retained;
79
82
  reportedCorruptStatus.set(statusPath, signature);
80
83
  console.error(line);
84
+ return retained;
81
85
  }
82
86
  function isNotFoundError(error) {
83
87
  return typeof error === "object"
@@ -464,7 +468,8 @@ export function listAsyncRuns(asyncDirRoot, options = {}, observeStatus) {
464
468
  observeStatus?.(null);
465
469
  if (!activeEntries.has(entry) || !isAsyncStatusIsolationError(asyncDir, error))
466
470
  throw error;
467
- isolateCorruptActiveRun(asyncDir, entry, error, options.now);
471
+ if (isolateCorruptActiveRun(asyncDir, entry, error, options.now) && isStatusAccessError(error, asyncDir))
472
+ options.onUnreadableActiveRun?.(entry, asyncDir);
468
473
  continue;
469
474
  }
470
475
  if (!status) {
@@ -8,6 +8,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
8
8
  import { type CompletionBatchConfig } from "./completion-batcher.ts";
9
9
  import { type ChildWatchdogProgress, type ChildWatchdogWarningSummary, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
10
10
  import { type ParentWake } from "../../shared/parent-wake.ts";
11
+ import { type KeptBranch } from "../shared/kept-branch-text.ts";
11
12
  import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
12
13
  export interface SubagentNotifyChildOutput {
13
14
  workflowKey?: string;
@@ -54,6 +55,8 @@ export interface SubagentNotifyDetails {
54
55
  sessionLabel?: string;
55
56
  sessionValue?: string;
56
57
  handoffPath?: string;
58
+ /** Branches worktree cleanup kept because their commits are on no other ref. */
59
+ keptBranches?: KeptBranch[];
57
60
  /** Present when a durable schedule launched the run. */
58
61
  scheduleOrigin?: ScheduleOrigin;
59
62
  watchdogBlockers?: SubagentNotifyWatchdogBlocker[];
@@ -13,6 +13,7 @@ import { COMPLETION_ACTION } from "../../shared/parent-wake.js";
13
13
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.js";
14
14
  import { isUnexplainedProcessSignal } from "../shared/process-signal.js";
15
15
  import { capSummaryOutputs } from "../shared/single-output.js";
16
+ import { formatParallelHandoffLines, parseKeptBranchLines, readKeptBranches } from "../shared/kept-branch-text.js";
16
17
  import { describeWorkflowResume } from "../../workflows/workflow-resume-claim.js";
17
18
  import { isReusableWorkflowStopCause } from "../../workflows/workflow-stop-cause.js";
18
19
  const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 2_000;
@@ -228,7 +229,7 @@ export function formatSingleCompletion(details) {
228
229
  formatResultPreview(details),
229
230
  ...(watchdogLines.length ? ["", ...watchdogLines] : []),
230
231
  details.handoffPath ? "" : undefined,
231
- details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,
232
+ ...(details.handoffPath ? formatParallelHandoffLines(details.handoffPath, details.keptBranches) : []),
232
233
  correlationLines.length && !details.handoffPath ? "" : undefined,
233
234
  ...correlationLines,
234
235
  sessionLine ? "" : undefined,
@@ -308,6 +309,7 @@ export function parseSubagentNotifyContent(content) {
308
309
  const resultEnd = firstMetadataIndex > 0 && body[firstMetadataIndex - 1]?.trim() === "" ? firstMetadataIndex - 1 : firstMetadataIndex;
309
310
  const resultPreview = body.slice(0, resultEnd).join("\n").trim() || "(no output)";
310
311
  const handoffPath = handoffIndex >= 0 ? body[handoffIndex].slice("Parallel handoff: ".length).trim() : undefined;
312
+ const keptBranches = handoffIndex >= 0 ? parseKeptBranchLines(body.slice(handoffIndex + 1)) : [];
311
313
  const workflowRunId = workflowRunIndex >= 0 ? body[workflowRunIndex].slice("Workflow run: ".length).trim() : undefined;
312
314
  const childRuns = childRunsIndex >= 0
313
315
  ? body[childRunsIndex].slice("Child runs: ".length).split(", ").map((part) => {
@@ -337,6 +339,7 @@ export function parseSubagentNotifyContent(content) {
337
339
  ...(workflowReceiptPath ? { workflowReceiptPath } : {}),
338
340
  resultPreview,
339
341
  ...(handoffPath ? { handoffPath } : {}),
342
+ ...(keptBranches.length ? { keptBranches } : {}),
340
343
  ...(workflowRunId ? { workflowRunId } : {}),
341
344
  ...(resumeNotice ? { resumeNotice } : {}),
342
345
  ...(childRuns?.length ? { childRuns } : {}),
@@ -359,7 +362,7 @@ export function formatGroupedCompletion(details) {
359
362
  blocks.push(formatResultPreview(detail));
360
363
  blocks.push(...formatWatchdogBlockerLines(detail));
361
364
  if (detail.handoffPath)
362
- blocks.push(`Parallel handoff: ${detail.handoffPath}`);
365
+ blocks.push(...formatParallelHandoffLines(detail.handoffPath, detail.keptBranches));
363
366
  blocks.push(...formatCorrelationLines(detail));
364
367
  if (sessionLine)
365
368
  blocks.push(sessionLine);
@@ -542,6 +545,7 @@ export function buildCompletionDetails(result) {
542
545
  ? result.parallelHandoff
543
546
  : undefined;
544
547
  const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
548
+ const keptBranches = readKeptBranches(parallelHandoff?.keptBranches);
545
549
  const receipt = result.workflowReceipt;
546
550
  const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
547
551
  ? receipt.path : undefined;
@@ -661,6 +665,7 @@ export function buildCompletionDetails(result) {
661
665
  resultPreview: watchdogConcerns.length ? `${resultPreview}\n\nHigh-importance watchdog concerns:\n${watchdogConcerns.map((warning) => `- ${warning}`).join("\n")}` : resultPreview,
662
666
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
663
667
  ...(handoffPath ? { handoffPath } : {}),
668
+ ...(handoffPath && keptBranches.length ? { keptBranches } : {}),
664
669
  ...(rawRunId ? { runId: rawRunId } : {}),
665
670
  ...(workflowRunId ? { workflowRunId } : {}),
666
671
  ...(resumeNotice ? { resumeNotice } : {}),
@@ -35,6 +35,7 @@ import { validHostStepNodes } from "../shared/host-step-status.js";
35
35
  import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.js";
36
36
  import { formatWorkflowKeyRevival, projectWorkflowKeyRevival } from "../../workflows/workflow-revival.js";
37
37
  import { capSummaryOutputs } from "../shared/single-output.js";
38
+ import { formatParallelHandoffLines } from "../shared/kept-branch-text.js";
38
39
  import { ownsRun } from "../shared/run-ownership.js";
39
40
  import { foregroundChildStateLabel } from "../foreground/foreground-history.js";
40
41
  import { waitToolName } from "../../shared/wait-tool-name.js";
@@ -632,7 +633,7 @@ export function inspectSubagentStatus(params, deps = {}) {
632
633
  status.turnBudget ? `Turn budget: ${status.turnBudget.turnCount}/${status.turnBudget.maxTurns}+${status.turnBudget.graceTurns} (${status.turnBudget.outcome})` : undefined,
633
634
  `Dir: ${asyncDir}`,
634
635
  outputPath ? `Output: ${outputPath}` : undefined,
635
- status.parallelHandoff ? `Parallel handoff: ${status.parallelHandoff.path}` : undefined,
636
+ ...(status.parallelHandoff ? formatParallelHandoffLines(status.parallelHandoff.path, status.parallelHandoff.keptBranches) : []),
636
637
  reconciliation.message ? `Diagnosis: ${reconciliation.message}` : undefined,
637
638
  reconciliation.resultPath && fs.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : undefined,
638
639
  ].filter((line) => Boolean(line));
@@ -807,7 +808,7 @@ export function inspectSubagentStatus(params, deps = {}) {
807
808
  const runId = data.runId ?? data.id ?? resolvedId;
808
809
  const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line) => Boolean(line));
809
810
  if (data.parallelHandoff?.path)
810
- lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
811
+ lines.push(...formatParallelHandoffLines(data.parallelHandoff.path, data.parallelHandoff.keptBranches));
811
812
  const receipt = data.workflowReceipt;
812
813
  const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
813
814
  ? receipt.path : undefined;
@@ -14,6 +14,7 @@ export function buildRunnerChildLaunch(step, ctx, attempt) {
14
14
  machine: step.machine,
15
15
  remoteSkillNames: step.skills,
16
16
  remoteReads: step.remoteReads,
17
+ acceptancePrompt,
17
18
  parentSessionId: step.parentSessionId,
18
19
  parentSessionFile: step.parentSessionFile,
19
20
  forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,
@@ -44,7 +44,7 @@ import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/c
44
44
  import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, formatStructuredOutputRejectionError, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.js";
45
45
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit, isUnexplainedProcessSignal } from "../shared/process-signal.js";
46
46
  import { formatChildToolDiagnostic } from "../shared/tool-availability.js";
47
- import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
47
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, remoteMutationEvidence, remoteMutationSnapshot, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
48
48
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.js";
49
49
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.js";
50
50
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.js";
@@ -79,7 +79,7 @@ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.js";
79
79
  import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.js";
80
80
  import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
81
81
  import { formatHerdrMachineHint, prepareHerdrMachineExternalCliRun } from "../shared/herdr-machine.js";
82
- import { isRexLocalMachine } from "../shared/rex-machine.js";
82
+ import { editsLocalDisk } from "../shared/rex-machine.js";
83
83
  import { HerdrExternalNeedsAttentionError, createHerdrExternalAdapter, prepareInternalHerdrExternalAdapter } from "../shared/herdr-external-adapters.js";
84
84
  import { runExternalJob } from "../shared/external-job-runner.js";
85
85
  import { createOrcaProgressTab } from "../shared/orca-progress-tabs.js";
@@ -606,6 +606,8 @@ export async function runSingleStepInner(step, ctx) {
606
606
  if (step.machine) {
607
607
  if (step.machine.provider !== "herdr")
608
608
  throw new Error("Rex supports native Pi children only.");
609
+ if (!("target" in step.machine))
610
+ throw new Error("Machine 'local' runs native Pi children only.");
609
611
  const runner = resolveExternalCliRunnerStatus({ ...step.runner, machine: step.machine });
610
612
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
611
613
  const placedRunId = `${ctx.id}-${ctx.flatIndex}`;
@@ -762,7 +764,7 @@ export async function runSingleStepInner(step, ctx) {
762
764
  }
763
765
  const effectiveCwd = step.cwd ?? ctx.cwd;
764
766
  // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
765
- const cwdError = step.machine && !isRexLocalMachine(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
767
+ const cwdError = step.machine && !editsLocalDisk(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
766
768
  if (cwdError)
767
769
  return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
768
770
  if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
@@ -781,7 +783,7 @@ export async function runSingleStepInner(step, ctx) {
781
783
  let toolBudgetBlocked = false;
782
784
  let actualLaunchContractDigest = step.launchContractDigest;
783
785
  // A machine 'local' child edits this disk, so its local Git evidence is authoritative, as for an unplaced run.
784
- const mutationSnapshot = step.machine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, cwd: step.cwd ?? ctx.cwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
786
+ const mutationSnapshot = step.machine && !editsLocalDisk(step.machine) ? remoteMutationSnapshot(step.cwd ?? ctx.cwd) : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
785
787
  let finalMutationEvidence = await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
786
788
  let contextOverflow = false;
787
789
  let launchWarningsEmitted = false;
@@ -944,7 +946,9 @@ export async function runSingleStepInner(step, ctx) {
944
946
  // A parked run still owes output diagnostics when it actually finishes.
945
947
  // Stopped/timedOut runs already have terminal failures, so terminal output diagnostics are deferred.
946
948
  const terminalDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
947
- const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
949
+ const recordedToolDiagnostic = launch.capture.toolDiagnostic();
950
+ // An undeclared allowlisted tool aborts the child itself, so its diagnostic explains that abort's error.
951
+ const toolDiagnostic = (run.exitCode === 0 && !run.error) || recordedToolDiagnostic?.undeclared ? recordedToolDiagnostic : undefined;
948
952
  const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
949
953
  const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
950
954
  const midToolExitError = run.currentTool
@@ -1007,8 +1011,7 @@ export async function runSingleStepInner(step, ctx) {
1007
1011
  const truncatedResponseError = hiddenError && !hiddenError.hasError && !validatedStructuredOutput && getTerminalAssistantStopReason(run.messages) === "length"
1008
1012
  ? TRUNCATED_RESPONSE_ERROR
1009
1013
  : undefined;
1010
- const remoteGitChanged = run.nativeMachine?.initialGit && run.nativeMachine.finalGit ? run.nativeMachine.initialGit.head !== run.nativeMachine.finalGit.head || run.nativeMachine.initialGit.dirty !== run.nativeMachine.finalGit.dirty : undefined;
1011
- const mutationEvidence = run.nativeMachine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1014
+ const mutationEvidence = run.nativeMachine && !editsLocalDisk(step.machine) ? remoteMutationEvidence(run.nativeMachine) : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1012
1015
  finalMutationEvidence = mutationEvidence;
1013
1016
  const mutationAttemptObserved = run.observedMutationAttempt === true || mutationEvidence.attemptedMutation === true;
1014
1017
  // Validated structured output is persistable file content even when the final text is only
@@ -1289,7 +1292,7 @@ async function runSingleStep(step, ctx) {
1289
1292
  }
1290
1293
  function externalRunnerStatus(runner, machine) {
1291
1294
  if (runner?.type === "external-cli") {
1292
- return resolveExternalCliRunnerStatus(machine?.provider === "herdr" ? { ...runner, machine } : runner);
1295
+ return resolveExternalCliRunnerStatus(machine?.provider === "herdr" && "target" in machine ? { ...runner, machine } : runner);
1293
1296
  }
1294
1297
  if (runner?.type === "external-job") {
1295
1298
  return {
@@ -27,7 +27,7 @@ import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/
27
27
  import { formatChildToolDiagnostic } from "../shared/tool-availability.js";
28
28
  import { formatChildModelResolutionDiagnostic, formatInheritedProviderDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.js";
29
29
  import { planAbortRecovery } from "../shared/abort-recovery.js";
30
- import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
30
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, remoteMutationEvidence, remoteMutationSnapshot, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
31
31
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, isSettlementFatalOutputError, resolveSingleOutput, validateFileOnlyOutputMode } from "../shared/single-output.js";
32
32
  import { formatSubagentModelVerificationError, isContextOverflow, resolveModelSelection, } from "../shared/model-resolution.js";
33
33
  import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
@@ -44,7 +44,7 @@ import { buildInProcessChildLaunch, createReportedChildSessionInput } from "../s
44
44
  import { childSessionFactory, childSessionHasQueuedMessages, projectChildSessionEventForJson } from "../shared/child-session.js";
45
45
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.js";
46
46
  import { clearProviderRetry, observeProviderDiagnostics, snapshotProviderDiagnostics } from "../../shared/provider-diagnostics.js";
47
- import { isRexLocalMachine } from "../shared/rex-machine.js";
47
+ import { editsLocalDisk } from "../shared/rex-machine.js";
48
48
  import { pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
49
49
  const artifactOutputByResult = new WeakMap();
50
50
  const acceptanceOutputByResult = new WeakMap();
@@ -278,6 +278,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
278
278
  machine: options.machine,
279
279
  remoteSkillNames: options.skills ?? agent.skills,
280
280
  remoteReads: options.remoteReads,
281
+ acceptancePrompt: shared.acceptancePrompt,
281
282
  extensionBindings: options.extensionBindings,
282
283
  requiredExtensions: options.requiredExtensions,
283
284
  sessionEnabled: shared.sessionEnabled,
@@ -399,6 +400,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
399
400
  index: options.index ?? 0,
400
401
  agent: agent.name,
401
402
  ...(childSessionName ? { sessionName: childSessionName } : {}),
403
+ ...(options.sessionFile ? { sessionFile: options.sessionFile } : {}),
402
404
  status: "running",
403
405
  task,
404
406
  skills: shared.resolvedSkillNames,
@@ -447,8 +449,8 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
447
449
  return result;
448
450
  }
449
451
  // A machine 'local' child edits this disk, so its local Git evidence is authoritative, as for an unplaced run.
450
- const mutationCwd = isRexLocalMachine(options.machine) ? options.machine.cwd : options.cwd ?? runtimeCwd;
451
- const mutationSnapshot = options.machine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, cwd: mutationCwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(mutationCwd);
452
+ const mutationCwd = editsLocalDisk(options.machine) ? options.machine.cwd : options.cwd ?? runtimeCwd;
453
+ const mutationSnapshot = options.machine && !editsLocalDisk(options.machine) ? remoteMutationSnapshot(mutationCwd) : snapshotTrackedMutations(mutationCwd);
452
454
  let structuredOutputToolInvoked = false;
453
455
  let structuredOutputMessageStartIndex;
454
456
  let toolAvailabilityError;
@@ -1574,8 +1576,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1574
1576
  tokens: progress.tokens,
1575
1577
  durationMs: progress.durationMs,
1576
1578
  };
1577
- const remoteGitChanged = result.nativeMachine?.initialGit && result.nativeMachine.finalGit ? result.nativeMachine.initialGit.head !== result.nativeMachine.finalGit.head || result.nativeMachine.initialGit.dirty !== result.nativeMachine.finalGit.dirty : undefined;
1578
- const mutationEvidence = result.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1579
+ const mutationEvidence = result.nativeMachine && !editsLocalDisk(options.machine) ? remoteMutationEvidence(result.nativeMachine) : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1579
1580
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1580
1581
  const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1581
1582
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1678,7 +1679,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
1678
1679
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
1679
1680
  const effectiveCwd = options.cwd ?? runtimeCwd;
1680
1681
  // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
1681
- const cwdError = options.machine && !isRexLocalMachine(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1682
+ const cwdError = options.machine && !editsLocalDisk(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1682
1683
  if (cwdError) {
1683
1684
  return redactResultPrompt(withRunContext({
1684
1685
  index: options.index ?? 0,
@@ -3372,6 +3372,21 @@ function writeWorkflowAggregateOutput(outputPath, text, producedChildOutputPaths
3372
3372
  return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3373
3373
  }
3374
3374
  }
3375
+ /**
3376
+ * Runs once as the script starts, never at the end: another run sharing the path may publish its report meanwhile,
3377
+ * and a failing run must not delete it.
3378
+ */
3379
+ function removeEarlierWorkflowOutput(outputPath) {
3380
+ if (!outputPath)
3381
+ return undefined;
3382
+ try {
3383
+ fs.rmSync(outputPath, { force: true });
3384
+ return undefined;
3385
+ }
3386
+ catch (error) {
3387
+ return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3388
+ }
3389
+ }
3375
3390
  function appendWorkflowOutputWarning(text, warning) {
3376
3391
  return warning ? `${text}\n\n${warning}` : text;
3377
3392
  }
@@ -5787,6 +5802,8 @@ export function createSubagentExecutor(deps) {
5787
5802
  step.async = runId !== undefined && path.basename(runId) === runId && fs.existsSync(path.join(path.dirname(asyncDir), runId));
5788
5803
  persist({ tolerateStatusWriteFailure: true });
5789
5804
  };
5805
+ // A relaunch never deletes: a child of the interrupted run, settled or still finishing when Pi exited, may have saved its report there, and a stale file is better than a lost one.
5806
+ const earlierOutputWarning = workflowReuseSource ? undefined : removeEarlierWorkflowOutput(workflowAggregateOutputPath);
5790
5807
  try {
5791
5808
  const workflow = await runWorkflowScript({
5792
5809
  script: workflowScript,
@@ -6139,7 +6156,10 @@ export function createSubagentExecutor(deps) {
6139
6156
  const terminalSummary = `${status.state === "complete"
6140
6157
  ? "Workflow completed after detached child finished."
6141
6158
  : errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6142
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
6159
+ // Only completion writes the declared file, so its existence never reads as a delivered report.
6160
+ const outputWarning = status.state === "complete"
6161
+ ? writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths)
6162
+ : earlierOutputWarning;
6143
6163
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
6144
6164
  const receiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
6145
6165
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
@@ -6227,6 +6247,7 @@ export function createSubagentExecutor(deps) {
6227
6247
  const liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "running", inventoryComplete: false, trace: liveWorkflow.trace, progress: childProgress, launches: childLaunches });
6228
6248
  onUpdate?.(workflowProgressUpdate(foregroundWorkflowRunId, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight));
6229
6249
  };
6250
+ const earlierOutputWarning = removeEarlierWorkflowOutput(workflowAggregateOutputPath);
6230
6251
  try {
6231
6252
  const workflow = await runWorkflowScript({
6232
6253
  script: requestParams.workflowScript,
@@ -6322,7 +6343,11 @@ export function createSubagentExecutor(deps) {
6322
6343
  (deps.state.blockingWorkflowChildren ??= new Set()).add(launch.runId);
6323
6344
  blockingWorkflowChildren.add(launch.runId);
6324
6345
  }
6325
- childLaunches.set(key, { agent: launch.agent, ...(launch.runId ? { runId: launch.runId } : {}) });
6346
+ childLaunches.set(key, {
6347
+ agent: launch.agent,
6348
+ ...(launch.runId ? { runId: launch.runId } : {}),
6349
+ ...(launch.sessionFile ? { sessionFile: launch.sessionFile } : {}),
6350
+ });
6326
6351
  // Telemetry must not decide the child's outcome, as with onTrace in scripted-workflow.
6327
6352
  try {
6328
6353
  sendWorkflowProgress();
@@ -6423,7 +6448,7 @@ export function createSubagentExecutor(deps) {
6423
6448
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
6424
6449
  const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
6425
6450
  const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
6426
- const displayText = formatWorkflowResultText({
6451
+ const displayText = appendWorkflowOutputWarning(formatWorkflowResultText({
6427
6452
  head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
6428
6453
  script: [
6429
6454
  `Workflow failed: ${text}`,
@@ -6436,10 +6461,11 @@ export function createSubagentExecutor(deps) {
6436
6461
  ...(outputMappings ? [outputMappings] : []),
6437
6462
  ],
6438
6463
  maxOutput: requestParams.maxOutput,
6439
- aggregateOutputPath: workflowAggregateOutputPath,
6464
+ // A failed workflow's text never goes to the declared output file; truncated text goes to the full-result file.
6465
+ aggregateOutputPath: undefined,
6440
6466
  fullResultPath: workflowFullResultPath,
6441
6467
  producedChildOutputPaths,
6442
- });
6468
+ }), earlierOutputWarning);
6443
6469
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6444
6470
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
6445
6471
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
@@ -26,6 +26,8 @@ export interface BuildInProcessChildLaunchInput {
26
26
  machine?: PlacementMachineReference;
27
27
  remoteSkillNames?: string[];
28
28
  remoteReads?: string[] | false;
29
+ /** Acceptance instructions already folded into `systemPrompt`; a placed child gets only these, since it builds the rest from its own agent file. */
30
+ acceptancePrompt?: string;
29
31
  parentSessionId?: string;
30
32
  /** The launching session's file; a new child session records it as its parent. */
31
33
  parentSessionFile?: string;
@@ -218,7 +218,7 @@ export function buildInProcessChildLaunch(input) {
218
218
  cwd: input.cwd,
219
219
  ...(input.machine ? { machine: input.machine } : {}),
220
220
  ...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
221
- ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
221
+ ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}), ...(input.acceptancePrompt ? { acceptancePrompt: input.acceptancePrompt } : {}) } } : {}),
222
222
  storage: childStorage(input),
223
223
  ...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
224
224
  ...(input.model ? { model: input.model } : {}),
@@ -37,12 +37,13 @@ export interface ChildSessionLaunch {
37
37
  projectTrusted?: boolean;
38
38
  /** Process-local provider source owned by the invoking foreground parent. */
39
39
  parentProviderRegistry?: ParentProviderRegistry;
40
- /** Logical names resolved only by the remote ambient package. */
40
+ /** Logical names resolved only by the remote ambient package, plus the parent's acceptance instructions, which no remote file holds. */
41
41
  remoteResources?: {
42
42
  agent: string;
43
43
  skills?: string[];
44
44
  toolCeiling?: string[];
45
45
  reads?: string[] | false;
46
+ acceptancePrompt?: string;
46
47
  };
47
48
  storage: ChildSessionStorage;
48
49
  /** The launching session's file, recorded as the new child session's `parentSession` header like Pi's forks. */
@@ -37,7 +37,13 @@ export interface HerdrForwardedConnection {
37
37
  type SshTarget = Pick<HerdrMachineReference, "target">;
38
38
  export declare function decodeHerdrJsonLine(line: Buffer): unknown;
39
39
  export declare function shellQuoteRemote(value: string): string;
40
+ export declare function shellScriptCommand(script: string, args?: string[]): string;
40
41
  export declare function remoteShellCommand(script: string, args?: string[]): string;
42
+ /**
43
+ * Points herdr at a recorded local server only: the calling process's own pane selectors (a background runner started from
44
+ * another pane) never choose it. A named session's server reports its name only when HERDR_SESSION says it (herdr 0.9.5).
45
+ */
46
+ export declare function herdrLocalEnv(socket: string, session: string | null | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
41
47
  export declare function runHerdrRemoteCommand(machine: SshTarget, command: string, options?: {
42
48
  sshBin?: string;
43
49
  env?: NodeJS.ProcessEnv;