@henryqw/pi-subagent 28.0.1 → 28.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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,7 +150,9 @@ 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 are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. 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. In the terminal, the menu replaces the editor and uses at most half the terminal height. It does not overlay the report or the transcript.
153
+ Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. 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
+
155
+ In the terminal, the menu replaces the editor and uses at most half the terminal height. It does not overlay the report or the transcript. While the menu waits for your selection, Pi reports that it needs user input. Key hints use Pi's configured bindings.
154
156
 
155
157
  Move through rows with the mouse wheel. Click a row to select it. You can also use the keyboard.
156
158
 
@@ -208,6 +210,8 @@ Route selection does not change. An available primary produces no fallback warni
208
210
 
209
211
  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
212
 
213
+ 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.
214
+
211
215
  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
216
 
213
217
  **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")) {
@@ -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. The cost is the sum of `usage.cost.total` from the same records, read in the same session read. Isolated task state records no usage, so isolated rows show no tokens or cost.
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. 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**.
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`. 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`.
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. `oauth.clientRegistration` must be `dcr` or `cimd`. A `cimd` entry cannot use `clientId` or `clientName`. Any `callbackUrl` must use localhost or 127.0.0.1 with path `/callback`.
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
 
@@ -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: StringEnum(["status", "diff", "show", "log", "blame", "rev-parse"]),
12
- mode: Type.Optional(StringEnum(["working", "staged", "committed"], { description: "Diff only; defaults to working (unstaged). Committed requires base and tip." })),
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,4 +1,4 @@
1
- import { getMarkdownTheme, getSelectListTheme, keyHint, keyText, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
1
+ import { getMarkdownTheme, getSelectListTheme, rawKeyHint, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { Box, 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";
@@ -342,7 +342,9 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
342
342
  const index = labels.indexOf(selected ?? "");
343
343
  return index < 0 ? undefined : items[index]!.value;
344
344
  }
345
- return ctx.ui.custom<T | undefined>((tui, theme, _keys, done) => {
345
+ return ctx.ui.custom<T | undefined>((tui, theme, keys, done) => {
346
+ const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action).join("/");
347
+ const keyHint = (action: Parameters<typeof keys.getKeys>[0], description: string) => rawKeyHint(keyText(action), description);
346
348
  const rows = labels.map((label, index) => ({ label, value: String(index) }));
347
349
  // The menu replaces the editor, not the screen; cap its height to leave room for other content.
348
350
  const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
@@ -372,7 +374,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
372
374
  listHeight = Math.min(lines.length, height);
373
375
  if (height < 4) return lines.slice(0, height);
374
376
  return [truncateToWidth(theme.fg("accent", title), width), ...lines,
375
- truncateToWidth([`${keyText("tui.select.up")}/${keyText("tui.select.down")} scroll`,
377
+ truncateToWidth([rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "scroll"),
376
378
  keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
377
379
  },
378
380
  handleInput(data) { list.handleInput(data); tui.requestRender(); },
@@ -388,7 +390,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
388
390
  },
389
391
  invalidate() { list.invalidate(); },
390
392
  };
391
- });
393
+ }, { blocked: { kind: "question", message: title } });
392
394
  }
393
395
 
394
396
  /** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
@@ -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 = StringEnum(PROFILE_NAMES, { description: "Task model profile" });
29
- const DirectKindSchema = StringEnum(["text"] as const);
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 = StringEnum(DIRECT_ACCESS, { description: ACCESS_GUIDANCE });
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.1",
3
+ "version": "28.1.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.3.0",
45
- "@earendil-works/pi-coding-agent": "^1.3.0",
46
- "@earendil-works/pi-tui": "^1.3.0",
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.0.0",
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.2.0",
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.3.0",
82
- "@earendil-works/pi-coding-agent": "1.3.0",
83
- "@earendil-works/pi-tui": "1.3.0",
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
  }