@ferris1225/pi-subagents 4.3.33 → 5.0.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 (37) hide show
  1. package/CHANGELOG.md +32 -349
  2. package/README.md +130 -549
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +52 -31
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +21 -15
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +101 -32
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +38 -10
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
@@ -1,10 +1,9 @@
1
1
  /**
2
- * Sub-agent result handling and resilient RPC launch orchestration.
2
+ * Sub-agent result handling and native Pi CLI launch orchestration.
3
3
  *
4
- * The process transport itself lives in rpc-run.ts. Each attempt starts pi in
5
- * persistent `--mode rpc`, sends commands over strict LF-delimited JSONL, and
6
- * settles only on `agent_settled`. This module owns startup-race recovery,
7
- * selected-to-main model handoff, capability-clamped thinking, accounting, and
4
+ * The process transport lives in cli-run.ts. Each attempt uses Pi's native
5
+ * one-shot `--mode json` event stream and
6
+ * settles only on `agent_settled`. This module owns selected-to-main model handoff, capability-clamped thinking, accounting, and
8
7
  * result formatting around those attempts.
9
8
  */
10
9
 
@@ -17,22 +16,21 @@ import type { AgentConfig } from "../delegation/agents.ts";
17
16
  import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "../configuration/config.ts";
18
17
  import {
19
18
  emptyUsage,
20
- RpcRunControl,
21
- type RpcSingleResult,
19
+ RunControl,
20
+ type RunResult,
22
21
  type SubagentLiveEvent,
23
22
  type UsageStats,
24
- } from "./rpc-control.ts";
23
+ } from "./run-control.ts";
25
24
  import {
26
25
  currentSubagentDepth,
27
- isRpcCommandTimeoutError,
28
- runRpcAgentAttempt,
26
+ runCliAgentAttempt,
29
27
  sessionExists,
30
- } from "./rpc-run.ts";
28
+ } from "./cli-run.ts";
31
29
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
32
30
 
33
31
  export {
34
32
  currentSubagentDepth,
35
- RpcRunControl,
33
+ RunControl,
36
34
  sessionExists,
37
35
  };
38
36
  export type { SubagentLiveEvent, UsageStats };
@@ -40,25 +38,7 @@ export type { SubagentLiveEvent, UsageStats };
40
38
  const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
41
39
  /** 0 disables the watchdog; dispatch supplies the configured timeout. */
42
40
  const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
43
- /** Base delays cover Pi's stale-lock window and leave headroom beyond the
44
- * default four-way launch fan-out. Additive jitter below reduces the chance
45
- * that contenders retry in the same lockstep waves. */
46
- const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500, 3000, 6000] as const;
47
- const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
48
- const MAX_SUBAGENT_STARTUP_RETRY_JITTER_MS = 1000;
49
-
50
- function normalizeStartupRetryDelay(delayMs: number): number {
51
- return Number.isFinite(delayMs) && delayMs > 0 ? delayMs : 0;
52
- }
53
-
54
- function addStartupRetryJitter(delayMs: number, randomValue = Math.random()): number {
55
- const baseDelay = Math.floor(normalizeStartupRetryDelay(delayMs));
56
- if (baseDelay === 0) return 0;
57
- const boundedRandom = Number.isFinite(randomValue) ? Math.max(0, Math.min(1, randomValue)) : 0;
58
- return baseDelay + Math.floor(Math.min(baseDelay, MAX_SUBAGENT_STARTUP_RETRY_JITTER_MS) * boundedRandom);
59
- }
60
-
61
- export interface SingleResult extends RpcSingleResult {}
41
+ export interface SingleResult extends RunResult {}
62
42
 
