@henryqw/pi-subagent 27.16.1 → 28.0.1

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
@@ -191,7 +191,7 @@ Role Markdown files in `~/.pi/agent/config/pi-subagent/` require frontmatter and
191
191
  | `tools` | Required base or internal tool-name array; `[]` selects none. Name `codemode` or `git_read` to activate it. |
192
192
  | `extensions` | Required array of trusted absolute paths, supported package sources, or Pi built-ins such as `builtin:codemode` |
193
193
  | `skills` | Required array of effective Pi Skill names |
194
- | `mcps` | Optional exact global server names from `~/.pi/agent/mcp.json`, using native `mcpServers` format. Omitted or `[]` denies access to `mcp.json` servers. Servers that Role extensions register always connect. |
194
+ | `mcps` | Optional exact global Model Context Protocol (MCP) server names from `~/.pi/agent/mcp.json`, using native `mcpServers` format. Omitted or `[]` denies access to `mcp.json` servers. Servers that Role extensions register always connect. |
195
195
  | body | Required system instructions |
196
196
 
197
197
  The package ships `implementer`, `reviewer`, and `scout`; same-name user Roles override built-ins. Roles define capabilities, not access or isolation. Unknown frontmatter keys invalidate that file. Other valid Roles load; duplicate names become unavailable. Delegation to an invalid file's claimed Role fails with that file's error. Inspect `/subagent roles`.
@@ -206,7 +206,11 @@ The same profile and fallback route warn once in the active parent session. A se
206
206
 
207
207
  Route selection does not change. An available primary produces no fallback warning. A direct `model` override produces no fallback warning because it replaces the configured model. It still keeps the resolved thinking level.
208
208
 
