@vicary/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-7W2IQFP4.js → chunk-464OJSDP.js} +4 -4
  5. package/bundle/{chunk-ETDE2VYK.js → chunk-4KQW5R6U.js} +2 -2
  6. package/bundle/{chunk-PFZZMVD5.js → chunk-4X3T5CPK.js} +12 -12
  7. package/bundle/{chunk-JRO2CU4D.js → chunk-5TXWZB73.js} +1 -1
  8. package/bundle/{chunk-CFIYO2IV.js → chunk-62OHSCQ6.js} +64 -12
  9. package/bundle/{chunk-7J4ZXMY7.js → chunk-72334PEI.js} +6 -4
  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-OVBUEVOT.js → chunk-DNDNLHTL.js} +11 -11
  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-7JLNWAMO.js → chunk-LODNNILA.js} +99 -30
  19. package/bundle/{chunk-GHJ6BH5U.js → chunk-LWH7IGI3.js} +8 -0
  20. package/bundle/{chunk-UQT2EQ4U.js → chunk-Q4VH72JI.js} +2 -2
  21. package/bundle/{chunk-443LPCRI.js → chunk-RHKIP45B.js} +6 -6
  22. package/bundle/{chunk-SWL2EITY.js → chunk-RHMU7SXN.js} +2 -2
  23. package/bundle/{chunk-WW6GQBBS.js → chunk-SRCMJY4F.js} +4 -4
  24. package/bundle/{chunk-KOLLMZ2X.js → chunk-SWGB2P5J.js} +1 -1
  25. package/bundle/{chunk-ZSCIHMUI.js → chunk-TXC7WIPL.js} +3 -2
  26. package/bundle/{chunk-6JD4XCA4.js → chunk-U753SUBC.js} +14 -6
  27. package/bundle/{chunk-A3INCQ6Z.js → chunk-UUW7P6KJ.js} +1 -1
  28. package/bundle/{chunk-MJHQIUU7.js → chunk-V4543APA.js} +33 -24
  29. package/bundle/{chunk-EPMRDKQT.js → chunk-VEEUXJDO.js} +1 -1
  30. package/bundle/{chunk-LEPIY76E.js → chunk-W7NDPDDJ.js} +8 -8
  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 +2 -2
  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
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@vicary/pi-subagents",
4
- "version": "0.89.0",
4
+ "version": "0.89.2",
5
5
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
6
6
  "author": "Nico Bailon",
7
7
  "license": "MIT",
@@ -135,5 +135,5 @@
135
135
  "./prompts"
136
136
  ]
137
137
  },
138
- "gitHead": "0551e1ca035818cefc5493b2a00ca7f7c7e1ec51"
138
+ "gitHead": "b760b32414835f0e07937227525205e321329a04"
139
139
  }
@@ -141,6 +141,7 @@ export interface SubagentLaunchContractRoots {
141
141
  eventsPath: string;
142
142
  processTerminalPath: string;
143
143
  processTerminalCandidatePath: string;
144
+ unobservedRunnerExitPath: string;
144
145
  };
145
146
  }
146
147
  export interface SubagentLaunchContract {
@@ -22,7 +22,7 @@ import { loadConfig } from "../extension/config.js";
22
22
  import { applyIntercomBridgeToAgent, resolveIntercomBridge, validateIntercomBridgeConfig } from "../intercom/intercom-bridge.js";
23
23
  import { AGENT_DEFINITION_PROJECTION_VERSION, resolveLaunchBinding, stableJsonDigest } from "../shared/launch-contract.js";
24
24
  import { DIRS, TEMP_ROOT_DIR } from "../shared/types.js";
25
- import { processTerminalCandidatePath, processTerminalPath } from "../runs/background/process-terminal.js";
25
+ import { processTerminalCandidatePath, processTerminalPath, unobservedRunnerExitPath } from "../runs/background/process-terminal.js";
26
26
  import { resultFilePath } from "../runs/background/result-files.js";
27
27
  import { nestedResultsPath } from "../runs/shared/nested-events.js";
28
28
  import { normalizeExtensionBindings } from "../runs/shared/extension-bindings.js";
@@ -398,6 +398,7 @@ export async function resolveSubagentLaunchContract(input) {
398
398
  eventsPath: path.join(lifecycleAsyncDir, "events.jsonl"),
399
399
  processTerminalPath: processTerminalPath(lifecycleAsyncDir),
400
400
  processTerminalCandidatePath: processTerminalCandidatePath(lifecycleAsyncDir),
401
+ unobservedRunnerExitPath: unobservedRunnerExitPath(lifecycleAsyncDir),
401
402
  },
402
403
  },
