@henryqw/pi-subagent 27.10.3 → 27.11.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 CHANGED
@@ -25,7 +25,7 @@ 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 that prevents Main and other direct writers from writing to the shared checkout. It remains held until worker 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; read classification is not a sandbox.
29
29
 
30
30
  **Isolated request**:
31
31
  A durable goal and dependency graph of text and changeset tasks, with checked results and recovery state.
package/README.md CHANGED
@@ -73,6 +73,8 @@ Every task requires `access: "read"` or `access: "write"`. Declare `write` for f
73
73
 
74
74
  Read requests run parallel tasks up to `maxSubagents`. Chains run in order, replace literal `{previous}` with the preceding successful answer, and stop on failure. Any `write` task makes the whole request serial and reserves checkout admission until all owned workers stop.
75
75
 
76
+ 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.
77
+
76
78
  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.
77
79
 
78
80
  Tasks in write requests must return one JSON completion object:
@@ -163,6 +165,8 @@ The extension sends follow-ups when a candidate becomes ready, a worker needs at
163
165
 
164
166
  Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. The menu groups rows under **Direct**, **Isolated**, and **Orphaned** headers. Each isolated row shows the request ID, the status, and a short goal summary. **Refresh** or a header reloads saved status without recovery or mutation. Invalid state IDs stay preserved with a warning. Direct recovery remains available outside Git or without isolated inventory.
165
167
 
168
+ In the terminal, use the Up and Down arrow keys to scroll through menu rows. Enter selects a row; Escape cancels the menu. The list fits the terminal height and keeps the current row visible when you resize the terminal. The menu shows your configured selection keys. In multiple-choice menus, the menu keeps the current row in view after you mark or clear it. Scroll to **Select all**, **Clear**, **Continue**, or **Cancel** below the work rows.
169
+
166
170
  Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. The extension calculates it from local and saved evidence without a model call. Without interactive UI, `/subagent` sends this report before the request list.
167
171
 
168
172
  A direct workflow is working only when this Pi process owns it and has a running worker. Direct work with a delivered result shows its outcome under **Completed / history** and is not in the report. Other recorded-only direct work shows as unverified. An isolated request is working only when its status is active and a live run holds the repository lease. Without a live lease, an active request shows as interrupted; run `/subagent recover`.
