@henryqw/pi-subagent 28.0.1 → 28.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -4
- package/dist/ephemeral.js +6 -0
- package/dist/mcp-role.js +2 -2
- package/docs/orchestration.md +13 -5
- package/extensions/git-read.ts +2 -3
- package/extensions/subagent-command.ts +117 -42
- package/extensions/workflow.ts +3 -4
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Delegate bounded work to configured Pi Roles through [Herdr](https://herdr.dev/)
|
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
|
-
Isolated work requires Herdr 0.9.3 or later for both the client and server. The server must run on API protocol 22 or later.
|
|
9
|
+
Requires Pi 1.5.0 or later in the 1.x series for native user-input status and schema support. Isolated work requires Herdr 0.9.3 or later for both the client and server. The server must run on API protocol 22 or later.
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
12
|
pi install npm:@henryqw/pi-task-models
|
|
@@ -150,11 +150,27 @@ Staging, validation, and promotion require clean, unchanged Main. After a defini
|
|
|
150
150
|
|
|
151
151
|
### Inspect work
|
|
152
152
|
|
|
153
|
-
Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows
|
|
153
|
+
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
154
|
|
|
155
|
-
|
|
155
|
+
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
156
|
|
|
157
|
-
|
|
157
|
+
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
|
+
|
|
159
|
+
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.
|
|
160
|
+
|
|
161
|
+
| Default key | Action |
|
|
162
|
+
| --- | --- |
|
|
163
|
+
| `Up` / `Down` | Move to another row. |
|
|
164
|
+
| `PageUp` / `PageDown` | Move one page within the list, not the transcript. |
|
|
165
|
+
| `Enter` | Select a row or toggle it in a multiple-selection menu. |
|
|
166
|
+
| `Ctrl+U` | Clear the filter and show all rows. |
|
|
167
|
+
| `Escape` | Cancel the menu without selecting a row. |
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
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.
|
|
172
|
+
|
|
173
|
+
**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.
|
|
158
174
|
|
|
159
175
|
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.
|
|
160
176
|
|
|
@@ -208,6 +224,8 @@ Route selection does not change. An available primary produces no fallback warni
|
|
|
208
224
|
|
|
209
225
|
Children load only declared resources and required adapters. Roles must list their model provider extension. `codemode` requires both `builtin:codemode` in `extensions` and `codemode` in `tools`. For discovery without scripts, add `builtin:tool-search` to `extensions` and `tool_search` to `tools`. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work. Main-only delegation/recovery tools and `ask_question` stay unavailable to children.
|
|
210
226
|
|
|
227
|
+
The global `mcp.json` can start with a byte-order mark, as supported by Pi since 1.4. The `oauth.clientRegistration` field accepts `auto` for automatic selection, `dcr` for dynamic client registration, or `cimd` for a client ID metadata document. OAuth, the authorization protocol, keeps Pi's callback and secure-transport checks.
|
|
228
|
+
|
|
211
229
|
Every selected MCP server keeps its validated `exposure` and `toolExposure`, with or without `codemode`. An absent exposure keeps Pi's native `codemode` default. Hidden tools stay unreachable. MCP configuration never activates `codemode` automatically.
|
|
212
230
|
|
|
213
231
|
**Upgrade to 28.0.0:** Roles without `codemode` no longer force servers to direct exposure or remove per-tool restrictions. Select a discovery tool, or configure only permitted tools as `direct` in the global `toolExposure`. See [Migrate MCP exposure](./docs/orchestration.md#migrate-mcp-exposure-to-2800) for configuration and library changes.
|
package/dist/ephemeral.js
CHANGED
|
@@ -315,6 +315,8 @@ function usageFrom(value) {
|
|
|
315
315
|
const cost = record.cost;
|
|
316
316
|
if (![cost.input, cost.output, cost.cacheRead, cost.cacheWrite, cost.total].every(nonNegativeNumber))
|
|
317
317
|
return;
|
|
318
|
+
if (cost.totalFromProvider !== undefined && typeof cost.totalFromProvider !== "boolean")
|
|
319
|
+
return;
|
|
318
320
|
if (record.cacheWrite1h !== undefined && !nonNegativeNumber(record.cacheWrite1h))
|
|
319
321
|
return;
|
|
320
322
|
if (record.reasoning !== undefined && !nonNegativeNumber(record.reasoning))
|
|
@@ -333,6 +335,7 @@ function usageFrom(value) {
|
|
|
333
335
|
cacheRead: cost.cacheRead,
|
|
334
336
|
cacheWrite: cost.cacheWrite,
|
|
335
337
|
total: cost.total,
|
|
338
|
+
...(cost.totalFromProvider === undefined ? {} : { totalFromProvider: cost.totalFromProvider }),
|
|
336
339
|
},
|
|
337
340
|
};
|
|
338
341
|
}
|
|
@@ -360,6 +363,9 @@ export function addUsage(left, right) {
|
|
|
360
363
|
cacheRead: left.cost.cacheRead + right.cost.cacheRead,
|
|
361
364
|
cacheWrite: left.cost.cacheWrite + right.cost.cacheWrite,
|
|
362
365
|
total: left.cost.total + right.cost.total,
|
|
366
|
+
// A mixed total is not wholly provider-reported; absence also means an estimate.
|
|
367
|
+
...(left.cost.totalFromProvider === undefined && right.cost.totalFromProvider === undefined ? {}
|
|
368
|
+
: { totalFromProvider: left.cost.totalFromProvider === true && right.cost.totalFromProvider === true }),
|
|
363
369
|
},
|
|
364
370
|
};
|
|
365
371
|
}
|
package/dist/mcp-role.js
CHANGED
|
@@ -62,7 +62,7 @@ const HTTP_CHECKS = {
|
|
|
62
62
|
}, "an http URL on localhost, 127.0.0.1, or [::1] without query or fragment, on the \"oauth.callbackPort\" port"],
|
|
63
63
|
"oauth.scope": [isString, "a string"],
|
|
64
64
|
"oauth.clientName": [(value) => typeof value === "string" && value.trim() !== "", "a non-empty string"],
|
|
65
|
-
"oauth.clientRegistration": [(value) => value === "dcr" || value === "cimd", '"dcr" or "cimd"'],
|
|
65
|
+
"oauth.clientRegistration": [(value) => value === "auto" || value === "dcr" || value === "cimd", '"auto", "dcr", or "cimd"'],
|
|
66
66
|
"oauth.authServerMetadataUrl": [(value) => isHttpsOrLoopback(parseUrl(value)), "an https URL, or http on localhost, 127.0.0.1, or [::1]"],
|
|
67
67
|
auth: [(value) => isRecord(value) && typeof value.provider === "string" && value.provider !== "", "an object with a non-empty \"provider\" string"],
|
|
68
68
|
};
|
|
@@ -121,7 +121,7 @@ export function loadRoleMcpConfig(agentDir, allowlist) {
|
|
|
121
121
|
const path = join(agentDir, "mcp.json");
|
|
122
122
|
let parsed = {};
|
|
123
123
|
try {
|
|
124
|
-
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
124
|
+
parsed = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
|
|
125
125
|
}
|
|
126
126
|
catch (error) {
|
|
127
127
|
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
|
package/docs/orchestration.md
CHANGED
|
@@ -184,7 +184,9 @@ The isolated widget shows the recorded task state and any retained workspace. It
|
|
|
184
184
|
|
|
185
185
|
A committed worker without a checked candidate can show attention, not readiness. Status glyphs use the active TUI theme. The text also names the status without color.
|
|
186
186
|
|
|
187
|
-
The direct widget and result summaries show measured tokens for the current task turn. This count adds input and output tokens from completed assistant usage records. It excludes cache-read and cache-write tokens. A continued worker counts only its new task turn. Missing usage stays unknown. This display count does not change token-limit accounting.
|
|
187
|
+
The direct widget and result summaries show measured tokens for the current task turn. This count adds input and output tokens from completed assistant usage records. It excludes cache-read and cache-write tokens. A continued worker counts only its new task turn. Missing usage stays unknown. This display count does not change token-limit accounting.
|
|
188
|
+
|
|
189
|
+
The cost is the sum of `usage.cost.total` from the same records, read in the same session read. Pi uses the provider's billed total when available; otherwise, it uses the catalog estimate. The extension does not replace a billed total with the sum of catalog cost fields. Isolated task state records no usage, so isolated rows show no tokens or cost.
|
|
188
190
|
|
|
189
191
|
A ready isolated candidate is **not promoted** to Main. To reload the menu and the isolated widget from saved state, choose **Refresh** in `/subagent`. Refresh does not recover or change a request. Use `/subagent` or `subagent_status` for exact identities, failures, and recovery.
|
|
190
192
|
|
|
@@ -283,7 +285,9 @@ After readiness, use `subagent_stage revise` with the exact candidate, generatio
|
|
|
283
285
|
|
|
284
286
|
### Inspect and revise active work
|
|
285
287
|
|
|
286
|
-
To select work by label, open `/subagent` without arguments.
|
|
288
|
+
Requires Pi 1.5.0 or later in the 1.x series. To select work by label, open `/subagent` without arguments. The inline selector reports Pi's native blocked status while it waits for user input. Pi clears this status when the selector closes. Key hints use the keybinding manager that Pi supplies.
|
|
289
|
+
|
|
290
|
+
First, a **Current subagent work** report shows the work that local and saved evidence proves is running: locally owned direct workflows with a running worker, and active isolated requests while a live run holds the repository lease. The report lists active requests without a live lease as interrupted, and recorded-only direct work as unverified. A live lease does not identify its request, so several active requests in one checkout all show as working. The menu shows direct records on this session branch and isolated requests in the current canonical Git checkout. This includes requests launched in other sessions. Select an isolated request. Then select **Inspect status and recovery**.
|
|
287
291
|
|
|
288
292
|
The menu also shows requests whose saved parent checkout no longer exists, in their own **Orphaned · parent checkout removed** group. Saved `running` and `pending` states have a `saved` prefix and an `unverified` suffix. The report lists them under **Unverified**, never **Working**, even if the current checkout has a live lease. These labels do not change saved state or prove completion. Orphaned requests with retained resources or `needs_attention` show under **Needs attention**. You can open this view from any checkout of the same repository. The saved worker or integration path identifies the primary repository. Orphaned requests have the same **Close and delete worktrees (discard work)** action, but no inspection or follow-up actions. The extension reads their original state directories; it does not recreate the removed parent checkout. Unreadable files stay preserved and are reported.
|
|
289
293
|
|
|
@@ -506,7 +510,9 @@ Pi's `codemode.mode` and `codemode.inlineBudget` settings apply in the child wit
|
|
|
506
510
|
|
|
507
511
|
Every child loads the Role MCP adapter. It also connects the servers that Role extensions register with `pi.registerMcpServer()`, for example the CodeGraph watcher of `pi-codegraph`. These servers keep the exposure that the extension sets, and `mcps` does not gate them, because the Role already trusts the extension.
|
|
508
512
|
|
|
509
|
-
The servers named in `mcps` come only from the global `~/.pi/agent/mcp.json`.
|
|
513
|
+
The servers named in `mcps` come only from the global `~/.pi/agent/mcp.json`. The file can start with one byte-order mark, as supported by Pi since 1.4. The adapter removes only that leading mark before parsing. Server selection and validation stay unchanged.
|
|
514
|
+
|
|
515
|
+
Every Role keeps each selected server's validated `exposure` and `toolExposure`, with or without `codemode`. An absent `exposure` keeps Pi's native `codemode` default. The adapter never changes these tools to `direct`, removes per-tool restrictions, or activates `codemode` automatically, even if the global file sets `autoEnableCodemode: true`.
|
|
510
516
|
|
|
511
517
|
| Exposure | Child access |
|
|
512
518
|
| --- | --- |
|
|
@@ -527,7 +533,9 @@ Before launch, the extension checks each selected entry against Pi's documented
|
|
|
527
533
|
- `auth.provider` uses plain HTTP outside `localhost`, `127.0.0.1`, or `[::1]`.
|
|
528
534
|
- `oauth.authServerMetadataUrl` does not use HTTPS outside those hosts.
|
|
529
535
|
|
|
530
|
-
The extension never modifies the file. Fix the entry or choose another server. The extension passes valid `auth`, `oauth`, and `description` fields through, so Pi's native provider auth and OAuth apply.
|
|
536
|
+
The extension never modifies the file. Fix the entry or choose another server. The extension passes valid `auth`, `oauth`, and `description` fields through, so Pi's native provider auth and OAuth apply.
|
|
537
|
+
|
|
538
|
+
`oauth.clientRegistration` accepts `auto` for automatic selection, `dcr` for dynamic client registration, or `cimd` for a client ID metadata document. A `cimd` entry cannot use `clientId` or `clientName`. Its `callbackUrl`, when set, must use localhost or 127.0.0.1 with path `/callback`. For all registration modes, a supplied callback must use HTTP on a loopback host without a query or fragment. An explicit callback port must match `callbackPort`, when set. Automatic selection does not bypass these checks or the secure-transport checks above.
|
|
531
539
|
|
|
532
540
|
The extension still ignores project MCP overrides. A project cannot change the global server allowlist or exposure of the Role. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work starts. The extension excludes Main-only delegation and recovery tools and `ask_question` from children.
|
|
533
541
|
|
|
@@ -618,7 +626,7 @@ const result = await executor.run({
|
|
|
618
626
|
|
|
619
627
|
The FIFO permit is acquired before `prepare`, so queued work can resolve fresh Role and route state without consuming timeout. Each child gets independent turn/token and idle/hard-runtime limits. Output, stderr, protocol events, callback draining, and descendant stream draining are bounded.
|
|
620
628
|
|
|
621
|
-
A result contains `outcome`, `exitCode`, bounded `output` and `stderr`, truncation state, optional stop reason/error, and aggregate usage. Abort, timeout, turn/token limit, spawn, protocol, preparation, and callback failures reject with typed `EphemeralSubagentError` codes.
|
|
629
|
+
A result contains `outcome`, `exitCode`, bounded `output` and `stderr`, truncation state, optional stop reason/error, and aggregate usage. The executor preserves `Usage.cost.totalFromProvider`: `true` means that the provider reported the billed total; `false` or absence means a catalog estimate. An aggregate is marked `true` only when every included usage record is marked `true`. Mixed totals are marked `false`; the field stays absent when all records omit it. Cost totals are added without recalculation from the component cost estimates. Abort, timeout, turn/token limit, spawn, protocol, preparation, and callback failures reject with typed `EphemeralSubagentError` codes.
|
|
622
630
|
|
|
623
631
|
Token accounting adds each completed assistant response once. A terminal response that crosses the configured token value succeeds. A continuing crossing turn completes tools and receives one response-only handoff; further continuation fails. Role tools provide a convergence warning near configured turn/token/runtime limits.
|
|
624
632
|
|
package/extensions/git-read.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
2
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
2
|
import { spawnBounded } from "@henryqw/pi-process";
|
|
4
3
|
import { ROLE_TOOL_POLICY_FLAG, roleToolPolicyFromArgv } from "@henryqw/pi-subagent";
|
|
@@ -8,8 +7,8 @@ import { Check } from "typebox/value";
|
|
|
8
7
|
const OUTPUT_BYTES = 32 * 1024;
|
|
9
8
|
const TIMEOUT_MS = 30_000;
|
|
10
9
|
const Parameters = Type.Object({
|
|
11
|
-
operation:
|
|
12
|
-
mode: Type.Optional(
|
|
10
|
+
operation: Type.Enum(["status", "diff", "show", "log", "blame", "rev-parse"], { type: "string" }),
|
|
11
|
+
mode: Type.Optional(Type.Enum(["working", "staged", "committed"], { type: "string", description: "Diff only; defaults to working (unstaged). Committed requires base and tip." })),
|
|
13
12
|
base: Type.Optional(Type.String()),
|
|
14
13
|
tip: Type.Optional(Type.String()),
|
|
15
14
|
revision: Type.Optional(Type.String({ description: "Commit ID or named ref with optional ~N/^N ancestry; defaults to HEAD. No ranges or reflog expressions." })),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getMarkdownTheme, getSelectListTheme,
|
|
2
|
-
import { Box, Markdown, SelectList, Spacer, Text, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
1
|
+
import { getMarkdownTheme, getSelectListTheme, rawKeyHint, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
|
|
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";
|
|
@@ -332,63 +332,123 @@ export function workingReport(direct: readonly DirectTask[], inventory: Isolated
|
|
|
332
332
|
}), ...moreSection(fitted.more)] };
|
|
333
333
|
}
|
|
334
334
|
|
|
335
|
-
type Choice<T> = { label: string; value: T };
|
|
336
|
-
|
|
335
|
+
type Choice<T> = { label: string; value: T; description?: string; detail?: string; search?: string; key?: string };
|
|
336
|
+
type MenuState = { index: number; query: string; key?: string };
|
|
337
|
+
async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], state: MenuState = { index: 0, query: "" }): Promise<T | undefined> {
|
|
337
338
|
// Numeric suffixes only tell duplicate labels apart. Never parse display text into an identity.
|
|
338
339
|
const clipped = items.map((item) => clean(item.label, 145));
|
|
339
|
-
const
|
|
340
|
+
const counts = new Map<string, number>();
|
|
341
|
+
for (const label of clipped) counts.set(label, (counts.get(label) ?? 0) + 1);
|
|
342
|
+
const labels = clipped.map((label, index) => counts.get(label) === 1 ? label : `${label} [${index + 1}]`);
|
|
340
343
|
if (ctx.mode !== "tui") {
|
|
341
344
|
const selected = await ctx.ui.select(title, labels);
|
|
342
345
|
const index = labels.indexOf(selected ?? "");
|
|
343
346
|
return index < 0 ? undefined : items[index]!.value;
|
|
344
347
|
}
|
|
345
|
-
return ctx.ui.custom<T | undefined>((tui, theme,
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
+
return ctx.ui.custom<T | undefined>((tui, theme, keys, done) => {
|
|
349
|
+
const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action)[0] ?? "unbound";
|
|
350
|
+
const keyHint = (action: Parameters<typeof keys.getKeys>[0], description: string) => rawKeyHint(keyText(action), description);
|
|
351
|
+
const rows = items.map((item, index) => ({ label: labels[index]!, value: String(index),
|
|
352
|
+
description: clean(item.description ?? "", 4000), detail: clean(item.detail ?? item.label, 4000).trim(),
|
|
353
|
+
search: clean([item.label, item.description, item.detail, item.search].filter(Boolean).join(" "), 8000) }));
|
|
354
|
+
const input = new Input({ prompt: "Find: ", placeholder: "type to filter", placeholderStyle: (text) => theme.fg("dim", text) });
|
|
355
|
+
input.setValue(state.query);
|
|
356
|
+
const previewText = new Text("", 0, 0);
|
|
357
|
+
const hints = new Text("", 0, 0);
|
|
358
|
+
const filter = () => fuzzyFilter(rows, input.getValue(), (row) => row.search);
|
|
359
|
+
let filtered = filter();
|
|
360
|
+
// The menu replaces the editor, not the screen; leave half the terminal for the transcript.
|
|
348
361
|
const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
|
|
349
362
|
let height = menuHeight();
|
|
363
|
+
let width = 0;
|
|
350
364
|
let listHeight = 0;
|
|
351
365
|
let pressed = false;
|
|
352
366
|
let cancelClick = false;
|
|
367
|
+
const headerHeight = () => height >= 6 ? 2 : height >= 4 ? 1 : 0;
|
|
368
|
+
const hintHeight = () => height >= 12 && width < 60 ? 3 : height >= 8 ? 2 : height >= 4 ? 1 : 0;
|
|
369
|
+
const detailHeight = () => height >= 12 ? 3 : height >= 10 ? 2 : 0;
|
|
370
|
+
const pageSize = () => Math.max(1, height - headerHeight() - hintHeight() - detailHeight() - 1);
|
|
371
|
+
const remember = (value: string) => { state.index = Number(value); state.key = items[state.index]!.key; };
|
|
353
372
|
const createList = () => {
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
list.
|
|
358
|
-
list.
|
|
359
|
-
list.
|
|
373
|
+
const list = new SelectList(filtered, pageSize(), { ...getSelectListTheme(), noMatch: () => theme.fg("warning", " No matches. Clear the filter.") }, { maxPrimaryColumnWidth: 42,
|
|
374
|
+
truncatePrimary: ({ text, maxWidth }) => truncateToWidth(text, maxWidth) });
|
|
375
|
+
const index = filtered.findIndex(({ value }) => state.key ? items[Number(value)]!.key === state.key : Number(value) === state.index);
|
|
376
|
+
list.setSelectedIndex(Math.max(0, index));
|
|
377
|
+
list.onSelectionChange = ({ value }) => remember(value);
|
|
378
|
+
list.onSelect = ({ value }) => { remember(value); done(items[Number(value)]!.value); };
|
|
360
379
|
return list;
|
|
361
380
|
};
|
|
362
381
|
let list = createList();
|
|
382
|
+
const resetPress = () => { if (pressed) cancelClick = true; pressed = false; };
|
|
363
383
|
return {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
384
|
+
// Native list paging must not scroll the fullscreen transcript instead.
|
|
385
|
+
capturesViewportInput: list.capturesViewportInput,
|
|
386
|
+
get focused() { return input.focused; },
|
|
387
|
+
set focused(value: boolean) { input.focused = value; },
|
|
388
|
+
render(nextWidth) {
|
|
389
|
+
if (height !== menuHeight() || width !== nextWidth) {
|
|
390
|
+
resetPress();
|
|
391
|
+
height = menuHeight(); width = nextWidth; list = createList();
|
|
370
392
|
}
|
|
371
|
-
const lines = list.render(width);
|
|
372
|
-
listHeight = Math.min(lines.length, height);
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
393
|
+
const lines = list.render(width).map((line) => truncateToWidth(line, width));
|
|
394
|
+
listHeight = Math.min(lines.length, height - headerHeight() - hintHeight() - detailHeight());
|
|
395
|
+
const selected = list.getSelectedItem();
|
|
396
|
+
const detail = selected ? rows[Number(selected.value)]!.detail : "No matches. Clear or change the filter.";
|
|
397
|
+
previewText.setText(theme.fg("muted", detail));
|
|
398
|
+
const limit = detailHeight();
|
|
399
|
+
const preview = limit ? previewText.render(width).slice(0, limit + 1) : [];
|
|
400
|
+
if (limit && preview.length > limit) preview[limit - 1] = truncateToWidth(`${preview[limit - 1]}…`, width, "…", true);
|
|
401
|
+
hints.setText([keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel"),
|
|
402
|
+
`${filtered.length}/${rows.length}`, rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "move"),
|
|
403
|
+
rawKeyHint(`${keyText("tui.select.pageUp")}/${keyText("tui.select.pageDown")}`, "page"), keyHint("tui.editor.deleteToLineStart", "clear")].join(" · "));
|
|
404
|
+
return [
|
|
405
|
+
...(headerHeight() ? [theme.fg("accent", title)] : []),
|
|
406
|
+
...(headerHeight() === 2 ? input.render(width) : []),
|
|
407
|
+
...lines.slice(0, listHeight),
|
|
408
|
+
...preview.slice(0, limit),
|
|
409
|
+
...hints.render(width).slice(0, hintHeight()),
|
|
410
|
+
].map((line) => truncateToWidth(line, width));
|
|
411
|
+
},
|
|
412
|
+
handleInput(data) {
|
|
413
|
+
resetPress();
|
|
414
|
+
if (keys.matches(data, "tui.select.cancel")) { done(undefined); return; }
|
|
415
|
+
if (keys.matches(data, "tui.select.confirm")) {
|
|
416
|
+
const selected = list.getSelectedItem();
|
|
417
|
+
if (selected) list.onSelect!(selected);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const index = filtered.findIndex(({ value }) => value === list.getSelectedItem()?.value);
|
|
421
|
+
const page = getSelectPageIndex(keys, data, index, filtered.length, pageSize());
|
|
422
|
+
const up = keys.matches(data, "tui.select.up"), down = keys.matches(data, "tui.select.down");
|
|
423
|
+
if (up || down || page !== undefined) {
|
|
424
|
+
if (filtered.length) list.setSelectedIndex(page ?? (index + (up ? -1 : 1) + filtered.length) % filtered.length);
|
|
425
|
+
const selected = list.getSelectedItem();
|
|
426
|
+
if (selected) remember(selected.value);
|
|
427
|
+
} else {
|
|
428
|
+
if (keys.matches(data, "tui.editor.deleteToLineStart")) input.setValue("");
|
|
429
|
+
else input.handleInput(data);
|
|
430
|
+
if (state.query !== input.getValue()) {
|
|
431
|
+
state.query = input.getValue(); filtered = filter(); list = createList();
|
|
432
|
+
const selected = list.getSelectedItem();
|
|
433
|
+
if (selected) remember(selected.value);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
tui.requestRender();
|
|
377
437
|
},
|
|
378
|
-
handleInput(data) { list.handleInput(data); tui.requestRender(); },
|
|
379
438
|
handleMouse(event: TuiMouseEvent) {
|
|
380
439
|
if (event.type === "click" && cancelClick) { cancelClick = false; return { handled: true }; }
|
|
381
440
|
if (event.type === "press") cancelClick = false;
|
|
382
|
-
|
|
441
|
+
if (headerHeight() === 2 && event.y === 1) return input.handleMouse({ ...event, y: 0, height: 1 });
|
|
442
|
+
const y = event.y - headerHeight();
|
|
383
443
|
if (y < 0 || y >= listHeight) return undefined;
|
|
384
444
|
const result = list.handleMouse({ ...event, y, height: listHeight });
|
|
385
445
|
if (event.type === "press") pressed = result?.handled === true;
|
|
386
446
|
if (event.type === "click") pressed = false;
|
|
387
447
|
return result;
|
|
388
448
|
},
|
|
389
|
-
invalidate() { list.invalidate(); },
|
|
449
|
+
invalidate() { input.invalidate(); list.invalidate(); previewText.invalidate(); hints.invalidate(); },
|
|
390
450
|
};
|
|
391
|
-
});
|
|
451
|
+
}, { blocked: { kind: "question", message: title } });
|
|
392
452
|
}
|
|
393
453
|
|
|
394
454
|
/** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
|
|
@@ -397,16 +457,16 @@ async function chooseMany<T>(ctx: ExtensionContext, title: string, items: readon
|
|
|
397
457
|
valid: () => boolean): Promise<T[] | undefined> {
|
|
398
458
|
type Pick = { kind: "toggle"; value: T } | { kind: "all" } | { kind: "clear" } | { kind: "continue" } | { kind: "cancel" };
|
|
399
459
|
const chosen = new Set(preselected);
|
|
400
|
-
|
|
460
|
+
const state: MenuState = { index: 0, query: "" };
|
|
401
461
|
for (;;) {
|
|
402
462
|
const choices: Choice<Pick>[] = [
|
|
403
|
-
...items.map((item) => ({ label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
|
|
463
|
+
...items.map((item) => ({ ...item, label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
|
|
404
464
|
{ label: "Select all", value: { kind: "all" } }, { label: "Clear", value: { kind: "clear" } },
|
|
405
465
|
{ label: `Continue (${chosen.size} selected)`, value: { kind: "continue" } }, { label: "Cancel", value: { kind: "cancel" } },
|
|
406
466
|
];
|
|
407
|
-
const picked = await choose(ctx, title
|
|
467
|
+
const picked = await choose(ctx, `${chosen.size} selected · ${title}`, choices, state);
|
|
408
468
|
if (!valid() || !picked || picked.kind === "cancel") return undefined;
|
|
409
|
-
|
|
469
|
+
state.index = choices.findIndex(({ value }) => value === picked);
|
|
410
470
|
if (picked.kind === "continue") return items.map(({ value }) => value).filter((value) => chosen.has(value));
|
|
411
471
|
if (picked.kind === "all") for (const { value } of items) chosen.add(value);
|
|
412
472
|
else if (picked.kind === "clear") chosen.clear();
|
|
@@ -606,7 +666,8 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
606
666
|
const options = reviewed.shown.filter((item) => item.prunable || item.override);
|
|
607
667
|
if (!options.length) return;
|
|
608
668
|
// Continue confirms prunable items; each is re-verified first. Blocked items need their own confirmation below.
|
|
609
|
-
const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item),
|
|
669
|
+
const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item),
|
|
670
|
+
detail: `${item.branch} · ${item.path ?? "no checkout"} · ${item.reason}`, value: item })),
|
|
610
671
|
options.filter((item) => item.prunable), valid);
|
|
611
672
|
if (!picked?.length) return;
|
|
612
673
|
const forceable = picked.filter((item) => item.override === "force");
|
|
@@ -672,6 +733,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
672
733
|
return;
|
|
673
734
|
}
|
|
674
735
|
let history = false;
|
|
736
|
+
const menu: MenuState = { index: 0, query: "" };
|
|
675
737
|
// The working report shows on open and on each Refresh, not after other menu actions.
|
|
676
738
|
let report = true;
|
|
677
739
|
for (;;) {
|
|
@@ -688,14 +750,27 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
688
750
|
if (unavailable) ctx.ui.notify(`Isolated inventory unavailable (${unavailable}). Direct branch recovery remains available; check the canonical Git checkout/configuration.`, "warning");
|
|
689
751
|
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");
|
|
690
752
|
type Selection = { kind: "direct"; task: DirectTask } | { kind: "isolated"; request: IsolatedRequest; root: string } | { kind: "refresh" } | { kind: "history" } | { kind: "many" } | { kind: "close" };
|
|
691
|
-
//
|
|
753
|
+
// Terminal rows carry their group, so headings cannot be mistaken for actions.
|
|
692
754
|
const group = <T extends { status: string }>(title: string, items: readonly T[], choice: (item: T) => Choice<Selection>): Choice<Selection>[] =>
|
|
693
|
-
items.length ? [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" } },
|
|
755
|
+
items.length ? [...(ctx.mode === "tui" ? [] : [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" as const } }]),
|
|
694
756
|
...[...items].sort((a, b) => priority(a.status) - priority(b.status)).map(choice)] : [];
|
|
695
757
|
const requests = (inventory?.requests ?? []).filter((request) => history || !completed(request.status) || /retained/i.test(request.status));
|
|
696
|
-
const isolatedChoice = (request: IsolatedRequest): Choice<Selection> =>
|
|
697
|
-
|
|
698
|
-
|
|
758
|
+
const isolatedChoice = (request: IsolatedRequest): Choice<Selection> => {
|
|
759
|
+
const group = request.orphaned ? "Orphaned · parent checkout removed" : "Isolated";
|
|
760
|
+
return { label: ` ${glyph(request.status)} ${ctx.mode === "tui" ? `${request.id} · ${request.status}` : isolatedLabel(request)}`,
|
|
761
|
+
description: `${group} · ${summary(request.name)}`, detail: `${group} · ${request.status} · ${request.id} · ${request.name}`,
|
|
762
|
+
key: `isolated:${request.directory ?? inventory!.root}:${request.id}`, value: { kind: "isolated", request, root: inventory!.root } };
|
|
763
|
+
};
|
|
764
|
+
// Put identity and status before the goal. Keep full context in the selected-row preview and search.
|
|
765
|
+
const directChoice = (task: DirectTask): Choice<Selection> => {
|
|
766
|
+
const [first] = task.workers;
|
|
767
|
+
const ref = first ? first.workers === 1 ? directRef(first) : `D${first.workflow} · ${first.workers} workers` : task.id;
|
|
768
|
+
return { label: ctx.mode === "tui" ? ` ${glyph(task.status)} ${ref} · ${task.status}${costSuffix(task.cost)}`
|
|
769
|
+
: ` ${glyph(task.status)} ${directLabel(task)} · ${task.status}${costSuffix(task.cost)}${task.workers.length || task.name === task.id ? "" : ` · ${task.id}`}`,
|
|
770
|
+
description: `Direct · ${directLabel(task)}`, detail: `Direct · ${task.status}${costSuffix(task.cost)} · ${task.id} · ${directLabel(task)}`,
|
|
771
|
+
search: [task.name, ...task.workers.map(workerLabel)].join(" "),
|
|
772
|
+
key: `direct:${task.id}`, value: { kind: "direct", task } };
|
|
773
|
+
};
|
|
699
774
|
const groups = [
|
|
700
775
|
group("Direct", direct.filter((task) => history || !completed(task.status)), directChoice),
|
|
701
776
|
group("Isolated", requests.filter((request) => !request.orphaned), isolatedChoice),
|
|
@@ -710,12 +785,12 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
710
785
|
{ label: "Close", value: { kind: "close" } },
|
|
711
786
|
];
|
|
712
787
|
if (!unavailable && !direct.length && !inventory?.requests.length && !inventory?.invalidIds.length) ctx.ui.notify("No direct tasks recorded on this session branch or isolated requests in this checkout. Ask Main to start delegation.", "info");
|
|
713
|
-
const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections);
|
|
788
|
+
const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections, menu);
|
|
714
789
|
if (!valid() || !selected || selected.kind === "close") return;
|
|
715
790
|
if (selected.kind === "refresh") { report = true; continue; }
|
|
716
791
|
if (selected.kind === "history") { history = !history; continue; }
|
|
717
792
|
if (selected.kind === "many") {
|
|
718
|
-
const picked = await chooseMany(ctx, "Subagent · select work", rows.map((
|
|
793
|
+
const picked = await chooseMany(ctx, "Subagent · select work", rows.map((item) => ({ ...item, label: item.label.trim() })), [], valid);
|
|
719
794
|
if (!picked?.length) { if (!valid()) return; continue; }
|
|
720
795
|
const isolated = picked.flatMap((item) => item.kind === "isolated" ? [item.request] : []);
|
|
721
796
|
const closable = picked.flatMap((item) => item.kind === "direct" && item.task.canClose ? [item.task] : []);
|
package/extensions/workflow.ts
CHANGED
|
@@ -2,7 +2,6 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { createReadStream } from "node:fs";
|
|
3
3
|
import { lstat, readlink } from "node:fs/promises";
|
|
4
4
|
import { posix } from "node:path";
|
|
5
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
6
5
|
import { DISPLAY_TEXT_CONTRACT } from "@henryqw/pi-subagent";
|
|
7
6
|
import { PROFILE_NAMES } from "@henryqw/pi-task-models";
|
|
8
7
|
import { Type, type Static } from "typebox";
|
|
@@ -25,13 +24,13 @@ const TaskNameSchema = Type.String({
|
|
|
25
24
|
const RoleSchema = Type.String({ minLength: 1, pattern: DISPLAY_TEXT_CONTRACT.pattern, description: "Configured Subagent role name" });
|
|
26
25
|
const TaskSchema = Type.String({ minLength: 1, description: "Bounded task packet" });
|
|
27
26
|
const ModelSchema = Type.String({ minLength: 1, pattern: DISPLAY_TEXT_CONTRACT.pattern, description: "Designated model as provider/modelId; replaces the selected route model" });
|
|
28
|
-
const ModelClassSchema =
|
|
29
|
-
const DirectKindSchema =
|
|
27
|
+
const ModelClassSchema = Type.Enum(PROFILE_NAMES, { type: "string", description: "Task model profile" });
|
|
28
|
+
const DirectKindSchema = Type.Enum(["text"], { type: "string" });
|
|
30
29
|
/** Main's honest per-task classification; only `write` reserves the checkout. Nothing enforces `read`. */
|
|
31
30
|
export const DIRECT_ACCESS = ["read", "write"] as const;
|
|
32
31
|
export type DirectAccess = (typeof DIRECT_ACCESS)[number];
|
|
33
32
|
const ACCESS_GUIDANCE = `Declare "write" when the task may change files, Git state, or external resources, otherwise "read". "read" is not enforced (no sandbox): it skips checkout admission and runs concurrently. Use mode isolated for checked writes.`;
|
|
34
|
-
const AccessSchema =
|
|
33
|
+
const AccessSchema = Type.Enum(DIRECT_ACCESS, { type: "string", description: ACCESS_GUIDANCE });
|
|
35
34
|
const DryRunSchema = Type.Boolean({ description: "Optional. When true, run every launch validation and return the resolved plan without starting workers, saving state, or reserving the checkout." });
|
|
36
35
|
const ContinueFromSchema = Type.String({ pattern: "^D[1-9][0-9]*\\.[1-9][0-9]*$", description: "Optional direct worker reference such as D7.1. Continues that finished worker's Pi session in a new tab with this task; role must equal the recorded Role." });
|
|
37
36
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@henryqw/pi-subagent",
|
|
3
|
-
"version": "28.0
|
|
3
|
+
"version": "28.2.0",
|
|
4
4
|
"description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -41,9 +41,9 @@
|
|
|
41
41
|
"pack:check": "npm pack --dry-run"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
|
-
"@earendil-works/pi-ai": "^1.
|
|
45
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
46
|
-
"@earendil-works/pi-tui": "^1.
|
|
44
|
+
"@earendil-works/pi-ai": "^1.5.0",
|
|
45
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
46
|
+
"@earendil-works/pi-tui": "^1.5.0",
|
|
47
47
|
"typebox": "^1.3.15"
|
|
48
48
|
},
|
|
49
49
|
"repository": {
|
|
@@ -70,17 +70,17 @@
|
|
|
70
70
|
"image": "https://raw.githubusercontent.com/HenryQW/pi-harness/main/extensions/pi-subagent/example.png"
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@henryqw/pi-config-store": "^4.
|
|
73
|
+
"@henryqw/pi-config-store": "^4.1.3",
|
|
74
74
|
"@henryqw/pi-herdr": "^0.6.2",
|
|
75
75
|
"@henryqw/pi-multi-codex": "^3.0.0",
|
|
76
76
|
"@henryqw/pi-process": "^0.2.0",
|
|
77
|
-
"@henryqw/pi-task-models": "^9.
|
|
77
|
+
"@henryqw/pi-task-models": "^9.3.0",
|
|
78
78
|
"proper-lockfile": "^4.1.2"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@earendil-works/pi-ai": "1.
|
|
82
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
83
|
-
"@earendil-works/pi-tui": "1.
|
|
81
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
82
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
83
|
+
"@earendil-works/pi-tui": "1.5.0",
|
|
84
84
|
"@types/proper-lockfile": "^4.1.4"
|
|
85
85
|
}
|
|
86
86
|
}
|