403
404
  protocol: {
@@ -171,7 +171,7 @@ export default function registerHerdrPiBridge(pi) {
171
171
  else if (request.operation === "follow-up")
172
172
  api.sendUserMessage(request.text ?? "", { deliverAs: "followUp" });
173
173
  else if (request.operation === "abort")
174
- api.abort();
174
+ ctx.abort();
175
175
  else {
176
176
  const entry = request.supervisorId ? supervisor.get(request.supervisorId) : undefined;
177
177
  if (!entry)
@@ -1,6 +1,7 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import type { Details, SubagentState } from "../../shared/types.ts";
3
3
  import { type HerdrClient, type HerdrErrorCode } from "./client.ts";
4
+ import { type ShellFlavor } from "../shell-command.ts";
4
5
  export declare const HERDR_PROJECT_PANE_ACTIONS: readonly ["project.open", "project.status", "project.close"];
5
6
  export type HerdrProjectPaneAction = typeof HERDR_PROJECT_PANE_ACTIONS[number];
6
7
  /** Versioned public contract exported through `pi-subagents/project-panes`. */
@@ -127,6 +128,7 @@ export declare function readHerdrProjectPaneBinding(projectRoot: string): HerdrP
127
128
  /** Strict public reader for extension integrations. */
128
129
  export declare function readProjectPaneBinding(projectRoot: string): ProjectPaneResult<HerdrProjectPaneBinding | undefined>;
129
130
  export declare function restoreHerdrProjectPaneSnapshots(state: SubagentState, projectRoots: Iterable<string>, now?: number): void;
131
+ export declare function projectPaneShellFlavor(platform: NodeJS.Platform, shell: string | undefined): ShellFlavor;
130
132
  export declare function createProjectPaneManager(options?: ProjectPaneManagerOptions): ProjectPaneManager;
131
133
  export declare function openProjectPane(options: OpenProjectPaneOptions): Promise<ProjectPaneResult<OpenProjectPaneData>>;
132
134
  export declare function getProjectPaneStatus(options: GetProjectPaneStatusOptions): Promise<ProjectPaneResult<ProjectPaneStatusData>>;
@@ -254,10 +254,16 @@ async function inspectPane(client, paneId, signal) {
254
254
  return projectPaneError("INVALID_PANE_RESPONSE", `Herdr pane get returned no pane runtime for '${paneId}'.`, { details: live.data });
255
255
  return { ok: true, data: runtime };
256
256
  }
257
+ export function projectPaneShellFlavor(platform, shell) {
258
+ // Herdr types the command into the pane's own shell: Git Bash on Windows cannot parse PowerShell's `&` call operator.
259
+ if (platform !== "win32")
260
+ return "auto";
261
+ return /(^|[\\/])(bash|zsh|sh|dash|ksh)(\.exe)?$/i.test(shell ?? "") ? "posix" : "auto";
262
+ }
257
263
  function projectPaneCommand(message) {
258
264
  const args = message?.trim() ? [message.trim()] : [];
259
265
  const command = getPiSpawnCommand(args);
260
- return formatShellCommand(command.command, command.args);
266
+ return formatShellCommand(command.command, command.args, process.platform, projectPaneShellFlavor(process.platform, process.env.SHELL));
261
267
  }
262
268
  function canonicalRuntimePath(value) {
263
269
  if (!value)
@@ -1 +1,2 @@
1
- export declare function formatShellCommand(exe: string, args: readonly string[], platform?: NodeJS.Platform): string;
1
+ export type ShellFlavor = "auto" | "posix";
2
+ export declare function formatShellCommand(exe: string, args: readonly string[], platform?: NodeJS.Platform, flavor?: ShellFlavor): string;
@@ -6,11 +6,13 @@ function shellQuote(value, platform) {
6
6
  function isBareExecutable(value) {
7
7
  return /^[\w./@:-]+$/.test(value);
8
8
  }
9
- export function formatShellCommand(exe, args, platform = process.platform) {
10
- const quotedArgs = args.map((arg) => shellQuote(arg, platform));
11
- if (platform === "win32")
12
- return `& ${[shellQuote(exe, platform), ...quotedArgs].join(" ")}`;
9
+ export function formatShellCommand(exe, args, platform = process.platform, flavor = "auto") {
10
+ const posix = flavor === "posix" || (flavor === "auto" && platform !== "win32");
11
+ const quotePlatform = posix ? "linux" : platform;
12
+ const quotedArgs = args.map((arg) => shellQuote(arg, quotePlatform));
13
+ if (!posix)
14
+ return `& ${[shellQuote(exe, quotePlatform), ...quotedArgs].join(" ")}`;
13
15
  // Nushell treats a leading quoted token as a string, so use a bare invoker for paths that need quoting.
14
- const invocation = isBareExecutable(exe) ? exe : `sh -c 'exec "$0" "$@"' ${shellQuote(exe, platform)}`;
16
+ const invocation = isBareExecutable(exe) ? exe : `sh -c 'exec "$0" "$@"' ${shellQuote(exe, quotePlatform)}`;
15
17
  return [invocation, ...quotedArgs].join(" ");
16
18
  }
@@ -8,7 +8,8 @@ import { checkPidLiveness, checkRecordedPidLiveness } from "./stale-run-reconcil
8
8
  import { currentBootId } from "./boot-id.js";
9
9
  import { currentPidNamespaceScope } from "./pid-namespace.js";
10
10
  import { readProcessTerminal } from "./process-terminal.js";
11
- import { isTerminalAsyncState as terminalState, readWorkflowChildEvidence, readWorkflowChildProcessEvidence } from "./workflow-terminal-proof.js";
11
+ import { readWorkflowChildEvidence, readWorkflowChildProcessEvidence } from "./workflow-terminal-proof.js";
12
+ import { isTerminalAsyncState as terminalState } from "./active-run-index.js";
12
13
  export const ACTIVE_ASYNC_CAPACITY_DIR = path.join(TEMP_ROOT_DIR, "session-active-async-capacity");
13
14
  export const DEFAULT_ABANDONED_SLOT_RELEASE_AFTER_MS = 20 * 60 * 1000;
14
15
  export const MIN_ABANDONED_SLOT_RELEASE_AFTER_MS = 5 * 60 * 1000;
@@ -2,6 +2,7 @@ import type { AsyncStatus } from "../../shared/types.ts";
2
2
  export declare const ACTIVE_RUN_INDEX_DIR = ".active-runs";
3
3
  export declare const DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS: number;
4
4
  export declare function isActiveAsyncState(state: AsyncStatus["state"]): boolean;
5
+ export declare function isTerminalAsyncState(state: AsyncStatus["state"]): state is Exclude<AsyncStatus["state"], "queued" | "running" | "paused">;
5
6
  export declare function releaseActiveRunIndex(asyncDir: string): void;
6
7
  export declare function updateActiveRunIndex(asyncDir: string, state: AsyncStatus["state"], toolCallId?: string, options?: {
7
8
  retryCapacityErrors?: boolean;
@@ -34,6 +34,9 @@ function removeEmptyAncestors(start, stop) {
34
34
  export function isActiveAsyncState(state) {
35
35
  return state === "queued" || state === "running";
36
36
  }
37
+ export function isTerminalAsyncState(state) {
38
+ return state !== "queued" && state !== "running" && state !== "paused";
39
+ }
37
40
  function releaseToolCallAliases(asyncDir) {
38
41
  const root = path.join(indexDir(path.dirname(asyncDir)), TOOL_CALL_INDEX_DIR);
39
42
  let entries;
@@ -194,6 +194,8 @@ interface AsyncSingleParams {
194
194
  runFanoutBudget?: RunFanoutBudgetDescriptor;
195
195
  parentWorkflowRunId?: string;
196
196
  workflowKey?: string;
197
+ /** Workflow child label; names the child session and its status step. */
198
+ label?: string;
197
199
  lane?: WorkflowLaneMetadata;
198
200
  workflowAwaitAsync?: boolean;
199
201
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
@@ -587,7 +587,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
587
587
  // Diagnostic only; process-terminal proof stays authoritative.
588
588
  }
589
589
  // The runner may outlive its wrapper; only a confirmed-dead runner in this pid namespace finalizes here,
590
- // otherwise status-pid reconciliation does it later.
590
+ // otherwise a later status read in the runner's pid namespace records the proof as unknown once its pid is dead.
591
591
  if (!runnerIdentity || runnerIdentity.pidNamespaceScope !== currentPidNamespaceScope()
592
592
  || checkRecordedPidLiveness(runnerIdentity) !== "dead")
593
593
  return;
@@ -1969,6 +1969,7 @@ export function executeAsyncSingle(id, params) {
1969
1969
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1970
1970
  agent,
1971
1971
  task: taskText,
1972
+ ...(params.label ? { label: params.label } : {}),
1972
1973
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
1973
1974
  ...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
1974
1975
  ...(machine ? { machine } : {}),
@@ -2091,7 +2092,7 @@ export function executeAsyncSingle(id, params) {
2091
2092
  chainStepCount: 1,
2092
2093
  ...(lane ? { lane } : {}),
2093
2094
  ...(launcher ? { launcher } : {}),
2094
- steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2095
+ steps: [{ agent, status: "pending", ...(params.label ? { label: params.label } : {}), ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2095
2096
  }, path.join(asyncDir, "status.json"), launchParentSessionId, (proof) => emitProcessTerminalEvent(ctx, proof), (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId), params.requestedCwd ?? runnerCwd);
2096
2097
  }
2097
2098
  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
  }