@xzzpig/pi-subagents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +342 -0
  5. package/docs/configuration.md +328 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +119 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +174 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +17 -8
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/project-panes.ts +30 -0
  22. package/src/extension/config.ts +28 -1
  23. package/src/extension/fanout-child.ts +5 -4
  24. package/src/extension/index.ts +75 -30
  25. package/src/extension/rpc.ts +7 -6
  26. package/src/extension/schemas.ts +29 -8
  27. package/src/extension/subagent-guide.ts +39 -0
  28. package/src/extension/tool-description.ts +30 -12
  29. package/src/inspectors/herdr/project-panes.ts +459 -63
  30. package/src/intercom/native-supervisor-channel.ts +102 -4
  31. package/src/missions/actions.ts +25 -2
  32. package/src/missions/lifecycle.ts +21 -2
  33. package/src/missions/store.ts +79 -2
  34. package/src/missions/types.ts +33 -0
  35. package/src/missions/workflow-state.ts +19 -13
  36. package/src/runs/background/active-run-index.ts +42 -0
  37. package/src/runs/background/async-execution.ts +17 -6
  38. package/src/runs/background/async-job-tracker.ts +293 -133
  39. package/src/runs/background/async-resume.ts +19 -3
  40. package/src/runs/background/async-status.ts +33 -5
  41. package/src/runs/background/completion-replay.ts +267 -0
  42. package/src/runs/background/control-channel.ts +95 -54
  43. package/src/runs/background/result-watcher.ts +113 -10
  44. package/src/runs/background/resume-guidance.ts +33 -0
  45. package/src/runs/background/run-status.ts +18 -0
  46. package/src/runs/background/scheduled-runs.ts +25 -1
  47. package/src/runs/background/stale-run-reconciler.ts +12 -24
  48. package/src/runs/background/subagent-runner.ts +69 -11
  49. package/src/runs/background/subagent-wait.ts +5 -2
  50. package/src/runs/background/wait-completions.ts +39 -5
  51. package/src/runs/background/wait-subscriptions.ts +21 -5
  52. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  53. package/src/runs/foreground/async-steering-action.ts +7 -8
  54. package/src/runs/foreground/chain-execution.ts +3 -0
  55. package/src/runs/foreground/execution.ts +7 -0
  56. package/src/runs/foreground/foreground-history.ts +137 -0
  57. package/src/runs/foreground/subagent-executor.ts +466 -61
  58. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  59. package/src/runs/shared/dynamic-fanout.ts +1 -1
  60. package/src/runs/shared/model-fallback.ts +8 -4
  61. package/src/runs/shared/model-scope.ts +12 -2
  62. package/src/runs/shared/parallel-utils.ts +1 -0
  63. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  64. package/src/runs/shared/worktree.ts +3 -2
  65. package/src/shared/artifacts.ts +15 -15
  66. package/src/shared/display-text.ts +100 -0
  67. package/src/shared/file-coalescer.ts +9 -0
  68. package/src/shared/fork-context.ts +13 -0
  69. package/src/shared/formatters.ts +4 -6
  70. package/src/shared/prompt-resources.ts +51 -0
  71. package/src/shared/settings.ts +15 -2
  72. package/src/shared/types.ts +45 -2
  73. package/src/shared/utf8.ts +11 -0
  74. package/src/shared/utils.ts +43 -33
  75. package/src/slash/prompt-workflows.ts +2 -15
  76. package/src/slash/slash-commands.ts +22 -2
  77. package/src/tui/fleet-status.ts +22 -12
  78. package/src/tui/fleet.ts +135 -25
  79. package/src/tui/render.ts +150 -33
  80. package/src/watchdog/change-signature.ts +4 -3
  81. package/src/workflows/scripted-workflow.ts +210 -13
