@henryqw/pi-subagent 31.0.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.
package/README.md CHANGED
@@ -22,7 +22,7 @@ Print and JSON sessions receive the direct result in the tool call. Saved intera
22
22
 
23
23
  Direct workers share 4,096 bytes of inline answer text per request. A short answer appears once. The result links to a private file for each oversized answer. A chain passes the complete answer to its next worker. A dependent receives a verified file reference when its prerequisite excerpt is incomplete.
24
24
 
25
- Use the `scout`, `reviewer`, `implementer`, `planner`, or `oracle` role. Main can cancel an owned workflow with `mode: "cancel"` and its exact `id`.
25
+ Use the `scout`, `reviewer`, `implementer`, `planner`, or `oracle` role. Main can cancel an owned workflow with `mode: "cancel"` and its exact `id`. After a restart, the same call stops a recovered native writer and releases its checkout reservation. It finds the writer by its saved PID and the process lease that it held from spawn. Other recovered records need the user in `/subagent`.
26
26
 
27
27
  The [delegation measurements](./docs/measurement.md) compare parent results and report live worker usage.
28
28
 
@@ -26,6 +26,11 @@ export interface DirectHandle {
26
26
  export declare function exactDirectTerminalTurn(jsonl: string, prompt: string): boolean;
27
27
  /** Refuse continuation unless the saved session's exact recorded turn is terminal and no later user turn exists. */
28
28
  export declare function assertSettledDirectSession(sessionFile: string, turn: string, provedStopped?: boolean): Promise<void>;
29
+ /** A write-access worker ended its turn normally and reported that it did not succeed. */
30
+ export declare class DirectReportedOutcomeError extends Error {
31
+ readonly outcome: "failed" | "blocked";
32
+ constructor(outcome: "failed" | "blocked", answer: string);
33
+ }
29
34
  export declare function exactDirectAnswer(jsonl: string, prompt: string, requireSuccess?: boolean): string;
30
35
  /** Measured from one session read; each field is absent when no turn record carried it. */
31
36
  export interface DirectUsage {
@@ -117,6 +117,14 @@ export async function assertSettledDirectSession(sessionFile, turn, provedStoppe
117
117
  throw new Error(`Saved Pi session ${sessionFile} has no terminal final turn for the recorded prompt; the worker may still be running`);
118
118
  }
119
119
  }
120
+ /** A write-access worker ended its turn normally and reported that it did not succeed. */
121
+ export class DirectReportedOutcomeError extends Error {
122
+ outcome;
123
+ constructor(outcome, answer) {
124
+ super(`Direct task reported ${outcome}: ${answer}`);
125
+ this.outcome = outcome;
126
+ }
127
+ }
120
128
  export function exactDirectAnswer(jsonl, prompt, requireSuccess = false) {
121
129
  const final = exactFinalTurn(jsonl, prompt);
122
130
  if (!final || final.stopReason !== "stop" || !Array.isArray(final.content)) {
@@ -143,7 +151,7 @@ export function exactDirectAnswer(jsonl, prompt, requireSuccess = false) {
143
151
  throw new Error("Pi write-access completion must have a valid outcome and a non-empty answer.");
144
152
  }
145
153
  if (completion.outcome !== "succeeded")
146
- throw new Error(`Direct task reported ${completion.outcome}: ${completion.answer}`);
154
+ throw new DirectReportedOutcomeError(completion.outcome, completion.answer);
147
155
  return completion.answer;
148
156
  }
149
157
  class DirectSessionState {
@@ -39,6 +39,8 @@ export interface EphemeralSubagentRunInput {
39
39
  retryReadOnlySpawn?: boolean;
40
40
  /** Distinguish confirmed absence before spawn from an observed process exit. */
41
41
  onProcessEnd?: (reason: "not-started" | "exited") => void;
42
+ /** Receives the worker PID right after spawn. A throw stops the worker. */
43
+ onSpawn?: (pid: number) => void;
42
44
  prepare: () => Promise<{
43
45
  launch: PiLaunch;
44
46
  task: string;
package/dist/ephemeral.js CHANGED
@@ -116,6 +116,9 @@ function validateRunInput(value) {
116
116
  if (input.onProcessEnd !== undefined && typeof input.onProcessEnd !== "function") {
117
117
  throw new TypeError("run.onProcessEnd must be a function.");
118
118
  }
119
+ if (input.onSpawn !== undefined && typeof input.onSpawn !== "function") {
120
+ throw new TypeError("run.onSpawn must be a function.");
121
+ }
119
122
  return value;
120
123
  }
121
124
  function record(value, field) {
@@ -621,6 +624,14 @@ async function runPiAttempt(prepared, input, budget, invocation, startedAt, allo
621
624
  signalCallbackFailure();
622
625
  stop(true);
623
626
  };
627
+ if (child.pid !== undefined && input.onSpawn) {
628
+ try {
629
+ input.onSpawn(child.pid);
630
+ }
631
+ catch (cause) {
632
+ failCallback("onSpawn", cause);
633
+ }
634
+ }
624
635
  let activityQueue = Promise.resolve();
625
636
  const invokeCallback = (name, callback, value) => {
626
637
  if (!callback || callbackFailure)
@@ -98,7 +98,7 @@ Set `"dryRun": true` to preview Role, model, resources, access, and continuation
98
98
 
99
99
  Read requests skip checkout admission and return plain text. Parallel `tasks` run concurrently up to `maxSubagents`; chains stay ordered. The extension does not enforce `read`. Results stay in request order.
100
100
 
101
- Direct mode uses a native Pi child in every terminal. Before a write starts, Main saves its session and process lease identity in the admission journal. Writers run alone within their request. Ready readers in a named dependency graph can run together. Release requires the observed child exit and two empty scans of the original lease. A definite final acceptance failure can release admission after termination proof. Other rejected writes require explicit cleanup. After a restart, `/subagent` provides journal recovery.
101
+ Direct mode uses a native Pi child in every terminal. Before a write starts, Main saves its session and process lease identity in the admission journal. Writers run alone within their request. Ready readers in a named dependency graph can run together. Release requires the observed child exit and two empty scans of the original lease. A definite final acceptance failure can release admission after termination proof. A writer that ends its turn and reports `blocked` releases admission after the same proof, and later writers in its request do not start. Other rejected writes require explicit cleanup. A write request whose Role has only read tools, and no extensions or MCP servers, is refused before admission. Checkout admission blocks every Main tool except read-only tools, whatever path or project the tool input names, because Main tools run from the session checkout. After a restart, `/subagent` provides journal recovery.
102
102
 
103
103
  Native workers save a private Pi session and process lease. To continue a native worker, Main must have observed its process exit in this Pi process. The Role, checkout and last saved turn must match. Two lease scans must be empty. An interrupted turn can resume after these checks. Continuation after a Pi restart is unavailable. Use `{"mode":"cancel","id":"<exact workflow ID>"}` to stop locally owned work on the current branch. The `/subagent` menu also provides Close. Cancellation does not prove that detached descendants stopped.
104
104
 
@@ -163,7 +163,9 @@ A legacy worker without its original saved lease identity cannot be stopped or c
163
163
 
164
164
  Local Close remains the only release authority for locally owned work. It can retry a failed continuation stop or release write. It does not close an unverified allocation or a present shell without proved ownership. Resolve such resources before retrying Close.
165
165
 
166
- For a recovered reservation, select **Review recovered checkout protection**:
166
+ Main can release a recovered reservation itself, without the user and without a restart. It calls `delegate_task` with `{"mode":"cancel","id":"<workflow ID>"}`. The admission block message names this call and the workflow ID. Cancel first accepts complete saved proof. Otherwise, every saved worker must be a native worker that held its process lease from spawn (`spawnLease`) and has a saved PID (`native-process`). Each native writer inherits a descriptor of its lease at launch, so the lease names the live worker before its first instruction. Main closes its own copy when the worker process exits, and journals the worker PID and spawn time right after spawn. Cancel checks each lease identity. It sends `SIGTERM`, then `SIGKILL`, to the process group of a lease holder only when the holder has the saved PID, still leads its process group, and started within 3 seconds of the saved spawn time. A process title hides the worker command line, so cancel does not use it. It sends no signal to other holders, such as an acceptance check witness or a diagnostic tool, and keeps protection while they hold the lease. It releases only after two consecutive empty scans of every lease. The journal saves the release as `agent-scanned` with the reviewed evidence, and replay accepts that kind only for records with spawn leases and saved PIDs. Cancel does not close worker tabs or change files, commits or sessions. Herdr tab workers, allocations, continuation sources and records from older versions keep the human action below. Older package versions cannot replay an `agent-scanned` release and block writes.
167
+
168
+ For the human path, select **Review recovered checkout protection**:
167
169
 
168
170
  - Complete saved proof permits a confirmed release without worker control. Proof means no effect was dispatched, or the local owner saved complete termination evidence before the release write failed. The latter requires complete allocation intents, exact verified tab and pane records, matching original lease identities, and coverage of every saved resource. Missing fields or conflicting identities permit no proof-based release.
169
171
  - Missing proof offers **Keep protection** first. The separate **Release protection despite unproved termination** action requires the exact typed session, task, and token identity. It saves the typed identity and reviewed evidence in a distinct receipt before clearing only that reservation.
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { dirname, isAbsolute, normalize } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
- import { isProcessLeaseIdentity } from "../dist/process-lease.js";
4
+ import { isProcessLeaseIdentity, type ProcessLeaseIdentity } from "../dist/process-lease.js";
5
5
  import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
6
6
  import * as herdr from "@henryqw/pi-herdr";
7
7
  export { registerCheckoutAdmission } from "@henryqw/pi-herdr";
@@ -11,7 +11,7 @@ const JOURNAL = "subagent-direct-admission";
11
11
  const checkoutToolCanWrite = herdr.checkoutToolCanWrite ?? ((name: string, input: unknown, direct: (input: unknown) => boolean) =>
12
12
  name === "delegate_task" ? direct(input) : !["read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode"].includes(name));
13
13
  type Record = { version: 1; sessionId: string; taskId: string; token: string; checkouts: string[]; state: "held" | "released";
14
- proof?: "not-dispatched" | "unproved" | "stopped"; resources?: unknown[]; release?: "proved" | "user-unproved";
14
+ proof?: "not-dispatched" | "unproved" | "stopped"; resources?: unknown[]; release?: "proved" | "user-unproved" | "agent-scanned";
15
15
  waiver?: { identity: string; evidence: string } };
16
16
  const owner = (record: Record) => JSON.stringify([JOURNAL, record.sessionId, record.taskId, record.token]);
17
17
  const text = (value: unknown): value is string => typeof value === "string" && value.length > 0 && !value.includes("\0");
@@ -23,9 +23,9 @@ const parse = (value: unknown): Record => {
23
23
  || new Set(record.checkouts).size !== record.checkouts.length
24
24
  || (record.resources !== undefined && !Array.isArray(record.resources))
25
25
  || (record.proof !== undefined && (!["not-dispatched", "unproved", "stopped"].includes(record.proof) || !Array.isArray(record.resources)))
26
- || (record.state === "released" ? !["proved", "user-unproved"].includes(record.release ?? "") : record.release !== undefined)
26
+ || (record.state === "released" ? !["proved", "user-unproved", "agent-scanned"].includes(record.release ?? "") : record.release !== undefined)
27
27
  || (record.release === "proved" && !["not-dispatched", "stopped"].includes(record.proof ?? ""))
28
- || (record.release === "user-unproved" ? !text(record.waiver?.identity) || !text(record.waiver?.evidence) : record.waiver !== undefined)) throw new Error("Malformed direct admission journal entry.");
28
+ || (record.release === "user-unproved" || record.release === "agent-scanned" ? !text(record.waiver?.identity) || !text(record.waiver?.evidence) : record.waiver !== undefined)) throw new Error("Malformed direct admission journal entry.");
29
29
  return record;
30
30
  };
31
31
  const sameSet = (a: Record, b: Record) => a.checkouts.length === b.checkouts.length && a.checkouts.every((path, index) => path === b.checkouts[index]);
@@ -39,11 +39,13 @@ const hasProof = (record: Record, entries: readonly SessionEntry[]) => {
39
39
  if (!resources) return false;
40
40
  if (record.proof === "not-dispatched") return !resources.length && !resourceEntries(record, entries).length;
41
41
  if (record.proof !== "stopped" || !resources.length) return false;
42
- if (resources.every((resource) => resource?.kind === "native-intent")) {
42
+ if (resources.every((resource) => resource?.kind === "native-intent" || resource?.kind === "native-process")) {
43
43
  const keys = new Set<string>();
44
44
  const saved = resourceEntries(record, entries);
45
- if (saved.length !== resources.length) return false;
46
- return resources.every((resource) => {
45
+ // A native-process resource only adds the PID of a saved native intent.
46
+ const intents = resources.filter((resource) => resource.kind === "native-intent");
47
+ if (saved.length !== intents.length || !resources.every((resource) => resource.kind === "native-intent" || nativeProcess(resource, intents))) return false;
48
+ return intents.every((resource) => {
47
49
  if (!["entryId", "sessionFile", "leasePath", "turn", "cwd", "role"].every((key) => text(resource[key]))
48
50
  || !isProcessLeaseIdentity(resource.leaseIdentity)
49
51
  || !["sessionFile", "leasePath", "cwd"].every((key) => isAbsolute(resource[key]) && normalize(resource[key]) === resource[key])
@@ -90,6 +92,26 @@ const hasProof = (record: Record, entries: readonly SessionEntry[]) => {
90
92
  });
91
93
  };
92
94
 
95
+ const nativeProcess = (resource: any, intents: any[]) => Number.isSafeInteger(resource.pid) && resource.pid > 1 && Number.isSafeInteger(resource.spawnedAt)
96
+ && intents.filter((intent) => intent.entryId === resource.entryId && intent.leasePath === resource.leasePath).length === 1;
97
+
98
+ /** Worker processes that Main may stop and prove absent after a restart. Each native worker must have held its lease
99
+ * from spawn and have a saved PID; any other saved resource (legacy tab, allocation, continuation) returns undefined. */
100
+ export function agentLeases(record: { resources?: unknown[] }): { leasePath: string; leaseIdentity: ProcessLeaseIdentity; pid: number; spawnedAt: number }[] | undefined {
101
+ const resources = (record.resources ?? []) as any[];
102
+ const intents = resources.filter((resource) => resource?.kind === "native-intent");
103
+ const processes = resources.filter((resource) => resource?.kind === "native-process");
104
+ const valid = intents.length > 0 && intents.length + processes.length === resources.length
105
+ && intents.every((resource) => resource.spawnLease === true && text(resource.leasePath) && isAbsolute(resource.leasePath)
106
+ && normalize(resource.leasePath) === resource.leasePath && isProcessLeaseIdentity(resource.leaseIdentity)
107
+ && processes.filter((item) => item.entryId === resource.entryId && item.leasePath === resource.leasePath).length === 1)
108
+ && processes.every((resource) => nativeProcess(resource, intents));
109
+ return valid ? intents.map((intent) => {
110
+ const saved = processes.find((item) => item.entryId === intent.entryId && item.leasePath === intent.leasePath)!;
111
+ return { leasePath: intent.leasePath, leaseIdentity: intent.leaseIdentity, pid: saved.pid, spawnedAt: saved.spawnedAt };
112
+ }) : undefined;
113
+ }
114
+
93
115
  const identity = (record: Record) => `${record.sessionId}/${record.taskId}/${record.token}`;
94
116
  const evidence = (record: Record, entries: readonly SessionEntry[]) => {
95
117
  const sources = (record.resources ?? []).flatMap((resource: any) => resource?.kind === "continuation-sources" && Array.isArray(resource.sources) ? resource.sources : []);
@@ -125,7 +147,8 @@ function replay(entries: readonly SessionEntry[]): Map<string, Record> {
125
147
  const { release, waiver, ...checkpoint } = record;
126
148
  if (!isDeepStrictEqual({ ...checkpoint, state: "held" }, previous)
127
149
  || (release === "proved" ? !hasProof(previous!, entries)
128
- : waiver!.identity !== identity(previous!) || waiver!.evidence !== evidence(previous!, entries))) {
150
+ : waiver!.identity !== identity(previous!) || waiver!.evidence !== evidence(previous!, entries)
151
+ || (release === "agent-scanned" && !agentLeases(previous!)))) {
129
152
  throw new Error("Direct release has incomplete or changed proof or user consent; protection retained.");
130
153
  }
131
154
  } else held.add(JSON.stringify(record));
@@ -228,12 +251,14 @@ export function registerDirectAdmission(pi: ExtensionAPI, canWrite: (input: unkn
228
251
  claims.add(key); // Claim before the first dialog, not after confirmation.
229
252
  return {
230
253
  close: () => { claims.delete(key); },
231
- release(kind: "proved" | "user-unproved", typedIdentity?: string) {
254
+ /** `agent-scanned`: Main proved that every saved process lease is empty; the receipt keeps the reviewed evidence. */
255
+ release(kind: "proved" | "user-unproved" | "agent-scanned", typedIdentity?: string) {
232
256
  requireReady();
233
257
  if (!claims.has(key) || !valid()) throw new Error("Direct recovery scope or evidence changed; protection retained.");
234
258
  if (kind === "proved" && !hasProof(reviewed, ctx.sessionManager.getEntries())) throw new Error("Worker termination is unproved; protection retained.");
235
- if (kind === "user-unproved" && typedIdentity !== identity(reviewed)) throw new Error("Exact typed reservation identity is required; protection retained.");
236
- save({ ...reviewed, state: "released", release: kind, ...(kind === "user-unproved"
259
+ if (kind !== "proved" && typedIdentity !== identity(reviewed)) throw new Error("Exact typed reservation identity is required; protection retained.");
260
+ if (kind === "agent-scanned" && !agentLeases(reviewed)) throw new Error("Only native workers that held their lease from spawn permit an agent release; protection retained.");
261
+ save({ ...reviewed, state: "released", release: kind, ...(kind !== "proved"
237
262
  ? { waiver: { identity: typedIdentity!, evidence: savedEvidence } } : {}) });
238
263
  admission.complete(key);
239
264
  },
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync } from "node:fs";
2
3
  import { mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { dirname, join } from "node:path";
@@ -21,6 +22,7 @@ export async function runNativeDirect(input: {
21
22
  write: boolean;
22
23
  requireSuccess: boolean;
23
24
  onProcessEnd: (reason: "not-started" | "exited") => void;
25
+ onSpawn?: (session: NativeSession, pid: number) => void;
24
26
  prepare: () => Promise<PreparedRoleLaunch>;
25
27
  source?: NativeSession;
26
28
  onSession: (session: NativeSession) => void;
@@ -29,10 +31,14 @@ export async function runNativeDirect(input: {
29
31
  onUsage: (usage: { totalTokens: number; cost: { total: number } }) => void;
30
32
  }): Promise<{ text: string; inline: string; answerFile?: string }> {
31
33
  let transient: Awaited<ReturnType<typeof materializeTransientLaunch>> | undefined;
34
+ // The worker inherits this descriptor at spawn, so the lease names the live worker from its first instruction.
35
+ // Main closes its own copy when the worker process ends, before any lease scan can see Main as a holder.
36
+ let descriptor: number | undefined;
37
+ const closeDescriptor = () => { if (descriptor !== undefined) { const fd = descriptor; descriptor = undefined; closeSync(fd); } };
32
38
  let session!: NativeSession;
33
39
  let prompt = "";
34
40
  try {
35
- const result = await input.executor.run({ signal: input.signal, retryReadOnlySpawn: !input.write, onProcessEnd: input.onProcessEnd, onTokens: input.onTokens, onActivity: input.onActivity, prepare: async () => {
41
+ const result = await input.executor.run({ signal: input.signal, retryReadOnlySpawn: !input.write, onProcessEnd: (reason) => { closeDescriptor(); input.onProcessEnd(reason); }, onSpawn: (pid) => input.onSpawn?.(session, pid), onTokens: input.onTokens, onActivity: input.onActivity, prepare: async () => {
36
42
  const prepared = await input.prepare();
37
43
  input.signal.throwIfAborted();
38
44
  const directory = input.source ? dirname(input.source.sessionFile) : await mkdtemp(join(tmpdir(), "pi-subagent-native-"));
@@ -40,6 +46,10 @@ export async function runNativeDirect(input: {
40
46
  const leasePath = input.source?.leasePath ?? join(directory, "process.lease");
41
47
  if (!input.source) await writeFile(leasePath, "", { flag: "wx", mode: 0o600 });
42
48
  const leaseIdentity = await processLeaseIdentity(leasePath, input.source?.leaseIdentity);
49
+ closeDescriptor();
50
+ descriptor = openSync(leasePath, constants.O_RDONLY | constants.O_NOFOLLOW);
51
+ const opened = fstatSync(descriptor, { bigint: true });
52
+ if (String(opened.dev) !== leaseIdentity.device || String(opened.ino) !== leaseIdentity.inode) throw new Error("Opened process lease differs from its saved identity.");
43
53
  session = { sessionFile: input.source?.sessionFile ?? join(directory, "session.jsonl"), leasePath, leaseIdentity, turn, cwd: input.cwd, role: input.role };
44
54
  let task = input.task;
45
55
  const reader = directTaskReader(task, prepared.tools);
@@ -58,7 +68,7 @@ export async function runNativeDirect(input: {
58
68
  if (args.length !== transient.launch.args.length - 1) throw new Error("Role launch must contain exactly one --no-session option.");
59
69
  input.signal.throwIfAborted();
60
70
  input.onSession(session);
61
- return { launch: { args: [...args, "--session", session.sessionFile], env: { ...prepared.env, [PI_SUBAGENT_PROCESS_LEASE]: leasePath } }, task: prompt.slice(6), cwd: input.cwd };
71
+ return { launch: { args: [...args, "--session", session.sessionFile], env: { ...prepared.env, [PI_SUBAGENT_PROCESS_LEASE]: leasePath } }, task: prompt.slice(6), cwd: input.cwd, leaseFd: descriptor };
62
72
  } });
63
73
  if (result.usage) input.onUsage(result.usage);
64
74
  if (result.outcome !== "success") throw new Error(result.errorMessage || result.stderr || `Native Pi exited with ${result.exitCode} (${result.stopReason ?? "unknown"}).`);
@@ -74,6 +84,6 @@ export async function runNativeDirect(input: {
74
84
  if (error instanceof EphemeralSubagentError && error.usage) input.onUsage(error.usage);
75
85
  throw error;
76
86
  } finally {
77
- if (transient) await transient.cleanup();
87
+ try { closeDescriptor(); } finally { if (transient) await transient.cleanup(); }
78
88
  }
79
89
  }
@@ -8,7 +8,7 @@ import { registerConfigReporting } from "@henryqw/pi-config-store";
8
8
  import { capEphemeralSubagentOutput as capOutput, createEphemeralSubagentExecutor, createSubagentConfigStore, DEFAULT_SUBAGENT_CONFIG, DELEGATE_TASK, DIRECT_ROLE_TASKS, directRoleTask, findRole, formatDuration, loadRoleCatalog, prepareRoleLaunch, resolveRolePackageResources, resolveTaskRoute, ROLE_TOOL_POLICY_FLAG, type ExecutionPolicySnapshot, type Role } from "@henryqw/pi-subagent";
9
9
  import { resolveExecutionPolicy } from "./config.ts";
10
10
  import { captureFallbackWarning } from "./task-model-fallback.ts";
11
- import { registerDirectAdmission } from "./admission.ts";
11
+ import { agentLeases, registerDirectAdmission } from "./admission.ts";
12
12
  import { registerIsolatedExtension } from "./isolated.ts";
13
13
  import { registerWorkspaceExtension } from "./workspace.ts";
14
14
  import { resolveWorkspaceScope } from "../dist/workspace-scope.js";
@@ -17,7 +17,7 @@ import { MODEL_CLASS_GUIDANCE } from "./model-class-policy.ts";
17
17
  import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowResult, workerOutputForMain, type BackgroundWorkflowTransportDetails, type WorkflowTransportEntry } from "./result-transport.ts";
18
18
  import { checkoutNote, DelegateTaskParameters, identifyWorkflowEntries, isDependencyGraph, parseDelegateTask, parseWorkflow, runDependencyGraph, runForegroundWorkflow, snapshotCheckout, writesCheckout, type CheckoutSnapshot, type ParsedWorkflow, type WorkflowEntry } from "./workflow.ts";
19
19
  import { workspaceNeedsCollection } from "../dist/collection.js";
20
- import { assertSettledDirectSession, createDirectHerdr, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity } from "../dist/direct-herdr.js";
20
+ import { assertSettledDirectSession, createDirectHerdr, DirectReportedOutcomeError, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity } from "../dist/direct-herdr.js";
21
21
  import { isProcessLeaseIdentity, processLeaseIdentity, scanProcessLease } from "../dist/process-lease.js";
22
22
  import { setTimeout as sleep } from "node:timers/promises";
23
23
  import { runNativeDirect, type NativeSession } from "./direct-native.ts";
@@ -28,6 +28,8 @@ const WIDGET_KEY = "subagent-status";
28
28
  const WIDGET_INTERVAL_MS = 1_000;
29
29
  const MAX_WIDGET_ITEMS = 8;
30
30
  const MAX_WIDGET_LINES = 6;
31
+ // Tools that cannot change files; a Role limited to these, without extensions or MCP servers, cannot write.
32
+ const READ_ONLY_ROLE_TOOLS: ReadonlySet<string> = new Set(["read", "grep", "find", "ls", "git_read", "fffind", "ffgrep", "codegraph_explore"]);
31
33
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32
34
 
33
35
  type WidgetStatus = "working" | "success" | "failure";
@@ -523,7 +525,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
523
525
  const owned = () => current() && !directTasks.has(task.id);
524
526
  const claim = directAdmission.claim(record, ctx, owned);
525
527
  try {
526
- const review = `Reservation: ${task.admission.identity}\nComplete checkout set:\n${record.checkouts.join("\n")}\nSaved resources:\n${directAdmission.evidence(record, ctx)}\n${task.recovery ?? ""}`;
528
+ // The /subagent report above shows the saved resources; a long dialog title can push the choices out of view.
529
+ const review = `Reservation: ${task.admission.identity}\nComplete checkout set:\n${record.checkouts.join("\n")}\nSaved resources: see the workflow report above.\n${task.recovery ?? ""}`;
527
530
  const proof = directAdmission.hasProof(record, ctx);
528
531
  if (proof) {
529
532
  if (!await ctx.ui.confirm("Release protection from saved proof", `${review}\nNo worker will be stopped, replayed, or deleted. Release this exact reservation?`) || !owned()) return "Protection retained.";
@@ -799,7 +802,13 @@ export default function subagentExtension(pi: ExtensionAPI): void {
799
802
  const graph = isDependencyGraph(workflow);
800
803
  const selected = workflow.repositories ? await resolveWorkspaceScope(ctx.cwd, workflow.repositories, signal) : undefined;
801
804
  const catalog = loadRoleCatalog();
802
- for (const delegation of workflow.delegations) findRole(catalog, delegation.role);
805
+ for (const delegation of workflow.delegations) {
806
+ const role = findRole(catalog, delegation.role);
807
+ // A Role limited to read tools cannot complete a write and would hold admission for nothing.
808
+ if (delegation.access === "write" && !role.extensions.length && !role.mcps?.length && role.tools.every((tool) => READ_ONLY_ROLE_TOOLS.has(tool))) {
809
+ throw new Error(`Role ${role.name} has only read tools (${role.tools.join(", ") || "none"}), so task ${delegation.name} cannot use access "write". Use a Role with write tools, or set access "read".`);
810
+ }
811
+ }
803
812
  const policy = currentPolicy();
804
813
  const savedPolicy = claimRecovery?.policy;
805
814
  const limits = executorLimits(policy);
@@ -968,6 +977,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
968
977
  if (signal?.aborted) abort();
969
978
  const run = (async () => {
970
979
  let stopDispatch = false;
980
+ // Writers that ended normally and reported blocked; their release still needs lease proof.
981
+ const reportedBlocked = new Set<string>();
971
982
  const prelaunchFailures = new Set<string>();
972
983
  let remainingCorrections = policy.maxCorrections;
973
984
  try {
@@ -1028,9 +1039,12 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1028
1039
  if (reason === "exited") nativeCompletedTurns.set(key, session);
1029
1040
  },
1030
1041
  task: `${task}${entry.delegation.verification ? `\n\nAcceptance criteria: ${entry.delegation.verification.criteria}` : ""}${selected ? `\n\nExplicit selected repository map: ${JSON.stringify(workflow.repositories)}. Do not modify other repositories or workspace-root files.` : ""}\n\nFinal answer budget: ${answerBytes} bytes; put conclusions first.`, answerBytes,
1042
+ // The saved PID and spawn time let Main signal only this worker after a restart.
1043
+ onSpawn: (session, pid) => releaseAdmission?.effect({ kind: "native-process", entryId: turnId, leasePath: session.leasePath, pid, spawnedAt: Date.now() }),
1031
1044
  onSession: (session) => {
1032
1045
  if (!current()) throw new Error("Launching session changed before native start.");
1033
- releaseAdmission?.effect({ kind: "native-intent", entryId: turnId, ...session });
1046
+ // spawnLease: the worker held this lease from spawn, so Main may prove its exit by lease scans after a restart.
1047
+ releaseAdmission?.effect({ kind: "native-intent", entryId: turnId, spawnLease: true, ...session });
1034
1048
  const evidence: NativeRecord = { taskId, entryId: turnId, access: writes ? "write" : "read", ref: `${ref}.${turnId === entry.id ? entry.index + 1 : entries.length + entry.index + 1}`, display: nativeDisplays[entry.index]!, ...session };
1035
1049
  sessions.set(turnId, session);
1036
1050
  nativeSessionClaims.add(session.sessionFile);
@@ -1113,6 +1127,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1113
1127
  finishWidgetItem(entry.id, "success");
1114
1128
  return output.text;
1115
1129
  } catch (error) {
1130
+ if (writes && !graph && !verifying && error instanceof DirectReportedOutcomeError && error.outcome === "blocked") reportedBlocked.add(entry.id);
1116
1131
  if (verifying) {
1117
1132
  stopDispatch = true;
1118
1133
  local.recovery = "Acceptance did not complete successfully; inspect the edits and close the workflow to release the checkout.";
@@ -1144,7 +1159,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1144
1159
  states.set(entry.id, { ...states.get(entry.id)!, status: "rejected", failure });
1145
1160
  prelaunchFailures.add(entry.id); // No worker was launched for this entry.
1146
1161
  });
1147
- if (writes && !controller.signal.aborted && !stopDispatch && [...states.values()].every((state) => state.status === "succeeded" || (state.status === "rejected" && prelaunchFailures.has(state.id)) || (prelaunchFailures.size > 0 && (state.status === "blocked" || state.status === "pending")))) await local.close!(() => current());
1162
+ if (writes && !controller.signal.aborted && !stopDispatch && [...states.values()].every((state) => state.status === "succeeded" || (state.status === "rejected" && (prelaunchFailures.has(state.id) || reportedBlocked.has(state.id))) || ((prelaunchFailures.size > 0 || reportedBlocked.size > 0) && (state.status === "blocked" || state.status === "pending")))) await local.close!(() => current());
1148
1163
  } catch { /* Cancellation and worker failures are reflected in the entry states. */ }
1149
1164
  finally {
1150
1165
  if (controller.signal.aborted) try { journal?.stop(); } catch (error) { if (ctx.hasUI) ctx.ui.notify(`Recovery journal: ${boundedError(error).message}`, "warning"); }
@@ -1179,6 +1194,58 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1179
1194
  return { content: [{ type: "text" as const, text: `Native direct ${writes ? "write" : "read"} started · ${ref} · ${taskId}. ${entries.length} task(s); one follow-up will arrive in this session. Use /subagent to cancel. ${writes ? "Checkout admission stays held until completion and process termination are proved." : "Read access is not enforced."}` }], details: { taskId, mode: workflow.mode, entries: entries.map(({ id, index, delegation }) => ({ id, index, name: delegation.name, role: delegation.role })) } };
1180
1195
  };
1181
1196
 
1197
+ /** Main's own release of a reservation that no live owner in this process holds: stop every saved lease holder,
1198
+ * then require two empty scans of each original lease. Saved records without exact leases keep the human release. */
1199
+ const releaseRecovered = async (record: ReturnType<typeof directAdmission.inventory>["records"][number], ctx: ExtensionContext): Promise<string> => {
1200
+ const epoch = sessionEpoch, manager = ctx.sessionManager, session = manager.getSessionId();
1201
+ const current = () => epoch === sessionEpoch && session === manager.getSessionId() && !directTasks.has(record.taskId);
1202
+ const reservation = `${record.sessionId}/${record.taskId}/${record.token}`;
1203
+ const claim = directAdmission.claim(record, ctx, current);
1204
+ try {
1205
+ if (directAdmission.hasProof(record, ctx)) {
1206
+ claim.release("proved");
1207
+ return `Saved proof accepted; reservation ${reservation} released. Files, commits and session evidence preserved. Inspect changes in ${record.checkouts.join(", ")} before new work.`;
1208
+ }
1209
+ const leases = agentLeases(record);
1210
+ if (!leases) throw new Error(`Reservation ${reservation} has saved worker resources that Main cannot check: only native workers with a lease held from spawn and a saved PID qualify. Protection retained. Ask the user to open /subagent, select the workflow, and choose "Review recovered checkout protection".`);
1211
+ const stopped: number[] = [];
1212
+ for (const { leasePath, leaseIdentity, pid: workerPid, spawnedAt } of leases) {
1213
+ const scan = async (pid?: number) => {
1214
+ if (!current()) throw new Error("Session or branch changed during recovered release; protection retained.");
1215
+ await processLeaseIdentity(leasePath, leaseIdentity);
1216
+ const holders = await scanProcessLease(leasePath, (args) => pi.exec("lsof", args, { cwd: ctx.cwd, timeout: 3_000 }), pid);
1217
+ await processLeaseIdentity(leasePath, leaseIdentity);
1218
+ return holders;
1219
+ };
1220
+ // Signal only the saved worker: the saved PID, still leading its own process group, started when Main spawned it.
1221
+ // The process title hides argv, and an acceptance check witness also leads a group, so neither identifies a worker.
1222
+ const isWorker = async (pid: number) => {
1223
+ if (pid !== workerPid) return false;
1224
+ const result = await pi.exec("ps", ["-o", "pgid=,etime=", "-p", String(pid)], { cwd: ctx.cwd, timeout: 3_000 });
1225
+ const match = result.code === 0 ? /^\s*(\d+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(result.stdout) : null;
1226
+ if (!match || Number(match[1]) !== pid) return false;
1227
+ const elapsed = ((Number(match[2] ?? 0) * 24 + Number(match[3] ?? 0)) * 60 + Number(match[4])) * 60 + Number(match[5]);
1228
+ return Math.abs(Date.now() - elapsed * 1_000 - spawnedAt) <= 3_000;
1229
+ };
1230
+ let holders = await scan();
1231
+ for (const [signal, delay] of [["SIGTERM", 1_000], ["SIGKILL", 250]] as const) {
1232
+ if (!holders.length) break;
1233
+ for (const pid of holders) {
1234
+ if (!(await scan(pid)).includes(pid) || !await isWorker(pid)) continue;
1235
+ try { process.kill(-pid, signal); stopped.push(pid); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
1236
+ }
1237
+ await sleep(delay);
1238
+ holders = await scan();
1239
+ }
1240
+ if (holders.length) throw new Error(`Worker lease ${leasePath} is still held by process(es) ${holders.join(", ")}, which are not the saved worker or did not stop. Protection retained; Main sends no signal to them. Retry after they end, or ask the user to stop them.`);
1241
+ await sleep(50);
1242
+ if ((await scan()).length) throw new Error(`Worker lease ${leasePath} did not stay empty for two scans; protection retained.`);
1243
+ }
1244
+ claim.release("agent-scanned", reservation);
1245
+ return `Recovered reservation ${reservation} released after ${leases.length} saved worker lease(s) scanned empty twice.${stopped.length ? ` Stopped process(es): ${[...new Set(stopped)].join(", ")}.` : " No worker process was running."} Worker tabs, files, commits and sessions were not changed. Inspect changes in ${record.checkouts.join(", ")} before new work.`;
1246
+ } finally { claim.close(); }
1247
+ };
1248
+
1182
1249
  pi.registerTool({
1183
1250
  name: "delegate_task",
1184
1251
  label: "Subagent",
@@ -1187,7 +1254,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1187
1254
  promptGuidelines: [
1188
1255
  "Keep small mechanical tasks in Main. For direct work supply role, name, task, access. Use dependsOn names in tasks for prerequisites, or pass {previous} through a chain. Scope each brief and verify worker evidence.",
1189
1256
  "Direct work shares the checkout. Reads run concurrently without a sandbox. Any possible mutation needs write access and reserves the checkout. For direct writers, optional verification runs structured executable and args checks with acceptance criteria, then at most one correction. dryRun previews a task.",
1190
- "Print and JSON return the answer inline. Other sessions receive one follow-up. Set wait=true to return inline when Main needs the result immediately. Use continueFrom for a follow-up with the same Role. To stop active work, send mode cancel with its exact workflow id, then inspect partial changes.",
1257
+ "Print and JSON return the answer inline. Other sessions receive one follow-up. Set wait=true to return inline when Main needs the result immediately. Use continueFrom for a follow-up with the same Role. To stop active work, send mode cancel with its exact workflow id, then inspect partial changes. Cancel also stops and releases a recovered writer reservation that blocks Main after a restart.",
1191
1258
  MODEL_CLASS_GUIDANCE,
1192
1259
  ],
1193
1260
  parameters: DelegateTaskParameters,
@@ -1220,6 +1287,11 @@ export default function subagentExtension(pi: ExtensionAPI): void {
1220
1287
  && tabs?.every((tab) => manager.getBranch().some((entry) => entry.type === "custom"
1221
1288
  && entry.customType === DIRECT_TAB_TYPE && (entry.data as DirectTabRecord)?.taskId === parsed.id
1222
1289
  && (entry.data as DirectTabRecord)?.tabId === tab.tabId)) === true;
1290
+ const recovered = local ? undefined : directAdmission.inventory(ctx).records.find((record) => record.taskId === parsed.id && record.state === "held");
1291
+ if (recovered) {
1292
+ const text = await releaseRecovered(recovered, ctx);
1293
+ return { content: [{ type: "text" as const, text }], details: { taskId: parsed.id, outcome: "cancelled" } };
1294
+ }
1223
1295
  if (!local || !(local.native ? local.nativeCurrent?.() : tabs?.length) || !current() || local.allocation) throw new Error("Cancellation requires a locally owned workflow on this session branch. Inspect /subagent for recovery.");
1224
1296
  const text = await closeDirect({ id: parsed.id, tabs }, current);
1225
1297
  return { content: [{ type: "text" as const, text }], details: { taskId: parsed.id, outcome: "cancelled" } };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "31.0.0",
3
+ "version": "31.1.0",
4
4
  "description": "Run bounded Pi workers in the current checkout and see their progress in a native widget.",
5
5
  "keywords": [
6
6
  "pi-package",