209
- 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`. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work. Main-only delegation/recovery tools and `ask_question` stay unavailable to children.
209
+ 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
+
211
+ 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
+
213
+ **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.
210
214
 
211
215
  Read [Role and resource policy](./docs/orchestration.md#role-and-resource-policy) for extension exposure, MCP validation, OAuth constraints, and child budgets. Project MCP overrides cannot change a Role's global allowlist or exposure.
212
216
 
@@ -555,7 +555,8 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
555
555
  "--timeout", String(Math.max(1, Math.min(current === "idle" ? 1000 : OPERATION_MS - 1000, remaining)))];
556
556
  const waited = await herdr.exec(args, options(signal));
557
557
  if (waited.code !== 0 || waited.killed) {
558
- if (!waited.killed && hasHerdrErrorCode(waited, "timeout")) {
558
+ // A complete timeout permits another read-only wait, even if exec killed the command.
559
+ if (!signal.aborted && hasHerdrErrorCode(waited, "timeout")) {
559
560
  continue;
560
561
  }
561
562
  throw new Error(herdrCommandFailure(args, waited));
package/dist/index.d.ts CHANGED
@@ -14,11 +14,6 @@ export declare function roleMcpAllowlistFromArgv(args: readonly string[]): strin
14
14
  export declare function parseRoleToolPolicy(value: unknown): string[];
15
15
  /** Read child tool policy before Pi binds registered extension flag values. */
16
16
  export declare function roleToolPolicyFromArgv(args: readonly string[]): string[];
17
- /**
18
- * Whether a tool policy activates `codemode` in the child, so scripts can reach tools with
19
- * `codemode` or `deferred` exposure. Loading `builtin:codemode` alone registers the tool inactive.
20
- */
21
- export declare function roleActivatesCodemode(tools: readonly string[]): boolean;
22
17
  export declare const CHILD_EXCLUDED_TOOL_NAMES: readonly ["delegate_task", "ask_question", "subagent_status", "subagent_resume", "subagent_stage", "subagent_abort", "subagent_workspace"];
23
18
  export declare const DELEGATE_TASK: {
24
19
  readonly id: "pi-subagent/delegateTask";
package/dist/index.js CHANGED
@@ -20,7 +20,6 @@ const GIT_READ_EXTENSION = fileURLToPath(new URL("../extensions/git-read.ts", im
20
20
  export { PI_SUBAGENT_PROCESS_LEASE } from "./process-lease.js";
21
21
  export const ROLE_MCP_POLICY_FLAG = "pi-subagent-role-mcps";
22
22
  export const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
23
- const CODEMODE_TOOL = "codemode";
24
23
  /** The value after a flag that must appear exactly once in a child's argv. */
25
24
  function flagValueFromArgv(args, flag) {
26
25
  const indexes = args.flatMap((arg, index) => arg === flag ? [index] : []);
@@ -52,13 +51,6 @@ export function parseRoleToolPolicy(value) {
52
51
  export function roleToolPolicyFromArgv(args) {
53
52
  return parseRoleToolPolicy(flagValueFromArgv(args, `--${ROLE_TOOL_POLICY_FLAG}`));
54
53
  }
55
- /**
56
- * Whether a tool policy activates `codemode` in the child, so scripts can reach tools with
57
- * `codemode` or `deferred` exposure. Loading `builtin:codemode` alone registers the tool inactive.
58
- */
59
- export function roleActivatesCodemode(tools) {
60
- return tools.includes(CODEMODE_TOOL);
61
- }
62
54
  export const CHILD_EXCLUDED_TOOL_NAMES = [
63
55
  "delegate_task",
64
56
  "ask_question",
@@ -487,7 +479,9 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
487
479
  throw new Error(`Invalid launch environment value: ${key}`);
488
480
  return [key, value];
489
481
  }));
490
- const args = ["--no-session", "--no-extensions", "--no-skills", "--exclude-tools", CHILD_EXCLUDED_TOOL_NAMES.join(",")];
482
+ // Native MCP registry changes can activate tool_search again unless registration is excluded.
483
+ const excludedTools = [...CHILD_EXCLUDED_TOOL_NAMES, ...(!tools.includes("tool_search") ? ["tool_search"] : [])];
484
+ const args = ["--no-session", "--no-extensions", "--no-skills", "--exclude-tools", excludedTools.join(",")];
491
485
  args.push(`--${ROLE_MCP_POLICY_FLAG}`, JSON.stringify(mcps));
492
486
  for (const extension of new Set(extensions))
493
487
  args.push("--extension", extension);
@@ -542,7 +536,7 @@ export function prepareRoleLaunch(pi, ctx, input) {
542
536
  assertNoMissingRoleSkills(input.role, prepared);
543
537
  // Validate the mcp.json the child reads: its environment inherits Main's, with launch overrides on top.
544
538
  if (input.role.mcps?.length) {
545
- loadRoleMcpConfig(prepared.env.PI_CODING_AGENT_DIR ?? getAgentDir(), input.role.mcps, { codemode: roleActivatesCodemode(prepared.tools) });
539
+ loadRoleMcpConfig(prepared.env.PI_CODING_AGENT_DIR ?? getAgentDir(), input.role.mcps);
546
540
  }
547
541
  return { ...prepared, role };
548
542
  }
@@ -553,7 +547,7 @@ export async function resolveConfiguredRoleLaunch(pi, ctx, input) {
553
547
  throw new Error("Configured Role launch requires an explicit modelClass.");
554
548
  const role = findRole(loadRoleCatalog(), roleName);
555
549
  if (role.mcps?.length)
556
- loadRoleMcpConfig(getAgentDir(), role.mcps, { codemode: roleActivatesCodemode(role.tools) });
550
+ loadRoleMcpConfig(getAgentDir(), role.mcps);
557
551
  const resources = await resolveRolePackageResources(role, ctx);
558
552
  const effectiveRole = { ...role, extensions: resources.extensions };
559
553
  const namedSkills = resolveRoleSkills(pi, effectiveRole);
@@ -2,11 +2,8 @@ import type { LoadedMcpConfig } from "@earendil-works/pi-coding-agent";
2
2
  export declare function parseRoleMcpAllowlist(value: unknown): string[];
3
3
  /**
4
4
  * Select the Role's allowlisted servers from the global `mcp.json` in Pi's native `mcpServers`
5
- * shape; the project `.pi/mcp.json` is ignored. A child that activates `codemode` keeps each
6
- * server's configured exposure, so scripts reach `codemode` and `deferred` tools. Any other child
7
- * cannot reach undeclared tools, so every selected server is forced to direct exposure. Codemode is
8
- * never activated by MCP configuration: the Role tool policy owns the active set.
5
+ * shape; the project `.pi/mcp.json` is ignored. Keep validated exposure and per-tool rules,
6
+ * including Pi's default when exposure is absent. MCP configuration never activates codemode:
7
+ * the Role tool policy owns the active set.
9
8
  */
10
- export declare function loadRoleMcpConfig(agentDir: string, allowlist: readonly string[], options?: {
11
- codemode: boolean;
12
- }): LoadedMcpConfig;
9
+ export declare function loadRoleMcpConfig(agentDir: string, allowlist: readonly string[]): LoadedMcpConfig;
package/dist/mcp-role.js CHANGED
@@ -71,7 +71,7 @@ const EXPOSURE_CHECKS = {
71
71
  toolExposure: [(value) => isRecord(value) && Object.values(value).every(isExposure), "an object mapping tool names to exposures"],
72
72
  };
73
73
  /** Validate one selected server against Pi's documented `mcpServers` rules; the native loader is bypassed by `loadConfig`. */
74
- function validateRoleMcpServer(path, name, value, codemode) {
74
+ function validateRoleMcpServer(path, name, value) {
75
75
  const fail = (message) => { throw new Error(`${path}: MCP server "${name}" ${message}`); };
76
76
  if (!SERVER_NAME.test(name))
77
77
  fail("has an invalid name (use letters, digits, \"_\" and \"-\").");
@@ -83,7 +83,7 @@ function validateRoleMcpServer(path, name, value, codemode) {
83
83
  const http = typeof value.url === "string" && value.url.trim() !== "" && (value.type === undefined || value.type === "http" || value.type === "streamable-http");
84
84
  if (stdio === http)
85
85
  fail("needs either a \"command\" (stdio) or a \"url\" (http or streamable-http).");
86
- for (const [field, [valid, shape]] of Object.entries({ ...COMMON_CHECKS, ...(stdio ? STDIO_CHECKS : HTTP_CHECKS), ...(codemode ? EXPOSURE_CHECKS : {}) })) {
86
+ for (const [field, [valid, shape]] of Object.entries({ ...COMMON_CHECKS, ...(stdio ? STDIO_CHECKS : HTTP_CHECKS), ...EXPOSURE_CHECKS })) {
87
87
  const fieldValue = field.split(".").reduce((parent, key) => (isRecord(parent) ? parent[key] : undefined), value);
88
88
  if (fieldValue !== undefined && !valid(fieldValue, value))
89
89
  fail(`field "${field}" must be ${shape}.`);
@@ -101,25 +101,20 @@ function validateRoleMcpServer(path, name, value, codemode) {
101
101
  if (value.auth !== undefined && !isHttpsOrLoopback(parseUrl(value.url))) {
102
102
  fail("field \"auth\" requires \"url\" to use https, or http on localhost, 127.0.0.1, or [::1].");
103
103
  }
104
- if (codemode) {
105
- const { exposure, toolExposure } = value;
106
- return {
107
- ...value,
108
- ...(typeof exposure === "string" ? { exposure: resolveExposure(exposure) } : {}),
109
- ...(isRecord(toolExposure) ? { toolExposure: Object.fromEntries(Object.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposure(entry)])) } : {}),
110
- };
111
- }
112
- const { toolExposure: _toolExposure, ...config } = value;
113
- return { ...config, exposure: "direct" };
104
+ const { exposure, toolExposure } = value;
105
+ return {
106
+ ...value,
107
+ ...(typeof exposure === "string" ? { exposure: resolveExposure(exposure) } : {}),
108
+ ...(isRecord(toolExposure) ? { toolExposure: Object.fromEntries(Object.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposure(entry)])) } : {}),
109
+ };
114
110
  }
115
111
  /**
116
112
  * Select the Role's allowlisted servers from the global `mcp.json` in Pi's native `mcpServers`
117
- * shape; the project `.pi/mcp.json` is ignored. A child that activates `codemode` keeps each
118
- * server's configured exposure, so scripts reach `codemode` and `deferred` tools. Any other child
119
- * cannot reach undeclared tools, so every selected server is forced to direct exposure. Codemode is
120
- * never activated by MCP configuration: the Role tool policy owns the active set.
113
+ * shape; the project `.pi/mcp.json` is ignored. Keep validated exposure and per-tool rules,
114
+ * including Pi's default when exposure is absent. MCP configuration never activates codemode:
115
+ * the Role tool policy owns the active set.
121
116
  */
122
- export function loadRoleMcpConfig(agentDir, allowlist, options = { codemode: false }) {
117
+ export function loadRoleMcpConfig(agentDir, allowlist) {
123
118
  // A Role without mcps must not depend on mcp.json being readable.
124
119
  if (!allowlist.length)
125
120
  return { servers: [], autoEnableCodemode: false, errors: [] };
@@ -146,7 +141,7 @@ export function loadRoleMcpConfig(agentDir, allowlist, options = { codemode: fal
146
141
  if (clash)
147
142
  throw new Error(`${path}: Role MCP server "${name}" conflicts with "${clash}": names that differ only in "-" and "_" share one tool namespace.`);
148
143
  namespaces.set(mcpNamespace(name), name);
149
- return { name, config: validateRoleMcpServer(path, name, configured[name], options.codemode), source: path, scope: "global" };
144
+ return { name, config: validateRoleMcpServer(path, name, configured[name]), source: path, scope: "global" };
150
145
  });
151
146
  return { servers, autoEnableCodemode: false, errors: [] };
152
147
  }
@@ -498,7 +498,7 @@ An empty `tools` list adds no base tools. Selected extension tools can still act
498
498
 
499
499
  Children run with `--no-extensions`. So a Role must list the extension that registers the provider of its route model. Only declared resources and required internal policy adapters load. `builtin:<name>` entries explicitly load Pi built-in extensions (`builtin:codemode`, `builtin:tool-search`, `builtin:llama.cpp`).
500
500
 
501
- The extension rejects `builtin:mcp` and direct loading of `pi-mcp-adapter`, because they bypass the `mcps` allowlist. Scripts can still call extension tools registered with `codemode` or `deferred` exposure. But the model gets their declarations only when `tools` names them.
501
+ The extension rejects `builtin:mcp` and direct loading of `pi-mcp-adapter`, because they bypass the `mcps` allowlist. Scripts can still call extension tools registered with `codemode` or `deferred` exposure. The model gets their declarations only when `tools` names them or `tool_search` loads them.
502
502
 
503
503
  To let a Role run `codemode` scripts, list `builtin:codemode` in `extensions`. Also list `codemode` in `tools`. Both are required, because the built-in registers the tool as inactive and the Role tool policy activates it. If `tools` has `codemode` alone, the launch fails with an unavailable tool.
504
504
 
@@ -506,9 +506,18 @@ Pi's `codemode.mode` and `codemode.inlineBudget` settings apply in the child wit
506
506
 
507
507
  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
508
 
509
- The servers named in `mcps` come only from the global `~/.pi/agent/mcp.json`. In a Role that activates `codemode`, each selected server keeps its configured `exposure` and `toolExposure`. Pi's default `codemode` exposure makes tools callable from scripts without declarations. `direct` declares them. `deferred` tools stay reachable from scripts, and `hidden` tools stay unreachable. An invalid exposure value fails the launch.
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`.
510
510
 