@@ -21,13 +21,15 @@ import {
21
21
  import { projectNestedRegistryForRoot, sanitizeSummary } from "../shared/nested-events.ts";
22
22
  import { resolveWatchPath } from "../../shared/utils.ts";
23
23
  import { recordWaitCompletion } from "./wait-completions.ts";
24
+ import { MISSION_BINDING_FILE, syncMissionFromAsyncCompletion } from "../../missions/lifecycle.ts";
24
25
  import type { CompletionNotifier, CompletionNotification } from "./notify.ts";
25
26
 
26
27
  const WATCHER_RESTART_DELAY_MS = 3000;
27
28
  const POLL_INTERVAL_MS = 3000;
29
+ const HEALTHY_SCAN_INTERVAL_MS = 60_000;
28
30
  const RETRY_DELAY_MS = 100;
29
31
 
30
- type ResultWatcherFs = Pick<typeof fs, "existsSync" | "readFileSync" | "unlinkSync" | "readdirSync" | "mkdirSync" | "realpathSync" | "watch">;
32
+ type ResultWatcherFs = Pick<typeof fs, "existsSync" | "readFileSync" | "unlinkSync" | "readdirSync" | "mkdirSync" | "realpathSync" | "statSync" | "watch">;
31
33
 
32
34
  type ResultWatcherTimers = {
33
35
  setTimeout: typeof setTimeout;
@@ -42,6 +44,10 @@ type ResultWatcherDeps = {
42
44
  notifier?: Pick<CompletionNotifier, "deliver">;
43
45
  /** Receives persisted completions before active-session delivery filtering. */
44
46
  observeCompletion?: (result: CompletionNotification & { runId: string }) => void;
47
+ /** Returns cross-session run ids that the completion observer currently owns. */
48
+ observedCompletionRunIds?: () => Iterable<string>;
49
+ /** Parses a relevant result payload after its lightweight identity check. */
50
+ parseResult?: (raw: string) => ResultFileData;
45
51
  /** External grouped-result transport. Disable when native completion notifications own delivery. */
46
52
  deliverIntercomResults?: boolean;
47
53
  };
@@ -75,6 +81,33 @@ type ResultFileData = CompletionNotification & {
75
81
  parallelHandoff?: ParallelHandoffReference;
76
82
  };
77
83
 
84
+ type ResultFileIdentity = {
85
+ sessionId?: string;
86
+ runId?: string;
87
+ asyncDir?: string;
88
+ };
89
+
90
+ function jsonStringProperty(raw: string, property: string): string | undefined {
91
+ const matches = raw.matchAll(new RegExp(`"${property}"\\s*:\\s*("(?:\\\\.|[^"\\\\])*")`, "g"));
92
+ let encoded: string | undefined;
93
+ for (const match of matches) encoded = match[1];
94
+ if (!encoded) return undefined;
95
+ try {
96
+ const value = JSON.parse(encoded) as unknown;
97
+ return typeof value === "string" && value ? value : undefined;
98
+ } catch {
99
+ return undefined;
100
+ }
101
+ }
102
+
103
+ function resultFileIdentity(raw: string, file: string): ResultFileIdentity {
104
+ return {
105
+ sessionId: jsonStringProperty(raw, "sessionId"),
106
+ runId: file.replace(/\.json$/i, ""),
107
+ asyncDir: jsonStringProperty(raw, "asyncDir"),
108
+ };
109
+ }
110
+
78
111
  function sanitizeNestedResultChildren(value: unknown, resultPath: string, label: string): NestedRunSummary[] | undefined {
79
112
  if (value === undefined) return undefined;
80
113
  if (!Array.isArray(value)) {
@@ -120,11 +153,14 @@ export function createResultWatcher(
120
153
  const fsApi = deps.fs ?? fs;
121
154
  const timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval };
122
155
  const notifier = deps.notifier ?? { deliver: async () => true };
156
+ const parseResult = deps.parseResult ?? ((raw: string) => JSON.parse(raw) as ResultFileData);
123
157
  const deliverIntercomResults = deps.deliverIntercomResults !== false;
124
158
  const pendingTriggerTurn = new Map<string, boolean>();
125
159
  const processing = new Set<string>();
160
+ const identityCache = new Map<string, { signature: string; identity: ResultFileIdentity }>();
126
161
  let deliveryActive = true;
127
162
  let deliveryEpoch = 0;
163
+ let resultScanTimer: ReturnType<typeof setInterval> | null = null;
128
164
  // The sole in-memory ownership lease. It is acquired for one active session
129
165
  // and revoked before the watcher, queues, or callbacks are torn down.
130
166
  let activeSessionId: string | null = null;
@@ -141,14 +177,58 @@ export function createResultWatcher(
141
177
  state.resultFileCoalescer.schedule(file, delayMs);
142
178
  };
143
179
 
180
+ const inspectResult = (file: string): ResultFileIdentity | undefined => {
181
+ const resultPath = path.join(resultsDir, file);
182
+ try {
183
+ const stat = fsApi.statSync(resultPath);
184
+ const signature = `${stat.size}:${stat.mtimeMs}`;
185
+ const cached = identityCache.get(file);
186
+ if (cached?.signature === signature) return cached.identity;
187
+ const identity = resultFileIdentity(fsApi.readFileSync(resultPath, "utf-8"), file);
188
+ identityCache.set(file, { signature, identity });
189
+ return identity;
190
+ } catch (error) {
191
+ identityCache.delete(file);
192
+ if (!isNotFound(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
193
+ return undefined;
194
+ }
195
+ };
196
+
197
+ const observedRunIds = (): ReadonlySet<string> => {
198
+ try {
199
+ return new Set(deps.observedCompletionRunIds?.() ?? []);
200
+ } catch (error) {
201
+ console.error("Failed to inspect observed subagent completion ids:", error);
202
+ return new Set();
203
+ }
204
+ };
205
+
206
+ const shouldProcessResult = (file: string, observed?: ReadonlySet<string>): boolean => {
207
+ const identity = inspectResult(file);
208
+ if (!identity) return false;
209
+ // Missing identity stays on the normal parser path so malformed or legacy
210
+ // files keep their existing diagnostics and compatibility behavior.
211
+ if (!identity.sessionId) return true;
212
+ if (identity.sessionId === state.currentSessionId) return true;
213
+ if (identity.asyncDir && fsApi.existsSync(path.join(identity.asyncDir, MISSION_BINDING_FILE))) return true;
214
+ if (identity.runId && (observed ?? observedRunIds()).has(identity.runId)) return true;
215
+ return Boolean(deps.observeCompletion && !deps.observedCompletionRunIds);
216
+ };
217
+
144
218
  const handleResult = async (file: string, triggerTurn: boolean) => {
145
219
  const resultPath = path.join(resultsDir, file);
146
220
  if (processing.has(file) || !fsApi.existsSync(resultPath)) return;
221
+ if (!shouldProcessResult(file)) return;
147
222
  processing.add(file);
148
223
  try {
149
- const data = JSON.parse(fsApi.readFileSync(resultPath, "utf-8")) as ResultFileData;
224
+ const data = parseResult(fsApi.readFileSync(resultPath, "utf-8"));
150
225
  if (typeof data.sessionId !== "string" || !data.sessionId) return;
151
226
  const runId = data.runId ?? data.id ?? file.replace(/\.json$/i, "");
227
+ try {
228
+ syncMissionFromAsyncCompletion({ ...data, runId });
229
+ } catch (error) {
230
+ console.error(`Mission completion sync failed for '${resultPath}':`, error);
231
+ }
152
232
  try {
153
233
  deps.observeCompletion?.({ ...data, runId });
154
234
  } catch (error) {
@@ -156,10 +236,12 @@ export function createResultWatcher(
156
236
  }
157
237
  const epoch = deliveryEpoch;
158
238
  if (!ownsSession(data.sessionId, epoch)) return;
159
- // Recorded before dedupe and before the unlink below: the result file is
160
- // the only durable carrier of the per-run payload, and subagent_wait
161
- // surfaces this record in details once the file is gone.
162
- recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs);
239
+ // Recorded before dedupe and before the unlink below so subagent_wait can
240
+ // use the in-memory record or its bounded durable replay after cleanup.
241
+ recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
242
+ resultsDir,
243
+ sessionId: data.sessionId,
244
+ });
163
245
  const hasExplicitNestedChildren = data.nestedChildren !== undefined;
164
246
  let nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren"));
165
247
  if (!nestedChildren?.length && !hasExplicitNestedChildren) {
@@ -180,6 +262,7 @@ export function createResultWatcher(
180
262
  if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
181
263
  try {
182
264
  fsApi.unlinkSync(resultPath);
265
+ identityCache.delete(file);
183
266
  } catch (error) {
184
267
  if (!isNotFound(error)) {
185
268
  console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
@@ -305,6 +388,7 @@ export function createResultWatcher(
305
388
  if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
306
389
  try {
307
390
  fsApi.unlinkSync(resultPath);
391
+ identityCache.delete(file);
308
392
  } catch (error) {
309
393
  if (!isNotFound(error)) {
310
394
  console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
@@ -329,15 +413,23 @@ export function createResultWatcher(
329
413
  const triggerTurn = options.triggerTurn !== false;
330
414
  fsApi.readdirSync(resultsDir)
331
415
  .filter((f) => f.endsWith(".json"))
332
- .forEach((file) => scheduleResult(file, triggerTurn));
416
+ .forEach((file) => {
417
+ if (shouldProcessResult(file)) scheduleResult(file, triggerTurn);
418
+ });
333
419
  } catch (error) {
334
420
  if (!isNotFound(error)) console.error(`Failed to scan subagent result directory '${resultsDir}':`, error);
335
421
  }
336
422
  };
337
423
 
424
+ const clearResultScan = () => {
425
+ if (resultScanTimer) timers.clearInterval(resultScanTimer);
426
+ resultScanTimer = null;
427
+ };
428
+
338
429
  const startPolling = (reason: unknown) => {
339
430
  state.watcher?.close();
340
431
  state.watcher = null;
432
+ clearResultScan();
341
433
  if (state.watcherRestartTimer) return;
342
434
  console.error(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${errorCode(reason) ?? "unknown error"}).`);
343
435
  primeExistingResults();
@@ -346,6 +438,7 @@ export function createResultWatcher(
346
438
  };
347
439
 
348
440
  const scheduleRestart = () => {
441
+ clearResultScan();
349
442
  if (state.watcherRestartTimer) return;
350
443
  state.watcherRestartTimer = timers.setTimeout(() => {
351
444
  state.watcherRestartTimer = null;
@@ -373,10 +466,16 @@ export function createResultWatcher(
373
466
  }
374
467
  try {
375
468
  const watchDir = resolveWatchPath(resultsDir, fsApi.realpathSync.native);
376
- state.watcher = fsApi.watch(watchDir, (event, file) => {
377
- if (event !== "rename" || !file) return;
469
+ state.watcher = fsApi.watch(watchDir, (_event, file) => {
470
+ if (!file) {
471
+ primeExistingResults();
472
+ return;
473
+ }
378
474
  const fileName = file.toString();
379
- if (fileName.endsWith(".json")) scheduleResult(fileName, true);
475
+ if (fileName.endsWith(".json")) {
476
+ identityCache.delete(fileName);
477
+ scheduleResult(fileName, true);
478
+ }
380
479
  });
381
480
  state.watcher.on("error", (error) => {
382
481
  if (shouldPoll(error)) return startPolling(error);
@@ -386,6 +485,8 @@ export function createResultWatcher(
386
485
  scheduleRestart();
387
486
  });
388
487
  state.watcher.unref?.();
488
+ resultScanTimer = timers.setInterval(primeExistingResults, HEALTHY_SCAN_INTERVAL_MS);
489
+ resultScanTimer.unref?.();
389
490
  } catch (error) {
390
491
  if (shouldPoll(error)) return startPolling(error);
391
492
  console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error);
@@ -405,9 +506,11 @@ export function createResultWatcher(
405
506
  timers.clearInterval(state.watcherRestartTimer);
406
507
  }
407
508
  state.watcherRestartTimer = null;
509
+ clearResultScan();
408
510
  state.resultFileCoalescer.clear();
409
511
  pendingTriggerTurn.clear();
410
512
  processing.clear();
513
+ identityCache.clear();
411
514
  };
412
515
 
413
516
  return { startResultWatcher, primeExistingResults, stopResultWatcher };
@@ -0,0 +1,33 @@
1
+ import * as fs from "node:fs";
2
+ import type { AsyncRunSummary } from "./async-status.ts";
3
+
4
+ export function formatAsyncReviveCommand(run: AsyncRunSummary): string | undefined {
5
+ const step = run.steps.find((candidate) => candidate.status === "failed" && candidate.sessionFile && fs.existsSync(candidate.sessionFile));
6
+ if (!step) {
7
+ if (run.steps.length === 1 && run.sessionFile && fs.existsSync(run.sessionFile)) {
8
+ return `subagent({ action: "resume", id: "${run.id}", message: "Continue from the persisted child session and report the result." })`;
9
+ }
10
+ return undefined;
11
+ }
12
+ const index = run.steps.length === 1 ? "" : `, index: ${step.index}`;
13
+ return `subagent({ action: "resume", id: "${run.id}"${index}, message: "Continue from the persisted child session and report the result." })`;
14
+ }
15
+
16
+ export function formatResumeFirstFailedRunDetail(run: AsyncRunSummary): string | undefined {
17
+ if (run.state !== "failed") return undefined;
18
+ const command = formatAsyncReviveCommand(run);
19
+ if (!command) return undefined;
20
+ return `Resume-first: failed run "${run.id}" has a persisted child session. Revive the original run with ${command} before reporting failure or launching a replacement. Launch a replacement only if revive fails or the user explicitly asks for one.`;
21
+ }
22
+
23
+ export function formatResumeFirstFailedRunsNote(runs: AsyncRunSummary[]): string {
24
+ const resumable = runs
25
+ .filter((run) => run.state === "failed")
26
+ .map((run) => ({ run, command: formatAsyncReviveCommand(run) }))
27
+ .filter((entry): entry is { run: AsyncRunSummary; command: string } => Boolean(entry.command));
28
+ if (resumable.length === 0) return "";
29
+ const guidance = resumable.length === 1
30
+ ? `failed run "${resumable[0]!.run.id}" has a persisted child session. Revive the original run with ${resumable[0]!.command}`
31
+ : `${resumable.length} failed runs have persisted child sessions. Inspect status and revive each original run before retrying`;
32
+ return ` Resume-first: ${guidance} before reporting failure or launching a replacement. Launch a replacement only if revive fails or the user explicitly asks for one.`;
33
+ }
@@ -7,6 +7,7 @@ import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
7
7
  import { formatModelThinking } from "../../shared/formatters.ts";
8
8
  import { formatActivityLabel } from "../../shared/status-format.ts";
9
9
  import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type NestedRunSummary, type SteeringStatus, type SubagentState } from "../../shared/types.ts";
10
+ import { readStatus } from "../../shared/utils.ts";
10
11
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
11
12
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
12
13
  import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
@@ -315,6 +316,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
315
316
  }
316
317
 
317
318
  if (asyncDir) {
319
+ const diskStatus = readStatus(asyncDir);
318
320
  let reconciliation;
319
321
  try {
320
322
  reconciliation = reconcileAsyncRun(asyncDir, { resultsDir, kill: deps.kill, now: deps.now });
@@ -327,6 +329,22 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
327
329
  };
328
330
  }
329
331
  const status = reconciliation.status;
332
+ if (!status && diskStatus?.displayDismissedAt !== undefined) {
333
+ if (params.view === "transcript") {
334
+ if (currentSessionId && diskStatus.sessionId !== currentSessionId) {
335
+ return {
336
+ content: [{ type: "text", text: "Transcript view is only available for async runs owned by the current session." }],
337
+ isError: true,
338
+ details: { mode: "single", results: [] },
339
+ };
340
+ }
341
+ return { content: [{ type: "text", text: formatAsyncRunTranscript(diskStatus, asyncDir, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
342
+ }
343
+ return {
344
+ content: [{ type: "text", text: `Run: ${diskStatus.runId}\nState: display-dismissed\nDismissed: ${new Date(diskStatus.displayDismissedAt).toISOString()}\nNo running work was terminated.` }],
345
+ details: { mode: "single", results: [] },
346
+ };
347
+ }
330
348
  const effectiveRunId = status?.runId ?? resolvedId ?? "unknown";
331
349
  const logPath = path.join(asyncDir, `subagent-log-${effectiveRunId}.md`);
332
350
  const eventsPath = path.join(asyncDir, "events.jsonl");
@@ -3,6 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
6
7
  import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
7
8
  import { shortenPath } from "../../shared/formatters.ts";
8
9
  import type { AsyncStatus, Details, ExtensionConfig } from "../../shared/types.ts";
@@ -87,7 +88,7 @@ export function scheduledRunsEnabled(config: ExtensionConfig): boolean {
87
88
  }
88
89
 
89
90
  export function scheduledRunStorePath(cwd: string, _sessionId?: string, root?: string): string {
90
- if (!root) return path.join(path.resolve(cwd), ".pi-subagents", "schedules");
91
+ if (!root) return path.join(getProjectSubagentsDir(path.resolve(cwd)), "schedules");
91
92
  const projectKey = createHash("sha256").update(path.resolve(cwd)).digest("hex").slice(0, 20);
92
93
  return path.join(root, projectKey);
93
94
  }
@@ -405,6 +406,29 @@ export class ScheduledRunManager {
405
406
  }
406
407
  }
407
408
 
409
+ observedCompletionRunIds(): Set<string> {
410
+ const runIds = new Set<string>();
411
+ for (const store of this.stores.values()) {
412
+ let ids: string[];
413
+ try {
414
+ ids = store.ids();
415
+ } catch (error) {
416
+ console.error(`Failed to inspect schedule store '${store.root}' during async completion discovery:`, error);
417
+ continue;
418
+ }
419
+ for (const id of ids) {
420
+ try {
421
+ for (const run of store.history(id)) {
422
+ if (run.state === "running" && run.asyncId) runIds.add(run.asyncId);
423
+ }
424
+ } catch (error) {
425
+ console.error(`Failed to inspect schedule '${id}' in '${store.root}' during async completion discovery:`, error);
426
+ }
427
+ }
428
+ }
429
+ return runIds;
430
+ }
431
+
408
432
  handleAsyncCompletion(payload: unknown): void {
409
433
  if (!payload || typeof payload !== "object") return;
410
434
  const data = payload as { id?: unknown; runId?: unknown; success?: unknown; state?: unknown; summary?: unknown };
@@ -1,6 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
4
+ import { updateActiveRunIndex } from "./active-run-index.ts";
5
+ import { readStatus } from "../../shared/utils.ts";
4
6
  import { DIRS, type AsyncParallelGroupStatus, type AsyncStatus, type NestedRunSummary, type SubagentRunMode } from "../../shared/types.ts";
5
7
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
6
8
  import { normalizeParallelGroups } from "./parallel-groups.ts";
@@ -84,26 +86,6 @@ function appendJsonlBestEffort(filePath: string, payload: object): void {
84
86
  }
85
87
  }
86
88
 
87
- function readStatusFile(asyncDir: string): AsyncStatus | null {
88
- const statusPath = path.join(asyncDir, "status.json");
89
- let content: string;
90
- try {
91
- content = fs.readFileSync(statusPath, "utf-8");
92
- } catch (error) {
93
- if (isNotFoundError(error)) return null;
94
- throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage(error)}`, {
95
- cause: error instanceof Error ? error : undefined,
96
- });
97
- }
98
- try {
99
- return JSON.parse(content) as AsyncStatus;
100
- } catch (error) {
101
- throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage(error)}`, {
102
- cause: error instanceof Error ? error : undefined,
103
- });
104
- }
105
- }
106
-
107
89
  interface ResultChildOutcome {
108
90
  agent?: string;
109
91
  success?: boolean;
@@ -172,7 +154,7 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
172
154
  modelAttempts: child?.modelAttempts ?? step.modelAttempts,
173
155
  };
174
156
  });
175
- return {
157
+ const terminalStatus: AsyncStatus = {
176
158
  ...status,
177
159
  state: repair.state,
178
160
  ...(status.lifecycleArtifactVersion === 3 && (!status.processTerminal || status.processTerminal.state === "pending") ? {
@@ -184,6 +166,8 @@ function terminalStatusFromResult(status: AsyncStatus, resultPath: string, now:
184
166
  endedAt: status.endedAt ?? now,
185
167
  steps,
186
168
  };
169
+ delete terminalStatus.displayDismissedAt;
170
+ return terminalStatus;
187
171
  }
188
172
 
189
173
  function buildStartedStatus(asyncDir: string, startedRun: StartedRunMetadata, now: number): AsyncStatus {
@@ -277,6 +261,7 @@ function writeFailedRepair(asyncDir: string, status: AsyncStatus, resultPath: st
277
261
  const repair = buildFailedRepair(status, asyncDir, now, reason);
278
262
  writeAtomicJson(resultPath, repair.result);
279
263
  writeAtomicJson(path.join(asyncDir, "status.json"), repair.status);
264
+ updateActiveRunIndex(asyncDir, repair.status.state);
280
265
  appendJsonlBestEffort(path.join(asyncDir, "events.jsonl"), {
281
266
  type: "subagent.run.repaired_stale",
282
267
  ts: now,
@@ -348,7 +333,7 @@ export function checkPidLiveness(pid: number, kill: KillFn = process.kill): PidL
348
333
 
349
334
  export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOptions = {}): ReconcileAsyncRunResult {
350
335
  const now = options.now?.() ?? Date.now();
351
- const status = readStatusFile(asyncDir);
336
+ const status = readStatus(asyncDir);
352
337
  const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : undefined;
353
338
  const effectiveStatus = status ?? startedStatus;
354
339
  if (!effectiveStatus) return { status: null, repaired: false };
@@ -358,7 +343,6 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
358
343
  if (stepRecord.model !== undefined && typeof stepRecord.model !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
359
344
  if (stepRecord.thinking !== undefined && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
360
345
  }
361
-
362
346
  const runId = effectiveStatus.runId || path.basename(asyncDir);
363
347
  const resultPath = path.join(options.resultsDir ?? DIRS.results, `${runId}.json`);
364
348
  if (fs.existsSync(resultPath)) {
@@ -367,9 +351,13 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
367
351
  : undefined;
368
352
  if (terminalStatus) {
369
353
  writeAtomicJson(path.join(asyncDir, "status.json"), terminalStatus);
354
+ updateActiveRunIndex(asyncDir, terminalStatus.state);
370
355
  return { status: terminalStatus, repaired: true, resultPath, message: "Existing async result file was used to repair stale running status." };
371
356
  }
372
- return { status: effectiveStatus, repaired: false, resultPath };
357
+ if (effectiveStatus.displayDismissedAt === undefined) return { status: effectiveStatus, repaired: false, resultPath };
358
+ }
359
+ if (effectiveStatus.displayDismissedAt !== undefined) {
360
+ return { status: null, repaired: false, resultPath };
373
361
  }
374
362
 
375
363
  if (effectiveStatus.state !== "running" || typeof effectiveStatus.pid !== "number") {
@@ -5,6 +5,8 @@ import * as path from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
7
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
8
+ import { createFileCoalescer } from "../../shared/file-coalescer.ts";
9
+ import { isActiveAsyncState, updateActiveRunIndex } from "./active-run-index.ts";
8
10
  import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
9
11
  import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, enqueueStepSteer, steerAcksDir, steerCapabilityPath, stepSteerInboxDir, watchAsyncControlInbox, type SteerAck, type SteerCapability, type SteerRequest } from "./control-channel.ts";
10
12
  import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
@@ -1955,6 +1957,47 @@ function combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSign
1955
1957
  return controller.signal;
1956
1958
  }
1957
1959
 
1960
+ async function runSingleStepWithTimeout(
1961
+ step: SubagentStep,
1962
+ ctx: SingleStepContext,
1963
+ parentDeadlineAt?: number,
1964
+ ): Promise<SingleStepResult> {
1965
+ if (step.timeoutMs === undefined) return runSingleStep(step, ctx);
1966
+
1967
+ const parentRemainingMs = parentDeadlineAt === undefined ? undefined : Math.max(0, parentDeadlineAt - Date.now());
1968
+ const timeoutMs = parentRemainingMs === undefined ? step.timeoutMs : Math.min(step.timeoutMs, parentRemainingMs);
1969
+ const timeoutMessage = parentRemainingMs !== undefined && parentRemainingMs <= step.timeoutMs
1970
+ ? ctx.timeoutMessage
1971
+ : `Subagent timed out after ${step.timeoutMs}ms.`;
1972
+ const timeoutController = new AbortController();
1973
+ let timeoutAction: (() => void) | undefined;
1974
+ let timeoutTriggered = false;
1975
+ const triggerTimeout = (): void => {
1976
+ if (timeoutTriggered) return;
1977
+ timeoutTriggered = true;
1978
+ timeoutController.abort();
1979
+ timeoutAction?.();
1980
+ };
1981
+ const registerTimeout = (action: (() => void) | undefined): void => {
1982
+ timeoutAction = action;
1983
+ ctx.registerTimeout?.(action ? triggerTimeout : undefined);
1984
+ if (action && timeoutTriggered) action();
1985
+ };
1986
+ const timer = setTimeout(triggerTimeout, timeoutMs);
1987
+ timer.unref?.();
1988
+ try {
1989
+ return await runSingleStep(step, {
1990
+ ...ctx,
1991
+ registerTimeout,
1992
+ timeoutSignal: combinedAbortSignal([ctx.timeoutSignal, timeoutController.signal]),
1993
+ timeoutMessage,
1994
+ });
1995
+ } finally {
1996
+ clearTimeout(timer);
1997
+ ctx.registerTimeout?.(undefined);
1998
+ }
1999
+ }
2000
+
1958
2001
  async function runSubagent(
1959
2002
  config: SubagentRunConfig,
1960
2003
  onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
@@ -2139,6 +2182,7 @@ async function runSubagent(
2139
2182
 
2140
2183
  fs.mkdirSync(asyncDir, { recursive: true });
2141
2184
  writeAtomicJson(statusPath, statusPayload);
2185
+ updateActiveRunIndex(asyncDir, statusPayload.state);
2142
2186
  let pendingParallelUsageCost: CostSummary = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
2143
2187
  const currentUsageTotals = (): CostSummary => {
2144
2188
  const cost = results.reduce<CostSummary>((sum, result) => ({
@@ -2211,11 +2255,25 @@ async function runSubagent(
2211
2255
  for (const node of graph.nodes) updateNode(node);
2212
2256
  statusPayload.workflowGraph = graph;
2213
2257
  };
2214
- const writeStatusPayload = (): void => {
2258
+ let lastIndexedActiveState = isActiveAsyncState(statusPayload.state);
2259
+ const writeStatusPayloadNow = (): void => {
2215
2260
  refreshWorkflowGraph();
2216
2261
  writeAtomicJson(statusPath, statusPayload);
2262
+ const activeState = isActiveAsyncState(statusPayload.state);
2263
+ if (activeState !== lastIndexedActiveState) {
2264
+ updateActiveRunIndex(asyncDir, statusPayload.state);
2265
+ lastIndexedActiveState = activeState;
2266
+ }
2217
2267
  emitNestedSelfEvent(statusPayload.state === "running" || statusPayload.state === "queued" ? "subagent.nested.updated" : "subagent.nested.completed");
2218
2268
  };
2269
+ const statusWriteCoalescer = createFileCoalescer(writeStatusPayloadNow, 100);
2270
+ const writeStatusPayload = (immediate = true): void => {
2271
+ if (immediate || statusPayload.state !== "running" || statusPayload.activityState !== undefined) {
2272
+ if (!statusWriteCoalescer.flush(statusPath)) writeStatusPayloadNow();
2273
+ return;
2274
+ }
2275
+ statusWriteCoalescer.schedule(statusPath);
2276
+ };
2219
2277
  const updateExternalProcess = (index: number, process: ExternalProcessStatus): void => {
2220
2278
  requiredStatusStep(statusPayload, index).externalProcess = process;
2221
2279
  statusPayload.lastUpdate = Date.now();
@@ -2287,7 +2345,7 @@ async function runSubagent(
2287
2345
  const nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);
2288
2346
  if (!nestedAsyncDir) continue;
2289
2347
  try {
2290
- deliverInterruptRequest(omitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: "ancestor-interrupt" }));
2348
+ deliverInterruptRequest({ asyncDir: nestedAsyncDir, source: "ancestor-interrupt" });
2291
2349
  } catch (error) {
2292
2350
  appendJsonl(eventsPath, JSON.stringify({
2293
2351
  type: "subagent.nested.interrupt_failed",
@@ -2742,7 +2800,7 @@ async function runSubagent(
2742
2800
  step.lastActivityAt = now;
2743
2801
  statusPayload.lastActivityAt = now;
2744
2802
  statusPayload.lastUpdate = now;
2745
- writeStatusPayload();
2803
+ writeStatusPayload(false);
2746
2804
  return;
2747
2805
  }
2748
2806
  if (event.type === "tool_execution_start" && event.toolName) {
@@ -2878,7 +2936,7 @@ async function runSubagent(
2878
2936
  statusPayload.lastActivityAt = now;
2879
2937
  statusPayload.lastUpdate = now;
2880
2938
  maybeEmitActiveLongRunning(flatIndex, now);
2881
- writeStatusPayload();
2939
+ writeStatusPayload(false);
2882
2940
  };
2883
2941
  const updateRunnerActivityState = (now: number): boolean => {
2884
2942
  if (!controlConfig.enabled) return false;
@@ -3449,7 +3507,7 @@ async function runSubagent(
3449
3507
  writeStatusPayload();
3450
3508
  appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent }));
3451
3509
  flushPendingStepSteers(fi);
3452
- const singleResult = await runSingleStep(task, compactOptional<SingleStepContext>({
3510
+ const singleResult = await runSingleStepWithTimeout(task, compactOptional<SingleStepContext>({
3453
3511
  previousOutput, placeholder, cwd, sessionEnabled,
3454
3512
  outputs,
3455
3513
  sessionDir: config.sessionDir ? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`) : undefined,
@@ -3479,7 +3537,7 @@ async function runSubagent(
3479
3537
  onWriterProcess,
3480
3538
  onExternalProcess: (process) => updateExternalProcess(fi, process),
3481
3539
  skipAcceptance: () => timedOut || stopped,
3482
- }));
3540
+ }), config.deadlineAt);
3483
3541
  const taskEndTime = Date.now();
3484
3542
  const childInterrupted = singleResult.interrupted === true;
3485
3543
  const childStopped = singleResult.stopped === true;
@@ -3831,7 +3889,7 @@ async function runSubagent(
3831
3889
  const { taskForRun, taskCwd } = prepareParallelTaskRun(task, cwd, worktreeSetup, taskIdx);
3832
3890
  flushPendingStepSteers(fi);
3833
3891
 
3834
- const singleResult = await runSingleStep(taskForRun, compactOptional<SingleStepContext>({
3892
+ const singleResult = await runSingleStepWithTimeout(taskForRun, compactOptional<SingleStepContext>({
3835
3893
  previousOutput, placeholder, cwd: taskCwd, sessionEnabled,
3836
3894
  outputs,
3837
3895
  sessionDir: taskSessionDir,
@@ -3861,7 +3919,7 @@ async function runSubagent(
3861
3919
  onWriterProcess,
3862
3920
  onExternalProcess: (process) => updateExternalProcess(fi, process),
3863
3921
  skipAcceptance: () => timedOut || stopped,
3864
- }));
3922
+ }), config.deadlineAt);
3865
3923
  if (task.sessionFile) {
3866
3924
  latestSessionFile = task.sessionFile;
3867
3925
  }
@@ -4120,7 +4178,7 @@ async function runSubagent(
4120
4178
  }));
4121
4179
 
4122
4180
  flushPendingStepSteers(flatIndex);
4123
- const singleResult = await runSingleStep(seqStep, compactOptional<SingleStepContext>({
4181
+ const singleResult = await runSingleStepWithTimeout(seqStep, compactOptional<SingleStepContext>({
4124
4182
  previousOutput, placeholder, cwd, sessionEnabled,
4125
4183
  outputs: statusPayload.mode === "single" ? undefined : outputs,
4126
4184
  sessionDir: config.sessionDir,
@@ -4150,7 +4208,7 @@ async function runSubagent(
4150
4208
  onWriterProcess,
4151
4209
  onExternalProcess: (process) => updateExternalProcess(flatIndex, process),
4152
4210
  skipAcceptance: () => timedOut || stopped,
4153
- }));
4211
+ }), config.deadlineAt);
4154
4212
  if (seqStep.sessionFile) {
4155
4213
  latestSessionFile = seqStep.sessionFile;
4156
4214
  }
@@ -4439,6 +4497,7 @@ async function runSubagent(
4439
4497
  statusPayload.error = `Step failed: ${failedStep.agent}`;
4440
4498
  }
4441
4499
  }
4500
+ writeStatusPayload();
4442
4501
  try {
4443
4502
  writeAtomicJson(resultPath, {
4444
4503
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -4592,7 +4651,6 @@ async function runSubagent(
4592
4651
  console.error(`Failed to write process-terminal candidate for '${id}':`, error);
4593
4652
  }
4594
4653
  }
4595
- writeStatusPayload();
4596
4654
  }
4597
4655
 
4598
4656
  async function waitForStartupControl(