pi-subagents 0.89.0 → 0.89.2

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 (79) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-TGABNSG5.js → chunk-2UCFLUE4.js} +64 -12
  5. package/bundle/{chunk-7W2IQFP4.js → chunk-464OJSDP.js} +4 -4
  6. package/bundle/{chunk-ETDE2VYK.js → chunk-4KQW5R6U.js} +2 -2
  7. package/bundle/{chunk-JRO2CU4D.js → chunk-5TXWZB73.js} +1 -1
  8. package/bundle/{chunk-7J4ZXMY7.js → chunk-72334PEI.js} +6 -4
  9. package/bundle/{chunk-CHEABMO2.js → chunk-76WVWEFE.js} +33 -24
  10. package/bundle/{chunk-S77ZKDLS.js → chunk-77VQEATI.js} +1 -1
  11. package/bundle/{chunk-HZDLR73C.js → chunk-AHGJSJYY.js} +4 -3
  12. package/bundle/{chunk-4ALRHKGE.js → chunk-DGLXVN3F.js} +1 -1
  13. package/bundle/{chunk-SLLZJ5EC.js → chunk-DHY5TY2Y.js} +237 -199
  14. package/bundle/{chunk-2I6YN6ET.js → chunk-DYBRIEIF.js} +8 -8
  15. package/bundle/{chunk-NQ26PJSQ.js → chunk-FF5K5HQU.js} +11 -6
  16. package/bundle/{chunk-HSHLPYCQ.js → chunk-FO2GIU5F.js} +27 -18
  17. package/bundle/{chunk-JFACGAJT.js → chunk-JEYG7CNC.js} +8 -4
  18. package/bundle/{chunk-X5ZOTDHO.js → chunk-KA4MKMYT.js} +11 -11
  19. package/bundle/{chunk-GHJ6BH5U.js → chunk-LWH7IGI3.js} +8 -0
  20. package/bundle/{chunk-AZW4HXNU.js → chunk-ME4IS3Y3.js} +99 -30
  21. package/bundle/{chunk-UQT2EQ4U.js → chunk-Q4VH72JI.js} +2 -2
  22. package/bundle/{chunk-443LPCRI.js → chunk-RHKIP45B.js} +6 -6
  23. package/bundle/{chunk-PPPAEFRA.js → chunk-ROJH7KPK.js} +2 -2
  24. package/bundle/{chunk-WW6GQBBS.js → chunk-SRCMJY4F.js} +4 -4
  25. package/bundle/{chunk-KOLLMZ2X.js → chunk-SWGB2P5J.js} +1 -1
  26. package/bundle/{chunk-ZSCIHMUI.js → chunk-TXC7WIPL.js} +3 -2
  27. package/bundle/{chunk-6JD4XCA4.js → chunk-U753SUBC.js} +14 -6
  28. package/bundle/{chunk-YX7R55CR.js → chunk-UBPAMRVL.js} +12 -12
  29. package/bundle/{chunk-A3INCQ6Z.js → chunk-UUW7P6KJ.js} +1 -1
  30. package/bundle/{chunk-EPMRDKQT.js → chunk-VEEUXJDO.js} +1 -1
  31. package/bundle/{chunk-NONHDYXE.js → chunk-YJIU5WF4.js} +1 -1
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +4 -4
  37. package/docs/agents.md +2 -2
  38. package/docs/observability.md +3 -1
  39. package/docs/watchdog.md +3 -2
  40. package/package.json +1 -1
  41. package/src/api/preflight.d.ts +1 -0
  42. package/src/api/preflight.js +2 -1
  43. package/src/extension/herdr-pi-bridge.js +1 -1
  44. package/src/inspectors/herdr/project-panes.d.ts +2 -0
  45. package/src/inspectors/herdr/project-panes.js +7 -1
  46. package/src/inspectors/shell-command.d.ts +2 -1
  47. package/src/inspectors/shell-command.js +7 -5
  48. package/src/runs/background/active-async-capacity.js +2 -1
  49. package/src/runs/background/active-run-index.d.ts +1 -0
  50. package/src/runs/background/active-run-index.js +3 -0
  51. package/src/runs/background/async-execution.d.ts +2 -0
  52. package/src/runs/background/async-execution.js +3 -2
  53. package/src/runs/background/async-job-tracker.js +85 -9
  54. package/src/runs/background/async-status.d.ts +2 -0
  55. package/src/runs/background/async-status.js +8 -3
  56. package/src/runs/background/process-terminal.d.ts +6 -0
  57. package/src/runs/background/process-terminal.js +34 -2
  58. package/src/runs/background/run-status.js +2 -1
  59. package/src/runs/background/stale-run-reconciler.d.ts +8 -0
  60. package/src/runs/background/stale-run-reconciler.js +38 -8
  61. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  62. package/src/runs/background/workflow-terminal-proof.js +4 -4
  63. package/src/runs/foreground/execution.js +2 -2
  64. package/src/runs/foreground/subagent-executor.d.ts +2 -0
  65. package/src/runs/foreground/subagent-executor.js +10 -1
  66. package/src/runs/shared/herdr-machine.js +3 -1
  67. package/src/runs/shared/herdr-pane-host.js +10 -2
  68. package/src/runs/shared/mcp-config-sources.d.ts +1 -0
  69. package/src/runs/shared/mcp-config-sources.js +1 -1
  70. package/src/runs/shared/mcp-direct-tool-allowlist.js +1 -0
  71. package/src/runs/shared/subagent-prompt-runtime.js +6 -5
  72. package/src/shared/types.d.ts +2 -0
  73. package/src/shared/utils.d.ts +2 -0
  74. package/src/shared/utils.js +9 -0
  75. package/src/tui/fleet-transcript.js +21 -9
  76. package/src/watchdog/runtime.d.ts +4 -0
  77. package/src/watchdog/runtime.js +50 -12
  78. package/src/watchdog/turn-delta.d.ts +2 -0
  79. package/src/watchdog/turn-delta.js +21 -0
