@vicary/pi-subagents 0.89.1 → 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 (57) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/bundle/child-tool-plan.js +1 -1
  3. package/bundle/{chunk-C22YEYFZ.js → chunk-464OJSDP.js} +2 -2
  4. package/bundle/{chunk-YLU5JFW2.js → chunk-4KQW5R6U.js} +1 -1
  5. package/bundle/{chunk-WMGQNIP7.js → chunk-4X3T5CPK.js} +6 -6
  6. package/bundle/{chunk-UNLGCAC4.js → chunk-62OHSCQ6.js} +62 -10
  7. package/bundle/{chunk-7J4ZXMY7.js → chunk-72334PEI.js} +6 -4
  8. package/bundle/{chunk-R3NH5XAL.js → chunk-AHGJSJYY.js} +3 -2
  9. package/bundle/{chunk-TRN65L4F.js → chunk-DGLXVN3F.js} +1 -1
  10. package/bundle/{chunk-KCDPTXHT.js → chunk-DHY5TY2Y.js} +235 -197
  11. package/bundle/{chunk-JLZFSOEL.js → chunk-DNDNLHTL.js} +7 -7
  12. package/bundle/{chunk-MIX3MCIF.js → chunk-FF5K5HQU.js} +8 -3
  13. package/bundle/{chunk-URKQZHVH.js → chunk-FO2GIU5F.js} +23 -14
  14. package/bundle/{chunk-OUM6SEVD.js → chunk-JEYG7CNC.js} +6 -2
  15. package/bundle/{chunk-R5XS4CVE.js → chunk-LODNNILA.js} +15 -15
  16. package/bundle/{chunk-BERAWSQQ.js → chunk-RHKIP45B.js} +4 -4
  17. package/bundle/{chunk-4FFKVLBG.js → chunk-SRCMJY4F.js} +3 -3
  18. package/bundle/{chunk-SG3NCWZW.js → chunk-U753SUBC.js} +1 -1
  19. package/bundle/{chunk-NLDROUCR.js → chunk-V4543APA.js} +24 -15
  20. package/bundle/{chunk-DVOXHOTY.js → chunk-W7NDPDDJ.js} +3 -3
  21. package/bundle/index.js +1 -1
  22. package/bundle/preflight.js +7 -5
  23. package/bundle/project-panes.js +2 -2
  24. package/docs/observability.md +3 -1
  25. package/docs/watchdog.md +3 -2
  26. package/package.json +2 -2
  27. package/src/api/preflight.d.ts +1 -0
  28. package/src/api/preflight.js +2 -1
  29. package/src/inspectors/herdr/project-panes.d.ts +2 -0
  30. package/src/inspectors/herdr/project-panes.js +7 -1
  31. package/src/inspectors/shell-command.d.ts +2 -1
  32. package/src/inspectors/shell-command.js +7 -5
  33. package/src/runs/background/active-async-capacity.js +2 -1
  34. package/src/runs/background/active-run-index.d.ts +1 -0
  35. package/src/runs/background/active-run-index.js +3 -0
  36. package/src/runs/background/async-execution.d.ts +2 -0
  37. package/src/runs/background/async-execution.js +3 -2
  38. package/src/runs/background/process-terminal.d.ts +6 -0
  39. package/src/runs/background/process-terminal.js +34 -2
  40. package/src/runs/background/run-status.js +2 -1
  41. package/src/runs/background/stale-run-reconciler.d.ts +8 -0
  42. package/src/runs/background/stale-run-reconciler.js +38 -8
  43. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  44. package/src/runs/background/workflow-terminal-proof.js +4 -4
  45. package/src/runs/foreground/execution.js +2 -2
  46. package/src/runs/foreground/subagent-executor.d.ts +2 -0
  47. package/src/runs/foreground/subagent-executor.js +10 -1
  48. package/src/runs/shared/herdr-pane-host.js +10 -2
  49. package/src/runs/shared/mcp-config-sources.d.ts +1 -0
  50. package/src/runs/shared/mcp-config-sources.js +1 -1
  51. package/src/runs/shared/mcp-direct-tool-allowlist.js +1 -0
  52. package/src/shared/types.d.ts +2 -0
  53. package/src/tui/fleet-transcript.js +21 -9
  54. package/src/watchdog/runtime.d.ts +4 -0
  55. package/src/watchdog/runtime.js +50 -12
  56. package/src/watchdog/turn-delta.d.ts +2 -0
  57. package/src/watchdog/turn-delta.js +21 -0
package/docs/watchdog.md CHANGED
@@ -69,8 +69,9 @@ Child watchdog findings are lifted into the parent in three ways:
69
69
 
70
70
  ## What the reviewer is given
71
71
 