@@ -1,82 +1 @@
1
- import { realpath } from "node:fs/promises";
2
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
-
4
- // Main's own tools that never change a checkout; every other Main call may write.
5
- // `codemode` mutates nothing itself: its nested tool calls are admitted by their own names.
6
- const MAIN_NON_WRITING_TOOLS = new Set([
7
- "read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode",
8
- ]);
9
-
10
- async function checkoutKey(pi: ExtensionAPI, ctx: ExtensionContext): Promise<string> {
11
- const cwd = await realpath(ctx.cwd);
12
- const result = await pi.exec("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000 });
13
- if (result.code !== 0 || result.killed) return cwd;
14
- const root = result.stdout.replace(/\r?\n$/, "");
15
- if (!root || /[\r\n\0]/.test(root)) throw new Error("Git returned a malformed checkout root during delegation admission.");
16
- return await realpath(root);
17
- }
18
-
19
- /**
20
- * Reserve checkouts only for direct writers. Main writes can run together, but
21
- * each call must finish before a direct writer can start in that checkout.
22
- * External processes and trusted extension lifecycle code are not intercepted.
23
- */
24
- export function registerCheckoutAdmission(pi: ExtensionAPI, directCanWrite: (input: unknown) => boolean): (toolCallId: string) => () => void {
25
- const heldCalls = new Set<string>();
26
- const ownerByCheckout = new Map<string, string>();
27
- const calls = new Map<string, { direct: boolean; key?: string }>();
28
- // One Git lookup per working directory per session; a failed lookup is retried.
29
- const checkouts = new Map<string, Promise<string>>();
30
- const lookup = (ctx: ExtensionContext) => {
31
- const cached = checkouts.get(ctx.cwd);
32
- if (cached) return cached;
33
- const key = checkoutKey(pi, ctx);
34
- checkouts.set(ctx.cwd, key);
35
- key.catch(() => { if (checkouts.get(ctx.cwd) === key) checkouts.delete(ctx.cwd); });
36
- return key;
37
- };
38
- const release = (toolCallId: string) => {
39
- if (heldCalls.has(toolCallId)) return;
40
- const call = calls.get(toolCallId);
41
- calls.delete(toolCallId);
42
- if (call?.key && ownerByCheckout.get(call.key) === toolCallId) ownerByCheckout.delete(call.key);
43
- };
44
- pi.on("tool_call", async (event, ctx) => {
45
- const direct = event.toolName === "delegate_task";
46
- if (direct ? !directCanWrite(event.input) : MAIN_NON_WRITING_TOOLS.has(event.toolName)) return;
47
- const call: { direct: boolean; key?: string } = { direct };
48
- calls.set(event.toolCallId, call);
49
- const key = await lookup(ctx);
50
- if (calls.get(event.toolCallId) !== call) {
51
- return { block: true, reason: `Call ${event.toolCallId} already settled; use mode: isolated to keep Main free.` };
52
- }
53
- const owner = ownerByCheckout.get(key);
54
- const main = direct ? [...calls].find(([, active]) => !active.direct && active.key === key)?.[0] : undefined;
55
- if (owner || main) {
56
- release(event.toolCallId);
57
- return {
58
- block: true,
59
- reason: `Checkout ${key} has ${owner ? `an admitted direct writer (${owner})` : `a Main potentially-writing call in flight (${main})`}; retry after it stops, or use mode: isolated to keep Main free.`,
60
- };
61
- }
62
- call.key = key;
63
- if (direct) ownerByCheckout.set(key, event.toolCallId);
64
- });
65
- pi.on("tool_result", (event) => release(event.toolCallId));
66
- pi.on("tool_execution_end", (event) => release(event.toolCallId));
67
- pi.on("session_start", () => checkouts.clear());
68
- pi.on("session_shutdown", () => {
69
- checkouts.clear();
70
- // Session replacement is not proof that a held direct worker stopped.
71
- for (const toolCallId of calls.keys()) release(toolCallId);
72
- });
73
- // The tool returns a handle before its worker stops. Release only after verified termination.
74
- return (toolCallId) => {
75
- const call = calls.get(toolCallId);
76
- if (!call?.direct || !call.key) {
77
- throw new Error(`Direct call ${toolCallId} was not admitted as a checkout writer; delegate again.`);
78
- }
79
- heldCalls.add(toolCallId);
80
- return () => { heldCalls.delete(toolCallId); release(toolCallId); };
81
- };
82
- }
1
+ export { registerCheckoutAdmission } from "@henryqw/pi-herdr";
@@ -1,5 +1,5 @@
1
- import { getMarkdownTheme, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
- import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
1
+ import { getMarkdownTheme, getSelectListTheme, keyHint, keyText, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Box, Markdown, SelectList, Spacer, Text, truncateToWidth } from "@earendil-works/pi-tui";
3
3
  import type { DiscardPlan } from "../dist/discard.js";
4
4
  import type { PruneItem } from "../dist/prune.js";
5
5
  import { TERMINAL_RUN_STATUSES } from "../dist/schema.js";
@@ -331,28 +331,59 @@ export function workingReport(direct: readonly DirectTask[], inventory: Isolated
331
331
  }
332
332
 
333
333
  type Choice<T> = { label: string; value: T };
334
- async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[]): Promise<T | undefined> {
334
+ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], selectedIndex = 0): Promise<T | undefined> {
335
335
  // Numeric suffixes only tell duplicate labels apart. Never parse display text into an identity.
336
336
  const clipped = items.map((item) => clean(item.label, 145));
337
337
  const labels = clipped.map((label, index) => clipped.indexOf(label) === clipped.lastIndexOf(label) ? label : `${label} [${index + 1}]`);
338
- const selected = await ctx.ui.select(title, labels);
339
- const index = labels.indexOf(selected ?? "");
340
- return index < 0 ? undefined : items[index]!.value;
338
+ if (ctx.mode !== "tui") {
339
+ const selected = await ctx.ui.select(title, labels);
340
+ const index = labels.indexOf(selected ?? "");
341
+ return index < 0 ? undefined : items[index]!.value;
342
+ }
343
+ return ctx.ui.custom<T | undefined>((tui, theme, _keys, done) => {
344
+ const rows = labels.map((label, index) => ({ label, value: String(index) }));
345
+ const createList = () => {
346
+ // Reserve title, key hints, and the native scroll indicator. Very short terminals show only the list.
347
+ const height = tui.terminal.rows;
348
+ const list = new SelectList(rows, Math.max(1, height - (height >= 4 ? 3 : 1)), getSelectListTheme());
349
+ list.setSelectedIndex(selectedIndex);
350
+ list.onSelectionChange = ({ value }) => { selectedIndex = Number(value); };
351
+ list.onSelect = ({ value }) => done(items[Number(value)]!.value);
352
+ list.onCancel = () => done(undefined);
353
+ return list;
354
+ };
355
+ let list = createList();
356
+ return {
357
+ render(width) {
358
+ list = createList();
359
+ const lines = list.render(width);
360
+ if (tui.terminal.rows < 4) return lines.slice(0, tui.terminal.rows);
361
+ return [truncateToWidth(theme.fg("accent", title), width), ...lines,
362
+ truncateToWidth([`${keyText("tui.select.up")}/${keyText("tui.select.down")} scroll`,
363
+ keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
364
+ },
365
+ handleInput(data) { list.handleInput(data); tui.requestRender(); },
366
+ invalidate() { list.invalidate(); },
367
+ };
368
+ }, { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 } });
341
369
  }
342
370
 
343
- /** Multi-select on single-choice `select`: each pick toggles one row until Continue. Returns chosen values in
371
+ /** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
344
372
  * item order, or undefined on Cancel or a changed session. Only selectable rows are offered. */
345
373
  async function chooseMany<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], preselected: readonly T[],
346
374
  valid: () => boolean): Promise<T[] | undefined> {
347
375
  type Pick = { kind: "toggle"; value: T } | { kind: "all" } | { kind: "clear" } | { kind: "continue" } | { kind: "cancel" };
348
376
  const chosen = new Set(preselected);
377
+ let selectedIndex = 0;
349
378
  for (;;) {
350
- const picked = await choose<Pick>(ctx, title, [
379
+ const choices: Choice<Pick>[] = [
351
380
  ...items.map((item) => ({ label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
352
381
  { label: "Select all", value: { kind: "all" } }, { label: "Clear", value: { kind: "clear" } },
353
382
  { label: `Continue (${chosen.size} selected)`, value: { kind: "continue" } }, { label: "Cancel", value: { kind: "cancel" } },
354
- ]);
383
+ ];
384
+ const picked = await choose(ctx, title, choices, selectedIndex);
355
385
  if (!valid() || !picked || picked.kind === "cancel") return undefined;
386
+ selectedIndex = choices.findIndex(({ value }) => value === picked);
356
387
  if (picked.kind === "continue") return items.map(({ value }) => value).filter((value) => chosen.has(value));
357
388
  if (picked.kind === "all") for (const { value } of items) chosen.add(value);
358
389
  else if (picked.kind === "clear") chosen.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.10.3",
3
+ "version": "27.11.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.0.0",
74
- "@henryqw/pi-herdr": "^0.5.0",
74
+ "@henryqw/pi-herdr": "^0.6.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.0.0",