63
43
  export interface SubagentDetails {
64
44
  mode: "single" | "parallel";
@@ -225,16 +205,6 @@ export function isModelLevelFailure(result: SingleResult): boolean {
225
205
  if (!isFailedResult(result)) return false;
226
206
  if (result.stopReason === "aborted") return false;
227
207
  if (result.dispatchFailed) return false;
228
- if (result.rpcStartupFailed) return false;
229
- // A negative RPC response proves Pi rejected the prompt before execution. It
230
- // remains safe to hand off even though dispatch was attempted; local write,
231
- // close, timeout, and lost-ACK failures never set this explicit flag.
232
- if (result.rpcPromptRejected) return true;
233
- // The prompt write completed but its ACK never arrived. With no later activity
234
- // we cannot know whether Pi started the model or tools, so neither startup
235
- // retry nor selected→main fallback may replay this objective.
236
- if (result.rpcPromptDispatched && !result.rpcPromptAccepted && !result.rpcActivity) return false;
237
- if (isRpcCommandTimeoutError(result.errorMessage)) return false;
238
208
  if (result.integrationStatus === "retained") return false;
239
209
  if (result.errorMessage?.includes("idle timeout")) return true;
240
210
 
@@ -250,77 +220,7 @@ export function isModelLevelFailure(result: SingleResult): boolean {
250
220
  }
251
221
 
252
222
  if ((result.failedTools?.length ?? 0) > 0) return false;
253
- // No accepted prompt, no activity, and no assistant turn means the provider
254
- // was never reached. Stderr or an exit error here is a startup/transport miss.
255
- if (!result.rpcPromptAccepted && !result.rpcActivity) return false;
256
- return Boolean(
257
- result.rpcPromptAccepted ||
258
- result.rpcActivity ||
259
- result.errorMessage?.trim() ||
260
- result.stderr.trim(),
261
- );
262
- }
263
-
264
- export function isRetryableStartupFailure(result: SingleResult, durationMs: number): boolean {
265
- if (result.exitCode === 0) return false;
266
- if (result.stopReason === "aborted") return false;
267
- if (result.dispatchFailed) return false;
268
- if (result.rpcPromptDispatched || result.rpcPromptAccepted || result.rpcActivity) return false;
269
- if (result.errorMessage?.includes("idle timeout")) return false;
270
- if (getFinalOutput(result.messages)) return false;
271
- if (result.messages.length > 0) return false;
272
- const usage = result.usage;
273
- if (usage.turns || usage.input || usage.output || usage.cacheRead || usage.cacheWrite || usage.cost) return false;
274
- if (result.rpcStartupFailed) return true;
275
- if (durationMs > MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS) return false;
276
- if (result.stderr.trim().length > 0) return false;
277
- if (result.errorMessage && result.errorMessage.trim().length > 0) return false;
278
- return true;
279
- }
280
-
281
- function formatStartupRetryExhaustedError(model: string, attempts: number): string {
282
- return `Subagent failed to start after ${attempts} attempt${attempts === 1 ? "" : "s"} on ${model}: the child failed before its initial RPC prompt was dispatched and produced no model, tool, output, or usage activity. Main handles this phase; inspect launch diagnostics instead of redispatching it.`;
283
- }
284
-
285
- async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
286
- const normalizedDelay = normalizeStartupRetryDelay(delayMs);
287
- if (normalizedDelay === 0) return !signal?.aborted;
288
- if (!signal) {
289
- return new Promise<boolean>((resolve) => {
290
- const timer = setTimeout(() => resolve(true), normalizedDelay);
291
- if (typeof timer.unref === "function") timer.unref();
292
- });
293
- }
294
- if (signal.aborted) return false;
295
- return new Promise<boolean>((resolve) => {
296
- let settled = false;
297
- const finish = (shouldRetry: boolean): void => {
298
- if (settled) return;
299
- settled = true;
300
- clearTimeout(timer);
301
- signal.removeEventListener("abort", onAbort);
302
- resolve(shouldRetry);
303
- };
304
- const onAbort = (): void => finish(false);
305
- const timer = setTimeout(() => finish(true), normalizedDelay);
306
- if (typeof timer.unref === "function") timer.unref();
307
- signal.addEventListener("abort", onAbort, { once: true });
308
- });
309
- }
310
-
311
- async function waitForControlledRetry(
312
- delayMs: number,
313
- signal: AbortSignal | undefined,
314
- control: RpcRunControl | undefined,
315
- ): Promise<boolean> {
316
- let remaining = normalizeStartupRetryDelay(delayMs);
317
- while (remaining > 0) {
318
- if (control?.isStopRequested()) return false;
319
- const slice = Math.min(remaining, 50);
320
- if (!(await waitForStartupRetry(slice, signal))) return false;
321
- remaining -= slice;
322
- }
323
- return !signal?.aborted && !control?.isStopRequested();
223
+ return result.activityObserved === true;
324
224
  }