511
- In every other Role, the extension forces selected servers to `direct` exposure. It ignores `toolExposure`, because that child cannot reach undeclared tools. Declared tools show to the model as `mcp__<server>__<tool>` after the server connects. Pi replaces `-` in server and tool names with `_`. Pi appends a hash suffix when two tool names collide or a name is longer than 64 characters.
511
+ | Exposure | Child access |
512
+ | --- | --- |
513
+ | `codemode` | Callable from scripts or discoverable with `tool_search`; not declared at connection |
514
+ | `deferred` | Callable from scripts; `tool_search` can load a declaration |
515
+ | `direct` | Declared when connected and callable from scripts |
516
+ | `hidden` | Unreachable, including from scripts and `tool_search` |
517
+
518
+ `codemode-deferred` is accepted as an alias for `codemode`. `toolExposure` uses exact server tool names or `*` patterns. Exact names win; the first matching pattern wins. Invalid server or per-tool exposures fail before launch, even in a Role without `codemode`.
519
+
520
+ Declared tools show to the model as `mcp__<server>__<tool>` after the server connects. Pi replaces `-` in server and tool names with `_`. Pi appends a hash suffix when two tool names collide or a name is longer than 64 characters.
512
521
 
513
522
  Before launch, the extension checks each selected entry against Pi's documented `mcpServers` rules, in Main and again in the child. The launch fails with the file path and field for each of these conditions:
514
523
 
@@ -524,6 +533,46 @@ The extension still ignores project MCP overrides. A project cannot change the g
524
533
 
525
534
  Isolated Herdr Role launches receive the same turn, token, and child-runtime budget metadata as ephemeral launches. Retained workers therefore keep one non-refilling session budget across follow-ups rather than receiving a new request budget.
526
535
 
536
+ ### Migrate MCP exposure to 28.0.0
537
+
538
+ Earlier releases forced selected global servers to `direct` and removed `toolExposure` when a Role did not activate `codemode`. That behavior could expose hidden tools. Version 28.0.0 removes it. Existing Roles can therefore lose direct tool declarations. Inspect the global server rules before upgrading; do not make all tools direct to restore the old behavior.
539
+
540
+ ```mermaid
541
+ flowchart LR
542
+ G[Global mcp.json] --> S[Select explicit mcps names]
543
+ S --> V[Validate server and per-tool exposure]
544
+ V --> N[Pi native exposure]
545
+ R[Explicit Role tools and extensions] --> N
546
+ ```
547
+
548
+ Keep the required server names in the Role's `mcps`. Choose the smallest access path:
549
+
550
+ | Required access | Role configuration |
551
+ | --- | --- |
552
+ | Discover tools without scripts | Add `builtin:tool-search` to `extensions` and `tool_search` to `tools`. Both `codemode` and `deferred` tools can be found. |
553
+ | Run scripts | Add `builtin:codemode` to `extensions` and `codemode` to `tools`. This does not change server exposure or activate base tools such as `bash`. |
554
+ | Direct calls to permitted tools only | Set only those tools to `direct` in the global `toolExposure`. No discovery extension is required. |
555
+
556
+ Loading `builtin:tool-search` alone does not permit discovery. The final tool policy must select `tool_search`; Role tools and caller additions both count. Otherwise, Pi excludes it from registration, including later registration and MCP registry changes.
557
+
558
+ For example, to declare only `search` from `docs`, use this global configuration. Replace the example command with your server command:
559
+
560
+ ```json
561
+ {
562
+ "mcpServers": {
563
+ "docs": {
564
+ "command": "docs-server",
565
+ "exposure": "hidden",
566
+ "toolExposure": { "search": "direct" }
567
+ }
568
+ }
569
+ }
570
+ ```
571
+
572
+ A Role with `mcps: [docs]` can call `search` directly. Other tools stay hidden. Keep the Role's provider extension; `tools: []` selects no base tools but still permits the declared direct server tool. These global rules also apply to Main. Project overrides cannot restore direct access in children. If neither discovery tool is selected, non-direct tools stay undeclared; Pi can warn that they cannot be called. The adapter does not add capabilities to resolve that warning.
573
+
574
+ Library callers must remove the third `options` argument from `loadRoleMcpConfig(agentDir, allowlist)`. The unused `roleActivatesCodemode` export is removed. `roleToolPolicyFromArgv` remains available for child tool policy.
575
+
527
576
  ### Reviewer Git inspection
