@henryqw/pi-subagent 30.1.0 → 31.1.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 (41) hide show
  1. package/CONTEXT.md +2 -2
  2. package/README.md +19 -23
  3. package/dist/direct-herdr.d.ts +5 -0
  4. package/dist/direct-herdr.js +9 -1
  5. package/dist/ephemeral.d.ts +9 -3
  6. package/dist/ephemeral.js +70 -11
  7. package/dist/herdr-runtime.js +4 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/native-host.d.ts +96 -0
  11. package/dist/native-host.js +243 -0
  12. package/dist/runner.d.ts +8 -1
  13. package/dist/runner.js +22 -15
  14. package/dist/schema.d.ts +71 -2
  15. package/dist/schema.js +14 -1
  16. package/dist/workspace-schema.d.ts +11 -0
  17. package/dist/workspace.d.ts +5 -2
  18. package/dist/workspace.js +58 -29
  19. package/docs/measurement.md +12 -1
  20. package/docs/orchestration-architecture.html +4 -4
  21. package/docs/orchestration-architecture.svg +2 -2
  22. package/docs/orchestration.md +72 -259
  23. package/docs/workspace.md +4 -80
  24. package/extensions/admission.ts +36 -11
  25. package/extensions/direct-check-exec.py +91 -0
  26. package/extensions/direct-check-supervisor.mjs +42 -0
  27. package/extensions/direct-check-witness.mjs +34 -0
  28. package/extensions/direct-native.ts +17 -5
  29. package/extensions/direct-outbox.ts +189 -0
  30. package/extensions/direct-owner.ts +49 -0
  31. package/extensions/direct-verification.ts +73 -0
  32. package/extensions/isolated.ts +25 -301
  33. package/extensions/prerequisite-evidence.ts +81 -0
  34. package/extensions/result-transport.ts +6 -4
  35. package/extensions/subagent-command.ts +12 -7
  36. package/extensions/subagent.ts +378 -499
  37. package/extensions/workflow-recovery.ts +359 -0
  38. package/extensions/workflow.ts +156 -40
  39. package/extensions/workspace.ts +16 -74
  40. package/package.json +2 -2
  41. package/skills/pi-subagent/SKILL.md +15 -37