72
- - **Turn delta** with changed repo paths. Over-long input keeps the first 6,000 characters and the tail.
72
+ - **Turn delta** with changed repo paths. Over-long input keeps up to the first 6,000 characters and the tail. Whenever any of the run's turn text was left out to fit (whole turns dropped, or one long turn or the delta cut), the delta starts with a note saying how much, and the reviewer is told not to report an instruction as missing when it may be in an omitted part.
73
73
  - **Current scope** (`scope.enabled`, default on): bounded real user prompts. Side questions are additive; only explicit changes supersede older requirements. Scope survives compaction within the current session.
74
+ - **Supervisor replies** (with scope, child watchdogs): paired `contact_supervisor` decision and interview requests with their non-error replies, kept outside the turn delta so a long run cannot drop them. Each entry is bounded to 3,000 characters, with a 6,000-character recent tail kept for the session like scope.
74
75
  - **`watchdog_diff`** when inside git: diff since the session-start commit, including later commits, plus untracked paths to inspect with `read`; accepts `path` and `stat:true`.
75
76
  - **`WATCHDOG.md`** standing instructions, read fresh on every review: `<project>/.pi/WATCHDOG.md` first, then `~/.pi/agent/WATCHDOG.md`, capped at 8,000 characters. Set `guidance.watchdogMd: false` to ignore them.
76
77
  - **LSP diagnostics** from `typescript-language-server`, auto-detected in `node_modules/.bin` or `PATH`; it is never installed and never run over the whole workspace. Errors become blockers, warnings concerns, and info/hints stay in status.
@@ -122,7 +123,7 @@ With this opt-in, completed `turn_end` events retain a recent actual-activity ta
122
123
 
123
124
  New unreviewed activity permits at most one additional boundary review per user prompt even with no local edit. Side questions keep earlier authorized task evidence available; they do not themselves trigger a model call. Activity gathered after that prompt's extra review remains available for the next prompt. Warning continuations cannot supply fresh triggering activity. No polling, task scheduling, cross-worktree scans or idle calls are added.
124
125
 
125
- **Visibility limit:** external task/gate completions are visible when returned through those parent tool results. Standalone native completion notifications, arbitrary custom messages, direct shell/CI output, and events not delivered to the parent through these contracts are not ingested by this activity tail. Existing scope retains at most eight prompts (2,000 characters each); new streaming user input cancels an active review but is not added to scope unless `before_agent_start` fires. Reminders depend on retained evidence and model judgment, not an exhaustive view of running work.
126
+ **Visibility limit:** external task/gate completions are visible when returned through those parent tool results. Standalone native completion notifications, arbitrary custom messages, direct shell/CI output, and events not delivered to the parent through these contracts are not ingested by this activity tail. Existing scope retains at most eight prompts (2,000 characters each); new streaming user input cancels an active review and is added to scope. Reminders depend on retained evidence and model judgment, not an exhaustive view of running work.
126
127
 
127
128
  Set `subagents.watchdog.clarification: true` in Pi settings alongside `enabled: true`. It defaults to `false` and applies **only to the main watchdog**, not child watchdogs or child permission arbitration.
128
129
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@vicary/pi-subagents",
4
- "version": "0.89.1",
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": "f466f3b427dcef136202f4fb9b129b6e0ca760d2"
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: {
@@ -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) {
@@ -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
@@ -78,6 +78,8 @@ export interface SubagentParamsLike {
78
78
  /** Internal workflow ownership metadata; not part of the public schema. */
79
79
  workflowParentRunId?: string;
80
80
  workflowKey?: string;
81
+ /** Workflow child's `runs.run` label, trimmed; names the child's own session instead of a task excerpt. */
82
+ label?: string;
81
83
  lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
82
84
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
83
85
  scheduleOrigin?: ScheduleOrigin;
@@ -3271,6 +3271,8 @@ async function runAsyncPath(data, deps) {
3271
3271
  runFanoutBudget: data.runFanoutBudget,
3272
3272
  parentWorkflowRunId: params.workflowParentRunId,
3273
3273
  workflowKey: params.workflowKey,
3274
+ // Top-level calls pass unknown keys through; only a workflow child's label is normalized.
3275
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3274
3276
  lane: params.lane,
3275
3277
  workflowAwaitAsync: params.workflowAwaitAsync,
3276
3278
  }));