528
577
 
529
578
  `git_read` is an internal child tool. The extension loads and registers it only for Roles that declare it. It accepts structured parameters, not shell commands or arbitrary Git options:
@@ -1,5 +1,5 @@
1
1
  import { createMcpExtension, getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { loadRoleMcpConfig, roleActivatesCodemode, roleMcpAllowlistFromArgv, ROLE_MCP_POLICY_FLAG, roleToolPolicyFromArgv } from "@henryqw/pi-subagent";
2
+ import { loadRoleMcpConfig, roleMcpAllowlistFromArgv, ROLE_MCP_POLICY_FLAG } from "@henryqw/pi-subagent";
3
3
 
4
4
  export default function roleMcp(pi: ExtensionAPI): void | Promise<void> {
5
5
  pi.registerFlag(ROLE_MCP_POLICY_FLAG, {
@@ -7,8 +7,6 @@ export default function roleMcp(pi: ExtensionAPI): void | Promise<void> {
7
7
  type: "string",
8
8
  });
9
9
  // Pi binds extension flag values after factories load. Throwing here exits the child non-zero.
10
- const config = loadRoleMcpConfig(getAgentDir(), roleMcpAllowlistFromArgv(process.argv), {
11
- codemode: roleActivatesCodemode(roleToolPolicyFromArgv(process.argv)),
12
- });
10
+ const config = loadRoleMcpConfig(getAgentDir(), roleMcpAllowlistFromArgv(process.argv));
13
11
  return createMcpExtension({ loadConfig: () => config })(pi);
14
12
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.16.1",
3
+ "version": "28.0.1",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",