325
225
 
326
226
  /** Runtime/assistant diagnostics, never an inference from individual failed tools. */
@@ -378,28 +278,24 @@ export interface RunSingleOptions {
378
278
  /** Resolve the effective level for each runtime model candidate. */
379
279
  thinkingLevelForModel?: (modelRef?: string) => ThinkingLevel;
380
280
  idleTimeoutMs?: number;
381
- startupRetryDelaysMs?: readonly number[];
382
281
  sessionDir?: string;
383
282
  sessionId?: string;
384
283
  /** Parent directory for a fresh session directory: the project-scoped
385
284
  * sessions root, so retained sessions survive reloads and restarts. */
386
285
  sessionRoot: string;
387
- /** Parent directory for per-attempt transient files (child prompt, retry
388
- * policy): the project-scoped tmp root, so nothing lands in the OS temp. */
286
+ /** Project-scoped temporary prompt files, separate from retained sessions. */
389
287
  scratchRoot: string;
390
- /** Initial RPC prompt. Kept under the old name to limit caller churn. */
288
+ /** Plain-text prompt passed to Pi over stdin. */
391
289
  stdinText?: string;
392
- /** Refresh parent-derived tools immediately before every startup retry and
290
+ /** Refresh parent-derived tools immediately before every selected model and
393
291
  * selected-to-main fallback process is spawned. */
394
292
  resolveAgentForAttempt?: (agent: AgentConfig) => AgentConfig;
395
293
  signal?: AbortSignal;
396
294
  onLive?: (event: SubagentLiveEvent) => void;
397
- makeDetails: (results: SingleResult[]) => SubagentDetails;
398
295
  env?: NodeJS.ProcessEnv;
399
- /** Stable logical-generation controller shared across retry attempts. */
400
- control?: RpcRunControl;
401
- rpcReadyTimeoutMs?: number;
402
- rpcCommandTimeoutMs?: number;
296
+ /** Stable logical-generation controller shared across model attempts. */
297
+ control?: RunControl;
298
+ startupTimeoutMs?: number;
403
299
  }
404
300
 
405
301
  function controlledDisposition(options: RunSingleOptions, base?: SingleResult): SingleResult | undefined {
@@ -424,15 +320,7 @@ function controlledDisposition(options: RunSingleOptions, base?: SingleResult):
424
320
  return result;
425
321
  }
426
322
 