@@ -3868,6 +3870,7 @@ async function runSinglePath(data, deps) {
3868
3870
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3869
3871
  cwd: singleCwd,
3870
3872
  requestedCwd: data.requestedCwd,
3873
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3871
3874
  signal,
3872
3875
  abortedAsStopped: params.workflowParentRunId !== undefined,
3873
3876
  interruptSignal: interruptController.signal,
@@ -4651,6 +4654,12 @@ export function prepareWorkflowLaunchParams(workflowDefaults, childParams, paren
4651
4654
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4652
4655
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
4653
4656
  };
4657
+ // Scripts pass `label` unchecked; keep only a non-empty string so session naming can trust the field.
4658
+ const label = typeof childParams.label === "string" ? childParams.label.trim() : "";
4659
+ if (label)
4660
+ launchParams.label = label;
4661
+ else
4662
+ delete launchParams.label;
4654
4663
  if (launchParams.extensionBindings !== undefined)
4655
4664
  launchParams.extensionBindings = normalizeExtensionBindings(launchParams.extensionBindings).value;
4656
4665
  const normalizedGate = normalizeGateParams(launchParams);
@@ -7785,7 +7794,7 @@ export function createSubagentExecutor(deps) {
7785
7794
  if (workflowLaunchObserver) {
7786
7795
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
7787
7796
  const singleSessionName = hasSingle
7788
- ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task })
7797
+ ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task, label: effectiveParams.label })
7789
7798
  : singleTask
7790
7799
  ? deriveChildSessionName({ agent: singleTask.agent, task: singleTask.task })
7791
7800
  : undefined;
@@ -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
  }
@@ -2537,6 +2537,8 @@ export interface RunSyncOptions {
2537
2537
  remoteReads?: string[] | false;
2538
2538
  /** Original cwd input retained for launch diagnostics. */
2539
2539
  requestedCwd?: string;
2540
+ /** Workflow child label; names the child session instead of the task excerpt. */
2541
+ label?: string;
2540
2542
  signal?: AbortSignal;
2541
2543
  /** Report a child ended by `signal` as stopped; set for workflow children, whose signal is the workflow's. */
2542
2544
  abortedAsStopped?: boolean;
@@ -39,8 +39,17 @@ function renderExpandedTool(event, width, theme) {
39
39
  const output = event.output ?? event.error;
40
40
  const outputColor = event.status === "error" ? "error" : "toolOutput";
41
41
  if (event.name === "bash") {
42
- const command = jsonScalar(args?.command) ?? event.args ?? "(unknown command)";
43
- lines.push(railLine(`${glyph} ${theme.fg("toolTitle", theme.bold(`$ ${command}`))}`, width, theme));
42
+ const command = jsonScalar(args?.command);
43
+ let first = true;
44
+ for (const commandLine of (command ?? event.args ?? "(unknown command)").split(/\r?\n/)) {
45
+ for (const wrapped of renderWrapped(theme.fg("toolTitle", theme.bold(first ? `$ ${commandLine}` : commandLine)), Math.max(1, width - 4))) {
46
+ lines.push(railLine(`${first ? glyph : " "} ${wrapped}`, width, theme));
47
+ first = false;
48
+ }
49
+ }
50
+ // An unparseable payload was cut at the transcript size cap; show it raw so its truncation marker is visible.
51
+ if (command === undefined && !args && event.argsPayload)
52
+ lines.push(...renderArgsPayload(event.argsPayload, width, theme));
44
53
  if (output) {
45
54
  for (const outputLine of output.replace(/\s+$/, "").split(/\r?\n/)) {
46
55
  for (const wrapped of renderWrapped(theme.fg(outputColor, outputLine), Math.max(1, width - 4))) {
@@ -71,13 +80,8 @@ function renderExpandedTool(event, width, theme) {
71
80
  return lines;
72
81
  }
73
82
  lines.push(railLine(`${glyph} ${theme.fg("toolTitle", theme.bold(event.name))}`, width, theme));
74
- if (event.argsPayload) {
75
- lines.push(railLine(theme.fg("dim", " args"), width, theme));
76
- for (const argLine of event.argsPayload.split(/\r?\n/)) {
77
- for (const wrapped of renderWrapped(theme.fg("muted", argLine), Math.max(1, width - 4)))
78
- lines.push(railLine(` ${wrapped}`, width, theme));
79
- }
80
- }
83
+ if (event.argsPayload)
84
+ lines.push(...renderArgsPayload(event.argsPayload, width, theme));
81
85
  if (output) {
82
86
  lines.push(railLine(theme.fg(event.status === "error" ? "error" : "dim", event.status === "error" ? " error" : " output"), width, theme));
83
87
  for (const outputLine of output.split(/\r?\n/)) {
@@ -90,6 +94,14 @@ function renderExpandedTool(event, width, theme) {
90
94
  function bounded(text, width) {
91
95
  return truncateToWidth(text, Math.max(0, width));
92
96
  }
97
+ function renderArgsPayload(payload, width, theme) {
98
+ const lines = [railLine(theme.fg("dim", " args"), width, theme)];
99
+ for (const argLine of payload.split(/\r?\n/)) {
100
+ for (const wrapped of renderWrapped(theme.fg("muted", argLine), Math.max(1, width - 4)))
101
+ lines.push(railLine(` ${wrapped}`, width, theme));
102
+ }
103
+ return lines;
104
+ }
93
105
  function railLine(content, width, theme) {
94
106
  return bounded(`${theme.fg("borderMuted", "│")} ${content}`, width);
95
107
  }