@@ -0,0 +1,49 @@
1
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+
6
+ const HANDOFF_LIMIT = 64;
7
+
8
+ export function ownerAlive(owner: { host: string; pid: number }) {
9
+ if (owner.host !== hostname()) return true; // A different host cannot prove the original process stopped.
10
+ try { process.kill(owner.pid, 0); return true; }
11
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
12
+ }
13
+
14
+ export function claimOwner(root: string, name: string, token: string): string | undefined {
15
+ let target = join(root, name);
16
+ const candidate = join(root, `.${randomUUID()}.claim`);
17
+ mkdirSync(candidate, { mode: 0o700 });
18
+ try {
19
+ const fd = openSync(join(candidate, "owner.json"), "wx", 0o600);
20
+ try { writeFileSync(fd, JSON.stringify({ host: hostname(), pid: process.pid, token })); fsyncSync(fd); }
21
+ finally { closeSync(fd); }
22
+ const candidateDir = openSync(candidate, "r");
23
+ try { fsyncSync(candidateDir); } finally { closeSync(candidateDir); }
24
+ for (let generation = 0; generation < HANDOFF_LIMIT; generation++) {
25
+ try {
26
+ renameSync(candidate, target);
27
+ const parent = openSync(root, "r");
28
+ try { fsyncSync(parent); } finally { closeSync(parent); }
29
+ return target;
30
+ } catch (error) {
31
+ if (!["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
32
+ const ownerData = readFileSync(join(target, "owner.json"), "utf8");
33
+ const owner = JSON.parse(ownerData) as { host: string; pid: number; token?: string };
34
+ if (!owner || typeof owner.host !== "string" || !Number.isSafeInteger(owner.pid) || owner.pid < 1) return undefined;
35
+ if (owner.host === hostname() && owner.pid === process.pid && owner.token === token && !existsSync(join(target, "released"))) return target;
36
+ if (ownerAlive(owner) && !existsSync(join(target, "released"))) return undefined;
37
+ // Each immutable predecessor determines exactly one successor slot.
38
+ const predecessor = createHash("sha256").update(target).update("\0").update(ownerData).digest("hex");
39
+ target = join(root, `${name}.${predecessor}`);
40
+ }
41
+ }
42
+ throw new Error("Recovery handoff generation limit reached.");
43
+ } finally {
44
+ if (existsSync(candidate)) {
45
+ try { unlinkSync(join(candidate, "owner.json")); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
46
+ try { rmdirSync(candidate); } catch { /* Retain a failed cleanup. */ }
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,73 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { processLeaseIdentity } from "../dist/process-lease.js";
6
+ import type { NativeSession } from "./direct-native.ts";
7
+ import { VERIFICATION_LIMITS, type Delegation } from "./workflow.ts";
8
+
9
+ type Check = NonNullable<Delegation["verification"]>["checks"][number];
10
+ export type VerificationProof = { state: "pending" | "proved" | "lost" };
11
+
12
+ /** A private supervisor holds the exact lease until the check group is empty. */
13
+ export async function runAcceptanceCheck(check: Check, session: NativeSession, signal: AbortSignal, scope: () => boolean, onWitness?: (proof: VerificationProof) => void): Promise<{ code: number; output: string }> {
14
+ signal.throwIfAborted();
15
+ if (!scope()) throw new Error("Verification scope changed before launch.");
16
+ if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("Verification process groups require macOS or Linux.");
17
+ const file = await open(session.leasePath, constants.O_RDONLY | constants.O_NOFOLLOW);
18
+ try {
19
+ const identity = await processLeaseIdentity(session.leasePath, session.leaseIdentity);
20
+ const actual = await file.stat({ bigint: true });
21
+ if (String(actual.dev) !== identity.device || String(actual.ino) !== identity.inode) throw new Error("Verification lease descriptor changed.");
22
+ signal.throwIfAborted();
23
+ if (!scope()) throw new Error("Verification scope changed before launch.");
24
+ return await new Promise((resolve, reject) => {
25
+ const witnessArgs = [fileURLToPath(new URL("./direct-check-witness.mjs", import.meta.url)), String(check.timeoutMs), check.executable, ...check.args];
26
+ const linux = process.platform === "linux";
27
+ const args = linux ? ["-I", fileURLToPath(new URL("./direct-check-exec.py", import.meta.url)), "reap", process.execPath, ...witnessArgs] : witnessArgs;
28
+ const child = spawn(linux ? "/usr/bin/python3" : process.execPath, args,
29
+ { cwd: session.cwd, stdio: ["ignore", "pipe", "pipe", file.fd, "ipc"], detached: true });
30
+ let settled = false, interrupted = "", size = 0, truncated = false;
31
+ let result: { code?: number; error?: string } | undefined;
32
+ const chunks: Buffer[] = [];
33
+ const collect = (chunk: Buffer) => {
34
+ const remaining = VERIFICATION_LIMITS.outputBytes - size;
35
+ if (remaining > 0) { const part = chunk.subarray(0, remaining); chunks.push(part); size += part.length; }
36
+ if (chunk.length > remaining) truncated = true;
37
+ };
38
+ child.stdout!.on("data", collect);
39
+ child.stderr!.on("data", collect);
40
+ const proof: VerificationProof = { state: "pending" };
41
+ onWitness?.(proof);
42
+ child.on("message", (message) => {
43
+ if (message && typeof message === "object") result = message as typeof result;
44
+ });
45
+ const lost = () => { if (proof.state === "pending") proof.state = "lost"; };
46
+ child.once("error", lost);
47
+ // The message proves the group is empty; exit proves the witness no longer holds the lease.
48
+ child.once("exit", () => { if (proof.state === "pending") proof.state = result ? "proved" : "lost"; });
49
+ let hard: ReturnType<typeof setTimeout> | undefined;
50
+ const stop = (reason: string) => {
51
+ if (interrupted) return;
52
+ interrupted = reason;
53
+ if (child.connected) child.send("stop", () => {});
54
+ hard = setTimeout(() => finish(new Error(`${reason}; process exit was not observed.`)), 2000);
55
+ };
56
+ const abort = () => stop("Verification cancelled");
57
+ const timer = setTimeout(() => stop("Verification timed out"), check.timeoutMs);
58
+ const finish = (error?: Error, code?: number | null, termination?: NodeJS.Signals | null) => {
59
+ if (settled) return;
60
+ settled = true;
61
+ clearTimeout(timer); if (hard) clearTimeout(hard);
62
+ signal.removeEventListener("abort", abort);
63
+ child.stdout!.destroy(); child.stderr!.destroy();
64
+ if (error || interrupted || code !== 0 || termination || !result || typeof result.code !== "number") reject(error ?? new Error(interrupted || result?.error || `Verification supervisor ended without an exit result${termination ? ` (${termination})` : ""}.`));
65
+ else resolve({ code: result.code, output: Buffer.concat(chunks).toString("utf8") + (truncated ? "\n[output truncated]" : "") });
66
+ };
67
+ child.once("error", (error) => finish(error));
68
+ child.once("close", (code, termination) => finish(undefined, code, termination));
69
+ signal.addEventListener("abort", abort, { once: true });
70
+ if (signal.aborted) abort();
71
+ });
72
+ } finally { await file.close(); }
73
+ }
@@ -1,8 +1,7 @@
1
- import { basename } from "node:path";
2
1
  import type { JsonValue } from "@earendil-works/pi-ai";
3
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
3
  import { truncateToWidth } from "@earendil-works/pi-tui";
5
- import { capEphemeralSubagentOutput, utf8Prefix, type EphemeralSubagentExecutor } from "../dist/ephemeral.js";
4
+ import { utf8Prefix, type EphemeralExecutorPool } from "../dist/ephemeral.js";
6
5
  import {
7
6
  createCanonicalGitRootResolver,
8
7
  createExactJudgmentExecutor,
@@ -11,25 +10,19 @@ import {
11
10
  CheckedGitRuntime,
12
11
  type DirectProcessRunner,
13
12
  } from "../dist/git-runtime.js";
13
+ import { NativeHostRuntime } from "../dist/native-host.js";
14
14
  import { HerdrHostRuntime } from "../dist/herdr-runtime.js";
15
15
  import { inspectPruneCandidates, listHerdrPanes, removePruneCandidates, type PruneGuards, type PruneItem, type PruneProgress } from "../dist/prune.js";
16
16
  import { runProcess as directRunProcess } from "../dist/process.js";
17
17
  import { RoleLaunchRuntime, type LaunchRuntimeOptions } from "../dist/launch-runtime.js";
18
- import { IsolatedRunner, nextIntegrationAction, type ExecutePlan, type OperationContext, type RunResponse } from "../dist/runner.js";
18
+ import { IsolatedRunner, type OperationContext, type RunResponse } from "../dist/runner.js";
19
19
  import {
20
20
  IdOnlySchema,
21
- ResumeRequestParameters,
22
- StageRequestSchema,
23
- IntegrationActionParameters,
24
- parseIntegrationAction,
25
- parseStageRequest,
26
21
  parseIdOnly,
27
22
  formatCheckCommand,
28
- parseResumeRequest,
29
23
  sameIdentity,
30
24
  StatusOutputSchema,
31
25
  type CheckBatchEvidence,
32
- type ExecuteRequest,
33
26
  type ExecutionPolicySnapshot,
34
27
  type ModelClass,
35
28
  type ReviewEvidence,
@@ -60,7 +53,7 @@ export type CreateIsolatedComponents = (options: {
60
53
  pi: ExtensionAPI;
61
54
  context(): ExtensionContext;
62
55
  captureFallbackWarning?: LaunchRuntimeOptions["captureFallbackWarning"];
63
- executor: EphemeralSubagentExecutor;
56
+ executor: EphemeralExecutorPool;
64
57
  policy: ExecutionPolicySnapshot;
65
58
  currentPolicy(): ExecutionPolicySnapshot;
66
59
  onStateSaved(state: RunState): void;
@@ -86,14 +79,13 @@ export const createIsolatedComponents: CreateIsolatedComponents = ({
86
79
  context,
87
80
  captureFallbackWarning,
88
81
  resolveRoot,
89
- preflightHost: async ({ root }, operation) => await host.preflightHost({ root }, operation),
90
82
  inspectMainBase: async (input, operation) => await git.inspectMainBase(input, operation),
91
83
  });
92
84
  return {
93
85
  resolveRoot,
94
86
  runner: new IsolatedRunner(
95
87
  coordinator,
96
- host,
88
+ new NativeHostRuntime(host, coordinator, executor, git),
97
89
  git,
98
90
  new FileRunStore(undefined, onStateSaved),
99
91
  executor,
@@ -139,7 +131,8 @@ export function workspaceWidgetLines(state: RunState): string[] | undefined {
139
131
  candidate.kind === "workspace" && candidate.status !== "absent",
140
132
  );
141
133
  const workspaceCleanup = attempt?.cleanup.find((step) => step.kind === "workspace");
142
- if (workspaceCleanup?.status === "completed" || (!allocation && !["allocating", "working", "attention"].includes(status))) return [];
134
+ const nativeWorker = attempt?.allocations.some((item) => item.kind === "native" && item.status === "owned");
135
+ if (nativeWorker ? ["completed", "aborted", "rejected"].includes(status) : workspaceCleanup?.status === "completed" || (!allocation && !["allocating", "working", "attention"].includes(status))) return [];
143
136
  const symbol = status === "attention" ? "!" : status === "ready" || status === "completed" ? "✓"
144
137
  : ["working", "allocating", "integrating", "cleanup"].includes(status) ? "◌" : "■";
145
138
  const detail = status === "ready" ? "candidate ready · Main not promoted"
@@ -160,6 +153,7 @@ function renderWorkspaceWidget(ctx: ExtensionContext, rowsByRequest: Map<string,
160
153
  const shown = allRows.length > MAX_WORKSPACE_WIDGET_LINES
161
154
  ? [...allRows.slice(0, MAX_WORKSPACE_WIDGET_LINES - 1), `+${allRows.length - MAX_WORKSPACE_WIDGET_LINES + 1} more · /subagent`]
162
155
  : allRows;
156
+ if (ctx.mode === "rpc") { ctx.ui.setWidget(WORKSPACE_WIDGET_KEY, shown.length ? shown : undefined); return; }
163
157
  ctx.ui.setWidget(WORKSPACE_WIDGET_KEY, shown.length ? (_tui, theme) => ({
164
158
  invalidate() {},
165
159
  render(width) {
@@ -293,10 +287,10 @@ function publicNeedsAttention(state: RunState, verdictMaxBytes: number, preferre
293
287
  ...(failedReview ? { failedReview } : {}),
294
288
  };
295
289
  }
296
- const nextAction = nextIntegrationAction(state);
290
+ const generation = state.integration.generations.at(-1);
297
291
  return {
298
292
  scope: "request" as const,
299
- ...(nextAction ? { nextAction } : { failure: "Request needs attention without a task or final failure." }),
293
+ ...(generation ? { nextAction: `Inspect saved integration generation ${generation.number} (${generation.status}) before handling its retained changes.` } : { failure: "Request needs attention without a task or final failure." }),
300
294
  };
301
295
  }
302
296
 
@@ -319,7 +313,7 @@ function publicState(state: RunState, verdictMaxBytes: number, preferredTaskId?:
319
313
  } } : {}),
320
314
  ...(task.kind === "changeset" && state.integration.candidates.length ? { attempts: task.attempts.map((attempt) => ({
321
315
  number: attempt.number, superseded: attempt.superseded === true,
322
- workerId: attempt.allocations.flatMap((item) => item.kind === "agent" && item.status === "owned" ? [item.agentName] : [])[0],
316
+ workerId: attempt.allocations.flatMap((item) => (item.kind === "native" || item.kind === "agent") && item.status === "owned" ? [item.agentName] : [])[0],
323
317
  termination: attempt.termination?.status,
324
318
  worktree: attempt.allocations.flatMap((item) => item.kind === "worktree" && item.status === "owned" && item.worktree ? [item.worktree.path] : [])[0],
325
319
  cleanup: attempt.cleanup.filter((step) => step.status !== "completed"),
@@ -386,16 +380,9 @@ function failedReviewText(state: RunState): string {
386
380
  return parts.join("");
387
381
  }
388
382
 
389
- function hasTruncatedVerdict(state: ReturnType<typeof publicState>): boolean {
390
- const attention = state.needsAttention;
391
- return Boolean(attention && "failedReview" in attention && attention.failedReview?.verdictTruncated)
392
- || state.integration.generations.some((generation) => generation.failedReview?.verdictTruncated);
393
- }
394
-
395
- function inspectionNotices({ state, main, continuation }: RunResponse): string[] {
383
+ function inspectionNotices({ state, main }: RunResponse): string[] {
396
384
  const lines = [
397
385
  `Isolated request ${state.request.id}: ${state.status}; accepted: ${state.accepted}; final: ${state.final.status}; Main: ${main?.status ?? "not checked"}.`,
398
- ...(continuation ? [`Reported continuation: ${JSON.stringify(continuation)}`] : []),
399
386
  ];
400
387
  if (main) lines.push(main.status === "unavailable"
401
388
  ? `Main inspection unavailable: ${boundedPublicText(main.failure)}; expected: ${JSON.stringify(main.expected)}`
@@ -430,6 +417,7 @@ function inspectionNotices({ state, main, continuation }: RunResponse): string[]
430
417
  ? { worktree: allocation.worktree && { path: allocation.worktree.path, cwd: allocation.worktree.cwd, branch: allocation.worktree.branch, repoRoot: allocation.worktree.repoRoot } }
431
418
  : allocation.kind === "workspace" ? { label: allocation.label, workspaceId: allocation.workspaceId, worktreeCwd: allocation.worktreeCwd, mainRoot: allocation.mainRoot, herdrRepoRoot: allocation.herdrRepoRoot, repoKey: allocation.repoKey, rootTabId: allocation.rootTabId, rootPaneId: allocation.rootPaneId }
432
419
  : allocation.kind === "worker_tab" ? { label: allocation.label, workspaceId: allocation.workspaceId, workspaceRootTabId: allocation.workspaceRootTabId, workspaceRootPaneId: allocation.workspaceRootPaneId, tabId: allocation.tabId, paneId: allocation.paneId, leasePath: allocation.leasePath, worktreeCwd: allocation.worktreeCwd }
420
+ : allocation.kind === "native" ? { agentName: allocation.agentName, leasePath: allocation.leasePath, worktreeCwd: allocation.worktreeCwd }
433
421
  : { agentName: allocation.agentName, workspaceId: allocation.workspaceId, tabId: allocation.tabId, paneId: allocation.paneId, leasePath: allocation.leasePath, worktreeCwd: allocation.worktreeCwd };
434
422
  lines.push(`${label} ${allocation.kind} (${displayStatus}): ${JSON.stringify({ ...resource, possibleResources: allocation.possibleResources, failure: allocation.failure ? boundedPublicText(allocation.failure) : undefined })}`);
435
423
  }
@@ -462,65 +450,20 @@ function toolResult(response: RunResponse, ctx: ExtensionContext, rowsByRequest:
462
450
  ? response.continuation.taskId
463
451
  : undefined;
464
452
  const workspaces = workspaceWidgetLines(response.state);
453
+ const summary = `Saved request ${response.state.request.id}: ${response.state.status}.`;
465
454
  const text = ctx.hasUI === false && workspaces
466
- ? `${response.text}\n\nActive workspaces:\n${workspaces.join("\n")}`
467
- : response.text;
455
+ ? `${summary}\n\nActive workspaces:\n${workspaces.join("\n")}`
456
+ : summary;
468
457
  return {
469
458
  content: [{ type: "text" as const, text }],
470
459
  details: {
471
460
  state: publicState(response.state, PUBLIC_REVIEW_VERDICT_MAX_BYTES, preferredTaskId),
472
461
  ...(response.main ? { main: response.main } : {}),
473
- ...(response.continuation ? { continuation: response.continuation } : {}),
474
- },
475
- };
476
- }
477
-
478
- /** Bounded dry-run plan; a route missing from the coordinator report shows as unresolved. */
479
- export function formatExecutePlan({ request, root, main, routes }: ExecutePlan, hostChecked: boolean): { content: [{ type: "text"; text: string }]; details: unknown } {
480
- const route = (role: string, modelClass: ModelClass) => {
481
- const found = routes.find((candidate) => candidate.role === role && candidate.modelClass === modelClass);
482
- return found ? { model: found.model, thinkingLevel: found.thinkingLevel } : undefined;
483
- };
484
- const label = (role: string, modelClass: ModelClass) => {
485
- const resolved = route(role, modelClass);
486
- return `${role} · ${modelClass} → ${resolved ? `${resolved.model} · thinking ${resolved.thinkingLevel}` : "route not reported"}`;
487
- };
488
- const changesets = request.tasks.some((task) => task.kind === "changeset");
489
- const notChecked = [
490
- ...(changesets && !hostChecked ? ["Herdr host preflight (client and server versions, API schema, lsof, current workspace identity): it calls Herdr"] : []),
491
- "request ID uniqueness and saved-state admission: they need the state lock",
492
- ];
493
- const lines = [
494
- `Dry run passed: isolated request ${request.id} in ${root} at Main ${main.head.slice(0, 12)} (${main.branch}). No state, worktree, Herdr tab, lease, or follow-up was created.`,
495
- ...request.tasks.map((task, index) => [
496
- `${index + 1}. ${task.id} · ${task.kind} · ${label(task.role, task.modelClass)}`,
497
- ` depends on: ${task.dependsOn.join(", ") || "none"} · context from: ${task.contextFrom.join(", ") || "none"}`,
498
- ...(task.kind === "changeset" ? [` checks: ${task.checks.map(formatCheckCommand).join("; ")}`,
499
- ...(task.judgment ? [` judgment: ${label(task.judgment.role, task.judgment.modelClass)}`] : [])] : []),
500
- ].join("\n")),
501
- `Final checks: ${request.finalChecks.map(formatCheckCommand).join("; ") || "none"}`,
502
- ...(request.finalJudgment ? [`Final judgment: ${label(request.finalJudgment.role, request.finalJudgment.modelClass)}`] : []),
503
- ...notChecked.map((reason) => `Not checked: ${reason}.`),
504
- ];
505
- return {
506
- content: [{ type: "text", text: capEphemeralSubagentOutput(lines.join("\n")) }],
507
- details: {
508
- dryRun: true, mode: "isolated", id: request.id, root, main,
509
- tasks: request.tasks.map((task) => ({ id: task.id, kind: task.kind, role: task.role, modelClass: task.modelClass,
510
- ...route(task.role, task.modelClass), dependsOn: task.dependsOn, contextFrom: task.contextFrom,
511
- ...(task.kind === "changeset" ? { checks: task.checks, ...(task.judgment ? { judgment: { ...task.judgment, ...route(task.judgment.role, task.judgment.modelClass) } } : {}) } : {}) })),
512
- finalChecks: request.finalChecks,
513
- ...(request.finalJudgment ? { finalJudgment: { ...request.finalJudgment, ...route(request.finalJudgment.role, request.finalJudgment.modelClass) } } : {}),
514
- notChecked,
515
462
  },
516
463
  };
517
464
  }
518
465
 
519
466
  export interface IsolatedSurface {
520
- hasPendingResult(sessionId: string): boolean;
521
- /** Dry run of execute: validates and resolves without durable state or Herdr calls. */
522
- plan(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof formatExecutePlan>>;
523
- execute(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof toolResult>>;
524
467
  inventory(cwd: string, current?: () => boolean): Promise<IsolatedInventory>;
525
468
  collectTabs(cwd: string, eligible: (workspaceId: string) => Promise<boolean>, current: () => boolean): Promise<string[]>;
526
469
  recover(cwd: string): Promise<string>;
@@ -535,14 +478,13 @@ export interface IsolatedSurface {
535
478
  }
536
479
 
537
480
  export interface RegisterIsolatedOptions {
538
- executor: EphemeralSubagentExecutor;
481
+ executor: EphemeralExecutorPool;
539
482
  policy: ExecutionPolicySnapshot;
540
483
  currentPolicy(): ExecutionPolicySnapshot;
541
484
  /** Report new config issues, and throw when the config now blocks delegation, before each deferred Role launch. */
542
485
  beforeRoleLaunch?(ctx: ExtensionContext): void;
543
486
  componentsFactory?: CreateIsolatedComponents;
544
- /** Notification after productive work releases its lease. */
545
- onFinished?(ctx: ExtensionContext): void;
487
+
546
488
  }
547
489
 
548
490
  /** Register lifecycle surfaces; delegate_task remains the only start tool. */
@@ -552,9 +494,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
552
494
  let components: IsolatedExtensionComponents | undefined;
553
495
  const workspaceRowsByRequest = new Map<string, string[]>();
554
496
  let savedRevision = 0;
555
- const stateListeners = new Set<(state: RunState) => void>();
556
- const activeJobs = new Set<AbortController>();
557
- const jobOwners = new Map<string, { canDeliver(): boolean; pendingResult(): boolean }>();
558
497
  const discardDeliveries = new Map<string, () => boolean>();
559
498
  let sessionEpoch = 0;
560
499
  let sessionClosed = false;
@@ -583,11 +522,9 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
583
522
  currentPolicy: options.currentPolicy,
584
523
  onStateSaved: (state) => {
585
524
  savedRevision += 1;
586
- for (const listener of stateListeners) listener(state);
587
525
  const key = `${state.root}\0${state.request.id}`;
588
- const owner = jobOwners.get(key);
589
526
  const discardCurrent = discardDeliveries.get(key);
590
- if (!sessionClosed && (owner === undefined || owner.canDeliver()) && (discardCurrent === undefined || discardCurrent())) {
527
+ if (!sessionClosed && (discardCurrent === undefined || discardCurrent())) {
591
528
  updateWorkspaceWidgetSafely(latestContext(), state, workspaceRowsByRequest);
592
529
  }
593
530
  },
@@ -603,7 +540,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
603
540
  };
604
541
 
605
542
  pi.on("session_start", (_event, ctx) => {
606
- for (const controller of activeJobs) controller.abort();
607
543
  sessionEpoch += 1;
608
544
  sessionClosed = false;
609
545
  latestCtx = ctx;
@@ -611,7 +547,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
611
547
  if (ctx.hasUI) ctx.ui.setWidget(WORKSPACE_WIDGET_KEY, undefined);
612
548
  });
613
549
  pi.on("session_shutdown", () => {
614
- for (const controller of activeJobs) controller.abort();
615
550
  sessionEpoch += 1;
616
551
  sessionClosed = true;
617
552
  workspaceRowsByRequest.clear();
@@ -626,140 +561,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
626
561
  const requireCurrent = (current: () => boolean) => {
627
562
  if (!current() || sessionClosed) throw new Error("Session or branch changed; reopen /subagent.");
628
563
  };
629
- // FileRunStore emits the initial state only after fsync. A resumed run emits its
630
- // recovery record after saving it; validation acknowledges its saved exact intent.
631
- // Neither the tool call nor its abort signal
632
- // owns productive work after that durable boundary.
633
- const startInSession = async (
634
- id: string,
635
- root: string,
636
- signal: AbortSignal | undefined,
637
- ctx: ExtensionContext,
638
- acknowledged: (state: RunState) => boolean,
639
- start: (signal: AbortSignal) => Promise<RunResponse>,
640
- ): Promise<ReturnType<typeof toolResult>> => {
641
- const epoch = sessionEpoch;
642
- const sessionId = ctx.sessionManager?.getSessionId();
643
- const key = `${root}\0${id}`;
644
- if (jobOwners.has(key)) throw new Error(`Pi Subagent request ${id} is already active in this session runtime.`);
645
- const deliverySuppression = () => sessionClosed ? "session closed"
646
- : sessionEpoch !== epoch ? "session generation changed"
647
- : ctx.sessionManager?.getSessionId() !== sessionId ? "launching session changed"
648
- : latestCtx?.sessionManager?.getSessionId() !== sessionId ? "current session changed"
649
- : undefined;
650
- const canDeliver = () => deliverySuppression() === undefined;
651
- const controller = new AbortController();
652
- let durableAcknowledged = false;
653
- activeJobs.add(controller);
654
- const owner = { canDeliver, pendingResult: () => durableAcknowledged && !controller.signal.aborted && canDeliver() };
655
- jobOwners.set(key, owner);
656
- const notified = new Set<string>();
657
- const attentionNotified = new Set<string>();
658
- let candidateListener: ((state: RunState) => void) | undefined;
659
- const finish = () => {
660
- activeJobs.delete(controller);
661
- if (candidateListener) stateListeners.delete(candidateListener);
662
- if (jobOwners.get(key) === owner) jobOwners.delete(key);
663
- };
664
- const abortBeforeAck = () => controller.abort(signal?.reason);
665
- if (signal?.aborted) abortBeforeAck();
666
- else signal?.addEventListener("abort", abortBeforeAck, { once: true });
667
- let latestState: RunState | undefined;
668
- let accept!: (state: RunState) => void;
669
- let reject!: (error: unknown) => void;
670
- const durable = new Promise<RunState>((resolve, fail) => { accept = resolve; reject = fail; });
671
- const removeTurnAbort = () => signal?.removeEventListener("abort", abortBeforeAck);
672
- const listener = (state: RunState) => {
673
- if (state.root !== root || state.request.id !== id) return;
674
- latestState = state;
675
- if (!acknowledged(state)) return;
676
- durableAcknowledged = true;
677
- for (const candidate of state.integration.candidates) notified.add(`${candidate.taskId}\0${candidate.attempt}\0${candidate.tip.head}`);
678
- stateListeners.delete(listener);
679
- removeTurnAbort();
680
- accept(state);
681
- };
682
- stateListeners.add(listener);
683
- const deliver = (kind: "candidate" | "attention" | "terminal", text: string, response?: RunResponse) => {
684
- const suppression = deliverySuppression();
685
- if (suppression) {
686
- console.warn(`Pi Subagent ${id}: ${kind} delivery suppressed (${suppression}); durable request retained.`);
687
- return;
688
- }
689
- const state = response?.state ?? latestState;
690
- try {
691
- const preview = state ? publicState(state, PUBLIC_EVIDENCE_MAX_BYTES, response?.continuation && "taskId" in response.continuation
692
- ? response.continuation.taskId : undefined) : undefined;
693
- const details = preview ? {
694
- state: preview,
695
- ...(response?.continuation ? { continuation: response.continuation } : {}),
696
- } : { id };
697
- pi.sendMessage({
698
- customType: "pi-subagent-isolated-result",
699
- content: preview && hasTruncatedVerdict(preview)
700
- ? `${text}\n\nReview verdicts here are previews; run subagent_status for the full verdict.`
701
- : text,
702
- display: true,
703
- details,
704
- }, { triggerTurn: true, deliverAs: "followUp" });
705
- } catch {
706
- console.error(`Pi Subagent ${id}: ${kind} delivery failed (sendMessage threw); use subagent_status to recover. No delivery replayed.`);
707
- if (ctx.hasUI) ctx.ui.notify(`Pi Subagent ${id} result delivery failed; use subagent_status to recover.`, "error");
708
- }
709
- };
710
- candidateListener = (state) => {
711
- if (state.root !== root || state.request.id !== id) return;
712
- latestState = state;
713
- if (state.status !== "running") return;
714
- for (const task of state.tasks) {
715
- if (task.status !== "needs_attention") {
716
- attentionNotified.delete(task.taskId);
717
- continue;
718
- }
719
- if (attentionNotified.has(task.taskId)) continue;
720
- attentionNotified.add(task.taskId);
721
- deliver("attention", `Pi Subagent ${id}: ${task.taskId} needs attention. Inspect subagent_status for the saved worker evidence; do not replay an uncertain prompt.`);
722
- }
723
- for (const candidate of state.integration.candidates) {
724
- const identity = `${candidate.taskId}\0${candidate.attempt}\0${candidate.tip.head}`;
725
- if (candidate.decision || notified.has(identity)) continue;
726
- notified.add(identity);
727
- deliver("candidate", `Pi Subagent ${id}: ${candidate.taskId} ready to integrate. Inspect the exact candidate with subagent_status and stage it now; other workers may still be running.`);
728
- }
729
- };
730
- stateListeners.add(candidateListener);
731
- void Promise.resolve().then(() => start(controller.signal)).then(
732
- (response) => {
733
- finish();
734
- stateListeners.delete(listener);
735
- removeTurnAbort();
736
- if (!durableAcknowledged) {
737
- reject(new Error(`Pi Subagent ${id} finished without a durable acknowledgement.`));
738
- return;
739
- }
740
- deliver("terminal", `${response.text}\n\nState: ${JSON.stringify(publicState(response.state, PUBLIC_EVIDENCE_MAX_BYTES))}`, response);
741
- if (canDeliver()) options.onFinished?.(ctx);
742
- },
743
- (error: unknown) => {
744
- finish();
745
- stateListeners.delete(listener);
746
- removeTurnAbort();
747
- if (!durableAcknowledged) {
748
- reject(error);
749
- return;
750
- }
751
- deliver("terminal", `Pi Subagent ${id} stopped: ${boundedPublicText(error instanceof Error ? error.message : String(error))}. Use subagent_status to inspect the durable request before choosing an explicit recovery action.`);
752
- if (canDeliver()) options.onFinished?.(ctx);
753
- },
754
- );
755
- const state = await durable;
756
- if (!canDeliver()) throw new Error(`Pi Subagent ${id} was saved, but its launching session changed before acknowledgement. Use subagent_status to inspect the durable request.`);
757
- return toolResult({ text: `Pi Subagent ${id}: durable request accepted; productive work continues. Use subagent_status to inspect progress.`, state }, ctx, workspaceRowsByRequest);
758
- };
759
-
760
- // Status stays callable from codemode scripts and hands them the same bounded public projection
761
- // the model reads; every mutating tool below is model-only because its guarded transitions need
762
- // Main's visible reasoning.
763
564
  pi.registerTool({
764
565
  name: "subagent_status",
765
566
  label: "Subagent status",
@@ -777,63 +578,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
777
578
  return { ...result, content, structuredContent: result.details as JsonValue };
778
579
  },
779
580
  });
780
- pi.registerTool({
781
- name: "subagent_resume",
782
- label: "Subagent resume",
783
- description: "Resume one unfinished isolated request without resetting its recorded policy or correction count. For a retry that sends a same-worker correction, optional instruction (at most 32000 characters) is appended to that prompt as Main's instruction after the saved check or review failure; use it to name the exact fixes, including the review findings the worker must address. Other actions reject instruction.",
784
- parameters: ResumeRequestParameters,
785
- prepareArguments: parseResumeRequest,
786
- exposure: "model-only",
787
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
788
- latestCtx = ctx;
789
- const root = await lookupRoot(ctx.cwd, signal);
790
- return await startInSession(params.id, root, signal, ctx,
791
- (state) => state.recovery?.kind === "resume" && state.recovery.action === params.action
792
- && (!("taskId" in params) || state.recovery.taskId === params.taskId),
793
- (runSignal) => getComponents().runner.resume(params, root, runSignal));
794
- },
795
- });
796
- pi.registerTool({
797
- name: "subagent_stage",
798
- label: "Subagent stage",
799
- description: "Main stages/resolves an exact candidate, or rejects/revises one. Rejection of a staged candidate freezes the old generation; explicitly restage chosen candidates in a new generation. Never writes Main.",
800
- parameters: StageRequestSchema,
801
- prepareArguments: parseStageRequest,
802
- exposure: "model-only",
803
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
804
- latestCtx = ctx;
805
- const root = await lookupRoot(ctx.cwd, signal);
806
- return toolResult(await getComponents().runner.stage(params, root, signal), ctx, workspaceRowsByRequest);
807
- },
808
- });
809
- pi.registerTool({
810
- name: "subagent_integrate",
811
- label: "Subagent integrate",
812
- description: "Main advances staged dependents, refreshes after clean Main drift or evidence-less validation failure, validates in the background, corrects, promotes, reconciles interrupted validation/promotion, cleans up promoted resources, or explicitly releases rejected/superseded owned resources. Never replays an uncertain mutation.",
813
- parameters: IntegrationActionParameters,
814
- prepareArguments: parseIntegrationAction,
815
- exposure: "model-only",
816
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
817
- latestCtx = ctx;
818
- const root = await lookupRoot(ctx.cwd, signal);
819
- if (params.action === "validate") {
820
- return await startInSession(params.id, root, signal, ctx,
821
- (state) => {
822
- const generation = state.integration.generations.at(-1);
823
- return generation?.number === params.generation && generation.status === "validating"
824
- && sameIdentity(generation.combinedTip!, params.expectedTip);
825
- },
826
- (runSignal) => getComponents().runner.integrate(params, root, runSignal));
827
- }
828
- if (params.action === "advance") {
829
- return await startInSession(params.id, root, signal, ctx,
830
- (state) => state.status === "running" && state.waves.at(-1)?.status === "dispatching"
831
- && sameIdentity(state.waves.at(-1)!.base, params.expectedTip),
832
- (runSignal) => getComponents().runner.integrate(params, root, runSignal));
833
- }
834
- return toolResult(await getComponents().runner.integrate(params, root, signal), ctx, workspaceRowsByRequest);
835
- },
836
- });
837
581
  pi.registerTool({
838
582
  name: "subagent_abort",
839
583
  label: "Subagent abort",
@@ -848,8 +592,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
848
592
  },
849
593
  });
850
594
  return {
851
- hasPendingResult: (sessionId) => latestCtx?.sessionManager?.getSessionId() === sessionId
852
- && [...jobOwners.values()].some((owner) => owner.pendingResult()),
853
595
  async inventory(cwd, current) {
854
596
  const root = await lookupRoot(cwd);
855
597
  const revision = savedRevision;
@@ -891,22 +633,20 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
891
633
  ...blockers.map((blocker) => ` Blocker: ${blocker}`),
892
634
  ...(state.final.failure ? [` Final blocker: ${boundedPublicText(state.final.failure)}`] : []),
893
635
  ...(generation?.failure ? [` Integration blocker: ${boundedPublicText(generation.failure)}`] : []),
894
- ...(state.status !== "completed" && readyCandidates.length ? [` ${readyCandidates.length} retained candidate(s); Main selects exact candidates with subagent_stage after subagent_status.`] : []),
636
+ ...(state.status !== "completed" && readyCandidates.length ? [` ${readyCandidates.length} retained candidate(s); inspect the exact saved candidates with subagent_status.`] : []),
895
637
  ...(state.status === "completed" ? [" Retained resources after completion; inspect subagent_status for guarded cleanup."] : []),
896
- ...(generation ? [` Generation ${generation.number}: ${generation.status}; inspect subagent_status before any subagent_integrate action.`] : []),
897
- ...(!leaseBusy && response.continuation ? [` Reported next action: subagent_resume ${JSON.stringify(response.continuation)}.`] : []),
638
+ ...(generation ? [` Generation ${generation.number}: ${generation.status}; inspect subagent_status for its saved identities.`] : []),
898
639
  ].join("\n");
899
640
  }) : ["No unfinished or retained isolated requests."]),
900
641
  ...(invalidIds.length ? [`Unreadable state IDs (preserved; inspect with their compatible owner): ${invalidIds.map((id) => JSON.stringify(id)).join(", ")}.`] : []),
901
642
  leaseBusy ? "Wait for the active productive run; use subagent_status to inspect its current state. No work was taken over."
902
- : "Main: inspect subagent_status for exact identities and blockers before deciding stage, promote, resume, or guarded release. No worker prompt, merge, promotion, or cleanup was replayed.",
643
+ : "Main: inspect subagent_status for exact identities and blockers before reviewing retained work. No worker prompt, merge, promotion, or cleanup was replayed.",
903
644
  ];
904
645
  return boundedReport(lines, "recovery report lines omitted; use subagent_status for exact request evidence.");
905
646
  },
906
647
  async discardPlan(cwd, request) {
907
648
  return await getComponents().runner.discardPlan(cwd, request.id, request.directory, {
908
- panes: () => listHerdrPanes(cwd), current: () => !sessionClosed,
909
- blocked: async () => jobOwners.has(`${request.root}\0${request.id}`) ? "A local job is active for this request." : undefined,
649
+ panes: () => listHerdrPanes(cwd), current: () => !sessionClosed, blocked: async () => undefined,
910
650
  });
911
651
  },
912
652
  async discard(cwd, plan, current) {
@@ -917,8 +657,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
917
657
  discardDeliveries.set(key, canDeliver);
918
658
  try {
919
659
  const removals = await getComponents().runner.discard(cwd, plan, {
920
- panes: () => listHerdrPanes(cwd), current: canDeliver,
921
- blocked: async () => jobOwners.has(key) ? "A local job is active for this request." : undefined,
660
+ panes: () => listHerdrPanes(cwd), current: canDeliver, blocked: async () => undefined,
922
661
  });
923
662
  const count = (outcome: string) => removals.filter((item) => item.outcome === outcome).length;
924
663
  return { failed: count("failed"), skipped: count("skipped"), text: boundedReport([`Close and delete ${plan.requestId}:`,
@@ -959,21 +698,6 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
959
698
  requireCurrent(current);
960
699
  return getComponents().runner.drainFollowups(root, requestId, taskId);
961
700
  },
962
- async plan(request, signal, ctx) {
963
- latestCtx = ctx;
964
- latestContext();
965
- const root = await lookupRoot(ctx.cwd, signal);
966
- if (jobOwners.has(`${root}\0${request.id}`)) throw new Error(`Pi Subagent request ${request.id} is already active in this session runtime.`);
967
- return formatExecutePlan(await getComponents().runner.plan(request, ctx.cwd, signal), false);
968
- },
969
- async execute(request, signal, ctx) {
970
- latestCtx = ctx;
971
- latestContext();
972
- const root = await lookupRoot(ctx.cwd, signal);
973
- return await startInSession(request.id, root, signal, ctx,
974
- (state) => state.status === "pending" && state.createdAt === state.updatedAt
975
- && state.tasks.every((task) => task.status === "pending" && task.attempts.length === 0),
976
- (runSignal) => getComponents().runner.execute(request, ctx.cwd, runSignal));
977
- },
701
+
978
702
  };
979
703
  }