@@ -588,7 +588,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
588
588
  // Diagnostic only; process-terminal proof stays authoritative.
589
589
  }
590
590
  // The runner may outlive its wrapper; only a confirmed-dead runner in this pid namespace finalizes here,
591
- // otherwise status-pid reconciliation does it later.
591
+ // otherwise a later status read in the runner's pid namespace records the proof as unknown once its pid is dead.
592
592
  if (!runnerIdentity || runnerIdentity.pidNamespaceScope !== currentPidNamespaceScope()
593
593
  || checkRecordedPidLiveness(runnerIdentity) !== "dead")
594
594
  return;
@@ -1970,6 +1970,7 @@ export function executeAsyncSingle(id, params) {
1970
1970
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1971
1971
  agent,
1972
1972
  task: taskText,
1973
+ ...(params.label ? { label: params.label } : {}),
1973
1974
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
1974
1975
  ...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
1975
1976
  ...(machine ? { machine } : {}),
@@ -2092,7 +2093,7 @@ export function executeAsyncSingle(id, params) {
2092
2093
  chainStepCount: 1,
2093
2094
  ...(lane ? { lane } : {}),
2094
2095
  ...(launcher ? { launcher } : {}),
2095
- steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2096
+ steps: [{ agent, status: "pending", ...(params.label ? { label: params.label } : {}), ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2096
2097
  }, path.join(asyncDir, "status.json"), launchParentSessionId, (proof) => emitProcessTerminalEvent(ctx, proof), (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId), params.requestedCwd ?? runnerCwd);
2097
2098
  }
2098
2099
  catch (error) {
@@ -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,12 @@ export interface RunnerCloseObservation {
8
8
  signal: string | null;
9
9
  }
10
10
  export declare function processTerminalPath(asyncDir: string): string;
11
+ /**
12
+ * A status reader's verdict that a finished run's runner died with no Pi watching it. It is a separate file so a
13
+ * reader can never overwrite the proof the launching Pi writes when it does see the close; it shows only while
14
+ * process-terminal.json is still pending for the same runner.
15
+ */
16
+ export declare function unobservedRunnerExitPath(asyncDir: string): string;
11
17
  /** Establish ownership before authorizing a runner to start any child session. */
12
18
  export declare function initializeProcessTerminal(asyncDir: string, runId: string, runnerProcessInstanceId: string): void;
13
19
  export declare function sanitizeProcessTerminal(value: unknown, fallback: {
@@ -9,6 +9,14 @@ export { processTerminalCandidatePath, readProcessTerminalCandidate, writeProces
9
9
  export function processTerminalPath(asyncDir) {
10
10
  return path.join(asyncDir, "process-terminal.json");
11
11
  }
12
+ /**
13
+ * A status reader's verdict that a finished run's runner died with no Pi watching it. It is a separate file so a
14
+ * reader can never overwrite the proof the launching Pi writes when it does see the close; it shows only while
15
+ * process-terminal.json is still pending for the same runner.
16
+ */
17
+ export function unobservedRunnerExitPath(asyncDir) {
18
+ return path.join(asyncDir, "process-terminal-unobserved.json");
19
+ }
12
20
  function errorMessage(error) {
13
21
  return error instanceof Error ? error.message : String(error);
14
22
  }
@@ -84,11 +92,33 @@ export function sanitizeProcessTerminal(value, fallback, label = "status") {
84
92
  return unknownProof(fallback.runId ?? label, fallback.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
85
93
  }
86
94
  }
95
+ /** Throws for an unreadable or invalid file, like the sidecar it stands in for. */
96
+ function readUnobservedRunnerExit(asyncDir, pending) {
97
+ const filePath = unobservedRunnerExitPath(asyncDir);
98
+ let raw;
99
+ try {
100
+ raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
101
+ }
102
+ catch (error) {
103
+ if (error.code === "ENOENT")
104
+ return undefined;
105
+ throw error;
106
+ }
107
+ // Left behind by an earlier runner instance of this run.
108
+ if (isRecord(raw) && (raw.runId !== pending.runId || raw.runnerProcessInstanceId !== pending.runnerProcessInstanceId))
109
+ return undefined;
110
+ validateProof(raw, filePath);
111
+ const proof = raw;
112
+ if (proof.state !== "unknown" || proof.reason !== "observer-unavailable")
113
+ throw new Error(`Invalid unobserved runner exit in '${asyncDir}'.`);
114
+ return proof;
115
+ }
87
116
  export function readProcessTerminal(asyncDir, fallback) {
88
117
  try {
89
118
  const raw = JSON.parse(fs.readFileSync(processTerminalPath(asyncDir), "utf-8"));
90
119
  validateProof(raw, asyncDir, fallback);
91
- return raw;
120
+ const proof = raw;
121
+ return proof.state === "pending" ? readUnobservedRunnerExit(asyncDir, proof) ?? proof : proof;
92
122
  }
93
123
  catch (error) {
94
124
  if (error.code === "ENOENT")
@@ -136,7 +166,9 @@ export function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
136
166
  if (existing && fs.existsSync(processTerminalPath(asyncDir))) {
137
167
  if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId)
138
168
  return existing;
139
- if (existing.state === "unknown") {
169
+ // A status reader that saw the runner pid dead before this close event fired settled the proof as
170
+ // observer-unavailable; this process did observe the close, so it computes the full proof.
171
+ if (existing.state === "unknown" && existing.reason !== "observer-unavailable") {
140
172
  // A sticky runner-published unknown proof keeps its reason; only add the observed exit. Unreadable or mismatched sidecars read back as proof-write-failed and stay untouched.
141
173
  if (existing.instances?.length || existing.reason === "proof-write-failed")
142
174
  return existing;
@@ -14,7 +14,7 @@ import { readStatus } from "../../shared/utils.js";
14
14
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
15
15
  import { normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
16
16
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.js";
17
- import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.js";
17
+ import { readProcessTerminal, sanitizeProcessTerminal, unobservedRunnerExitPath } from "./process-terminal.js";
18
18
  import { readWorkflowTerminalProof } from "./workflow-terminal-proof.js";
19
19
  import { formatWaitSubscriptions } from "./wait-subscriptions.js";
20
20
  import { resolveAsyncRunLocation } from "./async-resume.js";
@@ -89,6 +89,7 @@ function formatRunLifecycleDebug(input) {
89
89
  `Status file: ${path.join(asyncDir, "status.json")}`,
90
90
  status.workflowReceiptPath ? `Workflow receipt: ${status.workflowReceiptPath}` : undefined,
91
91
  `Process terminal file: ${path.join(asyncDir, "process-terminal.json")}`,
92
+ `Unobserved runner exit file: ${unobservedRunnerExitPath(asyncDir)}`,
92
93
  `Session: ${status.sessionId ?? "unknown"}`,
93
94
  `State: ${status.state}`,
94
95
  `Mode: ${status.mode}`,
@@ -58,5 +58,13 @@ export interface RecordedPidObservation {
58
58
  * macOS host reading a Linux container's runs must not compare their boot ids.
59
59
  */
60
60
  export declare function checkRecordedPidLiveness(recorded: RecordedPid, observation?: RecordedPidObservation): PidLiveness;
61
+ /**
62
+ * Only the Pi process that spawned a runner sees it close and writes its process-terminal proof. When that
63
+ * process is gone, a finished run whose runner is confirmed dead would report a `pending` proof forever.
64
+ * Record it as unknown, never observed: nobody saw the exit. A workflow's pid is its host Pi, not a runner.
65
+ * The verdict goes to its own file, never process-terminal.json, so a close the launching Pi observes after the
66
+ * pending read above still wins.
67
+ */
68
+ export declare function settleUnobservedRunnerExit(asyncDir: string, status: AsyncStatus, observation?: RecordedPidObservation): void;
61
69
  export declare function reconcileAsyncRun(asyncDir: string, options?: ReconcileAsyncRunOptions, observeStatus?: RawDrainStatusObserver): ReconcileAsyncRunResult;
62
70
  export {};
@@ -2,8 +2,8 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { writeAtomicJson } from "../../shared/atomic-json.js";
4
4
  import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "./result-files.js";
5
- import { updateActiveRunIndex } from "./active-run-index.js";
6
- import { readProcessTerminal } from "./process-terminal.js";
5
+ import { isTerminalAsyncState, updateActiveRunIndex } from "./active-run-index.js";
6
+ import { readProcessTerminal, unobservedRunnerExitPath } from "./process-terminal.js";
7
7
  import { OWNING_SESSION_COMPLETION_OWNER } from "../../shared/completion-owner.js";
8
8
  import { readStatus } from "../../shared/utils.js";
9
9
  import { DIRS } from "../../shared/types.js";
@@ -14,7 +14,6 @@ import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.js";
14
14
  import { currentPidNamespaceScope } from "./pid-namespace.js";
15
15
  import { currentBootId } from "./boot-id.js";
16
16
  import { WORKFLOW_STOP_CAUSE_OWNER_EXITED } from "../../workflows/workflow-stop-cause.js";
17
- import { isTerminalAsyncState } from "./workflow-terminal-proof.js";
18
17
  function getErrorMessage(error) {
19
18
  return error instanceof Error ? error.message : String(error);
20
19
  }
@@ -427,6 +426,38 @@ export function checkRecordedPidLiveness(recorded, observation = { observedScope
427
426
  : checkPidLiveness(recorded.pid, observation.kill, scopeVerified);
428
427
  return liveness === "dead" && scopeMismatch ? "unknown" : liveness;
429
428
  }
429
+ /**
430
+ * Only the Pi process that spawned a runner sees it close and writes its process-terminal proof. When that
431
+ * process is gone, a finished run whose runner is confirmed dead would report a `pending` proof forever.
432
+ * Record it as unknown, never observed: nobody saw the exit. A workflow's pid is its host Pi, not a runner.
433
+ * The verdict goes to its own file, never process-terminal.json, so a close the launching Pi observes after the
434
+ * pending read above still wins.
435
+ */
436
+ export function settleUnobservedRunnerExit(asyncDir, status, observation = { observedScope: currentPidNamespaceScope(), observedBootId: currentBootId() }) {
437
+ const runnerProcessInstanceId = status.processTerminal?.runnerProcessInstanceId;
438
+ if (!terminal(status.state) || status.mode === "workflow" || status.processTerminal?.state !== "pending" || !runnerProcessInstanceId)
439
+ return;
440
+ if (typeof status.pid !== "number" || status.pidNamespaceScope !== observation.observedScope)
441
+ return;
442
+ if (readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId })?.state !== "pending")
443
+ return;
444
+ if (checkRecordedPidLiveness({ pid: status.pid, pidNamespaceScope: status.pidNamespaceScope, bootId: status.bootId }, observation) !== "dead")
445
+ return;
446
+ try {
447
+ const proof = {
448
+ version: 1,
449
+ state: "unknown",
450
+ runId: status.runId,
451
+ runnerProcessInstanceId,
452
+ reason: "observer-unavailable",
453
+ diagnostic: `Runner PID ${status.pid} is gone and no Pi recorded its exit.`,
454
+ };
455
+ writeAtomicJson(unobservedRunnerExitPath(asyncDir), proof);
456
+ }
457
+ catch {
458
+ // The proof stays pending; the next status read tries again.
459
+ }
460
+ }
430
461
  export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
431
462
  const now = options.now?.() ?? Date.now();
432
463
  const status = readStatus(asyncDir);
@@ -453,11 +484,10 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
453
484
  const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
454
485
  const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
455
486
  const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
456
- const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
457
- kill: options.kill,
458
- observedScope,
459
- observedBootId: options.bootId ? options.bootId() : currentBootId(),
460
- });
487
+ const observation = { kill: options.kill, observedScope, observedBootId: options.bootId ? options.bootId() : currentBootId() };
488
+ const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, observation);
489
+ if (status)
490
+ settleUnobservedRunnerExit(asyncDir, status, observation);
461
491
  if (existingResultPath) {
462
492
  // A live runner writes its result before its final status; repairing in that window would replace
463
493
  // its pending exit proof with a placeholder. Only a confirmed-alive pid defers: a result is better
@@ -1,5 +1,4 @@
1
1
  import type { AsyncStatus, ProcessTerminal, WorkflowChildSummary, WorkflowTerminalProof } from "../../shared/types.ts";
2
- export declare function isTerminalAsyncState(state: AsyncStatus["state"]): state is Exclude<AsyncStatus["state"], "queued" | "running" | "paused">;
3
2
  /**
4
3
  * The model an async workflow child reports for itself. Workflow lane records keep only
5
4
  * launch identity, so display projections fall back to the child's own status step.
@@ -2,10 +2,9 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { readStatus } from "../../shared/utils.js";
4
4
  import { readProcessTerminal } from "./process-terminal.js";
5
+ import { isTerminalAsyncState } from "./active-run-index.js";
6
+ import { settleUnobservedRunnerExit } from "./stale-run-reconciler.js";
5
7
  const TERMINAL_WORKFLOW_STATES = new Set(["completed", "failed", "stopped"]);
6
- export function isTerminalAsyncState(state) {
7
- return state !== "queued" && state !== "running" && state !== "paused";
8
- }
9
8
  /**
10
9
  * The model an async workflow child reports for itself. Workflow lane records keep only
11
10
  * launch identity, so display projections fall back to the child's own status step.
@@ -83,13 +82,14 @@ export function readWorkflowChildEvidence(workflowAsyncDir, step) {
83
82
  if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
84
83
  return { state: "resolved", proof: recorded };
85
84
  }
85
+ settleUnobservedRunnerExit(childDir, childStatus);
86
86
  const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
87
87
  if (proof?.state !== "observed" || proof.runId !== step.runId) {
88
88
  const proofState = proof?.state ?? "missing";
89
89
  const bound = childStatus.runId === step.runId && typeof recorded.runnerProcessInstanceId === "string";
90
90
  return {
91
91
  state: !proof || proof.state === "pending" ? "pending" : "unknown",
92
- reason: `async workflow child ${label} process-terminal proof is ${proofState}`,
92
+ reason: `async workflow child ${label} process-terminal proof is ${proofState}${proof?.state === "unknown" && proof.reason ? ` (${proof.reason})` : ""}`,
93
93
  ...(bound ? { unresolvedProof: { status: childStatus, proofState } } : {}),
94
94
  };
95
95
  }
@@ -259,7 +259,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
259
259
  // Display name for the child session: applied inside the child through its
260
260
  // runtime config and echoed back on the result payload so hosts can label
261
261
  // this run without reading the child's session file.
262
- const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task });
262
+ const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task, label: options.label });
263
263
  const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
264
264
  const childWatchdog = watchdogConfig.ok
265
265
  ? resolveChildWatchdogConfig({
@@ -1695,7 +1695,7 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1695
1695
  ...options,
1696
1696
  capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), options.childRuntime?.capabilityCeiling),
1697
1697
  };
1698
- const childSessionName = deriveChildSessionName({ agent: agentName, task });
1698
+ const childSessionName = deriveChildSessionName({ agent: agentName, task, label: options.label });
1699
1699
  const agent = agents.find((a) => a.name === agentName);
1700
1700
  if (!agent) {
1701
1701
  const diagnosticContext = options.unknownAgentDiagnosticContext
@@ -79,6 +79,8 @@ export interface SubagentParamsLike {
79
79
  /** Internal workflow ownership metadata; not part of the public schema. */
80
80
  workflowParentRunId?: string;
81
81
  workflowKey?: string;
82
+ /** Workflow child's `runs.run` label, trimmed; names the child's own session instead of a task excerpt. */
83
+ label?: string;
82
84
  lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
83
85
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
84
86
  scheduleOrigin?: ScheduleOrigin;
@@ -3283,6 +3283,8 @@ async function runAsyncPath(data, deps) {
3283
3283
  runFanoutBudget: data.runFanoutBudget,
3284
3284
  parentWorkflowRunId: params.workflowParentRunId,
3285
3285
  workflowKey: params.workflowKey,
3286
+ // Top-level calls pass unknown keys through; only a workflow child's label is normalized.
3287
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3286
3288
  lane: params.lane,
3287
3289
  workflowAwaitAsync: params.workflowAwaitAsync,
3288
3290
  }));
@@ -3880,6 +3882,7 @@ async function runSinglePath(data, deps) {
3880
3882
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3881
3883
  cwd: singleCwd,
3882
3884
  requestedCwd: data.requestedCwd,
3885
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3883
3886
  signal,
3884
3887
  abortedAsStopped: params.workflowParentRunId !== undefined,
3885
3888
  interruptSignal: interruptController.signal,
@@ -4663,6 +4666,12 @@ export function prepareWorkflowLaunchParams(workflowDefaults, childParams, paren
4663
4666
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4664
4667
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
4665
4668
  };
4669
+ // Scripts pass `label` unchecked; keep only a non-empty string so session naming can trust the field.
4670
+ const label = typeof childParams.label === "string" ? childParams.label.trim() : "";
4671
+ if (label)
4672
+ launchParams.label = label;
4673
+ else
4674
+ delete launchParams.label;
4666
4675
  if (launchParams.extensionBindings !== undefined)
4667
4676
  launchParams.extensionBindings = normalizeExtensionBindings(launchParams.extensionBindings).value;
4668
4677
  const normalizedGate = normalizeGateParams(launchParams);
@@ -7793,7 +7802,7 @@ export function createSubagentExecutor(deps) {
7793
7802
  if (workflowLaunchObserver) {
7794
7803
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
7795
7804
  const singleSessionName = hasSingle
7796
- ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task })
7805
+ ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task, label: effectiveParams.label })
7797
7806
  : singleTask
7798
7807
  ? deriveChildSessionName({ agent: singleTask.agent, task: singleTask.task })
7799
7808
  : undefined;
@@ -251,7 +251,9 @@ export function resolveMachinePlacement(input) {
251
251
  return { machine: resolveHerdrLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, herdrBin: input.herdrBin }) };
252
252
  if (env.REX_SESSION?.trim())
253
253
  return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env }) };
254
- throw new Error("Machine 'local' opens the child in a new tab of the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID) nor Rex (REX_SESSION).");
254
+ // Herdr Core (`hc`, the Herdr app's terminal server) is a different product from the herdr multiplexer, with a different CLI and protocol.
255
+ const core = env.HC_TERMINAL_ID?.trim() ? " It runs in a Herdr Core terminal (HC_TERMINAL_ID), which machine 'local' does not support." : "";
256
+ throw new Error(`Machine 'local' opens the child in a new tab of the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID) nor Rex (REX_SESSION).${core}`);
255
257
  }
256
258
  if (settings?.rex)
257
259
  return { machine: { provider: "rex", id: requested, target: settings.rex.ssh, cwd: validateRemoteCwd(remoteMachineCwd(input.stepCwd, settings.cwd, requested), requested) } };
@@ -121,7 +121,7 @@ export const herdrPaneHost = {
121
121
  async launch(connection, machine, runId, runtimeDir, request, onPane, options) { const owned = await provisionHerdrOwnedPane(connection, asHerdrMachine(machine), runId, runtimeDir, request.environment); await onPane(owned); const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options); return { owned, terminalId }; },
122
122
  async prompt(connection, identity, text, options = {}) {
123
123
  // Herdr registers a started agent's name asynchronously, so a prompt right after start can be refused; a refused prompt was not delivered.
124
- const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 100;
124
+ const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 20_000), pollMs = options.pollMs ?? 100;
125
125
  for (;;) {
126
126
  try {
127
127
  await connection.client.call("agent.prompt", { target: identity.agentName, text });
@@ -130,7 +130,15 @@ export const herdrPaneHost = {
130
130
  catch (error) {
131
131
  if (!(error instanceof Error) || !error.message.includes("is not an active named agent") || clock.now() >= deadline)
132
132
  throw error;
133
- await clock.wait(Math.min(pollMs, deadline - clock.now()));
133
+ const remainingMs = deadline - clock.now();
134
+ // Over RPC, agent.start returns with launch_pending and Herdr refuses prompts until the agent is observed ready; agent.wait blocks until then.
135
+ // A failed wait (older Herdr, name not registered yet, wait timeout) falls back to polling; the refusal stays the error reported at the deadline.
136
+ try {
137
+ await connection.client.call("agent.wait", { target: identity.agentName, until: ["idle", "done"], timeout_ms: remainingMs }, remainingMs + 5_000);
138
+ }
139
+ catch { }
140
+ // agent.wait returns at once for an idle agent that Herdr still holds as launch-pending, so always pause before the next prompt.
141
+ await clock.wait(Math.min(pollMs, Math.max(0, deadline - clock.now())));
134
142
  if (options.stopped?.())
135
143
  throw new Error("Remote Pi prompt was not sent because the run was stopped.", { cause: error });
136
144
  }
@@ -28,6 +28,7 @@ export interface McpServerDefinition {
28
28
  pluginDataDir?: string;
29
29
  literalEnv?: boolean;
30
30
  inheritEnv?: boolean;
31
+ openUi?: boolean;
31
32
  /** Only literal true disables a server, matching pi-mcp-adapter. */
32
33
  disabled?: boolean;
33
34
  }
@@ -25,7 +25,7 @@ export function isMcpServerDefinition(value) {
25
25
  if (value[field] !== undefined && !isStringRecord(value[field]))
26
26
  return false;
27
27
  }
28
- for (const field of ["exposeResources", "literalEnv", "inheritEnv"]) {
28
+ for (const field of ["exposeResources", "literalEnv", "inheritEnv", "openUi"]) {
29
29
  if (value[field] !== undefined && typeof value[field] !== "boolean")
30
30
  return false;
31
31
  }
@@ -407,6 +407,7 @@ export function computeMcpServerHash(definition) {
407
407
  includeTools: definition.includeTools,
408
408
  excludeTools: definition.excludeTools,
409
409
  protocolVersion: definition.protocolVersion,
410
+ ...(definition.openUi === false ? { openUi: false } : {}),
410
411
  };
411
412
  return createHash("sha256").update(stableStringify(identity)).digest("hex");
412
413
  }