427
- function signalAbortDisposition(options: RunSingleOptions, base: SingleResult): SingleResult | undefined {
428
- if (!options.signal?.aborted) return undefined;
429
- base.exitCode = 1;
430
- base.stopReason = "aborted";
431
- base.errorMessage = "Subagent was aborted";
432
- return base;
433
- }
434
-
435
- /** Spawn one RPC attempt and wait for stable settlement. */
323
+ /** Spawn one native JSON CLI attempt and wait for stable settlement. */
436
324
  async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult> {
437
325
  const {
438
326
  agent,
@@ -445,7 +333,7 @@ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult>
445
333
  if (disposition) return disposition;
446
334
  const objective = control?.getObjective() ?? options.task;
447
335
  const prompt = options.stdinText ?? `Task: ${objective}`;
448
- const result = await runRpcAgentAttempt({
336
+ const result = await runCliAgentAttempt({
449
337
  defaultCwd: options.defaultCwd,
450
338
  agent,
451
339
  agentName,
@@ -461,8 +349,7 @@ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult>
461
349
  onLive: options.onLive,
462
350
  env: options.env,
463
351
  control,
464
- rpcReadyTimeoutMs: options.rpcReadyTimeoutMs,
465
- rpcCommandTimeoutMs: options.rpcCommandTimeoutMs,
352
+ startupTimeoutMs: options.startupTimeoutMs,
466
353
  });
467
354
  result.task = control?.getObjective() ?? result.task;
468
355
  return result;
@@ -470,8 +357,7 @@ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult>
470
357
 
471
358
  /**
472
359
  * Run one logical generation on the selected model, then hand directly to the
473
- * current main model after any model/provider-level failure. Startup-race retries
474
- * remain process-level recovery; provider/model retries and extra candidates do not.
360
+ * current main model after any model/provider-level failure. A launch failure is returned to main without replaying an ambiguous prompt.
475
361
  * Both attempts resume the same retained Pi session.
476
362
  */
477
363
  export async function runSingleAgentWithMainFallback(
@@ -480,8 +366,6 @@ export async function runSingleAgentWithMainFallback(
480
366
  ): Promise<SingleResult> {
481
367
  const agent = options.agent;
482
368
  const launchedRef = agent?.model;
483
- const customStartupDelays = options.startupRetryDelaysMs;
484
- const startupDelays = customStartupDelays ?? SUBAGENT_STARTUP_RETRY_DELAYS_MS;
485
369
 
486
370
  const sessionId = options.sessionId ?? randomUUID();
487
371
  const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
@@ -518,52 +402,16 @@ export async function runSingleAgentWithMainFallback(
518
402
  };
519
403
  };
520
404
 
521
- const runWithStartupRetry = async (opts: RunSingleOptions): Promise<SingleResult> => {
522
- let lastResult: SingleResult;
523
- let retries = 0;
524
- for (let attempt = 0; ; attempt++) {
525
- const immediate = controlledDisposition(opts);
526
- if (immediate) return immediate;
527
- const start = Date.now();
528
- try {
529
- const attemptOptions = opts.resolveAgentForAttempt
530
- ? { ...opts, agent: opts.resolveAgentForAttempt(opts.agent) }
531
- : opts;
532
- lastResult = await runSingleAgent(attemptOptions);
533
- } catch (error) {
534
- const failed = await dispatchFailure(error);
535
- return controlledDisposition(opts, failed) ?? failed;
536
- }
537
- const durationMs = Date.now() - start;
538
- const controlled = controlledDisposition(opts, lastResult);
539
- if (controlled) return controlled;
540
- if (lastResult.stopReason === "aborted") return lastResult;
541
- if (!isRetryableStartupFailure(lastResult, durationMs)) {
542
- if (retries > 0 && !isFailedResult(lastResult)) lastResult.startupRetries = retries;
543
- return lastResult;
544
- }
545
- const delay = startupDelays[attempt];
546
- if (delay === undefined) {
547
- const reason = getResultError(lastResult);
548
- lastResult.errorMessage = [formatStartupRetryExhaustedError(
549
- lastResult.model ?? opts.agent.model ?? "default",
550
- attempt + 1,
551
- ), reason].filter(Boolean).join("\n");
552
- lastResult.stopReason ??= "error";
553
- lastResult.dispatchFailed = true;
554
- return lastResult;
555
- }
556
- opts.control?.markRetrying();
557
- try {
558
- opts.onLive?.({ kind: "status", status: "running" });
559
- } catch {
560
- /* never throw from event handling */
561
- }
562
- const retryDelay = customStartupDelays ? delay : addStartupRetryJitter(delay);
563
- if (!(await waitForControlledRetry(retryDelay, opts.signal, opts.control))) {
564
- return controlledDisposition(opts, lastResult) ?? signalAbortDisposition(opts, lastResult) ?? lastResult;
565
- }
566
- retries++;
405
+ const runAttempt = async (opts: RunSingleOptions): Promise<SingleResult> => {
406
+ const immediate = controlledDisposition(opts);
407
+ if (immediate) return immediate;
408
+ try {
409
+ const attemptOptions = opts.resolveAgentForAttempt ? { ...opts, agent: opts.resolveAgentForAttempt(opts.agent) } : opts;
410
+ const result = await runSingleAgent(attemptOptions);
411
+ return controlledDisposition(opts, result) ?? result;
412
+ } catch (error) {
413
+ const failed = await dispatchFailure(error);
414
+ return controlledDisposition(opts, failed) ?? failed;
567
415
  }
568
416
  };
569
417
 
@@ -654,7 +502,7 @@ export async function runSingleAgentWithMainFallback(
654
502
  /* never throw from event handling */
655
503
  }
656
504
 
657
- result = await runWithStartupRetry(candidateOptions);
505
+ result = await runAttempt(candidateOptions);
658
506
  if (result.stopReason === "aborted") return finish(result);
659
507
  if (!isModelLevelFailure(result)) return finish(result);
660
508
  // Any model-level failure advances immediately to the sole fallback (the
@@ -3,7 +3,7 @@
3
3
  * extension creates under a project's durable root.
4
4
  *
5
5
  * Two classes live there and both are swept the same way. Transient per-run
6
- * files (child prompt copies, the no-retry policy extension) sit in `tmp/`;
6
+ * files (child prompt copies) sit in `tmp/`;
7
7
  * retained child sessions and isolated worktrees sit in `sessions/` and
8
8
  * `worktrees/`, where they must outlive the process that made them for manual
9
9
  * recovery after reload. Every mkdtemp directory gets an owner marker with the
@@ -28,8 +28,7 @@ import { join } from "node:path";
28
28
  export const TEMP_OWNER_FILE_NAME = "owner.json";
29
29
 
30
30
  /** Transient directories created under `<project>/tmp`: the child prompt
31
- * copies (`pi-subagents-*`) and the no-retry policy extension
32
- * (`pi-subagents-policy-*`). The singular `pi-subagent-` prefixes below belong
31
+ * copies (`pi-subagents-*`), including policy-shim leftovers from older releases. The singular `pi-subagent-` prefixes below belong
33
32
  * to the durable roots and are swept separately, under a reference guard. */
34
33
  const TEMP_DIR_PREFIXES = ["pi-subagents-"] as const;
35
34
 
@@ -0,0 +1,36 @@
1
+ /** Cancel work owned by a cancelled parent turn or an abandoned conversation branch. */
2
+
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import { stopWorkflow } from "../workflow/engine.ts";
5
+ import type { SubagentRuntime } from "./runtime.ts";
6
+ import { stopThreads } from "./stop.ts";
7
+
8
+ const cancellations = new WeakMap<SubagentRuntime, Promise<void>>();
9
+
10
+ export function cancelActiveWork(runtime: SubagentRuntime, reason: string): Promise<void> {
11
+ const existing = cancellations.get(runtime);
12
+ if (existing) return existing;
13
+ runtime.suppressCompletions = true;
14
+ runtime.discardCompletions();
15
+ // Start every interruption before awaiting cleanup: a worktree's integration
16
+ // may need a repository lane held by a different shared writer.
17
+ const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
18
+ const graphStops = graphs.map(async (graph) => { await stopWorkflow(runtime, graph, reason); await graph.done; });
19
+ const threadIds = [...runtime.threads.values()]
20
+ .filter((thread) => !thread.workflow && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)))
21
+ .map((thread) => thread.id);
22
+ const done = Promise.all([...graphStops, stopThreads(runtime, threadIds, reason)]).then(() => undefined).finally(() => {
23
+ runtime.discardCompletions();
24
+ runtime.suppressCompletions = false;
25
+ cancellations.delete(runtime);
26
+ });
27
+ cancellations.set(runtime, done);
28
+ return done;
29
+ }
30
+
31
+ export function registerCancellationHooks(pi: ExtensionAPI, runtime: SubagentRuntime): void {
32
+ pi.on("agent_settled", (event) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.") : undefined);
33
+ pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch."));
34
+ // Pi emits session_shutdown for new/resume/fork/reload. The runtime's
35
+ // shutdown path stops children, retains recovery evidence, and disables delivery.
36
+ }
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { formatUsageTokens, sumUsage, type RunWaitReason } from "../presentation/monitor.ts";
11
- import type { UsageStats } from "../execution/rpc-control.ts";
11
+ import type { UsageStats } from "../execution/run-control.ts";
12
12
  export interface CompletionBatchTimings {
13
13
  debounceMs: number;
14
14
  maxWaitMs: number;
@@ -127,7 +127,6 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
127
127
  },
128
128
  finishRun,
129
129
  makeLiveHandler,
130
- makeDetails,
131
130
  });
132
131
 
133
132
  return {
@@ -18,7 +18,7 @@ import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
18
18
  import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
19
19
  import { uptime } from "node:os";
20
20
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
21
- import type { UsageStats } from "../execution/rpc-control.ts";
21
+ import type { UsageStats } from "../execution/run-control.ts";
22
22
  import { normalizePhaseId, normalizePhaseScope, type PhaseScope } from "../delegation/phase-scope.ts";
23
23
  import type { SubagentThread } from "./runtime.ts";
24
24
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
+ import { findDuplicateDispatch } from "../delegation/prompt.ts";
12
13
  import type { PhaseScope } from "../delegation/phase-scope.ts";
13
14
  import { rmSync } from "node:fs";
14
15
  import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
@@ -21,8 +22,8 @@ import {
21
22
  } from "./completion.ts";
22
23
  import { type ThinkingLevel } from "../configuration/config.ts";
23
24
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
24
- import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
25
- import type { RpcRunControl } from "../execution/rpc-control.ts";
25
+ import { isRunActiveStatus, monitor, type RunWorkflowTag } from "../presentation/monitor.ts";
26
+ import type { RunControl } from "../execution/run-control.ts";
26
27
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
27
28
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
28
29
  import type { WorkflowRun } from "../workflow/state.ts";
@@ -40,6 +41,8 @@ export interface SubagentThread {
40
41
  scope?: PhaseScope;
41
42
  /** Capability snapshot used by declared-scope admission, including after restore. */
42
43
  writeCapable?: boolean;
44
+ /** Live graph membership; graph summaries own delivery for these runs. */
45
+ workflow?: RunWorkflowTag;
43
46
  /** Caller-facing cwd in the original worktree. */
44
47
  cwd: string;
45
48
  /** Actual child cwd (the equivalent path inside an isolated worktree). */
@@ -51,7 +54,7 @@ export interface SubagentThread {
51
54
  /** Original durable evidence retained when its worktree handle is unavailable. */
52
55
  restorationRecord?: ThreadRecord;
53
56
  state: ThreadState;
54
- control: RpcRunControl;
57
+ control: RunControl;
55
58
  queueController?: AbortController;
56
59
  /** Resolves after the child, isolation finalization, and queue work fully quiesce. */
57
60
  generationCompletion: Promise<void>;
@@ -83,6 +86,9 @@ export interface SubagentRuntime {
83
86
  getToolInfos: () => ToolInfo[];
84
87
  /** False after session_shutdown; guards delivery and queue work. */
85
88
  sessionActive: boolean;
89
+ /** Cancelling a parent must not wake it again with old child results. */
90
+ suppressCompletions: boolean;
91
+ discardCompletions: () => void;
86
92
  /** Resolves when the load-time durable restore pass has finished. Everything
87
93
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
88
94
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -103,8 +109,6 @@ export interface SubagentRuntime {
103
109
  publishRunCompletion: (runId: number, item: CompletionMessageItem, immediate: boolean) => void;
104
110
  /** Mark awaited results as returned in the tool response. */
105
111
  completeAwaitDelivery: (runIds: readonly number[]) => void;
106
- /** Transfer aborted awaited calls back to completion delivery. */
107
- fallbackAwaitDelivery: (runIds: readonly number[]) => void;
108
112
  completionBatcher: CompletionBatcher<CompletionMessageItem>;
109
113
  /** Abort controllers per active run, so subagent_stop can cancel a run in-turn. */
110
114
  runControllers: Map<number, AbortController>;
@@ -133,6 +137,26 @@ export interface SubagentRuntime {
133
137
  shutdown: () => Promise<void>;
134
138
  }
135
139
 
140
+ /** Pending nodes reserve their phases before they allocate ordinary run ids. */
141
+ export function findPendingWorkflowPhase(
142
+ runtime: Pick<SubagentRuntime, "workflows">,
143
+ task: string,
144
+ cwd: string,
145
+ phaseId?: string,
146
+ excludeWorkflowId?: number,
147
+ ): { workflowId: number; nodeId: string; agent: string } | undefined {
148
+ for (const graph of runtime.workflows.values()) {
149
+ if (graph.state !== "running" || graph.id === excludeWorkflowId) continue;
150
+ for (const node of graph.nodes) {
151
+ if (node.state !== "pending" && !(node.state === "running" && node.runId === undefined)) continue;
152
+ if (findDuplicateDispatch([{ id: graph.id, agentName: node.agent, task: node.task, cwd: node.cwd, phaseId: node.phaseId, state: "queued" }], task, cwd, phaseId)) {
153
+ return { workflowId: graph.id, nodeId: node.id, agent: node.agent };
154
+ }
155
+ }
156
+ }
157
+ return undefined;
158
+ }
159
+
136
160
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
137
161
  const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
138
162
  let nextWorkflowId = 1;
@@ -143,22 +167,24 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
143
167
  let compactionInFlight = false;
144
168
  let heldCompletions: CompletionMessageItem[] = [];
145
169
 
146
- const runDeliveries = new Map<number, {
147
- route: "background" | "await";
148
- completion?: CompletionMessageItem;
149
- immediate: boolean;
150
- }>();
170
+ const runDeliveries = new Map<number, "background" | "await">();
151
171
  const runtime: SubagentRuntime = {
152
172
  configPath,
153
173
  backgroundQueue,
154
174
  getActiveTools: () => pi.getActiveTools(),
155
175
  getToolInfos: () => pi.getAllTools(),
156
176
  sessionActive: true,
177
+ suppressCompletions: false,
178
+ discardCompletions: () => {
179
+ runtime.completionBatcher.dispose();
180
+ heldCompletions = [];
181
+ runDeliveries.clear();
182
+ },
157
183
  durableRestore: Promise.resolve(),
158
184
  restoredRunIds: [],
159
185
  restoredNotified: false,
160
186
  sendCompletionGroup: (items) => {
161
- if (!runtime.sessionActive || items.length === 0) return;
187
+ if (!runtime.sessionActive || runtime.suppressCompletions || items.length === 0) return;
162
188
  // Direct (immediate-failure/stop) delivery must follow successes already
163
189
  // held by the debounce batcher. A batcher's own emit sees an empty batch.
164
190
  runtime.completionBatcher?.flush();
@@ -190,14 +216,11 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
190
216
  pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
191
217
  },
192
218
  claimRunDelivery: (runId, route) => {
193
- runDeliveries.set(runId, { route, immediate: false });
219
+ runDeliveries.set(runId, route);
194
220
  },
195
221
  publishRunCompletion: (runId, item, immediate) => {
196
- const delivery = runDeliveries.get(runId) ?? { route: "background" as const, immediate: false };
197
- delivery.completion = item;
198
- delivery.immediate = immediate;
199
- runDeliveries.set(runId, delivery);
200
- if (delivery.route === "await") return;
222
+ if (runtime.suppressCompletions) { runDeliveries.delete(runId); return; }
223
+ if (runDeliveries.get(runId) === "await") return;
201
224
  runDeliveries.delete(runId);
202
225
  if (immediate) {
203
226
  runtime.sendCompletionGroup([item]);
@@ -207,20 +230,10 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
207
230
  },
208
231
  completeAwaitDelivery: (runIds) => {
209
232
  for (const runId of runIds) {
210
- const delivery = runDeliveries.get(runId);
211
- if (delivery?.route === "await") runDeliveries.delete(runId);
212
- }
213
- },
214
- fallbackAwaitDelivery: (runIds) => {
215
- for (const runId of runIds) {
216
- const delivery = runDeliveries.get(runId);
217
- if (!delivery || delivery.route !== "await") continue;
218
- delivery.route = "background";
219
- if (delivery.completion) {
220
- runtime.publishRunCompletion(runId, delivery.completion, delivery.immediate);
221
- }
233
+ if (runDeliveries.get(runId) === "await") runDeliveries.delete(runId);
222
234
  }
223
235
  },
236
+
224
237
  completionBatcher: undefined as unknown as CompletionBatcher<CompletionMessageItem>,
225
238
  runControllers: new Map<number, AbortController>(),
226
239
  settledRuns: new Map<number, SingleResult>(),