@henryqw/pi-subagent 28.1.0 → 29.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.
- package/CONTEXT.md +4 -1
- package/README.md +28 -6
- package/dist/direct-herdr.d.ts +4 -2
- package/dist/direct-herdr.js +19 -7
- package/dist/process-lease.d.ts +6 -0
- package/dist/process-lease.js +18 -0
- package/docs/orchestration.md +50 -1
- package/extensions/admission.ts +266 -0
- package/extensions/subagent-command.ts +143 -47
- package/extensions/subagent.ts +91 -19
- package/package.json +2 -2
package/CONTEXT.md
CHANGED
|
@@ -25,7 +25,10 @@ A display and continuation reference for one recorded direct worker, such as `D7
|
|
|
25
25
|
A new direct worker that resumes a finished worker's saved Pi conversation in a new tab with a new Direct reference.
|
|
26
26
|
|
|
27
27
|
**Checkout admission**:
|
|
28
|
-
The exclusive permission held by a direct write request or managed background writer that prevents Main and other direct writers from writing to the shared checkout. Pi Herdr supplies the shared process-local coordinator. Each owner keeps admission until termination is proven; read classification is not a sandbox.
|
|
28
|
+
The exclusive permission held by a direct write request or managed background writer that prevents Main and other direct writers from writing to the shared checkout. Pi Herdr supplies the shared process-local coordinator. Each owner keeps admission until termination is proven or a human explicitly waives a recovered reservation. A waiver does not prove termination; read classification is not a sandbox.
|
|
29
|
+
|
|
30
|
+
**Human release**:
|
|
31
|
+
An explicit user decision to waive one exact recovered checkout reservation despite unproved worker termination. It preserves evidence and does not stop workers.
|
|
29
32
|
|
|
30
33
|
**Isolated request**:
|
|
31
34
|
A durable goal and dependency graph of text and changeset tasks, with checked results and recovery state.
|
package/README.md
CHANGED
|
@@ -15,6 +15,8 @@ pi install npm:@henryqw/pi-subagent
|
|
|
15
15
|
|
|
16
16
|
Configure the profiles that your Roles use in `/task-models`. Direct writer termination proof requires native `lsof`.
|
|
17
17
|
|
|
18
|
+
**Upgrade to 29.0.0:** Older saved workers without their original lease identity cannot continue. Unverified recovery cannot automatically release checkout protection. Keep their records. If the full reservation scope is known, use `/subagent` to review the evidence and explicitly approve release with the exact typed reservation identity. **This does not stop workers or prove termination; a worker can still change any listed checkout.** If scope is unknown, release stays blocked; restore authoritative evidence first.
|
|
19
|
+
|
|
18
20
|
## Works with
|
|
19
21
|
|
|
20
22
|
| Package | Relationship | Purpose |
|
|
@@ -76,6 +78,10 @@ Read requests run parallel tasks up to `maxSubagents`. Chains run in order, repl
|
|
|
76
78
|
|
|
77
79
|
Checkout admission is shared with managed background commands from `pi-herdr-tools`. An active or unknown background writer blocks direct writes. Main writes and direct writers block new command launches. Status and read tools remain available. This is process-local coordination, not an operating-system sandbox.
|
|
78
80
|
|
|
81
|
+
Direct writer admission survives `/reload` through a native Pi session journal. `/subagent` lists held reservations from all branches, including reservations without a tab. Use local Close for locally owned work. Recovered records cannot stop workers.
|
|
82
|
+
|
|
83
|
+
They permit release only from complete saved proof, or through a separate warned human release with an exact typed reservation identity. Reload requires explicit release authority and the matching saved proof or typed waiver evidence. **A human release does not prove termination: a worker can still change any listed checkout.** All evidence stays saved. Missing reservation scope or an incompatible coordinator blocks recovery; see [Reload and session changes](./docs/orchestration.md#reload-and-session-changes).
|
|
84
|
+
|
|
79
85
|
Direct writes change Main's checkout immediately, including dirty checkouts, and have no automatic checks or rollback. Preserve unrelated edits. See [Direct contract](./docs/orchestration.md#direct-contract) for write scope and checkout-admission rules.
|
|
80
86
|
|
|
81
87
|
Each write task must end with a JSON completion object; [Direct contract](./docs/orchestration.md#direct-contract) gives its format. Plain text, a malformed object, blocked work, or failure stops later dispatch. Success is the worker's report, not independent validation.
|
|
@@ -88,7 +94,7 @@ The launch returns a task ID and first Herdr tab, not the answer. One follow-up
|
|
|
88
94
|
|
|
89
95
|
Answers above the shared 40 KiB budget and packets above 64 KiB go to private files. A packet line above 50 KiB needs a Role with `bash`. See [Direct results and records](./docs/orchestration.md#direct-results-and-records).
|
|
90
96
|
|
|
91
|
-
To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`; see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker).
|
|
97
|
+
To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`; see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker). Its saved original lease identity is required. A current or replacement lease cannot supply missing historical proof.
|
|
92
98
|
|
|
93
99
|
### Review a change
|
|
94
100
|
|
|
@@ -150,13 +156,27 @@ Staging, validation, and promotion require clean, unchanged Main. After a defini
|
|
|
150
156
|
|
|
151
157
|
### Inspect work
|
|
152
158
|
|
|
153
|
-
Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows
|
|
159
|
+
Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows have **Direct**, **Isolated**, and **Orphaned · parent checkout removed** group labels. On a wide terminal, each row shows its group beside its reference and status. Group headings are not actions. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
|
|
154
160
|
|
|
155
|
-
In the terminal,
|
|
161
|
+
In the terminal, Pi's native input and selection list replace the editor and use at most half the terminal height. The menu does not cover the report or the transcript.
|
|
156
162
|
|
|
157
|
-
|
|
163
|
+
The selected row has an arrow. A detail preview wraps the selected row's context when space permits. Narrow terminals keep the reference and status before the goal. Very short terminals hide the search field, preview, or extra hints. While the menu waits for your selection, Pi reports that it needs user input.
|
|
158
164
|
|
|
159
|
-
|
|
165
|
+
Type to filter the current menu by reference, record identifier, Role, name, or status. Search includes details that do not fit in a row. The menu shows the number of matching rows and the total row count, including actions. Search changes no records. The menu keeps the filter and selected record when you return from details. Select **Refresh** to load current status; search and navigation use the loaded inventory only.
|
|
166
|
+
|
|
167
|
+
| Default key | Action |
|
|
168
|
+
| --- | --- |
|
|
169
|
+
| `Up` / `Down` | Move to another row. |
|
|
170
|
+
| `PageUp` / `PageDown` | Move one page within the list, not the transcript. |
|
|
171
|
+
| `Enter` | Select a row or toggle it in a multiple-selection menu. |
|
|
172
|
+
| `Ctrl+U` | Clear the filter and show all rows. |
|
|
173
|
+
| `Escape` | Cancel the menu without selecting a row. |
|
|
174
|
+
|
|
175
|
+
Key hints show Pi's configured bindings. In fullscreen mode, move through rows with the mouse wheel and click a row to select it. In regular mode, use the keyboard; the terminal owns mouse input.
|
|
176
|
+
|
|
177
|
+
Each work row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Status text stays beside the reference; color is not required. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
|
|
178
|
+
|
|
179
|
+
**Select multiple…** and prune review keep the filter after each toggle. The title shows the selected count, including selected rows hidden by the filter. Search does not select or clear rows. Clear the filter to reach **Select all**, **Clear**, or **Continue**. **Select all** selects every offered row, not only matches. **Continue** uses the selected rows; cancellation returns no selection.
|
|
160
180
|
|
|
161
181
|
Every isolated request, including an orphaned request, has **Close and delete worktrees (discard work)**. Select it to review owned resources and confirm deletion. **This permanently deletes committed, uncommitted, and ignored content in the listed checkouts.** Cancel makes no change, and agents and tools cannot trigger this action. **Select multiple…** applies one action to many rows, with one confirmation. See [Close and delete isolated worktrees](./docs/orchestration.md#close-and-delete-isolated-worktrees) for guards and partial cleanup.
|
|
162
182
|
|
|
@@ -248,7 +268,9 @@ The extension never pushes, opens pull requests, publishes, deploys, or silently
|
|
|
248
268
|
|
|
249
269
|
Role extensions and MCP servers are trusted executable code, not a sandbox. Select the smallest resource set and authorize write scope explicitly. Admission coordinates this Main's Pi calls, not other sessions, trusted extension lifecycle code, or external processes. Concurrent edits can make direct reads stale.
|
|
250
270
|
|
|
251
|
-
For uncertain direct termination, open `/subagent`, select the exact workflow, and choose **Close/cancel-and-release ALL owned workers in this workflow**. This stops all owned workers, not only the selected one. Resolve reported blockers and repeat the action.
|
|
271
|
+
For uncertain direct termination, open `/subagent`, select the exact workflow, and choose **Close/cancel-and-release ALL owned workers in this workflow**. This stops all owned workers, not only the selected one. Resolve reported blockers and repeat the action.
|
|
272
|
+
|
|
273
|
+
Recorded-only tasks cannot use local Close. Their separate recovery action requires complete saved proof or the warned human release. Restarting Pi does not prove termination. Inspect partial changes before new writes; never blindly repeat commits or delete work.
|
|
252
274
|
|
|
253
275
|
After Close/cancel-and-release proves pane absence, it terminates the processes that hold the exact private process lease of an owned worker (`SIGTERM`, then `SIGKILL`). Automatic completion, continuation, and Subagent Collection never send signals.
|
|
254
276
|
|
package/dist/direct-herdr.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import type { PreparedRoleLaunch, ResolvedRoleLaunch } from "./index.ts";
|
|
3
|
+
import { type ProcessLeaseIdentity } from "./process-lease.ts";
|
|
3
4
|
/** The Role tool that reads a file-backed task packet, or undefined for an inline packet; throws when no tool can read it in full. */
|
|
4
5
|
export declare function directTaskReader(task: string, tools: readonly string[]): "read" | "bash" | undefined;
|
|
5
6
|
/** A prompt is accepted only with the exact pane, agent, cwd and turn identity. */
|
|
@@ -48,6 +49,7 @@ export type DirectTab = Pick<DirectHandle, "name" | "tabId" | "paneId" | "sessio
|
|
|
48
49
|
turn: string;
|
|
49
50
|
workspaceId: string;
|
|
50
51
|
cwd: string;
|
|
52
|
+
leaseIdentity?: ProcessLeaseIdentity;
|
|
51
53
|
};
|
|
52
54
|
/** Allocation evidence is not ownership and must never authorize pane mutation. */
|
|
53
55
|
export type DirectAllocation = Omit<DirectTab, "tabId" | "paneId"> & {
|
|
@@ -67,9 +69,9 @@ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: s
|
|
|
67
69
|
* `settled` refuses to close a listed agent that is not idle or done. Only an explicit
|
|
68
70
|
* user stop or Close uses `terminate`: after pane absence it signals each holder that a
|
|
69
71
|
* per-PID scan still proves holds the exact lease. Other callers only prove. */
|
|
70
|
-
stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, mode?: "proof" | "settled" | "terminate"): Promise<void>;
|
|
72
|
+
stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath" | "leaseIdentity">, current?: () => boolean, mode?: "proof" | "settled" | "terminate"): Promise<void>;
|
|
71
73
|
/** Collection preserves the saved conversation and private lease for continuation and recovery. */
|
|
72
74
|
collect(tab: DirectTab, current: () => boolean): Promise<boolean>;
|
|
73
75
|
/** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
|
|
74
|
-
start(launch: ResolvedRoleLaunch & Pick<PreparedRoleLaunch, "tools">, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath"
|
|
76
|
+
start(launch: ResolvedRoleLaunch & Pick<PreparedRoleLaunch, "tools">, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath" | "leaseIdentity">, onIntent?: (allocation: DirectAllocation) => void): Promise<DirectHandle>;
|
|
75
77
|
};
|
package/dist/direct-herdr.js
CHANGED
|
@@ -7,7 +7,7 @@ import { setTimeout as sleep } from "node:timers/promises";
|
|
|
7
7
|
import { DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { createHerdrClient, hasHerdrErrorCode, herdrCommandFailure, startPiAgent } from "@henryqw/pi-herdr";
|
|
9
9
|
import { utf8Prefix } from "./ephemeral.js";
|
|
10
|
-
import {
|
|
10
|
+
import { isProcessLeaseIdentity, processLeaseIdentity, PI_SUBAGENT_PROCESS_LEASE, scanProcessLease } from "./process-lease.js";
|
|
11
11
|
const OPERATION_MS = 30_000;
|
|
12
12
|
const SESSION_LIMIT = 16 * 1024 * 1024;
|
|
13
13
|
// Leave room for boundary instructions below Linux's 128 KiB per-argument limit.
|
|
@@ -306,7 +306,10 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
306
306
|
const requireCurrent = () => { if (!current())
|
|
307
307
|
throw new Error("Direct task scope changed; reopen /subagent."); };
|
|
308
308
|
requireCurrent();
|
|
309
|
-
|
|
309
|
+
const leaseIdentity = tab.leaseIdentity;
|
|
310
|
+
if (!isProcessLeaseIdentity(leaseIdentity))
|
|
311
|
+
throw new Error("Original process lease identity is missing or invalid; worker stop is not authorized.");
|
|
312
|
+
await processLeaseIdentity(tab.leasePath, leaseIdentity);
|
|
310
313
|
const listed = result(await herdr.json(["agent", "list"], options()), "agent_list");
|
|
311
314
|
if (!Array.isArray(listed.agents))
|
|
312
315
|
throw new Error("Malformed Herdr agent list.");
|
|
@@ -344,7 +347,12 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
344
347
|
if ((await panes()).some((pane) => pane.pane_id === tab.paneId || pane.tab_id === tab.tabId)) {
|
|
345
348
|
throw new Error(`Owned pane ${tab.paneId} is still present; termination is unproved.`);
|
|
346
349
|
}
|
|
347
|
-
const scan = (pid) =>
|
|
350
|
+
const scan = async (pid) => {
|
|
351
|
+
await processLeaseIdentity(tab.leasePath, leaseIdentity);
|
|
352
|
+
const holders = await scanProcessLease(tab.leasePath, (args) => pi.exec("lsof", args, { cwd: workingDir, timeout: 3_000 }), pid);
|
|
353
|
+
await processLeaseIdentity(tab.leasePath, leaseIdentity);
|
|
354
|
+
return holders;
|
|
355
|
+
};
|
|
348
356
|
let holders = await scan();
|
|
349
357
|
if (mode === "terminate") {
|
|
350
358
|
for (const [signal, wait] of [["SIGTERM", 250], ["SIGKILL", 100]]) {
|
|
@@ -409,7 +417,10 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
409
417
|
return true;
|
|
410
418
|
},
|
|
411
419
|
/** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
|
|
412
|
-
async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume) {
|
|
420
|
+
async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume, onIntent) {
|
|
421
|
+
const originalLease = resume?.leaseIdentity;
|
|
422
|
+
if (resume && !isProcessLeaseIdentity(originalLease))
|
|
423
|
+
throw new Error("Original process lease identity is missing or invalid; continuation is not authorized.");
|
|
413
424
|
const reader = directTaskReader(task, launch.tools);
|
|
414
425
|
const caller = result(await herdr.json(["pane", "current", "--current"], options(signal)), "pane_current");
|
|
415
426
|
const pane = object(caller.pane, "calling pane");
|
|
@@ -421,7 +432,6 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
421
432
|
let leasePath;
|
|
422
433
|
if (resume) {
|
|
423
434
|
({ sessionFile, leasePath } = resume);
|
|
424
|
-
await assertPrivateLease(leasePath, false);
|
|
425
435
|
}
|
|
426
436
|
else {
|
|
427
437
|
const sessionDir = await mkdtemp(join(tmpdir(), "pi-subagent-direct-"));
|
|
@@ -429,6 +439,7 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
429
439
|
leasePath = join(sessionDir, "process.lease");
|
|
430
440
|
await writeFile(leasePath, "", { flag: "wx", mode: 0o600 });
|
|
431
441
|
}
|
|
442
|
+
const leaseIdentity = await processLeaseIdentity(leasePath, originalLease);
|
|
432
443
|
const turn = randomBytes(16).toString("hex");
|
|
433
444
|
if (reader) {
|
|
434
445
|
const taskFile = join(dirname(sessionFile), `task-${turn}.md`);
|
|
@@ -442,7 +453,8 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
442
453
|
signal.throwIfAborted();
|
|
443
454
|
// Tab creation is bounded but not session-cancellable: Herdr may create it
|
|
444
455
|
// before the CLI responds, and aborting the CLI loses the exact tab ID.
|
|
445
|
-
const allocation = { name, workspaceId, cwd: workingDir, label, sessionFile, leasePath, turn };
|
|
456
|
+
const allocation = { name, workspaceId, cwd: workingDir, label, sessionFile, leasePath, leaseIdentity, turn };
|
|
457
|
+
onIntent?.(allocation); // Durable evidence before creation can outlive this call.
|
|
446
458
|
let tabId;
|
|
447
459
|
let paneId;
|
|
448
460
|
try {
|
|
@@ -469,7 +481,7 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
|
|
|
469
481
|
}
|
|
470
482
|
try {
|
|
471
483
|
// Record the tab before the agent start can outlive an aborted launch.
|
|
472
|
-
onTab({ name, tabId, paneId, sessionFile, leasePath, turn, workspaceId, cwd: workingDir });
|
|
484
|
+
onTab({ name, tabId, paneId, sessionFile, leasePath, leaseIdentity, turn, workspaceId, cwd: workingDir });
|
|
473
485
|
signal.throwIfAborted();
|
|
474
486
|
const started = await startPiAgent(herdr, { name, pane: paneId,
|
|
475
487
|
args: [...sessionArgs, "--session", sessionFile], options: options(signal), shouldRetry: () => false });
|
package/dist/process-lease.d.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { HerdrExecResult } from "@henryqw/pi-herdr";
|
|
2
2
|
export declare const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
|
|
3
|
+
declare const LEASE_IDENTITY_FIELDS: readonly ["device", "inode", "birth", "parentDevice", "parentInode", "parentBirth"];
|
|
4
|
+
export type ProcessLeaseIdentity = Record<typeof LEASE_IDENTITY_FIELDS[number], string>;
|
|
5
|
+
export declare const isProcessLeaseIdentity: (value: unknown) => value is ProcessLeaseIdentity;
|
|
6
|
+
/** Save before dispatch and compare around each proof step; never recreate a missing lease. */
|
|
7
|
+
export declare function processLeaseIdentity(path: string, expected?: ProcessLeaseIdentity): Promise<ProcessLeaseIdentity>;
|
|
3
8
|
export declare function assertPrivateLease(path: string, allowMissing: boolean): Promise<boolean>;
|
|
4
9
|
/** Shared exact process-lease evidence for direct and isolated workers. */
|
|
5
10
|
export declare function scanProcessLease(path: string, execute: (args: string[]) => Promise<HerdrExecResult>, pid?: number, allowMissing?: boolean): Promise<number[]>;
|
|
11
|
+
export {};
|
package/dist/process-lease.js
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
import { lstat } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
2
3
|
export const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
|
|
4
|
+
const LEASE_IDENTITY_FIELDS = ["device", "inode", "birth", "parentDevice", "parentInode", "parentBirth"];
|
|
5
|
+
export const isProcessLeaseIdentity = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value)
|
|
6
|
+
&& LEASE_IDENTITY_FIELDS.every((key) => typeof value[key] === "string" && /^(0|[1-9]\d*)$/.test(value[key])));
|
|
7
|
+
/** Save before dispatch and compare around each proof step; never recreate a missing lease. */
|
|
8
|
+
export async function processLeaseIdentity(path, expected) {
|
|
9
|
+
await assertPrivateLease(path, false);
|
|
10
|
+
const [file, parent] = await Promise.all([lstat(path, { bigint: true }), lstat(dirname(path), { bigint: true })]);
|
|
11
|
+
if (!file.isFile() || file.isSymbolicLink() || (file.mode & 511n) !== 384n || (process.getuid && file.uid !== BigInt(process.getuid()))
|
|
12
|
+
|| !parent.isDirectory() || parent.isSymbolicLink() || (parent.mode & 511n) !== 448n || (process.getuid && parent.uid !== BigInt(process.getuid()))) {
|
|
13
|
+
throw new Error("Process lease and its parent must remain private current-user files, without symbolic links.");
|
|
14
|
+
}
|
|
15
|
+
const identity = { device: String(file.dev), inode: String(file.ino), birth: String(file.birthtimeNs),
|
|
16
|
+
parentDevice: String(parent.dev), parentInode: String(parent.ino), parentBirth: String(parent.birthtimeNs) };
|
|
17
|
+
if (expected && Object.entries(identity).some(([key, value]) => expected[key] !== value))
|
|
18
|
+
throw new Error("Original process lease or private parent was replaced; termination is unproved.");
|
|
19
|
+
return identity;
|
|
20
|
+
}
|
|
3
21
|
export async function assertPrivateLease(path, allowMissing) {
|
|
4
22
|
let info;
|
|
5
23
|
try {
|
package/docs/orchestration.md
CHANGED
|
@@ -101,7 +101,7 @@ After settlement, the coordinator closes exact owned writer panes. It releases a
|
|
|
101
101
|
|
|
102
102
|
Admission stays held if the close fails, identity changes, a leased child survives, or inspection is uncertain. In that case, open `/subagent`. Select the exact direct workflow. Then choose **Close/cancel-and-release ALL owned workers in this workflow** to cancel dispatch and try termination again. This action stops every owned worker of that workflow, not one selected worker.
|
|
103
103
|
|
|
104
|
-
The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot
|
|
104
|
+
The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot use local Close. Their separate recovery action cannot stop workers. After it proves pane absence, it sends `SIGTERM` to each process that holds the exact private lease of an owned worker. Then it sends `SIGKILL` to each process that survives. Before each signal, it scans the lease again for that PID, and it does not signal a PID that no longer holds the lease. If a holder survives, a scan fails, or ownership changes, admission stays held. Resolve the reported blocker, then do the same action again. A restart of Pi is not termination proof.
|
|
105
105
|
|
|
106
106
|
Inspect partial changes before new writes. To recover, never retry a commit or delete work without inspection.
|
|
107
107
|
|
|
@@ -115,6 +115,55 @@ Tasks in a write request must return one JSON completion object, such as `{"outc
|
|
|
115
115
|
|
|
116
116
|
But admission depends on proved termination, not on the reported outcome. Success is the explicit report of the worker. It is not an independent validation of its changes.
|
|
117
117
|
|
|
118
|
+
### Reload and session changes
|
|
119
|
+
|
|
120
|
+
Direct writes require a saved native Pi conversation. Before a worker allocation or a continued-worker stop, the extension saves an admission journal entry. It contains the session and task identities, a unique admission token, and the complete canonical checkout set. The set includes the workspace and every selected repository.
|
|
121
|
+
|
|
122
|
+
```mermaid
|
|
123
|
+
flowchart LR
|
|
124
|
+
A[Admit complete checkout set] --> B[Save held entry]
|
|
125
|
+
B --> I[Save exact effect intent]
|
|
126
|
+
I --> C[Allocate or continue worker]
|
|
127
|
+
C --> D[Prove all workers stopped]
|
|
128
|
+
D --> P[Save termination receipt]
|
|
129
|
+
P --> E[Save released entry]
|
|
130
|
+
E --> F[Clear checkout holds]
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
If the first journal write fails, no worker is allocated or stopped. A cancelled preparation saves release when no allocation or uncertain stop occurred. If a release write fails, admission stays held. A failed tab-record write also retains admission after allocation. No successful task answer substitutes for termination proof.
|
|
134
|
+
|
|
135
|
+
Native `/reload` replaces the extension instance and removes its event-bus listeners. The replacement replays **all session entries**, including entries outside the current tree branch, before it admits writes. Release must match the exact saved held checkpoint, admission identity, and checkout set. An exact earlier held entry cannot restore an already released owner.
|
|
136
|
+
|
|
137
|
+
Every release must name its authority. A proved release requires complete saved proof, not only a `stopped` status. A human release requires the saved typed identity and the exact reviewed admission and worker evidence. Missing, conflicting, or changed release evidence blocks writes and session replacement, including for older receipts. Replay never creates missing consent or inspects live workers. Native forks can change parent links and move labels without changing worker evidence.
|
|
138
|
+
|
|
139
|
+
A journal error blocks writes even when Pi reports the `session_start` error and continues. An older shared coordinator must support both journal capability detection and the required methods. Otherwise writes remain blocked; load the current Pi Herdr package in every extension. New read-only tasks and read tools remain available.
|
|
140
|
+
|
|
141
|
+
Recovered admission is a write barrier, not process-control authority. Replay does not restore worker handles, replay tasks, or stop processes. Continuation and collection of recorded workers wait while admission is unresolved. Reload is not termination proof.
|
|
142
|
+
|
|
143
|
+
The journal saves non-dispatch evidence first. It saves each exact allocation intent before tab creation, and each continuation source before its stop. An interrupted external operation stays unproved. New launches save the private lease and parent filesystem identities before dispatch. Termination checks compare them before and after lease scans. Missing, linked, replaced, or non-private leases block proof.
|
|
144
|
+
|
|
145
|
+
A legacy worker without its original saved lease identity cannot be stopped or continued. The current lease file cannot establish its historical identity. New workers keep their original baseline throughout local execution. Allocation intents are bound to verified tab and pane identities before agent start. Older receipts for allocated workers without that binding require the warned human release, not proof-based release.
|
|
146
|
+
|
|
147
|
+
`/subagent` lists local tasks and session-wide held reservations, even without a saved tab or on another branch. It shows the complete checkout set, reservation identity, saved resources, and recovery limit. A completed result does not hide a held reservation. Direct inventory remains available if isolated inventory fails. Without an interactive user interface, the command reports evidence but does not release protection.
|
|
148
|
+
|
|
149
|
+
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.
|
|
150
|
+
|
|
151
|
+
For a recovered reservation, select **Review recovered checkout protection**:
|
|
152
|
+
|
|
153
|
+
- 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.
|
|
154
|
+
- 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.
|
|
155
|
+
- A human release preserves all evidence. Its warning survives reload: **worker termination remains unproved; a worker can still change any listed checkout.** It sends no signal, closes no pane, deletes nothing, and does not replay work or undo changes.
|
|
156
|
+
|
|
157
|
+
Each recovery claims one exact reservation before dialogs. Session, branch, extension generation, and evidence must remain unchanged through release. A failed receipt write retains the whole checkout set. Releasing one reservation does not release overlapping owners.
|
|
158
|
+
|
|
159
|
+
Recovery does not inspect or stop live workers from saved records. Older records without non-dispatch or complete termination evidence need a human release, even when their panes appear absent. Empty lease scans cannot settle an unknown external operation. The private lease is not a sandbox for arbitrary extension code or detached processes. Explicit local termination also retains the small race between a process scan and its signal.
|
|
160
|
+
|
|
161
|
+
Session switch, new session, import, and fork are refused during direct-write preflight, held admission, or failed restore. Once replacement passes this check, new direct writes stay blocked until session start. If a later extension cancels replacement, run `/reload` before direct writing. A fork is also refused if its selected path omits a hold or its release. A complete path can be forked. Tree navigation remains available because replay reads all entries.
|
|
162
|
+
|
|
163
|
+
Historical records with an exact completed direct result and no recovery flag do not block writes. New read-only records also need no writer admission. For older unresolved records without a journal or an exact completed result, the full checkout set and access cannot be proved. The extension reports that limitation and blocks all writes and session replacement. It does not guess a checkout set or manufacture termination proof. There is no migration or session-wide risky waiver for unknown reservation scope. Restore authoritative evidence first.
|
|
164
|
+
|
|
165
|
+
Admission coordinates only this Main's Pi calls. Other Pi sessions and external processes remain outside it.
|
|
166
|
+
|
|
118
167
|
### Continue or stop one direct worker
|
|
119
168
|
|
|
120
169
|
Main can continue a finished direct worker, so it does not have to start a new one. It adds `continueFrom` with the reference of the worker, such as `"continueFrom": "D7.1"`, to any single, parallel, or chain task. It uses the same `role` that the worker ran with. The worker resumes its saved Pi session in a new Herdr tab without focus, so it keeps its earlier context.
|
package/extensions/admission.ts
CHANGED
|
@@ -1 +1,267 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { dirname, isAbsolute, normalize } from "node:path";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { isProcessLeaseIdentity } from "../dist/process-lease.js";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import * as herdr from "@henryqw/pi-herdr";
|
|
1
7
|
export { registerCheckoutAdmission } from "@henryqw/pi-herdr";
|
|
8
|
+
|
|
9
|
+
const JOURNAL = "subagent-direct-admission";
|
|
10
|
+
// An older installed package must still load this gate instead of failing a named import.
|
|
11
|
+
const checkoutToolCanWrite = herdr.checkoutToolCanWrite ?? ((name: string, input: unknown, direct: (input: unknown) => boolean) =>
|
|
12
|
+
name === "delegate_task" ? direct(input) : !["read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode"].includes(name));
|
|
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";
|
|
15
|
+
waiver?: { identity: string; evidence: string } };
|
|
16
|
+
const owner = (record: Record) => JSON.stringify([JOURNAL, record.sessionId, record.taskId, record.token]);
|
|
17
|
+
const text = (value: unknown): value is string => typeof value === "string" && value.length > 0 && !value.includes("\0");
|
|
18
|
+
const parse = (value: unknown): Record => {
|
|
19
|
+
const record = value as Record | undefined;
|
|
20
|
+
if (!record || record.version !== 1 || !text(record.sessionId) || !text(record.taskId) || !text(record.token)
|
|
21
|
+
|| (record.state !== "held" && record.state !== "released") || !Array.isArray(record.checkouts) || !record.checkouts.length
|
|
22
|
+
|| record.checkouts.some((path) => !text(path) || !isAbsolute(path) || normalize(path) !== path)
|
|
23
|
+
|| new Set(record.checkouts).size !== record.checkouts.length
|
|
24
|
+
|| (record.resources !== undefined && !Array.isArray(record.resources))
|
|
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)
|
|
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.");
|
|
29
|
+
return record;
|
|
30
|
+
};
|
|
31
|
+
const sameSet = (a: Record, b: Record) => a.checkouts.length === b.checkouts.length && a.checkouts.every((path, index) => path === b.checkouts[index]);
|
|
32
|
+
const exactTab = (a: any, b: any) => ["taskId", "entryId", "name", "tabId", "paneId", "sessionFile"].every((key) => text(a[key]))
|
|
33
|
+
&& ["taskId", "entryId", "name", "tabId", "paneId", "sessionFile", "leasePath", "turn", "cwd", "workspaceId"].every((key) => a[key] === b[key]);
|
|
34
|
+
|
|
35
|
+
const resourceEntries = (record: Record, entries: readonly SessionEntry[]) => entries.filter((entry) => entry.type === "custom"
|
|
36
|
+
&& ["subagent-direct-tab", "subagent-direct-allocation"].includes(entry.customType) && (entry.data as any)?.taskId === record.taskId);
|
|
37
|
+
const hasProof = (record: Record, entries: readonly SessionEntry[]) => {
|
|
38
|
+
const resources = record.resources as any[] | undefined;
|
|
39
|
+
if (!resources) return false;
|
|
40
|
+
if (record.proof === "not-dispatched") return !resources.length && !resourceEntries(record, entries).length;
|
|
41
|
+
if (record.proof !== "stopped" || !resources.length) return false;
|
|
42
|
+
const fields = ["entryId", "name", "sessionFile", "leasePath", "turn", "workspaceId", "cwd"];
|
|
43
|
+
const tabFields = [...fields, "taskId", "tabId", "paneId"];
|
|
44
|
+
const valid = (value: any, keys = fields) => value && typeof value === "object" && !Array.isArray(value)
|
|
45
|
+
&& keys.every((key) => text(value[key])) && isProcessLeaseIdentity(value.leaseIdentity)
|
|
46
|
+
&& ["sessionFile", "leasePath", "cwd"].every((key) => isAbsolute(value[key]) && normalize(value[key]) === value[key])
|
|
47
|
+
&& value.sessionFile !== value.leasePath && dirname(value.sessionFile) === dirname(value.leasePath);
|
|
48
|
+
const same = (left: any, right: any, keys = fields) => keys.every((key) => left[key] === right[key])
|
|
49
|
+
&& Object.entries(left.leaseIdentity).every(([key, value]) => right.leaseIdentity[key] === value);
|
|
50
|
+
const intents = resources.filter((resource) => resource?.kind === "allocation-intent");
|
|
51
|
+
const tabs = resources.filter((resource) => resource?.kind === "verified-tab");
|
|
52
|
+
// A pre-creation intent cannot establish the returned tab and pane identities.
|
|
53
|
+
if (!intents.every((intent) => valid(intent) && text(intent.label))
|
|
54
|
+
|| !tabs.every((tab) => valid(tab, tabFields) && tab.taskId === record.taskId)) return false;
|
|
55
|
+
if (!["entryId", "name", "tabId", "paneId"].every((key) => new Set(tabs.map((tab) => tab[key])).size === tabs.length)) return false;
|
|
56
|
+
const saved = entries.filter((entry) => entry.type === "custom" && entry.customType === "subagent-direct-tab")
|
|
57
|
+
.map((entry) => (entry as { data: any }).data);
|
|
58
|
+
return resources.every((resource) => {
|
|
59
|
+
if (resource?.kind === "allocation-intent") return tabs.filter((tab) => same(resource, tab)).length === 1;
|
|
60
|
+
if (resource?.kind === "verified-tab") return intents.filter((intent) => same(resource, intent)).length === 1;
|
|
61
|
+
if (resource?.kind !== "continuation-sources" || !Array.isArray(resource.sources) || !resource.sources.length) return false;
|
|
62
|
+
return resource.sources.every((source: any) => {
|
|
63
|
+
if (!valid(source, tabFields)) return false;
|
|
64
|
+
const originals = saved.filter((tab) => tab?.taskId === source.taskId && tab?.entryId === source.entryId);
|
|
65
|
+
return originals.length > 0 && originals.every((tab) => valid(tab, tabFields) && same(source, tab, tabFields));
|
|
66
|
+
});
|
|
67
|
+
}) && resourceEntries(record, entries).every((entry) => {
|
|
68
|
+
if (entry.type !== "custom" || entry.customType !== "subagent-direct-tab" || !valid(entry.data, tabFields)) return false;
|
|
69
|
+
return tabs.some((tab) => same(tab, entry.data, tabFields));
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const identity = (record: Record) => `${record.sessionId}/${record.taskId}/${record.token}`;
|
|
74
|
+
const evidence = (record: Record, entries: readonly SessionEntry[]) => {
|
|
75
|
+
const sources = (record.resources ?? []).flatMap((resource: any) => resource?.kind === "continuation-sources" && Array.isArray(resource.sources) ? resource.sources : []);
|
|
76
|
+
return JSON.stringify({ admission: record, records: entries.filter((entry) => entry.type === "custom"
|
|
77
|
+
&& ["subagent-direct-tab", "subagent-direct-allocation"].includes(entry.customType)
|
|
78
|
+
&& ((entry.data as any)?.taskId === record.taskId || sources.some((source) => text(source?.taskId) && source.taskId === (entry.data as any)?.taskId && source.entryId === (entry.data as any)?.entryId)))
|
|
79
|
+
// Native forks can change parent links and move labels; neither changes worker evidence.
|
|
80
|
+
.map(({ id, customType, data }: any) => ({ id, customType, data })) });
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
function replay(entries: readonly SessionEntry[]): Map<string, Record> {
|
|
84
|
+
const records = new Map<string, Record>();
|
|
85
|
+
const held = new Set<string>();
|
|
86
|
+
const tasks = new Map<string, string>();
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
if (entry.type !== "custom" || entry.customType !== JOURNAL) continue;
|
|
89
|
+
const record = parse(entry.data), key = owner(record), previous = records.get(key);
|
|
90
|
+
if (tasks.has(record.taskId) && tasks.get(record.taskId) !== key) throw new Error(`Direct task ${record.taskId} has conflicting reservation identities.`);
|
|
91
|
+
tasks.set(record.taskId, key);
|
|
92
|
+
if (previous && !sameSet(previous, record)) throw new Error(`Direct admission identity ${record.taskId} changed its checkout set.`);
|
|
93
|
+
if (!previous && record.state === "released") throw new Error(`Direct release ${record.taskId} has no matching admission.`);
|
|
94
|
+
// Release is terminal only for exact duplicates or an earlier saved hold.
|
|
95
|
+
if (previous?.state === "released") {
|
|
96
|
+
if (record.state === "released" ? !isDeepStrictEqual(previous, record) : !held.has(JSON.stringify(record))) {
|
|
97
|
+
throw new Error("Direct admission evidence changed after release.");
|
|
98
|
+
}
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (previous && ((record.proof === "not-dispatched" && previous.proof !== "not-dispatched")
|
|
102
|
+
|| (previous.resources && (!record.resources || previous.resources.some((resource, index) => JSON.stringify(resource) !== JSON.stringify(record.resources![index]))))
|
|
103
|
+
|| (previous.proof === "stopped" && record.proof !== "stopped"))) throw new Error("Direct admission lost or changed its effect evidence.");
|
|
104
|
+
if (record.state === "released") {
|
|
105
|
+
const { release, waiver, ...checkpoint } = record;
|
|
106
|
+
if (!isDeepStrictEqual({ ...checkpoint, state: "held" }, previous)
|
|
107
|
+
|| (release === "proved" ? !hasProof(previous!, entries)
|
|
108
|
+
: waiver!.identity !== identity(previous!) || waiver!.evidence !== evidence(previous!, entries))) {
|
|
109
|
+
throw new Error("Direct release has incomplete or changed proof or user consent; protection retained.");
|
|
110
|
+
}
|
|
111
|
+
} else held.add(JSON.stringify(record));
|
|
112
|
+
records.set(key, record);
|
|
113
|
+
}
|
|
114
|
+
for (const [index, entry] of entries.entries()) {
|
|
115
|
+
if (entry.type !== "custom" || !["subagent-direct-tab", "subagent-direct-allocation"].includes(entry.customType)) continue;
|
|
116
|
+
const tab = entry.data as any;
|
|
117
|
+
if (!tab || !text(tab.taskId)) throw new Error("Malformed legacy direct worker record.");
|
|
118
|
+
if (tasks.has(tab.taskId) || tab.access === "read") continue;
|
|
119
|
+
const completed = entry.customType === "subagent-direct-tab" && entries.slice(index + 1).some((result) => {
|
|
120
|
+
if (result.type !== "custom_message" || result.customType !== "subagent-direct-result") return false;
|
|
121
|
+
const details = result.details as any;
|
|
122
|
+
return details?.taskId === tab.taskId && ["completed", "failed"].includes(details.outcome) && details.recovery === undefined
|
|
123
|
+
&& Array.isArray(details.tabs) && details.tabs.some((saved: any) => saved && exactTab(tab, saved))
|
|
124
|
+
&& Array.isArray(details.entries) && details.entries.some((item: any) => item?.id === tab.entryId && ["succeeded", "rejected"].includes(item.status));
|
|
125
|
+
});
|
|
126
|
+
if (!completed) throw new Error(`Legacy direct task ${tab.taskId} has no admission journal or exact completed result. Its access and full checkout set cannot be proved; all writes and session switch/fork are blocked. Restore authoritative evidence; no scoped release is available.`);
|
|
127
|
+
}
|
|
128
|
+
return records;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Replay restores protection, not process-control authority. */
|
|
132
|
+
export function registerDirectAdmission(pi: ExtensionAPI, canWrite: (input: unknown) => boolean,
|
|
133
|
+
select: (input: unknown, ctx: { cwd: string }) => Promise<readonly string[]>,
|
|
134
|
+
) {
|
|
135
|
+
const admission = herdr.checkoutAdmission(pi);
|
|
136
|
+
const compatible = admission.supportsDirectJournal === true && admission.supportsCheckoutSets === true
|
|
137
|
+
&& [admission.beginReplacement, admission.admittedCheckouts, admission.restoreSet, admission.complete, admission.guard, admission.hold, admission.install, admission.classifyDirect].every((method) => typeof method === "function");
|
|
138
|
+
let failure = compatible ? "Direct admission journal has not loaded; writes are blocked." : "The active checkout coordinator cannot replay direct admission journals. Load the current Pi Herdr package in every extension; writes are blocked.";
|
|
139
|
+
let loadedSession: string | undefined;
|
|
140
|
+
let initialized = false;
|
|
141
|
+
let records = new Map<string, Record>();
|
|
142
|
+
const claims = new Set<string>();
|
|
143
|
+
const requireReady = () => { if (failure) throw new Error(failure); };
|
|
144
|
+
const restore = (ctx: ExtensionContext) => {
|
|
145
|
+
initialized = true;
|
|
146
|
+
if (!compatible) throw new Error(failure);
|
|
147
|
+
failure = "Direct admission journal restore failed; writes are blocked.";
|
|
148
|
+
try {
|
|
149
|
+
records = replay(ctx.sessionManager.getEntries());
|
|
150
|
+
for (const [key, record] of records) {
|
|
151
|
+
if (record.state === "released") admission.complete(key);
|
|
152
|
+
else admission.restoreSet(key, record.checkouts);
|
|
153
|
+
}
|
|
154
|
+
loadedSession = ctx.sessionManager.getSessionId();
|
|
155
|
+
failure = "";
|
|
156
|
+
} catch (error) {
|
|
157
|
+
failure = `${error instanceof Error ? error.message : String(error)} Writes are blocked.`;
|
|
158
|
+
throw new Error(failure, { cause: error });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
pi.on("session_start", (_event, ctx) => restore(ctx));
|
|
162
|
+
pi.on("tool_call", (event, ctx) => {
|
|
163
|
+
if (!checkoutToolCanWrite(event.toolName, event.input, canWrite)) return;
|
|
164
|
+
if (!initialized && compatible) { try { restore(ctx); } catch { /* Pi swallows lifecycle errors; keep this gate closed. */ } }
|
|
165
|
+
if (failure) return { block: true, reason: failure };
|
|
166
|
+
});
|
|
167
|
+
const beforeReplace = (event: { type: string; entryId?: string; position?: string }, ctx: ExtensionContext) => {
|
|
168
|
+
try {
|
|
169
|
+
restore(ctx);
|
|
170
|
+
if ([...records.values()].some(({ state }) => state === "held")) throw new Error("Direct writer admission is unresolved. Use /subagent before session switch or fork.");
|
|
171
|
+
if (event.type === "session_before_fork") {
|
|
172
|
+
const selected = ctx.sessionManager.getEntry(event.entryId!);
|
|
173
|
+
if (!selected) throw new Error("Fork target is unavailable.");
|
|
174
|
+
const leaf = event.position === "at" ? selected.id : selected.parentId;
|
|
175
|
+
const copied = replay(leaf ? ctx.sessionManager.getBranch(leaf) : []);
|
|
176
|
+
if ([...copied.values()].some(({ state }) => state === "held")) throw new Error("This fork path omits a direct admission release. Select a path with complete admission evidence.");
|
|
177
|
+
}
|
|
178
|
+
// Synchronous with the final check: cover admitted preflight and refuse later direct calls.
|
|
179
|
+
if (!admission.beginReplacement()) throw new Error("A direct writer is in preflight or still owns admission; session replacement is blocked.");
|
|
180
|
+
} catch (error) {
|
|
181
|
+
try { ctx.ui.notify(error instanceof Error ? error.message : String(error), "warning"); } catch { /* Notification cannot authorize replacement. */ }
|
|
182
|
+
return { cancel: true };
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
pi.on("session_before_switch", beforeReplace);
|
|
186
|
+
pi.on("session_before_fork", beforeReplace);
|
|
187
|
+
if (typeof admission.classifyDirect === "function") admission.classifyDirect(canWrite, select);
|
|
188
|
+
if (compatible) {
|
|
189
|
+
admission.guard(JOURNAL, async () => requireReady());
|
|
190
|
+
admission.install(pi);
|
|
191
|
+
}
|
|
192
|
+
const save = (record: Record) => { pi.appendEntry(JOURNAL, record); records.set(owner(record), record); };
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
hasProof: (record: Record, ctx: ExtensionContext) => hasProof(record, ctx.sessionManager.getEntries()),
|
|
196
|
+
evidence: (record: Record, ctx: ExtensionContext) => evidence(record, ctx.sessionManager.getEntries()),
|
|
197
|
+
inventory(ctx: ExtensionContext) {
|
|
198
|
+
try { restore(ctx); } catch { /* Show the failure without granting release authority. */ }
|
|
199
|
+
return { failure, records: [...records.values()].filter((record) => record.state === "held" || record.release === "user-unproved") };
|
|
200
|
+
},
|
|
201
|
+
claim(reviewed: Record, ctx: ExtensionContext, current: () => boolean) {
|
|
202
|
+
restore(ctx);
|
|
203
|
+
const key = owner(reviewed), snapshot = JSON.stringify(reviewed), savedEvidence = evidence(reviewed, ctx.sessionManager.getEntries());
|
|
204
|
+
const valid = () => current() && loadedSession === ctx.sessionManager.getSessionId()
|
|
205
|
+
&& JSON.stringify(replay(ctx.sessionManager.getEntries()).get(key)) === snapshot
|
|
206
|
+
&& evidence(reviewed, ctx.sessionManager.getEntries()) === savedEvidence;
|
|
207
|
+
if (!valid() || reviewed.state !== "held" || claims.has(key)) throw new Error("Direct reservation changed or recovery is already active; reopen /subagent.");
|
|
208
|
+
claims.add(key); // Claim before the first dialog, not after confirmation.
|
|
209
|
+
return {
|
|
210
|
+
close: () => { claims.delete(key); },
|
|
211
|
+
release(kind: "proved" | "user-unproved", typedIdentity?: string) {
|
|
212
|
+
requireReady();
|
|
213
|
+
if (!claims.has(key) || !valid()) throw new Error("Direct recovery scope or evidence changed; protection retained.");
|
|
214
|
+
if (kind === "proved" && !hasProof(reviewed, ctx.sessionManager.getEntries())) throw new Error("Worker termination is unproved; protection retained.");
|
|
215
|
+
if (kind === "user-unproved" && typedIdentity !== identity(reviewed)) throw new Error("Exact typed reservation identity is required; protection retained.");
|
|
216
|
+
save({ ...reviewed, state: "released", release: kind, ...(kind === "user-unproved"
|
|
217
|
+
? { waiver: { identity: typedIdentity!, evidence: savedEvidence } } : {}) });
|
|
218
|
+
admission.complete(key);
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
canUseRecordedTask(ctx: ExtensionContext) {
|
|
223
|
+
if (!initialized && compatible) { try { restore(ctx); } catch { return false; } }
|
|
224
|
+
return !failure && !claims.size && ![...records.values()].some((record) => record.state === "held");
|
|
225
|
+
},
|
|
226
|
+
hold(toolCallId: string, taskId: string, ctx: ExtensionContext) {
|
|
227
|
+
requireReady();
|
|
228
|
+
if (loadedSession !== ctx.sessionManager.getSessionId() || !ctx.sessionManager.getSessionFile()
|
|
229
|
+
|| !ctx.sessionManager.getEntries().some((entry) => entry.type === "message" && ["user", "assistant"].includes(entry.message.role))) {
|
|
230
|
+
throw new Error("Direct writes require the current saved Pi conversation; setup-only or in-memory sessions cannot persist admission.");
|
|
231
|
+
}
|
|
232
|
+
let record: Record = { version: 1, sessionId: loadedSession, taskId, token: randomUUID(),
|
|
233
|
+
checkouts: [...admission.admittedCheckouts(toolCallId)].sort(), state: "held", proof: "not-dispatched", resources: [] };
|
|
234
|
+
const release = admission.hold(toolCallId);
|
|
235
|
+
try { save(record); } catch (error) { release(); throw error; }
|
|
236
|
+
const key = owner(record);
|
|
237
|
+
admission.restoreSet(key, record.checkouts);
|
|
238
|
+
// Only this live handle retains observed tabs whose journal write failed.
|
|
239
|
+
const pendingTabs = new Set<unknown>();
|
|
240
|
+
const effect = (resource: unknown) => {
|
|
241
|
+
if ((resource as { kind?: string })?.kind === "verified-tab") pendingTabs.add(resource);
|
|
242
|
+
const next: Record = { ...record, proof: "unproved", resources: [...record.resources!, resource] };
|
|
243
|
+
save(next); // Persist uncertainty BEFORE the external effect can start.
|
|
244
|
+
record = next;
|
|
245
|
+
pendingTabs.delete(resource);
|
|
246
|
+
};
|
|
247
|
+
return Object.assign(() => {
|
|
248
|
+
if (records.get(key)?.state === "released") return;
|
|
249
|
+
if (ctx.sessionManager.getSessionId() !== record.sessionId) throw new Error("Direct release requires its original Pi session; admission retained.");
|
|
250
|
+
// Only the local finalizer calls this after all effects are stopped or proved absent.
|
|
251
|
+
if (pendingTabs.size) {
|
|
252
|
+
requireReady();
|
|
253
|
+
if (loadedSession !== record.sessionId || !isDeepStrictEqual(replay(ctx.sessionManager.getEntries()).get(key), record)) {
|
|
254
|
+
throw new Error("Direct reservation changed before local evidence retry; protection retained.");
|
|
255
|
+
}
|
|
256
|
+
for (const tab of pendingTabs) effect(tab);
|
|
257
|
+
}
|
|
258
|
+
const checkpoint: Record = record.proof === "not-dispatched" ? record : { ...record, proof: "stopped" };
|
|
259
|
+
if (!hasProof(checkpoint, ctx.sessionManager.getEntries())) throw new Error("Complete saved termination evidence is required; protection retained.");
|
|
260
|
+
if (record.proof !== checkpoint.proof) { save(checkpoint); record = checkpoint; }
|
|
261
|
+
save({ ...record, state: "released", release: "proved" });
|
|
262
|
+
admission.complete(key);
|
|
263
|
+
release();
|
|
264
|
+
}, { effect });
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getMarkdownTheme, getSelectListTheme, rawKeyHint, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { Box, Markdown, SelectList, Spacer, Text, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
2
|
+
import { Box, fuzzyFilter, getSelectPageIndex, Input, Markdown, SelectList, Spacer, Text, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
3
3
|
import type { DiscardPlan } from "../dist/discard.js";
|
|
4
4
|
import type { PruneItem, PruneProgress } from "../dist/prune.js";
|
|
5
5
|
import { TERMINAL_RUN_STATUSES } from "../dist/schema.js";
|
|
@@ -17,13 +17,14 @@ export interface DirectDisplay {
|
|
|
17
17
|
}
|
|
18
18
|
export const directRef = ({ workflow, worker }: DirectDisplay): string => `D${workflow}.${worker}`;
|
|
19
19
|
|
|
20
|
-
/**
|
|
20
|
+
/** Session-wide saved reservations and local ownership; records alone grant no process control. */
|
|
21
21
|
export interface DirectTask {
|
|
22
22
|
id: string;
|
|
23
23
|
/** Legacy label: saved allocation label, otherwise the exact task ID. */
|
|
24
24
|
name: string;
|
|
25
25
|
status: string;
|
|
26
26
|
canClose?: boolean;
|
|
27
|
+
admission?: { identity: string; checkouts: readonly string[]; evidence: string; proof: boolean; canRecover: boolean };
|
|
27
28
|
/** Entry IDs of running workers in a locally owned all-read workflow; each can be stopped alone. */
|
|
28
29
|
stoppable?: readonly string[];
|
|
29
30
|
recovery?: string;
|
|
@@ -74,6 +75,7 @@ export interface PrunePlan {
|
|
|
74
75
|
export interface SubagentCommandAdapter {
|
|
75
76
|
direct(ctx: ExtensionContext): readonly DirectTask[];
|
|
76
77
|
closeDirect(task: DirectTask, current: () => boolean): Promise<string>;
|
|
78
|
+
recoverDirect?(task: DirectTask, ctx: ExtensionContext, current: () => boolean): Promise<string>;
|
|
77
79
|
stopDirect(task: DirectTask, entryId: string, current: () => boolean): Promise<string>;
|
|
78
80
|
isolated(cwd: string, current: () => boolean): Promise<IsolatedInventory>;
|
|
79
81
|
recover(cwd: string): Promise<string>;
|
|
@@ -285,6 +287,11 @@ function directReport(task: DirectTask): Report {
|
|
|
285
287
|
const untabbed = task.workers.filter((worker) => !task.tabs.some((tab) => tab.display?.worker === worker.worker));
|
|
286
288
|
return { tone: statusTone(task.status), title: `Direct workflow ${directLabel(task)} · ${task.status}${costSuffix(task.cost)}`, sections: [
|
|
287
289
|
{ rows: [{ label: "ID", value: task.id, code: true }, ...(task.recovery ? [{ label: "recovery", value: clean(task.recovery, 4000), tone: "warning" as const }] : [])] },
|
|
290
|
+
...(task.admission ? [{ heading: "Checkout protection", rows: [
|
|
291
|
+
{ label: "reservation", value: task.admission.identity, code: true },
|
|
292
|
+
{ label: "complete checkout set", value: task.admission.checkouts.join("\n"), code: true },
|
|
293
|
+
{ label: "saved effect evidence", value: task.admission.evidence, code: true },
|
|
294
|
+
] }] : []),
|
|
288
295
|
...task.tabs.map((tab): Section => ({ heading: tab.display ? workerLabel(tab.display) : tab.name, rows: [
|
|
289
296
|
...([["task", tab.entryId], ["agent", tab.name], ["tab", tab.tabId], ["pane", tab.paneId], ["session", tab.sessionFile]] as const).map(([label, value]) => ({ label, value, code: true })),
|
|
290
297
|
...(compactCost(tab.cost) === undefined ? [] : [{ label: "cost", value: compactCost(tab.cost)! }]),
|
|
@@ -332,63 +339,121 @@ export function workingReport(direct: readonly DirectTask[], inventory: Isolated
|
|
|
332
339
|
}), ...moreSection(fitted.more)] };
|
|
333
340
|
}
|
|
334
341
|
|
|
335
|
-
type Choice<T> = { label: string; value: T };
|
|
336
|
-
|
|
342
|
+
type Choice<T> = { label: string; value: T; description?: string; detail?: string; search?: string; key?: string };
|
|
343
|
+
type MenuState = { index: number; query: string; key?: string };
|
|
344
|
+
async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], state: MenuState = { index: 0, query: "" }): Promise<T | undefined> {
|
|
337
345
|
// Numeric suffixes only tell duplicate labels apart. Never parse display text into an identity.
|
|
338
346
|
const clipped = items.map((item) => clean(item.label, 145));
|
|
339
|
-
const
|
|
347
|
+
const counts = new Map<string, number>();
|
|
348
|
+
for (const label of clipped) counts.set(label, (counts.get(label) ?? 0) + 1);
|
|
349
|
+
const labels = clipped.map((label, index) => counts.get(label) === 1 ? label : `${label} [${index + 1}]`);
|
|
340
350
|
if (ctx.mode !== "tui") {
|
|
341
351
|
const selected = await ctx.ui.select(title, labels);
|
|
342
352
|
const index = labels.indexOf(selected ?? "");
|
|
343
353
|
return index < 0 ? undefined : items[index]!.value;
|
|
344
354
|
}
|
|
345
355
|
return ctx.ui.custom<T | undefined>((tui, theme, keys, done) => {
|
|
346
|
-
const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action)
|
|
356
|
+
const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action)[0] ?? "unbound";
|
|
347
357
|
const keyHint = (action: Parameters<typeof keys.getKeys>[0], description: string) => rawKeyHint(keyText(action), description);
|
|
348
|
-
const rows =
|
|
349
|
-
|
|
358
|
+
const rows = items.map((item, index) => ({ label: labels[index]!, value: String(index),
|
|
359
|
+
description: clean(item.description ?? "", 4000), detail: clean(item.detail ?? item.label, 4000).trim(),
|
|
360
|
+
search: clean([item.label, item.description, item.detail, item.search].filter(Boolean).join(" "), 8000) }));
|
|
361
|
+
const input = new Input({ prompt: "Find: ", placeholder: "type to filter", placeholderStyle: (text) => theme.fg("dim", text) });
|
|
362
|
+
input.setValue(state.query);
|
|
363
|
+
const previewText = new Text("", 0, 0);
|
|
364
|
+
const hints = new Text("", 0, 0);
|
|
365
|
+
const filter = () => fuzzyFilter(rows, input.getValue(), (row) => row.search);
|
|
366
|
+
let filtered = filter();
|
|
367
|
+
// The menu replaces the editor, not the screen; leave half the terminal for the transcript.
|
|
350
368
|
const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
|
|
351
369
|
let height = menuHeight();
|
|
370
|
+
let width = 0;
|
|
352
371
|
let listHeight = 0;
|
|
353
372
|
let pressed = false;
|
|
354
373
|
let cancelClick = false;
|
|
374
|
+
const headerHeight = () => height >= 6 ? 2 : height >= 4 ? 1 : 0;
|
|
375
|
+
const hintHeight = () => height >= 12 && width < 60 ? 3 : height >= 8 ? 2 : height >= 4 ? 1 : 0;
|
|
376
|
+
const detailHeight = () => height >= 12 ? 3 : height >= 10 ? 2 : 0;
|
|
377
|
+
const pageSize = () => Math.max(1, height - headerHeight() - hintHeight() - detailHeight() - 1);
|
|
378
|
+
const remember = (value: string) => { state.index = Number(value); state.key = items[state.index]!.key; };
|
|
355
379
|
const createList = () => {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
list.
|
|
360
|
-
list.
|
|
361
|
-
list.
|
|
380
|
+
const list = new SelectList(filtered, pageSize(), { ...getSelectListTheme(), noMatch: () => theme.fg("warning", " No matches. Clear the filter.") }, { maxPrimaryColumnWidth: 42,
|
|
381
|
+
truncatePrimary: ({ text, maxWidth }) => truncateToWidth(text, maxWidth) });
|
|
382
|
+
const index = filtered.findIndex(({ value }) => state.key ? items[Number(value)]!.key === state.key : Number(value) === state.index);
|
|
383
|
+
list.setSelectedIndex(Math.max(0, index));
|
|
384
|
+
list.onSelectionChange = ({ value }) => remember(value);
|
|
385
|
+
list.onSelect = ({ value }) => { remember(value); done(items[Number(value)]!.value); };
|
|
362
386
|
return list;
|
|
363
387
|
};
|
|
364
388
|
let list = createList();
|
|
389
|
+
const resetPress = () => { if (pressed) cancelClick = true; pressed = false; };
|
|
365
390
|
return {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
391
|
+
// Native list paging must not scroll the fullscreen transcript instead.
|
|
392
|
+
capturesViewportInput: list.capturesViewportInput,
|
|
393
|
+
get focused() { return input.focused; },
|
|
394
|
+
set focused(value: boolean) { input.focused = value; },
|
|
395
|
+
render(nextWidth) {
|
|
396
|
+
if (height !== menuHeight() || width !== nextWidth) {
|
|
397
|
+
resetPress();
|
|
398
|
+
height = menuHeight(); width = nextWidth; list = createList();
|
|
399
|
+
}
|
|
400
|
+
const lines = list.render(width).map((line) => truncateToWidth(line, width));
|
|
401
|
+
listHeight = Math.min(lines.length, height - headerHeight() - hintHeight() - detailHeight());
|
|
402
|
+
const selected = list.getSelectedItem();
|
|
403
|
+
const detail = selected ? rows[Number(selected.value)]!.detail : "No matches. Clear or change the filter.";
|
|
404
|
+
previewText.setText(theme.fg("muted", detail));
|
|
405
|
+
const limit = detailHeight();
|
|
406
|
+
const preview = limit ? previewText.render(width).slice(0, limit + 1) : [];
|
|
407
|
+
if (limit && preview.length > limit) preview[limit - 1] = truncateToWidth(`${preview[limit - 1]}…`, width, "…", true);
|
|
408
|
+
hints.setText([keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel"),
|
|
409
|
+
`${filtered.length}/${rows.length}`, rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "move"),
|
|
410
|
+
rawKeyHint(`${keyText("tui.select.pageUp")}/${keyText("tui.select.pageDown")}`, "page"), keyHint("tui.editor.deleteToLineStart", "clear")].join(" · "));
|
|
411
|
+
return [
|
|
412
|
+
...(headerHeight() ? [theme.fg("accent", title)] : []),
|
|
413
|
+
...(headerHeight() === 2 ? input.render(width) : []),
|
|
414
|
+
...lines.slice(0, listHeight),
|
|
415
|
+
...preview.slice(0, limit),
|
|
416
|
+
...hints.render(width).slice(0, hintHeight()),
|
|
417
|
+
].map((line) => truncateToWidth(line, width));
|
|
418
|
+
},
|
|
419
|
+
handleInput(data) {
|
|
420
|
+
resetPress();
|
|
421
|
+
if (keys.matches(data, "tui.select.cancel")) { done(undefined); return; }
|
|
422
|
+
if (keys.matches(data, "tui.select.confirm")) {
|
|
423
|
+
const selected = list.getSelectedItem();
|
|
424
|
+
if (selected) list.onSelect!(selected);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const index = filtered.findIndex(({ value }) => value === list.getSelectedItem()?.value);
|
|
428
|
+
const page = getSelectPageIndex(keys, data, index, filtered.length, pageSize());
|
|
429
|
+
const up = keys.matches(data, "tui.select.up"), down = keys.matches(data, "tui.select.down");
|
|
430
|
+
if (up || down || page !== undefined) {
|
|
431
|
+
if (filtered.length) list.setSelectedIndex(page ?? (index + (up ? -1 : 1) + filtered.length) % filtered.length);
|
|
432
|
+
const selected = list.getSelectedItem();
|
|
433
|
+
if (selected) remember(selected.value);
|
|
434
|
+
} else {
|
|
435
|
+
if (keys.matches(data, "tui.editor.deleteToLineStart")) input.setValue("");
|
|
436
|
+
else input.handleInput(data);
|
|
437
|
+
if (state.query !== input.getValue()) {
|
|
438
|
+
state.query = input.getValue(); filtered = filter(); list = createList();
|
|
439
|
+
const selected = list.getSelectedItem();
|
|
440
|
+
if (selected) remember(selected.value);
|
|
441
|
+
}
|
|
372
442
|
}
|
|
373
|
-
|
|
374
|
-
listHeight = Math.min(lines.length, height);
|
|
375
|
-
if (height < 4) return lines.slice(0, height);
|
|
376
|
-
return [truncateToWidth(theme.fg("accent", title), width), ...lines,
|
|
377
|
-
truncateToWidth([rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "scroll"),
|
|
378
|
-
keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
|
|
443
|
+
tui.requestRender();
|
|
379
444
|
},
|
|
380
|
-
handleInput(data) { list.handleInput(data); tui.requestRender(); },
|
|
381
445
|
handleMouse(event: TuiMouseEvent) {
|
|
382
446
|
if (event.type === "click" && cancelClick) { cancelClick = false; return { handled: true }; }
|
|
383
447
|
if (event.type === "press") cancelClick = false;
|
|
384
|
-
|
|
448
|
+
if (headerHeight() === 2 && event.y === 1) return input.handleMouse({ ...event, y: 0, height: 1 });
|
|
449
|
+
const y = event.y - headerHeight();
|
|
385
450
|
if (y < 0 || y >= listHeight) return undefined;
|
|
386
451
|
const result = list.handleMouse({ ...event, y, height: listHeight });
|
|
387
452
|
if (event.type === "press") pressed = result?.handled === true;
|
|
388
453
|
if (event.type === "click") pressed = false;
|
|
389
454
|
return result;
|
|
390
455
|
},
|
|
391
|
-
invalidate() { list.invalidate(); },
|
|
456
|
+
invalidate() { input.invalidate(); list.invalidate(); previewText.invalidate(); hints.invalidate(); },
|
|
392
457
|
};
|
|
393
458
|
}, { blocked: { kind: "question", message: title } });
|
|
394
459
|
}
|
|
@@ -399,16 +464,16 @@ async function chooseMany<T>(ctx: ExtensionContext, title: string, items: readon
|
|
|
399
464
|
valid: () => boolean): Promise<T[] | undefined> {
|
|
400
465
|
type Pick = { kind: "toggle"; value: T } | { kind: "all" } | { kind: "clear" } | { kind: "continue" } | { kind: "cancel" };
|
|
401
466
|
const chosen = new Set(preselected);
|
|
402
|
-
|
|
467
|
+
const state: MenuState = { index: 0, query: "" };
|
|
403
468
|
for (;;) {
|
|
404
469
|
const choices: Choice<Pick>[] = [
|
|
405
|
-
...items.map((item) => ({ label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
|
|
470
|
+
...items.map((item) => ({ ...item, label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
|
|
406
471
|
{ label: "Select all", value: { kind: "all" } }, { label: "Clear", value: { kind: "clear" } },
|
|
407
472
|
{ label: `Continue (${chosen.size} selected)`, value: { kind: "continue" } }, { label: "Cancel", value: { kind: "cancel" } },
|
|
408
473
|
];
|
|
409
|
-
const picked = await choose(ctx, title
|
|
474
|
+
const picked = await choose(ctx, `${chosen.size} selected · ${title}`, choices, state);
|
|
410
475
|
if (!valid() || !picked || picked.kind === "cancel") return undefined;
|
|
411
|
-
|
|
476
|
+
state.index = choices.findIndex(({ value }) => value === picked);
|
|
412
477
|
if (picked.kind === "continue") return items.map(({ value }) => value).filter((value) => chosen.has(value));
|
|
413
478
|
if (picked.kind === "all") for (const { value } of items) chosen.add(value);
|
|
414
479
|
else if (picked.kind === "clear") chosen.clear();
|
|
@@ -608,7 +673,8 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
608
673
|
const options = reviewed.shown.filter((item) => item.prunable || item.override);
|
|
609
674
|
if (!options.length) return;
|
|
610
675
|
// Continue confirms prunable items; each is re-verified first. Blocked items need their own confirmation below.
|
|
611
|
-
const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item),
|
|
676
|
+
const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item),
|
|
677
|
+
detail: `${item.branch} · ${item.path ?? "no checkout"} · ${item.reason}`, value: item })),
|
|
612
678
|
options.filter((item) => item.prunable), valid);
|
|
613
679
|
if (!picked?.length) return;
|
|
614
680
|
const forceable = picked.filter((item) => item.override === "force");
|
|
@@ -661,8 +727,17 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
661
727
|
} finally { if (job.state.kind === "reviewing") clearPrune(job); }
|
|
662
728
|
}
|
|
663
729
|
if (!ctx.hasUI) {
|
|
664
|
-
const
|
|
665
|
-
|
|
730
|
+
const direct = adapter.direct(ctx);
|
|
731
|
+
let inventory: IsolatedInventory;
|
|
732
|
+
try { inventory = await adapter.isolated(ctx.cwd, current); }
|
|
733
|
+
catch (error) {
|
|
734
|
+
deliver(ctx, workingReport(direct, undefined));
|
|
735
|
+
for (const task of direct) deliver(ctx, directReport(task));
|
|
736
|
+
deliver(ctx, textReport("warning", `Isolated inventory unavailable: ${errorText(error)}. Direct release requires interactive confirmation.`));
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
deliver(ctx, workingReport(direct, inventory));
|
|
740
|
+
for (const task of direct) deliver(ctx, directReport(task));
|
|
666
741
|
const head: Report = { tone: "info", title: "Isolated requests (report only)", sections: [] };
|
|
667
742
|
const row = (request: IsolatedRequest): Row => ({ text: `${glyph(request.status)} ${request.orphaned ? "orphaned · " : ""}${isolatedLabel(request)}` });
|
|
668
743
|
const listed = fitItems(`${reportMarkdown(head)}\n`, inventory.requests, (request) => sectionMarkdown({ rows: [row(request)] }), ROLES_REPORT_CODE_POINTS,
|
|
@@ -674,6 +749,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
674
749
|
return;
|
|
675
750
|
}
|
|
676
751
|
let history = false;
|
|
752
|
+
const menu: MenuState = { index: 0, query: "" };
|
|
677
753
|
// The working report shows on open and on each Refresh, not after other menu actions.
|
|
678
754
|
let report = true;
|
|
679
755
|
for (;;) {
|
|
@@ -687,17 +763,30 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
687
763
|
if (!valid()) return;
|
|
688
764
|
if (report) deliver(ctx, workingReport(direct, inventory));
|
|
689
765
|
report = false;
|
|
690
|
-
if (unavailable) ctx.ui.notify(`Isolated inventory unavailable (${unavailable}). Direct
|
|
766
|
+
if (unavailable) ctx.ui.notify(`Isolated inventory unavailable (${unavailable}). Direct recovery remains available; check the canonical Git checkout/configuration.`, "warning");
|
|
691
767
|
if (inventory?.invalidIds.length) for (const id of inventory.invalidIds) ctx.ui.notify(`Unreadable isolated state ID: ${JSON.stringify(id)}. Preserve this file; inspect the state store before making changes.`, "warning");
|
|
692
768
|
type Selection = { kind: "direct"; task: DirectTask } | { kind: "isolated"; request: IsolatedRequest; root: string } | { kind: "refresh" } | { kind: "history" } | { kind: "many" } | { kind: "close" };
|
|
693
|
-
//
|
|
769
|
+
// Terminal rows carry their group, so headings cannot be mistaken for actions.
|
|
694
770
|
const group = <T extends { status: string }>(title: string, items: readonly T[], choice: (item: T) => Choice<Selection>): Choice<Selection>[] =>
|
|
695
|
-
items.length ? [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" } },
|
|
771
|
+
items.length ? [...(ctx.mode === "tui" ? [] : [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" as const } }]),
|
|
696
772
|
...[...items].sort((a, b) => priority(a.status) - priority(b.status)).map(choice)] : [];
|
|
697
773
|
const requests = (inventory?.requests ?? []).filter((request) => history || !completed(request.status) || /retained/i.test(request.status));
|
|
698
|
-
const isolatedChoice = (request: IsolatedRequest): Choice<Selection> =>
|
|
699
|
-
|
|
700
|
-
|
|
774
|
+
const isolatedChoice = (request: IsolatedRequest): Choice<Selection> => {
|
|
775
|
+
const group = request.orphaned ? "Orphaned · parent checkout removed" : "Isolated";
|
|
776
|
+
return { label: ` ${glyph(request.status)} ${ctx.mode === "tui" ? `${request.id} · ${request.status}` : isolatedLabel(request)}`,
|
|
777
|
+
description: `${group} · ${summary(request.name)}`, detail: `${group} · ${request.status} · ${request.id} · ${request.name}`,
|
|
778
|
+
key: `isolated:${request.directory ?? inventory!.root}:${request.id}`, value: { kind: "isolated", request, root: inventory!.root } };
|
|
779
|
+
};
|
|
780
|
+
// Put identity and status before the goal. Keep full context in the selected-row preview and search.
|
|
781
|
+
const directChoice = (task: DirectTask): Choice<Selection> => {
|
|
782
|
+
const [first] = task.workers;
|
|
783
|
+
const ref = first ? first.workers === 1 ? directRef(first) : `D${first.workflow} · ${first.workers} workers` : task.id;
|
|
784
|
+
return { label: ctx.mode === "tui" ? ` ${glyph(task.status)} ${ref} · ${task.status}${costSuffix(task.cost)}`
|
|
785
|
+
: ` ${glyph(task.status)} ${directLabel(task)} · ${task.status}${costSuffix(task.cost)}${task.workers.length || task.name === task.id ? "" : ` · ${task.id}`}`,
|
|
786
|
+
description: `Direct · ${directLabel(task)}`, detail: `Direct · ${task.status}${costSuffix(task.cost)} · ${task.id} · ${directLabel(task)}`,
|
|
787
|
+
search: [task.name, ...task.workers.map(workerLabel)].join(" "),
|
|
788
|
+
key: `direct:${task.id}`, value: { kind: "direct", task } };
|
|
789
|
+
};
|
|
701
790
|
const groups = [
|
|
702
791
|
group("Direct", direct.filter((task) => history || !completed(task.status)), directChoice),
|
|
703
792
|
group("Isolated", requests.filter((request) => !request.orphaned), isolatedChoice),
|
|
@@ -711,13 +800,13 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
711
800
|
{ label: history ? "Active work" : "Completed / history (including retained work)", value: { kind: "history" } },
|
|
712
801
|
{ label: "Close", value: { kind: "close" } },
|
|
713
802
|
];
|
|
714
|
-
if (!unavailable && !direct.length && !inventory?.requests.length && !inventory?.invalidIds.length) ctx.ui.notify("No direct tasks recorded
|
|
715
|
-
const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections);
|
|
803
|
+
if (!unavailable && !direct.length && !inventory?.requests.length && !inventory?.invalidIds.length) ctx.ui.notify("No direct tasks recorded in this session or isolated requests in this checkout. Ask Main to start delegation.", "info");
|
|
804
|
+
const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections, menu);
|
|
716
805
|
if (!valid() || !selected || selected.kind === "close") return;
|
|
717
806
|
if (selected.kind === "refresh") { report = true; continue; }
|
|
718
807
|
if (selected.kind === "history") { history = !history; continue; }
|
|
719
808
|
if (selected.kind === "many") {
|
|
720
|
-
const picked = await chooseMany(ctx, "Subagent · select work", rows.map((
|
|
809
|
+
const picked = await chooseMany(ctx, "Subagent · select work", rows.map((item) => ({ ...item, label: item.label.trim() })), [], valid);
|
|
721
810
|
if (!picked?.length) { if (!valid()) return; continue; }
|
|
722
811
|
const isolated = picked.flatMap((item) => item.kind === "isolated" ? [item.request] : []);
|
|
723
812
|
const closable = picked.flatMap((item) => item.kind === "direct" && item.task.canClose ? [item.task] : []);
|
|
@@ -749,13 +838,20 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
749
838
|
const label = clean(directLabel(task));
|
|
750
839
|
deliver(ctx, directReport(task));
|
|
751
840
|
const stoppable = task.tabs.filter((tab) => task.stoppable?.includes(tab.entryId));
|
|
752
|
-
if (task.canClose || stoppable.length) {
|
|
753
|
-
const action = await choose<{ kind: "close" | "back" } | { kind: "stop"; entryId: string }>(ctx, `Direct · ${label}`, [
|
|
841
|
+
if (task.canClose || stoppable.length || task.admission?.canRecover) {
|
|
842
|
+
const action = await choose<{ kind: "close" | "back" | "recover" } | { kind: "stop"; entryId: string }>(ctx, `Direct · ${label}`, [
|
|
754
843
|
...(task.canClose ? [{ label: "Close/cancel-and-release ALL owned workers in this workflow (preserve files and commits)", value: { kind: "close" as const } }] : []),
|
|
844
|
+
...(task.admission?.canRecover && adapter.recoverDirect ? [{ label: "Review recovered checkout protection", value: { kind: "recover" as const } }] : []),
|
|
755
845
|
...stoppable.map((tab) => ({ label: `Stop this worker: ${tab.display ? workerLabel(tab.display) : tab.name} (other workers continue)`, value: { kind: "stop" as const, entryId: tab.entryId } })),
|
|
756
846
|
{ label: "Back / refresh", value: { kind: "back" as const } },
|
|
757
847
|
]);
|
|
758
848
|
if (!valid()) return;
|
|
849
|
+
if (action?.kind === "recover") {
|
|
850
|
+
try {
|
|
851
|
+
const report = await adapter.recoverDirect!(task, ctx, current);
|
|
852
|
+
if (valid()) deliver(ctx, textReport(task.admission!.proof ? "info" : "warning", report));
|
|
853
|
+
} catch (error) { if (valid()) ctx.ui.notify(`Protection retained: ${errorText(error)}`, "error"); }
|
|
854
|
+
}
|
|
759
855
|
if (action?.kind === "stop") {
|
|
760
856
|
try {
|
|
761
857
|
const report = await adapter.stopDirect(task, action.entryId, current);
|
package/extensions/subagent.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { registerConfigReporting } from "@henryqw/pi-config-store";
|
|
|
6
6
|
import { capEphemeralSubagentOutput as capOutput, createEphemeralSubagentExecutor, createSubagentConfigStore, DEFAULT_SUBAGENT_CONFIG, DELEGATE_TASK, findRole, formatDuration, loadRoleCatalog, prepareRoleLaunch, resolveRolePackageResources, resolveTaskRoute, ROLE_TOOL_POLICY_FLAG, type ExecutionPolicySnapshot, type Role } from "@henryqw/pi-subagent";
|
|
7
7
|
import { resolveExecutionPolicy } from "./config.ts";
|
|
8
8
|
import { captureFallbackWarning } from "./task-model-fallback.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { registerDirectAdmission } from "./admission.ts";
|
|
10
10
|
import { registerIsolatedExtension } from "./isolated.ts";
|
|
11
11
|
import { registerWorkspaceExtension } from "./workspace.ts";
|
|
12
12
|
import { resolveWorkspaceScope } from "../dist/workspace-scope.js";
|
|
@@ -16,6 +16,7 @@ import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowRe
|
|
|
16
16
|
import { checkoutNote, DelegateTaskParameters, identifyWorkflowEntries, parseDelegateTask, runForegroundWorkflow, snapshotCheckout, writesCheckout, type CheckoutSnapshot, type ParsedWorkflow, type WorkflowEntry } from "./workflow.ts";
|
|
17
17
|
import { workspaceNeedsCollection } from "../dist/collection.js";
|
|
18
18
|
import { assertSettledDirectSession, createDirectHerdr, DirectAllocationError, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity, type DirectUsage } from "../dist/direct-herdr.js";
|
|
19
|
+
import { isProcessLeaseIdentity } from "../dist/process-lease.js";
|
|
19
20
|
import { materializeTransientLaunch } from "../dist/launch-runtime.js";
|
|
20
21
|
const WIDGET_KEY = "subagent-status";
|
|
21
22
|
const WIDGET_INTERVAL_MS = 1_000;
|
|
@@ -136,10 +137,10 @@ const DIRECT_RESULT_TYPE = "subagent-direct-result";
|
|
|
136
137
|
const DIRECT_TAB_TYPE = "subagent-direct-tab";
|
|
137
138
|
const DIRECT_ALLOCATION_TYPE = "subagent-direct-allocation";
|
|
138
139
|
// Legacy records have no display metadata.
|
|
139
|
-
type DirectAllocationRecord = DirectAllocation & { taskId: string; entryId: string; failure: string; display?: DirectDisplay };
|
|
140
|
+
type DirectAllocationRecord = DirectAllocation & { taskId: string; entryId: string; failure: string; access?: "read" | "write"; display?: DirectDisplay };
|
|
140
141
|
// Records saved before continuation support lack turn, workspace, and checkout identity and cannot be continued.
|
|
141
142
|
type DirectTabRecord = Omit<DirectTab, "turn" | "workspaceId" | "cwd"> & Partial<Pick<DirectTab, "turn" | "workspaceId" | "cwd">>
|
|
142
|
-
& { taskId: string; entryId: string; display?: DirectDisplay };
|
|
143
|
+
& { taskId: string; entryId: string; access?: "read" | "write"; display?: DirectDisplay };
|
|
143
144
|
|
|
144
145
|
function boundedError(error: unknown): Error {
|
|
145
146
|
const message = capOutput(error instanceof Error ? error.message : String(error));
|
|
@@ -235,7 +236,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
235
236
|
return true;
|
|
236
237
|
}
|
|
237
238
|
};
|
|
238
|
-
const
|
|
239
|
+
const directAdmission = registerDirectAdmission(pi, canWrite, async (input, ctx) => {
|
|
239
240
|
if (!input || typeof input !== "object" || !Object.hasOwn(input, "repositories")) return [];
|
|
240
241
|
const parsed = parseDelegateTask(input);
|
|
241
242
|
if (parsed.mode !== "direct" || !parsed.workflow.repositories) return [];
|
|
@@ -265,7 +266,6 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
265
266
|
beforeRoleLaunch,
|
|
266
267
|
onFinished: (ctx) => automaticCollection(ctx),
|
|
267
268
|
});
|
|
268
|
-
let directSequence = 0;
|
|
269
269
|
const directTasks = new Map<string, {
|
|
270
270
|
controller: AbortController; settled: Promise<void>; handles: DirectHandle[]; tabs: DirectTabRecord[];
|
|
271
271
|
pendingResult?: (sessionId: string) => boolean;
|
|
@@ -305,7 +305,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
305
305
|
seen.add(tab.tabId);
|
|
306
306
|
const unowned = () => current() && !directTasks.has(tab.taskId)
|
|
307
307
|
&& ![...directTasks.values()].some((task) => task.continues?.has(tab.sessionFile));
|
|
308
|
-
if (!unowned()) continue;
|
|
308
|
+
if (!unowned() || !directAdmission.canUseRecordedTask(ctx)) continue;
|
|
309
309
|
try {
|
|
310
310
|
if (!await eligible(tab.workspaceId) || !unowned()) continue;
|
|
311
311
|
const herdr = createDirectHerdr(pi, ctx.cwd, currentPolicy().childIdleMs);
|
|
@@ -375,9 +375,12 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
375
375
|
if (details?.taskId) results.set(details.taskId, details);
|
|
376
376
|
}
|
|
377
377
|
const entryCost = (taskId: string, entryId: string) => results.get(taskId)?.entries.find(({ id }) => id === entryId)?.cost;
|
|
378
|
-
for (const entry of ctx.sessionManager.
|
|
378
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
379
379
|
if (entry.type !== "custom" || !entry.data || (entry.customType !== DIRECT_TAB_TYPE && entry.customType !== DIRECT_ALLOCATION_TYPE)) continue;
|
|
380
380
|
const record = entry.data as DirectTabRecord | DirectAllocationRecord;
|
|
381
|
+
// Incomplete saved evidence is reported by the journal row, not treated as a tab.
|
|
382
|
+
const fields = entry.customType === DIRECT_TAB_TYPE ? ["taskId", "entryId", "name", "tabId", "paneId", "sessionFile"] : ["taskId", "label", "failure"];
|
|
383
|
+
if (fields.some((key) => typeof (record as any)[key] !== "string")) continue;
|
|
381
384
|
const local = directTasks.get(record.taskId);
|
|
382
385
|
let task = grouped.get(record.taskId);
|
|
383
386
|
if (!task) grouped.set(record.taskId, task = { id: record.taskId, name: record.taskId,
|
|
@@ -402,9 +405,57 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
402
405
|
task.tabs.push({ entryId, name, tabId, paneId, sessionFile, ...(display ? { display } : {}), ...(cost === undefined ? {} : { cost }) });
|
|
403
406
|
}
|
|
404
407
|
}
|
|
408
|
+
// Local ownership must remain visible even when its first tab write failed.
|
|
409
|
+
for (const [id, local] of directTasks) {
|
|
410
|
+
const task: NonNullable<ReturnType<typeof grouped.get>> = grouped.get(id) ?? { id, name: id, status: "observed locally", workers: [], tabs: [] };
|
|
411
|
+
Object.assign(task, { status: local.allocation ? "allocation unverified; admission retained locally" : local.recovery ? "admission retained locally" : "observed locally", recovery: local.recovery,
|
|
412
|
+
canClose: Boolean(local.close) && !local.allocation, tabs: [...local.tabs], workers: [...local.tabs, ...(local.allocation ? [local.allocation] : [])].flatMap(({ display }) => display ? [display] : []) });
|
|
413
|
+
grouped.set(id, task);
|
|
414
|
+
}
|
|
415
|
+
const inventory = directAdmission.inventory(ctx);
|
|
416
|
+
for (const record of inventory.records) {
|
|
417
|
+
const task: NonNullable<ReturnType<typeof grouped.get>> = grouped.get(record.taskId) ?? { id: record.taskId, name: record.taskId, status: "", workers: [], tabs: [] };
|
|
418
|
+
const local = directTasks.has(record.taskId);
|
|
419
|
+
task.status = record.state === "held" ? local ? directTasks.get(record.taskId)!.allocation ? "allocation unverified; admission retained locally" : "admission retained locally" : "recovered admission retained"
|
|
420
|
+
: "protection released by user; termination unproved";
|
|
421
|
+
task.admission = { identity: `${record.sessionId}/${record.taskId}/${record.token}`, checkouts: record.checkouts,
|
|
422
|
+
evidence: directAdmission.evidence(record, ctx), proof: directAdmission.hasProof(record, ctx),
|
|
423
|
+
canRecover: record.state === "held" && !local && !inventory.failure };
|
|
424
|
+
task.recovery = record.state === "released" ? "A worker may still change these checkouts. Inspect changes before new work."
|
|
425
|
+
: local ? task.recovery ?? "Use local Close; saved records do not replace local authority."
|
|
426
|
+
: task.admission.proof ? record.proof === "not-dispatched" ? "Saved proof: no external effect was dispatched."
|
|
427
|
+
: "Saved proof: the local owner proved every effect stopped before release failed."
|
|
428
|
+
: "Complete termination proof is unavailable. Saved records cannot stop workers. Only a warned human release can waive protection.";
|
|
429
|
+
grouped.set(record.taskId, task);
|
|
430
|
+
}
|
|
431
|
+
if (inventory.failure) grouped.set("journal-failure", { id: "journal-failure", name: "Direct admission journal", status: "admission recovery blocked",
|
|
432
|
+
recovery: `${inventory.failure} Reservation identity or scope may be unknown. Restore authoritative evidence; no session-wide waiver is available.`, workers: [], tabs: [] });
|
|
405
433
|
for (const task of grouped.values()) task.workers.sort((a, b) => a.worker - b.worker);
|
|
406
434
|
return [...grouped.values()];
|
|
407
435
|
},
|
|
436
|
+
async recoverDirect(task, ctx, current) {
|
|
437
|
+
if (!ctx.hasUI || !current() || directTasks.has(task.id) || !task.admission?.canRecover) throw new Error("Use local Close for owned tasks; recovered release requires the current interactive session.");
|
|
438
|
+
const record = directAdmission.inventory(ctx).records.find(({ taskId }) => taskId === task.id);
|
|
439
|
+
if (!record || `${record.sessionId}/${record.taskId}/${record.token}` !== task.admission.identity) throw new Error("Direct reservation changed; reopen /subagent.");
|
|
440
|
+
const owned = () => current() && !directTasks.has(task.id);
|
|
441
|
+
const claim = directAdmission.claim(record, ctx, owned);
|
|
442
|
+
try {
|
|
443
|
+
const review = `Reservation: ${task.admission.identity}\nComplete checkout set:\n${record.checkouts.join("\n")}\nSaved resources:\n${directAdmission.evidence(record, ctx)}\n${task.recovery ?? ""}`;
|
|
444
|
+
const proof = directAdmission.hasProof(record, ctx);
|
|
445
|
+
if (proof) {
|
|
446
|
+
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.";
|
|
447
|
+
claim.release("proved");
|
|
448
|
+
return "Saved proof accepted; exact checkout reservation released. Files, commits and session evidence preserved.";
|
|
449
|
+
}
|
|
450
|
+
const warning = "Release protection despite unproved termination";
|
|
451
|
+
const choice = await ctx.ui.select(`${review}\nA worker may still change ANY listed checkout. This does not stop workers or prove termination.`, ["Keep protection", warning]);
|
|
452
|
+
if (!owned() || choice !== warning) return "Protection retained.";
|
|
453
|
+
const typed = await ctx.ui.input(`Type the exact reservation identity to accept this risk: ${task.admission.identity}`);
|
|
454
|
+
if (!owned() || typed !== task.admission.identity) return "Protection retained; identity confirmation did not match.";
|
|
455
|
+
claim.release("user-unproved", typed);
|
|
456
|
+
return "Protection released by user; worker termination remains unproved. A worker may still change any listed checkout. Inspect changes before new work. All evidence preserved.";
|
|
457
|
+
} finally { claim.close(); }
|
|
458
|
+
},
|
|
408
459
|
async closeDirect(task, current) {
|
|
409
460
|
const local = directTasks.get(task.id);
|
|
410
461
|
const owned = () => current() && directTasks.get(task.id) === local;
|
|
@@ -464,7 +515,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
464
515
|
{ ...prepared, args: [...transient.launch.args] }, `i-${randomUUID().replaceAll("-", "").slice(0, 24)}`,
|
|
465
516
|
`${directRef(display)} ${display.title}`, `Analyze this saved, read-only status snapshot for request ${id}. Summarize blockers and safe next decisions; do not infer missing evidence. The subagent_status tool in Main remains authoritative for exact action identities.\n\n${READ_ACCESS_NOTICE}\n\n${snapshot}`,
|
|
466
517
|
controller.signal, (tab) => {
|
|
467
|
-
const record = { taskId, entryId: id, display, ...tab };
|
|
518
|
+
const record = { taskId, entryId: id, access: "read" as const, display, ...tab };
|
|
468
519
|
if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_TAB_TYPE, record);
|
|
469
520
|
tabs.push(record);
|
|
470
521
|
});
|
|
@@ -824,12 +875,14 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
824
875
|
const source = matches[0]!;
|
|
825
876
|
if (source.display!.role !== role) throw refuse(`it ran with Role ${source.display!.role}, not ${role}; use the recorded Role`);
|
|
826
877
|
if (source.turn === undefined) throw refuse("its record has no turn identity (saved by an older pi-subagent), so it is not continuable; start a fresh task");
|
|
878
|
+
if (!isProcessLeaseIdentity(source.leaseIdentity)) throw refuse("its original process lease identity is missing or invalid; do not use a replacement lease as proof");
|
|
827
879
|
if (source.workspaceId !== herdr.workspaceId || source.cwd !== herdr.cwd) {
|
|
828
880
|
throw refuse(`it ran in ${source.cwd ?? "an unrecorded checkout"} (Herdr workspace ${source.workspaceId ?? "unrecorded"}), not this checkout and workspace; start a fresh task here`);
|
|
829
881
|
}
|
|
830
882
|
if ([...directTasks.values()].some(({ tabs, continues }) => continues?.has(source.sessionFile)
|
|
831
883
|
|| tabs.some(({ sessionFile }) => sessionFile === source.sessionFile))) throw refuse("a locally active direct task still owns its session");
|
|
832
884
|
if ([...sources.values()].some(({ sessionFile }) => sessionFile === source.sessionFile)) throw refuse("this request already continues its session");
|
|
885
|
+
if (!directAdmission.canUseRecordedTask(ctx)) throw refuse("its admission is unresolved or cannot be restored; recorded evidence grants no stop authority");
|
|
833
886
|
sources.set(index, { ...source, turn: source.turn });
|
|
834
887
|
}
|
|
835
888
|
if (parsed.dryRun) return await planDirect(workflow, sources, herdr.cwd, latestCtx ?? ctx);
|
|
@@ -857,7 +910,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
857
910
|
...(usage?.cost === undefined ? {} : { cost: usage.cost }),
|
|
858
911
|
...(startedAt.has(id) ? { elapsedMs: Date.now() - startedAt.get(id)! } : {}),
|
|
859
912
|
});
|
|
860
|
-
const taskId = `direct-${
|
|
913
|
+
const taskId = `direct-${randomUUID()}`;
|
|
861
914
|
const workflowNumber = nextWorkflow(ctx);
|
|
862
915
|
const ref = `D${workflowNumber}`;
|
|
863
916
|
const displayOf = ({ index, delegation }: WorkflowEntry): DirectDisplay => ({
|
|
@@ -879,7 +932,9 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
879
932
|
const settled = new Promise<void>((resolve) => { resolveSettled = resolve; });
|
|
880
933
|
// Register before Herdr can create a tab: session switches must await this
|
|
881
934
|
// launch, including its identity callback, before copying recovery records.
|
|
882
|
-
|
|
935
|
+
signal?.throwIfAborted();
|
|
936
|
+
const releaseAdmission = writes ? directAdmission.hold(toolCallId, taskId, ctx) : Object.assign(() => {}, { effect: (_resource: unknown) => {} });
|
|
937
|
+
let pendingSource: DirectTabRecord | undefined;
|
|
883
938
|
const local: NonNullable<ReturnType<typeof directTasks.get>> = { controller, settled, handles, tabs,
|
|
884
939
|
continues: new Set([...sources.values()].map(({ sessionFile }) => sessionFile)) };
|
|
885
940
|
if (!writes) local.stopWorker = {
|
|
@@ -904,6 +959,10 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
904
959
|
const inScope = () => current() && (local.closeScope?.() ?? true);
|
|
905
960
|
try {
|
|
906
961
|
if (local.allocation) throw new Error(local.allocation.failure);
|
|
962
|
+
if (pendingSource) {
|
|
963
|
+
await herdr.stop(pendingSource, inScope, terminate ? "terminate" : "proof");
|
|
964
|
+
pendingSource = undefined;
|
|
965
|
+
}
|
|
907
966
|
for (const tab of tabs) await herdr.stop(tab, inScope, terminate ? "terminate" : "proof");
|
|
908
967
|
if (!inScope()) throw new Error("Direct task scope changed; reopen /subagent.");
|
|
909
968
|
releaseAdmission();
|
|
@@ -943,15 +1002,16 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
943
1002
|
handle = await herdr.start({ ...prepared, args: [...transient.launch.args] },
|
|
944
1003
|
`d-${randomUUID().replaceAll("-", "").slice(0, 24)}`, `${directRef(display)} ${display.title}`,
|
|
945
1004
|
`${entry.delegation.access === "read" ? `${entry.delegation.task}\n\n${READ_ACCESS_NOTICE}` : entry.delegation.task}${selected ? `\n\nExplicit selected repository map: ${JSON.stringify(workflow.repositories)}. Do not modify other repositories or workspace-root files. Selection and admission are not a sandbox.` : ""}\n\nFinal answer budget: ${answerBytes} bytes, conclusions first. Main sees only that much inline; a longer answer is saved to a file.`, activeSignal, (tab) => {
|
|
946
|
-
const record = { taskId, entryId: entry.id, display, ...tab };
|
|
947
|
-
//
|
|
948
|
-
if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_TAB_TYPE, record);
|
|
1005
|
+
const record = { taskId, entryId: entry.id, access: writes ? "write" as const : "read" as const, display, ...tab };
|
|
1006
|
+
// Keep local ownership even if saving the tab fails after allocation.
|
|
949
1007
|
tabs.push(record);
|
|
950
1008
|
tabByEntry.set(entry.id, record);
|
|
951
|
-
|
|
1009
|
+
releaseAdmission.effect({ kind: "verified-tab", ...record });
|
|
1010
|
+
if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_TAB_TYPE, record);
|
|
1011
|
+
}, writes, sources.get(entry.index), (allocation) => releaseAdmission.effect({ kind: "allocation-intent", entryId: entry.id, ...allocation }));
|
|
952
1012
|
} catch (error) {
|
|
953
1013
|
if (error instanceof DirectAllocationError) {
|
|
954
|
-
local.allocation = { taskId, entryId: entry.id, display, ...error.allocation, failure: error.message };
|
|
1014
|
+
local.allocation = { taskId, entryId: entry.id, access: writes ? "write" : "read", display, ...error.allocation, failure: error.message };
|
|
955
1015
|
if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_ALLOCATION_TYPE, local.allocation);
|
|
956
1016
|
}
|
|
957
1017
|
// A failed start can still be in flight. Keep its private prompt for recovery.
|
|
@@ -971,11 +1031,17 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
971
1031
|
const abortLaunch = () => controller.abort(signal?.reason);
|
|
972
1032
|
signal?.addEventListener("abort", abortLaunch, { once: true });
|
|
973
1033
|
try {
|
|
1034
|
+
if (signal?.aborted) abortLaunch();
|
|
1035
|
+
controller.signal.throwIfAborted();
|
|
974
1036
|
for (const [index, source] of sources) {
|
|
975
1037
|
try {
|
|
976
1038
|
await assertSettledDirectSession(source.sessionFile, source.turn);
|
|
977
|
-
//
|
|
1039
|
+
// Save this exact source before its stop; later sources have no effect yet.
|
|
1040
|
+
controller.signal.throwIfAborted();
|
|
1041
|
+
releaseAdmission.effect({ kind: "continuation-sources", sources: [source] });
|
|
1042
|
+
pendingSource = source;
|
|
978
1043
|
await herdr.stop(source, () => launchEpoch === sessionEpoch && !controller.signal.aborted, "settled");
|
|
1044
|
+
pendingSource = undefined;
|
|
979
1045
|
} catch (error) {
|
|
980
1046
|
throw new Error(`Cannot continue ${workflow.delegations[index]!.continueFrom}: ${error instanceof Error ? error.message : String(error)}.`, { cause: error });
|
|
981
1047
|
}
|
|
@@ -990,9 +1056,15 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
990
1056
|
} catch (error) {
|
|
991
1057
|
controller.abort();
|
|
992
1058
|
finishWidgetItem(entries[0]!.id, "failure");
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1059
|
+
try {
|
|
1060
|
+
if (!tabs.length && !local.allocation && (!writes || !pendingSource)) { releaseAdmission(); directTasks.delete(taskId); }
|
|
1061
|
+
else local.recovery = local.allocation?.failure ?? (pendingSource
|
|
1062
|
+
? `Continued worker ${pendingSource.tabId} stop is unproved; admission retained. Manual reconciliation is required.`
|
|
1063
|
+
: "Launch outcome uncertain; inspect the exact recorded tab before Close/cancel-and-release");
|
|
1064
|
+
} catch (releaseError) {
|
|
1065
|
+
local.recovery = `Admission release could not be saved: ${boundedError(releaseError).message}`;
|
|
1066
|
+
throw boundedError(new Error(`${boundedError(error).message}. ${local.recovery}`, { cause: releaseError }));
|
|
1067
|
+
} finally { resolveSettled(); }
|
|
996
1068
|
throw boundedError(error);
|
|
997
1069
|
} finally { signal?.removeEventListener("abort", abortLaunch); }
|
|
998
1070
|
local.pendingResult = (sessionId) => !controller.signal.aborted && launchEpoch === sessionEpoch
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@henryqw/pi-subagent",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "29.0.0",
|
|
4
4
|
"description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
73
|
"@henryqw/pi-config-store": "^4.1.3",
|
|
74
|
-
"@henryqw/pi-herdr": "^0.
|
|
74
|
+
"@henryqw/pi-herdr": "^0.7.0",
|
|
75
75
|
"@henryqw/pi-multi-codex": "^3.0.0",
|
|
76
76
|
"@henryqw/pi-process": "^0.2.0",
|
|
77
77
|
"@henryqw/pi-task-models": "^9.3.0",
|