diff --git a/docs/architecture.md b/docs/architecture.md index 66d9bcb657..0cb426b33f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -422,6 +422,10 @@ flowchart TB ([ADR 0158](ADRs/0158-overlays-may-grant-runtime-fetch-within-the-config-allowlist.md)). Decided, not yet implemented. - Plugins are runtime-scoped harness resources: a harness declares `plugins:` as one list of directories in its own repository (same trust and fetch path as skills), and each entry's format decides which runtime loads it — a `plugin.json` bundle is Claude Code's, a directory pi's `-e` loader resolves is uploaded and loaded after a tree-hash preflight computed from the host copy. Each runtime names and skips the entries in the other format, so the list survives a runtime switch. Because `--no-extensions` plus explicit `-e` closes the set of code that can register tools, no per-tool declaration is needed ([ADR 0094](ADRs/0094-pi-extensions-are-harness-resources.md)). +- Pi agents select native extension tools by exact registered name from vetted + harness extensions. Missing or ambiguous selections fail before inference; + empty selections exclude all extension tools. Child runs retain the parent's + permission intersection. See [Pi tool selection](runtimes/pi.md#extension-tools-and-tools). - The runner-owned native Codex child policy covers collaboration V1 and V2. Bootstrap requires the `Agent` tool, harness security and a direct-route parent selecting V1 or V2 in the bundled model catalog (absent means V1); diff --git a/docs/cli/run.md b/docs/cli/run.md index 5fb0b03177..74ab73745d 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -97,6 +97,13 @@ See [Harness Field Reference § `input_source`](../reference/harness-reference.m The runtime for a run is resolved once, in this order: `--runtime` flag, `FULLSEND_RUNTIME`, `runtime:` on the agent's `agents:` entry in `config.yaml` / `.fullsend/config.yaml`, the repo-wide `runtime:` there, then the built-in `claude`. The same order applies to the model (`--model`, `FULLSEND_MODEL`, `model:` on the agent's `agents:` entry, harness `model:`, agent frontmatter; `FULLSEND_PI_MODEL` on pi and `FULLSEND_CODEX_MODEL` on codex are lower-precedence aliases, each read only when that runtime is the one selected) and to effort (`--effort`, `FULLSEND_EFFORT`, `effort:` on the agent's `agents:` entry, harness `effort:`). `` is the name given to `fullsend run` (`triage`, `code`, …); see [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort). `FULLSEND_FALLBACK_MODELS=a,b` becomes Claude Code's `--fallback-model`; pi uses it for aliased models on the top-level run when Vertex does not serve the model (two specific 404/403 messages, same provider only; sub-agent children get none); codex ignores it with a warning. +With `--runtime pi`, native extension tools in agent `tools:` frontmatter must +resolve to exact names from vetted harness extensions before inference. Unknown +names are no longer silently dropped. An explicit empty list excludes built-in +and extension tools; the runner may still add `read` for skills. See +[Pi tool selection and migration](../runtimes/pi.md#extension-tools-and-tools). + + A `model` or `effort` set in the `harness:` block of the agent's `agents:` entry is a harness value. It ranks where harness `model:` and `effort:` do in the order above, and `override_source` reports the model as `harness`. Setting diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 4c9054d446..d4d9cc1820 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1111,18 +1111,15 @@ uses that loaded snapshot, not a mutable sidecar file. Changing the manifest resource names after load refuses the next dispatch. Child launch keeps registration permissions separate from activation. The -registration allowlist retains the callable union, while a child-only mode of -`fullsend-agent.js` restores only the inherited active subset at `session_start`, -before any model request. Parse, validation or activation failures terminate the -child nonzero: throwing alone is unsafe because pi logs extension-handler errors -and continues. The guard reads back the active set and refuses any name outside -the requested subset. Unregistered inherited names remain pending rather than -killing the child. It reapplies the subset at `before_agent_start`, -`agent_start` (after MCP startup handlers), and `turn_start`, so late -registrations can become active without activating nested-only tools. Inactive -codemode/deferred tools stay callable through an executor without being declared -directly to the model. The dispatcher script is included in `extensionDigests` -because children now load this guard too. The resource list is embedded in the +registration allowlist retains the callable union. The dispatcher loads +`-e /sandbox/pi-config/fullsend-tools.js --fullsend-selected-tools` with the +resolved callable and active lists. The selector checks the runner-exported +manifest digest and restores the active subset at `session_start`, +`before_agent_start`, `agent_start`, and `turn_start`. An unregistered non-MCP +selection, invalid payload, or activation mismatch exits 99 before inference. +MCP tools may register late. Inactive codemode and deferred tools retain their +nested-call permissions without becoming directly available to the model. +The resource list is embedded in the binary and copied into the digest-covered manifest, not uploaded as a sidecar. The pinned-pi parity test reads the complete upstream resource category, so additions fail the test. @@ -1132,26 +1129,34 @@ additions fail the test. | `enabled` | The tool is registered. `Run` also gates the `-e` and the integrity guard on it | | `piBin` | The `pi` binary the `Bootstrap` probe found (`command -v pi`); `pi` when it found nothing. Children do not start through it: the launch exports the `pi` and `node` it pinned before `.env` as `FULLSEND_PI_CHILD_BIN` and `FULLSEND_PI_CHILD_NODE`, and the extension starts children with those | | `sessionsDir` | Parent's session dir; child `` gets `--session-dir /agent-` | -| `extensions` | The `-e` list every child gets, in order: the vendored provider extensions actually present in the image (`test -d` at `Bootstrap`) then the hook adapter when security is on. `childArgs` separately adds `fullsend-agent.js` in child-only mode when it must restore the inherited active-tool subset | +| `extensions` | The `-e` list every child gets, in order: the vendored provider extensions actually present in the image (`test -d` at `Bootstrap`) then the hook adapter when security is on. `childArgs` adds the strict selector from `toolSelector` separately | | `mcpResourceTools` | Required list of MCP resource names copied from the embedded shared data into the digest-covered manifest. The dispatcher uses the loaded snapshot rather than a mutable sidecar. Missing or malformed data rejects dispatch before launch | | `declaredExtensions` | Host-vetted harness pi plugins: name, sandbox path, tree SHA-256, arguments and environment metadata. Children append these paths and arguments with `-e`, inheriting the parent's extension environment. The dispatcher asynchronously re-hashes every tree before each launch and fallback retry; changed, missing or non-regular content refuses dispatch. No metadata-only cache is used | -| `extensionDigests` | SHA-256 (hex) of each child `-e` entry `Bootstrap` itself wrote under the config dir — always `fullsend-agent.js`, plus the hook adapter and edit-repair extension when used, with the same bytes their launch guards check. Re-hashed before every dispatch; a mismatch refuses the dispatch naming the file. The vendored provider extensions are absent on purpose: root-owned and read-only in the image, outside anything the agent can write. Present for every enabled Agent manifest, including runs with hooks off and no `edit` tool | +| `extensionDigests` | SHA-256 (hex) of runner-written files checked before child dispatch. Includes the dispatcher (`fullsend-agent.js`) and strict selector (`fullsend-tools.js`), plus the hook adapter and edit-repair extension when used, with the same bytes their launch guards check. Re-hashed before every dispatch; a mismatch refuses the dispatch naming the file. The vendored provider extensions are absent on purpose: root-owned and read-only in the image, outside anything the agent can write. Present for every enabled Agent manifest, including runs with hooks off and no `edit` tool | | `gatewayConfigDigest` | SHA-256 (hex) of the `inference-gateway.json` the runner rendered, the same digest `piGatewayConfigGuard` checks at launch. Present only when a gateway run is registered for the sandbox (`SetPiGatewayRun`); absent otherwise, and then nothing below applies. The Agent extension reads that file once, when it loads (just after the launch guard), and refuses every gateway dispatch unless it is a regular file (not a symlink) with this digest. It keeps those bytes and gives each child its own copy in a new `mkdtemp` directory (file mode 0400), named by `INFERENCE_GATEWAY_CONFIG_FILE` and removed when the child exits, so a child never reads the agent-writable file and a file swapped there after load cannot reach it. Parent and children run as one sandbox user, so the copy is not a permission boundary against a concurrent writer with that uid; it removes the shared, predictable path between verification and the child's read. Before every dispatch the extension also still refuses when `inference-gateway.json` no longer has this digest or an `inference-gateway.local.json` entry exists, which signals an agent writing there (#8280) | | `editRepairExtension` | The edit-repair extension's path, when the children's tool set has `edit`. Kept out of `extensions` because it registers the edit tool: the Agent extension adds it only for a child whose `--tools` names `edit`, and empty child selections use `--tools ''` to filter extension tools too | | `models` | `default` (the agent's model, translated) plus the Claude aliases on the Anthropic Vertex provider. The extension resolves a call's `model` through this table and **rejects** anything it cannot serve | | `providerModels` | Per provider a run can serve with no `models` entry, the model ids it can serve: `google-vertex` verbatim from the catalog the pinned pi bundles (`@earendil-works/pi-ai` `dist/providers/data/google-vertex.json`), and `xai-vertex` from the ids the vendored extension registers (`xai/grok-4.6`, the publisher-qualified wire form). `openai` is present only when the run-scoped OpenAI provider is attached, listing the ids that configured children resolve to (`subagents.`, `subagents.default`, a persona's frontmatter `model:`; `runtime.OpenAIChildren`), and its presence is what lets a non-openai parent dispatch to `openai` and turns on the OpenAI launch safeguards for the children (#7981). `gateway` is present only when a gateway run is registered, listing the ids of the rendered `inference-gateway.json`; it admits the `gateway` provider under any parent, since the extension's `-e` directory (`inference-gateway`) does not name the provider id (#8280). A `provider/id` call is accepted only when the full spec is in `models`, is the parent's own spec, or is listed here — a provider prefix alone is not enough, or an invented id would reach the API. A Grok spec is normalized to `xai-vertex/xai/` first, exactly as `normalizeXaiVertexModel` does for the parent, and then goes through this same set | | `thinking` | Children's `--thinking`; `FULLSEND_PI_SUBAGENT_THINKING` (validated) else `medium` | -| `tools` / `toolMode` / `exploreTools` | Parent selection and launch mode (`default` or `explicit`). Each launch and fallback retry queries `pi.getActiveTools()` and `pi.getAllTools()` for active names plus registered `codemode`/`deferred` tools: pi permits nested calls to the latter even when inactive. Inactive direct tools (including `defaultActive: false` direct tools) and other inactive registrations are not added. Default mode retains that callable set; explicit lists restrict names/patterns further. No built-in classification list is needed. Patterns are resolved against concrete callable names, then intersected with the persona's selection or Explore's read-only built-ins, always excluding `Agent`/`Task`. Missing `toolMode` retains explicit-list selection only; it does not guarantee compatibility with older manifests. Missing or malformed `mcpResourceTools` returns a structured `rejected` result before acquiring a child slot. An empty child selection becomes `--tools ''`, filtering both built-in and extension tools. For explicit nonempty parent and child selections without `mcp__` entries, `--exclude-tools` denies `mcp__*` plus each unselected resource tool (`list_mcp_resources`, `list_mcp_resource_templates`, `read_mcp_resource`), preserving selected resource names/patterns. The Go tool mapper translates Claude's `ListMcpResourcesTool` to both list resource tools and `ReadMcpResourceTool` to `read_mcp_resource`. It also accepts the three pi-native resource names and scoped `list_mcp_*`/`read_mcp_*` patterns in parent and persona configuration; those spellings are pi-only. Pi otherwise retains these registrations callable through codemode/deferred exposure even when inactive. Parents without `tools:` keep default behavior. Parents whose translated tools are empty still use `--no-builtin-tools`, but have no `Agent`/`Task`, so Bootstrap writes no child manifest | +| `toolSelector` | Child extension path for the strict selector. The dispatcher loads it with the resolved child permissions before inference | +| `strictTools` | Top-level manifest flag for explicit agent tool selection. The selector requires the runner-held manifest digest and enforces the selection at activation and on tool calls | +| `nativeTools` | Top-level list of exact extension tool names. Each selected name must resolve to one visible registration supplied by a vetted harness extension | +| `tools` / `toolMode` / `exploreTools` | Parent selection and launch mode (`default` or `explicit`). Each launch and fallback retry queries `pi.getActiveTools()` and `pi.getAllTools()` for active names plus registered `codemode`/`deferred` tools: pi permits nested calls to the latter even when inactive. Inactive direct tools (including `defaultActive: false` direct tools) and other inactive registrations are not added. Default mode retains that callable set; explicit lists restrict names/patterns further. No built-in classification list is needed. Patterns are resolved against concrete callable names, then intersected with the persona's selection or Explore's read-only built-ins, always excluding `Agent`/`Task`. Missing `toolMode` retains explicit-list selection only; it does not guarantee compatibility with older manifests. Missing or malformed `mcpResourceTools` returns a structured `rejected` result before acquiring a child slot. An empty child selection becomes `--tools ''`, filtering both built-in and extension tools. For explicit nonempty parent and child selections without `mcp__` entries, `--exclude-tools` denies `mcp__*` plus each unselected resource tool (`list_mcp_resources`, `list_mcp_resource_templates`, `read_mcp_resource`), preserving selected resource names/patterns. The Go tool mapper translates Claude's `ListMcpResourcesTool` to both list resource tools and `ReadMcpResourceTool` to `read_mcp_resource`. It also accepts the three pi-native resource names and scoped `list_mcp_*`/`read_mcp_*` patterns in parent and persona configuration; those spellings are pi-only. Pi can retain inactive registrations for codemode/deferred calls. The strict selector blocks calls outside the selected names and MCP selectors. Parents without `tools:` keep default behavior. Parents whose translated tools are empty use `--tools ''`; both parent and child selections exclude unselected extension tools | | `personas` | Per-persona model/tools table, keyed by persona name. Present when `sub-agents/*.md` files were discovered under skill roots. The extension dispatches a `subagent_type` that names a persona using its resolved model and tool set; an unknown non-empty type is rejected when personas are registered. Model resolution: repo `subagents.` > frontmatter `model:` > `subagents.default` > the parent's live model. An entry carries **no** `model` for that last case, so the extension inherits the parent the same way an anonymous child does — writing the agent definition's model here instead would split the two apart whenever config or a flag overrode the parent. A persona's `tools` are intersected with the parent's at dispatch; a present-but-empty array means no tools, and Bootstrap refuses such a persona rather than letting it fall back to the parent's set. Each spec is canonicalised and checked against the trusted set before it enters the manifest, so a persona never widens the set that admits it (#7031) | | `subagentDefault` | The canonicalised `agents[].subagents.default` spec, carried separately from `personas` because it applies to children that name **no** persona — `retro` dispatches nothing else. It fills an empty `model` argument and outranks the parent's live model; an explicit argument still wins. A registered persona never reads it: its own frontmatter model comes first (#7031) | | `skippedPersonas` | Persona files that did not register, by name, with the reason. A dispatch naming one is rejected with that reason rather than run as an anonymous child (#7031) | | `maxConcurrent`, `timeoutSeconds` | Semaphore and per-child deadline (4, 900 s) | | `usageFile` | Where the extension appends one line per child; `Run` folds it into `RunMetrics` and `ExtractTranscripts` downloads it. A persona dispatch's line carries `persona`; aggregation stays keyed by model (#7031) | -- Children conditionally load `fullsend-agent.js` in child-only mode to restore - active tools. That branch returns before registering Agent. Children also run - with `FULLSEND_SUBAGENT_DEPTH=1`; the normal branch refuses to register Agent - when that variable is set, providing a recursion backstop. +- Children run the strict selector without registering Agent. + `FULLSEND_SUBAGENT_DEPTH=1` prevents Agent registration if the dispatcher + extension is loaded. A child selector requires the Bootstrap digest even + when the parent runs in default tool mode. +- The selector uses exit 99 for integrity and selection failures. The shell + guard reports `fullsend: pi tool selector missing or modified; refusing to run`. + Selector startup logs the specific `[fullsend-tools]` error, and Run reports + `pi strict tool selection failed or selector changed; refusing inference` for + a strict parent launch. - The extension's code is SHA-256-checked against the embedded copy in the same pre-`.env` guard block as the hook adapter, under its own exit 94 so `Run` can name the artifact that actually failed, and **the manifest it reads is checked the same way** @@ -1169,9 +1174,8 @@ additions fail the test. The launch guard checks it once; a parent with `write` can replace it mid-iteration, and a rewritten adapter simply drops its own `FULLSEND_PI_MANIFEST_SHA256` check, so verifying only the manifest would leave the adapter unprotected and every later child unhooked. `Bootstrap` - therefore records digests for every child extension file it writes under the - config dir: always `fullsend-agent.js`, plus the hook adapter and edit-repair - extension when used. This includes files outside `agent.extensions`. The + therefore records digests for the dispatcher and strict selector, along with + the hook adapter and edit-repair extension when used. This includes files outside `agent.extensions`. The dispatcher re-hashes them alongside the manifest before every dispatch, inside the slot the dispatch holds, and refuses changed files. The map is part of the manifest, so the manifest digest covers it. The vendored provider @@ -1182,13 +1186,11 @@ additions fail the test. reopens the verified paths. A same-user background writer can race that load, as with the [hook and extension launch guards](#pi-extensions-adr-0094). Closing this TOCTOU requires a stronger filesystem isolation boundary, not just another hash or an owner-writable copy. -- **`Bootstrap` and `Run` must run in one process** for any of the manifest guards to exist. The - digest lives in a package-level map keyed by sandbox name (`piManifestHashes`), recorded by - `Bootstrap` and read by `Run`; the CLI's `run` path does both in one process. A caller that - bootstrapped elsewhere gets no entry, and then neither the shell guard nor the - `FULLSEND_PI_MANIFEST_SHA256` export is emitted — silently, because failing closed there would - break every such caller. The per-dispatch checks above are unaffected: they compare against - bytes the extension read itself. +- **`Bootstrap` and `Run` share a process for manifest verification.** Bootstrap + records the digest in `piManifestHashes` by sandbox name. Run requires that + entry when the parent declares tools or the Agent manifest configures a child + selector. Other runs may bootstrap in a separate process, in which case Run + omits the manifest guard and `FULLSEND_PI_MANIFEST_SHA256` export. - The hook adapter's `*` PreToolUse groups therefore see `Agent` calls, and the manifest's `hooks.toolNames` carries `Agent`/`Task` verbatim (they are already Claude vocabulary). Claude Code runs the same hooks on its own `Agent` tool. @@ -1725,3 +1727,24 @@ Two artefacts of the run are worth knowing about: | The `enabled`, `disable_direct_message`, `max_wait_timeout_ms`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message`, `max_wait_timeout_ms` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.166.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | | The wait cap (`codexWaitTimeoutMaxMS`, 120000, #9657): the `max_wait_timeout_ms` key of `[features.multi_agent_v2]` (the table is `deny_unknown_fields`, so a renamed key fails config parsing), the V2 wait's check of `timeout_ms` against that max and the schema max it feeds, and V1's wait limits, which are constants with a max of 3600000 | on V2 the cap is Codex's own: the wait schema the parent reads carries the configured max and the wait returns an error to the model for a longer `timeout_ms`, so the parent waits again; the spawn guard passes a wait through unread (ADR 0126, ADR 0159). A renamed key fails the config of every run that renders the table with `disable_direct_message`; a V2 wait that stopped checking the max leaves only the dispatch note. V1 has no setting, its schema asks for longer waits, and the dispatch note's rule is the only cap there, so a changed V1 limit or wait default changes nothing the runner enforces | `codex-rs/core/src/config/mod.rs` (`max_wait_timeout_ms`, validated in `resolve_multi_agent_v2_config`), `codex-rs/core/src/tools/spec_plan.rs` (the V2 wait schema's max), `codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs` (the `timeout_ms` max check), `codex-rs/core/src/tools/handlers/multi_agents_common.rs` (V1's wait constants) | | The V2 child-result path: `SubagentStop` runs in a thread-spawned child with `last_assistant_message`, the text that becomes its result, before the turn completes and `notify_parent_of_terminal_turn` queues the result to the parent; exit 2 with a non-empty stderr makes the child continue with that stderr as its prompt (an empty one is ignored and the message delivered), `continue: false` ends the child and delivers the message, and the result reaches the parent's next model request as an `agent_message` item, which codex sends only from a thread on V2: the feature table must keep putting every thread of the run on V2, whatever the child's model | the child-result gate (ADR 0159 decision 4) rests on it: re-check on every bump that `SubagentStop` still runs before the result is delivered, that a block still continues the child, and that the hook runs after a block still carry `stop_hook_active: true` for the rest of the turn; if either of the first two changes, a flagged result reaches the parent unchecked, and if the third does, a blocked child can retry through the chain | `codex-rs/core/src/session/turn.rs` (the stop-hook block), `codex-rs/core/src/hook_runtime.rs` (`run_turn_stop_hooks`), `codex-rs/hooks/src/events/stop.rs`, `codex-rs/core/src/agent/control/completion.rs`, `codex-rs/core/src/session/mod.rs` (`record_inter_agent_communication`); run `go test ./internal/runtime/ -run 'TestCodexAdapter_SubagentStopGate'` | + + +### Exact native Pi tool selections + +`piToolsFor` preserves exact native tool names alongside built-in translation +and existing MCP selectors. Bootstrap installs `fullsend-tools.js`, records +native selections in the pinned manifest and includes the selector digest in +child integrity checks. Run checks the selector before and after environment +loading and before each retry. The selector loads after vetted extensions, +verifies native names and their source paths, restores the explicit active set +at session, agent and turn boundaries, and blocks calls outside the selection. +MCP patterns retain asynchronous registration and callable/active separation. +Children receive concrete callable and active intersections through the +runner-owned selector flag, alongside the same verified extension code. + +Run the offline pinned-Pi acceptance tests with `FULLSEND_TEST_PI_BIN` pointing +to Pi at `PI_VERSION` from `images/sandbox/Containerfile`: + +```bash +node --test internal/runtime/pi_extension/fullsend-tools.test.mjs +``` diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index c1d717615e..228181ac1b 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -545,6 +545,14 @@ The agent definition is Markdown with YAML frontmatter: | `skills` | [Skill](../../glossary.md#skill) names to load, as uploaded under `skills/`: a skill's declared `SKILL.md` `name:`, or its directory basename when none is declared | | `disallowedTools` | Bash patterns the agent is forbidden from running, e.g. `Bash(git push *), Bash(gh issue edit *)` | +On pi, select a vetted harness extension's native tool with its exact registered +name, for example `tools: [inspect_record]`. Missing or ambiguous tools fail +before inference. An explicit `tools: []` exposes no tools unless the runner +adds `read` for skills. When migrating, remove previously ignored Claude-only +names or provide the extension that implements them. See +[Pi extension tool selection](../../runtimes/pi.md#extension-tools-and-tools). + + When writing the agent body: - **The agent writes JSON, scripts do actions.** The agent's only output is a structured JSON file matching the [output schema](#output-schema). All side diff --git a/docs/runtimes/pi.md b/docs/runtimes/pi.md index 20ccaeaf79..c1da86d564 100644 --- a/docs/runtimes/pi.md +++ b/docs/runtimes/pi.md @@ -307,7 +307,7 @@ What a local pi run needs, beyond the guide: | `MultiEdit` | `edit` | pi has one edit tool | | `Glob` | `find` | `find` takes a **glob pattern**, not a bare directory. A model that means "list this directory" and sends `{"path": "docs/"}` gets a validation error and has to retry | | `LS` | `ls` | The tool to grant for directory listing. Claude Code itself dropped `LS`, so the entry does nothing on that runtime, and codex lists through the shell — it is pi where it counts | -| anything else | — | A persona naming a Claude-only tool (`WebFetch`, `TodoWrite`, ...) fails rather than silently losing it; see [Sub-agents troubleshooting](#troubleshooting-sub-agents) | +| Exact native extension name | unchanged | Must resolve to one tool supplied by a vetted harness extension before inference; for example `inspect_record` | So an agent that browses the tree wants `Glob` **and** `LS`: `Glob` to match a pattern, `LS` to see what is in a directory. With `Glob` alone the model tends to reach for a listing it cannot make. @@ -383,10 +383,39 @@ runtime, an interpreter, a proxy or a credential are refused; the deny-list is i ### Extension tools and `tools:` -An agent that declares `tools:` keeps its strict `--tools` allowlist and pi hides extension tools -under it — that is what a declared `tools:` means. An agent whose `tools:` maps to nothing pi -provides gets `--no-builtin-tools`, and its extensions still load: `-e` is independent of `--tools`. -An agent without `tools:` gets pi's default set plus whatever its extensions register. +An agent that declares `tools:` gets an explicit selection across built-in and +extension tools. Select a native tool by its exact registered name, for example +`tools: [inspect_record]`. Native names begin with an ASCII letter or underscore +and contain only ASCII letters, digits, underscores and hyphens; wildcards are +reserved for supported MCP selectors. The tool must come from the declared, +vetted harness extensions. Missing, hidden, ambiguous or non-vetted native +selections fail before inference. Selecting one tool exposes neither its +siblings nor built-in shell or editing tools. + +An explicit `tools: []` exposes no built-in or extension tools. An agent without +`tools:` retains pi's default tools plus its extensions. Skills still require +`read`, which the runner adds when the harness includes skills or the agent +selects `Skill`. + +Exact extension names in agent `tools:` are Pi-specific. Use a separate agent +definition for runtimes that do not load the extension. Adding `Bash` to a +shared declaration also grants the Pi agent access to its shell tool. Persona +`tools:` supports mapped tools and MCP selectors. Exact extension names in +persona declarations prevent registration. Setup fails if the repo config +references that persona. + +An explicit agent tool list or a child tool selector requires `Bootstrap` and +`Run` in the same process so the selector can verify the manifest digest. This +includes default-mode parents with sub-agent dispatch enabled. See the [tool selection requirements](https://github.com/fullsend-ai/fullsend/issues/9254). + +**Migration:** previously ignored unknown names now request exact native tools. +Pi treats an unmapped exact name such as `WebFetch` as an extension request +and checks the registry for a matching tool from a vetted extension. +Remove stale Claude-only names such as `WebFetch` unless a vetted extension +registers them. Correct typos and declare the extension that supplies each +requested tool. Invalid native patterns now fail setup instead of being dropped. +Tool selection does not grant shell, network or publication authority; sandbox +policy and hooks continue to apply, using each native tool's unchanged name. MCP tool names such as `mcp__docs__search` and patterns such as `mcp__docs__*` pass through the pi tool mapping. A bare server selector @@ -394,7 +423,7 @@ MCP tool names such as `mcp__docs__search` and patterns such as tool names and existing patterns are unchanged. Selectors must start with `mcp__` and contain only ASCII letters, digits, underscores, hyphens and `*`, with a nonempty suffix. Invalid selectors (including commas and whitespace) -are reported as unsupported rather than passed to pi's comma-delimited CLI. +fail setup rather than being passed to pi's comma-delimited CLI. Names must match what the declared harness extension registers. Fullsend does not normalize server or tool names: Claude-style hyphenated names are preserved. Pi's built-in MCP naming rules do not apply automatically, because fullsend @@ -418,28 +447,28 @@ is `codemode` or `deferred`. Pi permits nested calls to those tools even when inactive. Inactive direct tools (including `defaultActive: false` direct tools) and other inactive registrations are not added. Explicit parent selections and persona patterns still restrict this union; registration alone is not a grant. -The child registration allowlist retains the callable union, but a child-only -loadout guard restores the inherited active subset before the first model -request and again at agent/turn boundaries after MCP startup handlers. Inherited -names not yet registered may remain pending; any active name outside the -inherited subset terminates the child, as do parse, validation or setter -failures. A thrown extension error alone would let pi continue. Inactive -codemode/deferred tools remain nested-call permissions rather than becoming -directly available to the model. The guard script is digest-checked before -dispatch. An empty child allowlist hides both built-in and extension tools. Explicit +The child registration allowlist retains the callable union. The dispatcher +loads `-e /sandbox/pi-config/fullsend-tools.js --fullsend-selected-tools` with +the resolved callable and active tool lists. The selector verifies the manifest +digest, restores the active subset at session start, and reapplies it at agent +and turn boundaries. An unregistered non-MCP selection or invalid activation +exits 99 before inference. MCP tools may register late. Inactive codemode and +deferred tools keep their nested-call permissions without becoming directly +available to the model. The dispatcher checks the selector digest before launch. An empty child allowlist hides both built-in and extension tools. Explicit nonempty parent and child selections without `mcp__` entries also get `--exclude-tools`: `mcp__*` plus each unselected MCP resource tool (`list_mcp_resources`, `list_mcp_resource_templates`, `read_mcp_resource`). Selected resource names/patterns remain available. Pi otherwise retains these registrations, which can leave tools callable through codemode or deferred exposure even when inactive. Parents without `tools:` keep their defaults. -Parents whose tools map to an empty list still use `--no-builtin-tools`, but -cannot dispatch children: they have no `Agent` or `Task` tool. +Parents whose tools map to an empty list use `--tools ''`, which filters out +both built-in and extension tools, including `Agent` and `Task`. Direct-exposure MCP tools can reach the model through these tool lists. `codemode` and `deferred` tools need a separately reachable executor for nested calls. Fullsend uses `--no-extensions`, so pi's built-in MCP, codemode, and -search extensions do not load automatically. The tool mapper does not accept -`codemode` or `tool_search` in explicit frontmatter. The nested-call fixtures +search extensions do not load automatically. Explicit frontmatter uses Claude spellings such as +`Read` and `Bash` for mapped built-ins. The reserved Pi names `powershell`, +`codemode`, and `tool_search` are rejected during Bootstrap. The nested-call fixtures exercise pi's execution API; they are not examples of supported frontmatter. Parent and child resource exclusions originate from `mcp-resource-tools.json`. @@ -926,6 +955,13 @@ pi; the plan block's `Runtime:` line and stderr's `runtime: selected ...` show w **`--debug "..."` fails with `accepts 1 arg(s)`.** `--debug` takes an optional value: write `--debug='*'` (with `=`). +**`pi strict tool selection failed or selector changed` (exit 99).** Read the +`[fullsend-tools]` error in the Pi output for the invalid selection or manifest +failure. The shell guard emits `fullsend: pi tool selector missing or modified; refusing to run` +if the selector file fails its digest check. Check that selected non-MCP tools +are registered by the runtime or a vetted extension, and rerun Bootstrap if +the selector file is missing or changed. + **`fullsend: pi edit-repair extension missing or modified; refusing to run` (exit 93).** The runner-owned `/sandbox/pi-config/fullsend-edit-repair.js` is not the copy bootstrap wrote. Treat it as tampering, like the hook adapter's guard: something inside the sandbox rewrote runner config. diff --git a/internal/pluginformat/pi.go b/internal/pluginformat/pi.go index 35cef9ebe3..b620afa9d1 100644 --- a/internal/pluginformat/pi.go +++ b/internal/pluginformat/pi.go @@ -40,6 +40,7 @@ var PiReservedExtensionNames = []string{"fullsend-hooks", "fullsend-agent", "ful // such option (fullsend's own CLI does), so an extension may register it. var piReservedOptions = map[string]bool{ "--fullsend-child-active-tools": true, + "--fullsend-selected-tools": true, "--extension": true, "--no-extensions": true, "--approve": true, "--no-approve": true, "--tools": true, "--no-tools": true, "--no-builtin-tools": true, "--exclude-tools": true, "--model": true, "--models": true, "--provider": true, "--thinking": true, "--api-key": true, diff --git a/internal/pluginformat/pi_test.go b/internal/pluginformat/pi_test.go index e0d1daef24..be9e593130 100644 --- a/internal/pluginformat/pi_test.go +++ b/internal/pluginformat/pi_test.go @@ -418,6 +418,8 @@ func TestPiArgsProblem(t *testing.T) { {"value starts with at", []string{"--a=@/etc/passwd"}, `args[0] "--a=@/etc/passwd": the value after "=" must not start with '-' or '@'`}, {"child loadout separate", []string{"--fullsend-child-active-tools", "[]"}, `args[0] "--fullsend-child-active-tools" is one of pi's own options`}, {"child loadout equals", []string{"--fullsend-child-active-tools=[]"}, `args[0] "--fullsend-child-active-tools" is one of pi's own options`}, + {"child selector separate", []string{"--fullsend-selected-tools", "{}"}, `args[0] "--fullsend-selected-tools" is one of pi's own options`}, + {"child selector equals", []string{"--fullsend-selected-tools={}"}, `args[0] "--fullsend-selected-tools" is one of pi's own options`}, {"pi use-theme", []string{"--use-theme", "dark"}, `args[0] "--use-theme" is one of pi's own options`}, {"pi tui-mode", []string{"--tui-mode=fullscreen"}, `args[0] "--tui-mode" is one of pi's own options`}, } diff --git a/internal/runtime/openai_seeder_test.go b/internal/runtime/openai_seeder_test.go index 36a6e190e5..a0b1423e60 100644 --- a/internal/runtime/openai_seeder_test.go +++ b/internal/runtime/openai_seeder_test.go @@ -128,7 +128,8 @@ func TestOpenAIChildren(t *testing.T) { // their model must not create a provider. unregistrable := t.TempDir() writePersonaFile(t, unregistrable, "bashy", "---\nname: bashy\nmodel: openai/gpt-5.6-luna\ntools: Bash(git)\n---\nRun git.\n") - writePersonaFile(t, unregistrable, "webby", "---\nname: webby\nmodel: openai/gpt-5.6-luna\ntools: WebSearch\n---\nSearch.\n") + writePersonaFile(t, unregistrable, "webby", "---\nname: webby\nmodel: openai/gpt-5.6-luna\ntools: WebSearch*\n---\nSearch.\n") + writePersonaFile(t, unregistrable, "native", "---\nname: native\nmodel: openai/gpt-5.6-luna\ntools: WebSearch\n---\nSearch.\n") writePersonaFile(t, unregistrable, "empty", "---\nname: empty\nmodel: openai/gpt-5.6-luna\ntools: []\n---\nNothing.\n") writePersonaFile(t, unregistrable, "multiline", "---\nname: multiline\nmodel: |\n openai/gpt-5\n ::warning::injected\n---\nInject.\n") writePersonaFile(t, unregistrable, "dispatcher", "---\nname: dispatcher\nmodel: openai/gpt-5.6-luna\ntools: Agent, Task\n---\nDispatch.\n") diff --git a/internal/runtime/pi_agent.go b/internal/runtime/pi_agent.go index 0ab6e1c9df..c1d4fb37ca 100644 --- a/internal/runtime/pi_agent.go +++ b/internal/runtime/pi_agent.go @@ -185,9 +185,9 @@ func parseClaudeToolSpecs(specs []string) (tools, bashAllowlist []string) { // read, bash, edit, write, grep, find, ls — every non-Windows built-in; pi // also has powershell — all activated via settings.json defaultTools, since // pi alone starts with only the first four). Claude tools without a pi -// counterpart are reported as unsupported; Skill maps to no tool (pi's -// skills are prompt-driven), and Bootstrap adds read for it, since pi only -// emits the skills section of the system prompt when read is active. +// counterpart resolve as exact vetted extension tool names. Skill maps to +// no tool (pi's skills are prompt-driven), and Bootstrap adds read for it: +// pi emits the skills section of the system prompt only when read is active. var piToolForClaude = map[string]string{ "Bash": "bash", "Read": "read", @@ -311,8 +311,11 @@ func piToolsFor(claudeTools []string) (tools, unsupported []string) { } pt, ok := piToolForClaude[ct] if !ok { - unsupported = append(unsupported, ct) - continue + if !piNativeToolName(ct) { + unsupported = append(unsupported, ct) + continue + } + pt = ct } if !seen[pt] { seen[pt] = true @@ -321,3 +324,35 @@ func piToolsFor(claudeTools []string) (tools, unsupported []string) { } return tools, unsupported } + +// Exact native names cannot contain wildcards or CLI list separators. +var piExactNativeTool = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_-]*$`) + +func piNativeToolsFor(specs []string) []string { + var out []string + for _, name := range specs { + if _, builtin := piToolForClaude[name]; builtin || name == "Skill" || name == piAgentToolName || name == piAgentToolAlias || name == "ListMcpResourcesTool" || name == "ReadMcpResourceTool" || piMCPSelectorPattern.MatchString(name) || piMCPResourcePattern(name) { + continue + } + if piNativeToolName(name) && !hasTool(out, name) { + out = append(out, name) + } + } + return out +} + +func piReservedUnmappedToolName(name string) bool { + switch name { + case "powershell", "codemode", "tool_search": + return true + default: + return false + } +} + +func piNativeToolName(name string) bool { + if _, builtin := claudeToolForPi[name]; builtin || piReservedUnmappedToolName(name) { + return false + } + return piExactNativeTool.MatchString(name) && !strings.HasPrefix(name, "mcp__") && !strings.HasPrefix(name, "list_mcp_") && !strings.HasPrefix(name, "read_mcp_") +} diff --git a/internal/runtime/pi_agent_test.go b/internal/runtime/pi_agent_test.go index 6861e0ddc0..7023ce83f9 100644 --- a/internal/runtime/pi_agent_test.go +++ b/internal/runtime/pi_agent_test.go @@ -150,8 +150,8 @@ func TestPiToolsFor(t *testing.T) { assert.Nil(t, unsupported) tools, unsupported = piToolsFor([]string{"Read", "Edit", "MultiEdit", "Glob", "WebFetch", "Task", "LS"}) - assert.Equal(t, []string{"read", "edit", "find", "Agent", "Task", "ls"}, tools, "Task is the legacy alias of Agent; both pi tool names are activated, in place") - assert.Equal(t, []string{"WebFetch"}, unsupported) + assert.Equal(t, []string{"read", "edit", "find", "WebFetch", "Agent", "Task", "ls"}, tools, "Task is the legacy alias of Agent; both pi tool names are activated, in place") + assert.Empty(t, unsupported) tools, unsupported = piToolsFor([]string{"Agent", "Task", "Bash"}) assert.Equal(t, []string{"Agent", "Task", "bash"}, tools, "Agent and Task activate the same pair once") diff --git a/internal/runtime/pi_bootstrap.go b/internal/runtime/pi_bootstrap.go index 3e6f7db9d5..1a13100b81 100644 --- a/internal/runtime/pi_bootstrap.go +++ b/internal/runtime/pi_bootstrap.go @@ -76,15 +76,16 @@ type piAgentManifest struct { SessionsDir string `json:"sessionsDir"` // Extensions are the -e paths every child gets, in order: the provider // extensions present in the image, then the hook adapter when security - // is enabled. childArgs separately adds this extension in child-only mode - // when it must restore the inherited active-tool subset. + // is enabled. childArgs adds the strict selector separately. Extensions []string `json:"extensions"` // DeclaredExtensions are the vetted harness plugins inherited by children. // The dispatcher rechecks their tree hashes before every child launch. DeclaredExtensions []piManifestExtension `json:"declaredExtensions,omitempty"` + ToolSelector string `json:"toolSelector,omitempty"` MCPResourceTools []string `json:"mcpResourceTools"` // ExtensionDigests holds sha256 (hex) digests for runner-written child - // extensions: always fullsend-agent.js, plus hook/repair adapters when used. + // extensions and the dispatcher: always fullsend-tools.js and + // fullsend-agent.js, plus hook/repair adapters when used. // The dispatcher re-hashes them before every dispatch; see // piAgentExtensionDigests for why the vendored ones are absent. ExtensionDigests map[string]string `json:"extensionDigests,omitempty"` @@ -154,7 +155,9 @@ type piManifest struct { Model string `json:"model,omitempty"` // Tools are pi tool names for --tools; nil means the settings.json // defaultTools set (piDefaultTools). - Tools []string `json:"tools"` + Tools []string `json:"tools"` + StrictTools bool `json:"strictTools"` + NativeTools []string `json:"nativeTools,omitempty"` // BashAllowlist is the Bash(a,b) first-token allowlist from the agent // definition. Under Claude Code it is steering, not a security control // (ADR 0027: the sandbox is the boundary and tool-level restrictions are @@ -291,8 +294,20 @@ func (r PiRuntime) Bootstrap(input BootstrapInput) error { } tools, unsupported := piToolsFor(def.Tools) - for _, u := range unsupported { - fmt.Fprintf(os.Stderr, "Agent tool %q has no pi equivalent and is dropped from the allowlist\n", u) + if len(unsupported) != 0 { + for _, name := range unsupported { + if claude, builtin := claudeToolForPi[name]; builtin { + return fmt.Errorf("reserved Pi tool name %q: use Claude spelling %q in tools:", name, claude) + } + if piReservedUnmappedToolName(name) { + return fmt.Errorf("reserved Pi tool name %q has no supported Claude spelling", name) + } + } + return fmt.Errorf("pi tool selections must be exact names (MCP selectors may use supported patterns): %q", unsupported) + } + // Children always have an explicit selection, even for a default-mode parent. + if err := uploadBytes(sandboxName, cfg+"/"+piToolSelectionExtensionFile, piToolSelectionExtensionJS); err != nil { + return fmt.Errorf("installing tool selector: %w", err) } // pi's skills are prompt-driven: the system prompt tells the model to // `read` a skill's SKILL.md, and that section is only emitted when the @@ -306,6 +321,8 @@ func (r PiRuntime) Bootstrap(input BootstrapInput) error { Description: def.Description, Model: def.Model, Tools: tools, + StrictTools: def.Tools != nil, + NativeTools: piNativeToolsFor(def.Tools), BashAllowlist: def.BashAllowlist, BashAllowlistMode: piBashAllowlistMode(), Extensions: extensions, @@ -358,12 +375,14 @@ func (r PiRuntime) Bootstrap(input BootstrapInput) error { if err != nil { return err } + block.ToolSelector = cfg + "/" + piToolSelectionExtensionFile block.DeclaredExtensions = extensions block.MCPResourceTools = append([]string{}, piMCPResourceTools...) if block.ExtensionDigests == nil { block.ExtensionDigests = map[string]string{} } sum := sha256.Sum256(piAgentExtensionJS) + block.ExtensionDigests[block.ToolSelector] = piToolSelectionDigest() block.ExtensionDigests[cfg+"/"+piAgentExtensionFile] = hex.EncodeToString(sum[:]) manifest.Agent = block } @@ -399,17 +418,10 @@ func (r PiRuntime) Bootstrap(input BootstrapInput) error { // map is the seam — no Runtime interface method, and nothing on disk in // the sandbox for the agent to reach. // -// Run turns the digest into the shell guard that refuses to start pi on a -// modified manifest. Without an entry (Run reached without this process -// having bootstrapped that sandbox) the guard is simply not emitted: -// failing closed there would break any caller that bootstraps separately, -// and the agent cannot cause the entry to be missing. -// -// So the guard exists only when Bootstrap and Run run in one process. The -// CLI's `run` path does, which is why this is a seam and not a gap — but a -// caller that bootstrapped in one process and ran in another would lose -// both the manifest guard and the FULLSEND_PI_MANIFEST_SHA256 export the -// hook adapter re-checks in every sub-agent, with nothing to say so. +// Run uses the digest to guard the manifest and exports it for extensions +// that verify the manifest at load time. An explicit tool list or a child +// selector requires this entry. Other runs omit the manifest digest guard +// and export when Bootstrap ran in another process. var piManifestHashes sync.Map // sandboxName -> hex sha256 of the manifest bytes func recordPiManifestHash(sandboxName string, manifestJSON []byte) { @@ -701,9 +713,8 @@ func piApplyChildFallbacks(m *piAgentManifest, personas []piPersona, subagentsCf } // piAgentExtensionDigests records hook/repair digests. Bootstrap additionally -// records fullsend-agent.js, whose child-only mode restores the active loadout. -// Together they cover runner-written child -e files: the dispatcher itself, -// the hook adapter (piHooksGuard's bytes) and the edit-repair extension +// records the dispatcher and strict selector digests. Together they cover +// the dispatcher, selector, hook adapter (piHooksGuard's bytes), and edit-repair extension // (piEditRepairGuard's bytes). The dispatcher digest is present even with // hooks off and no edit tool. fullsend-agent.js re-hashes all these files // immediately before every dispatch: the launch guard diff --git a/internal/runtime/pi_bootstrap_test.go b/internal/runtime/pi_bootstrap_test.go index 9b8ba484be..3c02d534b4 100644 --- a/internal/runtime/pi_bootstrap_test.go +++ b/internal/runtime/pi_bootstrap_test.go @@ -835,8 +835,13 @@ func TestPiAgentTool_ManifestBlock(t *testing.T) { "the publisher-qualified wire id the vendored extension registers, so xai-vertex/xai/grok-4.6 resolves and an invented Grok id does not") hooksExt := cfg + "/fullsend-hooks.js" editExt := cfg + "/fullsend-edit-repair.js" - require.Len(t, m.Agent.ExtensionDigests, 3, + require.Len(t, m.Agent.ExtensionDigests, 4, "both child -e entries Bootstrap wrote into the config dir are digest-covered, so the extension can re-check them before every dispatch") + selector := cfg + "/" + piToolSelectionExtensionFile + assert.Equal(t, selector, m.Agent.ToolSelector) + assert.Equal(t, piToolSelectionDigest(), m.Agent.ExtensionDigests[selector]) + assert.False(t, m.StrictTools) + assert.Empty(t, m.NativeTools) require.NotEmpty(t, m.Agent.ExtensionDigests[hooksExt]) assert.Contains(t, piHooksGuard(hooksExt, cfg+"/fullsend-manifest.json"), m.Agent.ExtensionDigests[hooksExt], "and against the same digest the launch guard checks, so the two cannot drift") @@ -875,7 +880,7 @@ func TestPiAgentTool_ManifestBlock(t *testing.T) { assert.Equal(t, []string{"read", "grep"}, m.Agent.Tools, "children get the built-ins only") assert.Equal(t, "explicit", m.Agent.ToolMode) assert.Equal(t, []string{piVertexExtensionPath}, m.Agent.Extensions, "no hook adapter without security") - require.Len(t, m.Agent.ExtensionDigests, 1, "the child loadout guard is always checked") + require.Len(t, m.Agent.ExtensionDigests, 2, "the child loadout guard is always checked") assert.NotEmpty(t, m.Agent.ExtensionDigests[cfg+"/fullsend-agent.js"]) assert.Equal(t, piMCPResourceTools, m.Agent.MCPResourceTools) assert.Empty(t, m.Agent.EditRepairExtension, "the tools: list names no edit") @@ -891,7 +896,7 @@ func TestPiAgentTool_ManifestBlock(t *testing.T) { assert.Equal(t, []string{"read", "edit"}, m.Agent.Tools, "children keep edit, minus the sub-agent tools") assert.Equal(t, cfg+"/fullsend-edit-repair.js", m.Agent.EditRepairExtension, "a declared list naming Edit carries the extension") assert.NotContains(t, m.Agent.Extensions, cfg+"/fullsend-edit-repair.js", "never in the shared list: a child without edit must not load it") - require.Len(t, m.Agent.ExtensionDigests, 2, "repair and child loadout guard are checked") + require.Len(t, m.Agent.ExtensionDigests, 3, "repair and child loadout guard are checked") require.NotEmpty(t, m.Agent.ExtensionDigests[cfg+"/fullsend-edit-repair.js"]) assert.Equal(t, piEditRepairExtensionJS, storedUpload(t, store, cfg+"/fullsend-edit-repair.js")) }) @@ -1249,8 +1254,8 @@ func forgetPiManifestHash(t *testing.T, sandboxName string) { // TestPiManifestHash covers the Bootstrap-to-Run seam: the digest is // recorded per sandbox and read back by name, and a sandbox this process -// never bootstrapped yields "" so Run emits no guard rather than failing a -// caller that bootstrapped elsewhere. +// never bootstrapped yields an empty digest so Run can check whether the +// manifest requires the strict selector. func TestPiManifestHash(t *testing.T) { forgetPiManifestHash(t, "sb-hash") assert.Empty(t, piManifestHash("sb-hash"), "not bootstrapped in this process") diff --git a/internal/runtime/pi_edit_repair_test.go b/internal/runtime/pi_edit_repair_test.go index d77b37a0d5..e04911bf57 100644 --- a/internal/runtime/pi_edit_repair_test.go +++ b/internal/runtime/pi_edit_repair_test.go @@ -47,7 +47,7 @@ func TestBuildPiRunCommand_EditRepairGate(t *testing.T) { "runner-owned before declared; a declared extension must not also register edit, since pi rejects two extensions that register the same tool name") cmd = buildPiRunCommand(piTestParams(), &piManifest{AgentName: "code", Tools: []string{}}, nil, "") - assert.Contains(t, cmd, "--no-builtin-tools") + assert.Contains(t, cmd, "--tools ''") assert.NotContains(t, cmd, piEditRepairExtensionFile, "under --no-builtin-tools the extension's edit would not be filtered") cmd = buildPiRunCommand(piTestParams(), &piManifest{AgentName: "triage", Tools: []string{"bash", "read"}}, nil, "") diff --git a/internal/runtime/pi_extension/fullsend-agent.js b/internal/runtime/pi_extension/fullsend-agent.js index 7927389ce8..83b487d79c 100644 --- a/internal/runtime/pi_extension/fullsend-agent.js +++ b/internal/runtime/pi_extension/fullsend-agent.js @@ -9,10 +9,10 @@ // hook adapter with -e, a strict --tools allowlist, its own session dir. // pi runs sibling tool calls from one assistant message concurrently, which // is the parallel dispatch the skills ask for; `run_in_background` is -// accepted and ignored. Children conditionally load this file in child-only -// mode to restore active tools before the first model request; that mode -// returns without registering Agent. FULLSEND_SUBAGENT_DEPTH also prevents -// Agent registration if this file loads in normal mode inside a child. +// accepted and ignored. Children use fullsend-tools.js to restore active tools. +// Older Agent manifests without toolSelector can still load this file in +// child-only mode. FULLSEND_SUBAGENT_DEPTH prevents Agent registration if +// the dispatcher loads in normal mode inside a child. // // The prompt goes over the child's stdin, never as a positional argument. // Without a terminator pi's argv parser (0.84.4 dist/cli/args.js) reads a @@ -530,8 +530,11 @@ export function childArgs(agent, { seq, modelSpec, tools, activeTools = tools, p args.push("--tools", tools.join(",")); // The CLI allowlist controls registration as well as activation. Keep the // callable union registered, then restore only the inherited active subset - // before the first model request. This child-only mode registers no Agent. - if (activeTools.length !== tools.length || activeTools.some((t, i) => t !== tools[i])) { + // before the first model request. Bootstrap always emits toolSelector for + // current manifests. The fallback serves older manifests without that field. + if (agent.toolSelector) { + args.push("-e", agent.toolSelector, "--fullsend-selected-tools", JSON.stringify({ tools, activeTools })); + } else if (activeTools.length !== tools.length || activeTools.some((t, i) => t !== tools[i])) { args.push("-e", fileURLToPath(import.meta.url), "--fullsend-child-active-tools", JSON.stringify(activeTools)); } // pi 1.5.0 keeps MCP registrations when a nonempty --tools list has no diff --git a/internal/runtime/pi_extension/fullsend-agent.test.mjs b/internal/runtime/pi_extension/fullsend-agent.test.mjs index 02bf227756..8d17497b71 100644 --- a/internal/runtime/pi_extension/fullsend-agent.test.mjs +++ b/internal/runtime/pi_extension/fullsend-agent.test.mjs @@ -403,6 +403,20 @@ test("childArgs mirrors the runner's pi command line, extensions in manifest ord assert.ok(!empty.includes("--no-builtin-tools")); }); +test("childArgs passes callable and active tools to the strict selector", () => { + const { manifest } = fixture(); + const selector = "/sandbox/pi-config/fullsend-tools.js"; + const tools = ["read", "codemode"]; + const activeTools = ["read"]; + const args = childArgs({ ...manifest.agent, toolSelector: selector }, { + seq: 1, modelSpec: "m", tools, activeTools, + }); + const index = args.indexOf("--fullsend-selected-tools"); + assert.ok(index >= 2); + assert.deepEqual(args.slice(index - 2, index), ["-e", selector]); + assert.deepEqual(JSON.parse(args[index + 1]), { tools, activeTools }); +}); + test("childArgs denies MCP registrations for non-MCP selections only", () => { const { manifest } = fixture(); for (const tools of [["codemode"], ["read"], [], ["codemode", "mcp__docs__search"]]) { diff --git a/internal/runtime/pi_extension/fullsend-tools.js b/internal/runtime/pi_extension/fullsend-tools.js new file mode 100644 index 0000000000..88b9d69f29 --- /dev/null +++ b/internal/runtime/pi_extension/fullsend-tools.js @@ -0,0 +1,101 @@ +// Runner-owned strict tool selection. This file registers no tool and loads +// after vetted extensions. Pinned Pi print mode refuses extension conflict +// diagnostics before session_start; this selector checks exact registry identity. +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve, relative, isAbsolute } from "node:path"; + +export const SELECTION_EXIT = 99; + +function within(file, directory) { + if (typeof file !== "string" || typeof directory !== "string") return false; + const rel = relative(resolve(directory), resolve(file)); + return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); +} + +// MCP selectors retain their existing asynchronous registration and exposure +// semantics. Exact native selections must already exist before inference. +const mcpSelector = (name) => name.startsWith("mcp__") || /^(list|read)_mcp_/.test(name); +const matches = (pattern, name) => { + const escaped = pattern.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return new RegExp(`^${escaped.join(".*")}$`).test(name); +}; + +export function selectTools(manifest, registry) { + if (!manifest?.strictTools || !Array.isArray(manifest.tools)) throw new Error("strict tool declaration missing"); + if (!Array.isArray(registry)) throw new Error("tool registry unavailable"); + const selected = [...new Set(manifest.tools.filter((name) => !mcpSelector(name)))]; + for (const name of selected) { + const matches = registry.filter((tool) => tool.name === name); + if (matches.length !== 1) throw new Error(`missing or ambiguous tool: ${name}`); + const tool = matches[0]; + if (tool.exposure === "hidden") throw new Error(`hidden tool: ${name}`); + if ((manifest.nativeTools ?? []).includes(name)) { + if (!(manifest.extensions ?? []).some((ext) => within(tool.sourceInfo?.path, ext.path))) { + throw new Error(`native tool is not supplied by a vetted extension: ${name}`); + } + } + } + return selected; +} + +export function initializeSelector(pi, manifest, { fatal = (message) => { console.error(`[fullsend-tools] ${message}`); process.exit(SELECTION_EXIT); } } = {}) { + let allowed = new Set(); + const activate = () => { + try { + const selected = selectTools(manifest, pi.getAllTools()); + // Preserve MCP active/callable separation, including late registration. + const mcpActive = pi.getActiveTools().filter((name) => + mcpSelector(name) && manifest.tools.some((pattern) => matches(pattern, name))); + const active = manifest.activeTools ?? [...selected, ...mcpActive]; + pi.setActiveTools(active); + const actual = pi.getActiveTools(); + if (actual.some((name) => !active.includes(name)) || + active.some((name) => !mcpSelector(name) && !actual.includes(name))) { + throw new Error("runtime did not enforce exact active tool set"); + } + allowed = new Set(selected); + } catch (err) { fatal(err.message); } + }; + pi.on("session_start", activate); + pi.on("before_agent_start", activate); + pi.on("agent_start", activate); + pi.on("turn_start", activate); + pi.on("tool_call", (event) => { + const name = event.toolName; + if (allowed.has(name) || (mcpSelector(name) && manifest.tools.some((pattern) => matches(pattern, name)))) return; + return { block: true, reason: "tool is outside the strict Fullsend selection" }; + }); +} + +export default function toolSelector(pi) { + let manifest; + try { + const bytes = readFileSync(process.env.FULLSEND_PI_MANIFEST || "/sandbox/pi-config/fullsend-manifest.json"); + const want = process.env.FULLSEND_PI_MANIFEST_SHA256; + if (!want || createHash("sha256").update(bytes).digest("hex") !== want) throw new Error("manifest integrity missing or changed"); + manifest = JSON.parse(bytes); + } catch (err) { + console.error(`[fullsend-tools] ${err.message}`); + process.exit(SELECTION_EXIT); + return; + } + const flag = "fullsend-selected-tools"; + if (process.argv.includes("--" + flag)) { + pi.registerFlag(flag, { type: "string", description: "Runner-resolved child tool permissions" }); + pi.on("session_start", () => { + try { + const child = JSON.parse(pi.getFlag(flag)); + if (!Array.isArray(child.tools) || !Array.isArray(child.activeTools) || + child.tools.some((name) => typeof name !== "string" || name.includes("*")) || + child.activeTools.some((name) => !child.tools.includes(name))) throw new Error("invalid child selection"); + Object.assign(manifest, { strictTools: true, tools: child.tools, activeTools: child.activeTools }); + } catch (err) { + console.error(`[fullsend-tools] ${err.message}`); + process.exit(SELECTION_EXIT); + return; + } + }); + } + initializeSelector(pi, manifest); +} diff --git a/internal/runtime/pi_extension/fullsend-tools.test.mjs b/internal/runtime/pi_extension/fullsend-tools.test.mjs new file mode 100644 index 0000000000..f9f5b1e471 --- /dev/null +++ b/internal/runtime/pi_extension/fullsend-tools.test.mjs @@ -0,0 +1,193 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { childArgs, childTools } from "./fullsend-agent.js"; +import { initializeSelector, selectTools, SELECTION_EXIT } from "./fullsend-tools.js"; + +const native = (name = "inspect_record", path = "/vetted/inspect_record/index.js") => ({ name, exposure: "direct", sourceInfo: { path } }); +const manifest = (tools = ["inspect_record"]) => ({ strictTools: true, tools, nativeTools: ["inspect_record"], extensions: [{ path: "/vetted/inspect_record" }] }); + +test("exact native tool selected without unrelated builtin or extension tools", () => { + assert.deepEqual(selectTools(manifest(), [native(), native("unrelated"), { name: "bash" }]), ["inspect_record"]); +}); +test("empty is explicit and default selection is not an authority proof", () => { + assert.deepEqual(selectTools(manifest([]), [native()]), []); + assert.throws(() => selectTools({ tools: [] }, []), /strict tool declaration/); +}); +test("missing, ambiguous and non-vetted registrations fail", () => { + for (const registry of [[], [native(), native()], [native("inspect_record", "/vetted/inspect_record-other/index.js")]]) { + assert.throws(() => selectTools(manifest(), registry)); + } + assert.throws(() => selectTools(manifest(), [{ ...native(), exposure: "hidden" }]), /hidden/); +}); +test("session startup fails before activating a missing native tool", () => { + const handlers = {}; + const pi = { + on: (name, fn) => { handlers[name] = fn; }, + getAllTools: () => [native("unrelated")], + setActiveTools: () => assert.fail("activated tools with a missing selection"), + }; + initializeSelector(pi, manifest(), { fatal: (message) => { throw new Error(message); } }); + assert.throws(() => handlers.session_start(), /missing or ambiguous tool: inspect_record/); + assert.equal(handlers.tool_call({ toolName: "unrelated" }).block, true); +}); +test("activation and hook enforcement share canonical names", () => { + const handlers = {}; let active = []; + const pi = { on: (name, fn) => { handlers[name] = fn; }, getAllTools: () => [native(), { name: "read" }], setActiveTools: (names) => { active = names; }, getActiveTools: () => active }; + initializeSelector(pi, manifest(["inspect_record", "read"]), { fatal: (message) => { throw new Error(message); } }); + handlers.session_start(); + assert.deepEqual(active, ["inspect_record", "read"]); + assert.equal(handlers.tool_call({ toolName: "inspect_record" }), undefined); + assert.equal(handlers.tool_call({ toolName: "bash" }).block, true); + active.push("bash"); handlers.before_agent_start(); + assert.deepEqual(active, ["inspect_record", "read"]); +}); +test("a runtime ignoring exact activation fails", () => { + const handlers = {}; + const pi = { on: (name, fn) => { handlers[name] = fn; }, getAllTools: () => [native()], setActiveTools: () => {}, getActiveTools: () => ["bash", "inspect_record"] }; + initializeSelector(pi, manifest(), { fatal: (message) => { throw new Error(message); } }); + assert.throws(() => handlers.session_start(), /did not enforce/); +}); + +// Offline acceptance against the pinned Pi binary. Inspection exits +// on session_start, before any inference request or credential use. +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const realPi = process.env.FULLSEND_TEST_PI_BIN; +const selectorPath = fileURLToPath(new URL("./fullsend-tools.js", import.meta.url)); + +async function actualSelection({ tools = ["inspect_record"], duplicate = false, missing = false, wrongOrigin = false, exercise = false, deny = false, child = null, corruptManifest = false } = {}) { + const dir = mkdtempSync(join(tmpdir(), "fullsend-exact-pi-")); + try { + const home = join(dir, "home"); mkdirSync(home); + const plugin = join(dir, "plugin"); mkdirSync(plugin); + const tool = (name) => `pi.registerTool({name:${JSON.stringify(name)},label:'fixture',description:'offline fixture',parameters:{type:'object',properties:{}},execute:async()=>{console.error('EXECUTED='+${JSON.stringify(name)});return {content:[{type:'text',text:'fixture'}]}}});`; + writeFileSync(join(plugin, "index.js"), `export default function(pi){${tool(missing ? "other" : "inspect_record")}${tool("unrelated")}${tool("bash")}${tool("edit")}}`); + const paths = [plugin]; + if (duplicate) { + const second = join(dir, "second"); mkdirSync(second); + writeFileSync(join(second, "index.js"), `export default function(pi){${tool("inspect_record")}}`); + paths.push(second); + } + const provider = join(dir, "provider.js"); + writeFileSync(provider, `import {fauxAssistantMessage,fauxProvider,fauxToolCall} from "@earendil-works/pi-ai"; +export default function(pi){ + const faux=fauxProvider({provider:"faux",models:[{id:"fixture"}]}); + faux.setResponses([fauxAssistantMessage([${["inspect_record", "unrelated", "bash", "edit"].map((name) => `fauxToolCall(${JSON.stringify(name)},{})`).join(",")}],{stopReason:"toolUse"}),fauxAssistantMessage("done")]); + pi.registerProvider(faux.provider); + pi.on("before_agent_start",()=>{console.error("MODEL_START");}); + +}`); + const inspector = join(dir, "inspector.js"); + writeFileSync(inspector, 'import {writeSync} from "node:fs"; export default function(pi){pi.on("session_start",()=>{writeSync(1,"FULLSEND_SELECTION="+JSON.stringify(pi.getActiveTools())+"\\n");EXIT});}'.replace("EXIT", exercise ? "" : "process.exit(0);")); + const config = { strictTools: true, tools, nativeTools: tools.filter((name) => name === "inspect_record"), extensions: paths.map((path) => ({ path: wrongOrigin ? join(dir, "different") : path })) }; + if (deny) { + writeFileSync(join(dir, "deny.py"), 'import json, sys\npayload=json.load(sys.stdin)\nprint(json.dumps({"decision":"block","reason":"fixture denial: "+payload["tool_name"]}))\n'); + config.hooks = { dir, toolNames: {}, groups: [{phase:"PreToolUse",tools:["inspect_record"],scripts:["deny.py"]}] }; + } + const hooksPath = fileURLToPath(new URL("./fullsend-hooks.js", import.meta.url)); + const manifestPath = join(dir, "manifest.json"); const bytes = JSON.stringify(config); writeFileSync(manifestPath, bytes); + const args = ["--print", "--mode", "json", "--no-approve", "--no-extensions", "--no-prompt-templates", "--no-themes", "--no-session", "--model", exercise ? "faux/fixture" : "openai/gpt-5", "--api-key", "offline-not-a-key", "--tools", tools.join(","), ...(exercise ? ["-e", provider] : []), ...(deny ? ["-e", hooksPath] : []), ...paths.flatMap((path) => ["-e", path]), "-e", selectorPath, "-e", inspector]; + if (child) { + const agent = { sessionsDir: join(dir, "sessions"), extensions: exercise ? [provider] : [], declaredExtensions: paths.map((path) => ({path})), toolSelector: selectorPath, mcpResourceTools: ["list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"] }; + args.splice(0, args.length, ...childArgs(agent, {seq: 1, modelSpec: exercise ? "faux/fixture" : "openai/gpt-5", ...child}), "--api-key", "offline-not-a-key", "-e", inspector); + } + if (exercise) args.push("exercise fixture"); + return await new Promise((resolveResult, reject) => { + const child = spawn(resolve(realPi), args, { cwd: dir, env: { PATH: process.env.PATH, HOME: home, PI_CODING_AGENT_DIR: home, PI_OFFLINE: "1", PI_TELEMETRY: "0", FULLSEND_PI_HOOK_PYTHON: "/usr/bin/python3", FULLSEND_PI_HOOK_PATH: "/usr/bin:/bin", FULLSEND_PI_MANIFEST: manifestPath, FULLSEND_PI_MANIFEST_SHA256: corruptManifest ? "incorrect-digest" : createHash("sha256").update(bytes).digest("hex") }, stdio: ["pipe", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stdout.on("data", (bytes) => { stdout += bytes; }); child.stderr.on("data", (bytes) => { stderr += bytes; }); + const timeout = setTimeout(() => { child.kill("SIGKILL"); reject(new Error("offline Pi startup timed out")); }, 20000); + child.on("error", reject); child.on("close", (code) => { clearTimeout(timeout); resolveResult({ code, stdout, stderr }); }); + child.stdin.end(); + }); + } finally { rmSync(dir, { recursive: true, force: true }); } +} + +test("real Pi exposes only the selected native tool", { skip: !realPi }, async () => { + const result = await actualSelection(); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /FULLSEND_SELECTION=\["inspect_record"\]/); +}); +test("real Pi refuses missing, ambiguous and non-vetted selections before inference", { skip: !realPi }, async () => { + for (const config of [{ missing: true }, { duplicate: true }, { wrongOrigin: true }]) { + const result = await actualSelection({...config, exercise: true}); + assert.doesNotMatch(result.stderr, /MODEL_START|EXECUTED=/); + assert.notEqual(result.code, 0, result.stderr); + assert.doesNotMatch(result.stdout, /FULLSEND_SELECTION=/); + assert.match(result.stderr, /\[fullsend-tools\]|Failed to load extension/); + } +}); +test("real Pi explicit empty tool set exposes no builtins or unrelated extensions", { skip: !realPi }, async () => { + const result = await actualSelection({ tools: [] }); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /FULLSEND_SELECTION=\[\]/); +}); + + +test("real Pi executes only the selected tool, including in child mode", { skip: !realPi }, async () => { + for (const child of [null, { tools: ["inspect_record"], activeTools: ["inspect_record"] }]) { + const result = await actualSelection({ exercise: true, child }); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stderr, /EXECUTED=inspect_record/); + assert.doesNotMatch(result.stderr, /EXECUTED=(unrelated|bash|edit)/); + } +}); + +test("real Pi hook denial prevents the selected native tool executing", { skip: !realPi }, async () => { + const result = await actualSelection({ exercise: true, deny: true }); + assert.equal(result.code, 0, result.stderr); + assert.doesNotMatch(result.stderr, /EXECUTED=/); + assert.match(result.stdout, /fixture denial: inspect_record/); +}); + +test("real Pi empty selections prevent all tool execution", { skip: !realPi }, async () => { + for (const child of [null, {tools: [], activeTools: []}]) { + const result = await actualSelection({ tools: [], exercise: true, child }); + assert.equal(result.code, 0, result.stderr); + assert.doesNotMatch(result.stderr, /EXECUTED=/); + } +}); + +test("real Pi refuses a modified manifest before inference", { skip: !realPi }, async () => { + const result = await actualSelection({ exercise: true, corruptManifest: true }); + assert.equal(result.code, SELECTION_EXIT, result.stderr); + assert.doesNotMatch(result.stderr, /MODEL_START|EXECUTED=/); +}); + +test("MCP patterns preserve late, deferred and active tool permissions", () => { + const handlers = {}; let active = ["mcp__docs__search"]; let registry = []; + const pi = {on:(name,fn)=>{handlers[name]=fn;},getAllTools:()=>registry,getActiveTools:()=>active,setActiveTools:(names)=>{active=names;}}; + initializeSelector(pi, manifest(["mcp__docs__*"]), {fatal:(message)=>{throw new Error(message);}}); + handlers.session_start(); + assert.deepEqual(active,["mcp__docs__search"]); + registry=[{name:"mcp__docs__search",exposure:"direct"},{name:"mcp__docs__fetch",exposure:"deferred"}]; + handlers.before_agent_start(); + assert.deepEqual(active,["mcp__docs__search"]); + assert.equal(handlers.tool_call({toolName:"mcp__docs__fetch"}),undefined); + assert.equal(handlers.tool_call({toolName:"mcp__other__fetch"}).block,true); +}); + + +test("child callable-only tools stay inactive after late activation between turns", () => { + const handlers = {}; let active = ["mcp__docs__search"]; + const pi = {on:(name,fn)=>{handlers[name]=fn;},getAllTools:()=>[],getActiveTools:()=>active,setActiveTools:(names)=>{active=[...names];}}; + initializeSelector(pi, {...manifest(["mcp__docs__search","mcp__docs__fetch"]),activeTools:["mcp__docs__search"]}, {fatal:(message)=>{throw new Error(message);}}); + handlers.agent_start(); + active.push("mcp__docs__fetch"); + handlers.turn_start(); + assert.deepEqual(active,["mcp__docs__search"]); + assert.equal(handlers.tool_call({toolName:"mcp__docs__fetch"}),undefined); +}); + + +test("native child selections intersect parent and persona before launch", () => { + const agent = {toolMode:"explicit",tools:["inspect_record","read"],personas:{allowed:{tools:["inspect_record","unrelated"]},forbidden:{tools:["unrelated"]}}}; + assert.deepEqual(childTools(agent,"allowed",["inspect_record","read"]),["inspect_record"]); + assert.deepEqual(childTools(agent,"forbidden",["inspect_record","read"]),[]); + assert.deepEqual(childTools(agent,"Explore",["inspect_record","read"]),["read"]); +}); diff --git a/internal/runtime/pi_frontmatter_mcp_test.go b/internal/runtime/pi_frontmatter_mcp_test.go index 06d275dc8f..537bb0a61d 100644 --- a/internal/runtime/pi_frontmatter_mcp_test.go +++ b/internal/runtime/pi_frontmatter_mcp_test.go @@ -29,6 +29,7 @@ func testPiDirectMCP(t *testing.T, selector, persona string) { } work := t.TempDir() store := filepath.Join(work, "store") + forgetPiManifestHash(t, "sb") fakeOpenshellPi(t, filepath.Join(work, "openshell.log"), store, "/dev/null") extension := filepath.Join(work, "docs-plugin") require.NoError(t, os.MkdirAll(extension, 0700)) @@ -41,15 +42,22 @@ func testPiDirectMCP(t *testing.T, selector, persona string) { sandboxName: "sb", agentName: "code", skillDirs: []string{skill}, plugins: piPlugins(extension), agentPath: writeAgentFile(t, "---\nname: code\ntools: [Agent, '"+selector+"']\n---\nSearch docs."), })) + manifest := storedUpload(t, store, PiRuntime{}.piManifestPath()) var m piManifest - require.NoError(t, json.Unmarshal(storedUpload(t, store, PiRuntime{}.ConfigDir()+"/fullsend-manifest.json"), &m)) + require.NoError(t, json.Unmarshal(manifest, &m)) require.NotNil(t, m.Agent) // Render the real parent's selection as well as the generated child manifest. - command := buildPiRunCommand(piTestParams(), &m, m.Extensions, "") + digest := piManifestHash("sb") + require.NotEmpty(t, digest) + command := buildPiRunCommand(piTestParams(), &m, m.Extensions, digest) require.Contains(t, command, "-e "+shellQuote(m.Extensions[0].Path)) encoded, err := json.Marshal(m.Agent) require.NoError(t, err) - node := exec.Command("node", "testdata/pi-direct-mcp.mjs", string(encoded), command, extension) + manifestPath := filepath.Join(work, "manifest.json") + require.NoError(t, os.WriteFile(manifestPath, manifest, 0600)) + selectorPath := filepath.Join(work, piToolSelectionExtensionFile) + require.NoError(t, os.WriteFile(selectorPath, storedUpload(t, store, m.Agent.ToolSelector), 0600)) + node := exec.Command("node", "testdata/pi-direct-mcp.mjs", string(encoded), command, extension, selectorPath, manifestPath, digest) require.Equal(t, piMCPResourceTools, m.Agent.MCPResourceTools) node.Env = append(os.Environ(), "FULLSEND_TEST_PI_BIN="+bin) out, err := node.CombinedOutput() diff --git a/internal/runtime/pi_personas.go b/internal/runtime/pi_personas.go index 226c5d61f7..b244780ee9 100644 --- a/internal/runtime/pi_personas.go +++ b/internal/runtime/pi_personas.go @@ -459,9 +459,13 @@ func piChildSpecResolver(modelsTable map[string]string, modelFallbacks map[strin // the same rule so a persona that will not register never counts. func piPersonaTools(claudeTools []string) (filtered, unsupported []string) { piTools, unsupported := piToolsFor(claudeTools) + // Persona dispatch intersects names before launch and cannot validate + // exact extension declarations that fall out of that intersection. + native := piNativeToolsFor(claudeTools) + unsupported = append(unsupported, native...) filtered = make([]string, 0, len(piTools)) for _, t := range piTools { - if t != piAgentToolName && t != piAgentToolAlias { + if t != piAgentToolName && t != piAgentToolAlias && !hasTool(native, t) { filtered = append(filtered, t) } } diff --git a/internal/runtime/pi_run.go b/internal/runtime/pi_run.go index 59a08a76b5..e1c9c9aed4 100644 --- a/internal/runtime/pi_run.go +++ b/internal/runtime/pi_run.go @@ -482,6 +482,9 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi // assignment to the pinned name (envDataLoad's extra drop names). // The launch below uses the path, which no function or alias can shadow. parts = append(parts, "&& "+piBinaryPin()) + if m.Tools != nil { + parts = append(parts, "&& "+piToolSelectionGuard(r.ConfigDir()+"/"+piToolSelectionExtensionFile)) + } if hooksEnabled { // Before .env: that file is agent-writable and could otherwise // shadow the guard's tools with functions or a PATH entry. @@ -637,6 +640,9 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi "&& export "+piManifestSumEnv+"="+shellQuote(manifestSum), ) } + if m.Tools != nil { + parts = append(parts, "&& unset -f test [ command sha256sum cut", "&& "+piToolSelectionGuard(r.ConfigDir()+"/"+piToolSelectionExtensionFile)) + } // Declared extensions' env goes last, which protects nothing on its // own: it is exported after the runtime's pins and the provider // hygiene, and pi hands its whole environment to every hook script it @@ -698,8 +704,7 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi if agentEnabled { // After the adapter, so its PreToolUse hooks see Agent calls // (Claude Code runs the same hooks on its Agent tool). Children - // get their -e list from the manifest; they load this file only - // in child-only mode to restore inherited active tools. + // load the strict tool selector to restore inherited active tools. parts = append(parts, "-e "+shellQuote(agentExt)) } if editRepair { @@ -714,12 +719,14 @@ func buildPiRunCommand(params RunParams, m *piManifest, exts []piManifestExtensi // handlers in -e order and the first block wins, so the adapter's // PreToolUse hooks see every call before any declared extension does. parts = append(parts, piExtensionArgs(exts)...) + if m.Tools != nil { + parts = append(parts, "-e "+shellQuote(r.ConfigDir()+"/"+piToolSelectionExtensionFile)) + } if m.Tools != nil { tools := m.Tools if len(tools) == 0 { - // An agent that lists only tools pi cannot provide (or only - // Skill) gets no built-in tools rather than the defaultTools set. - parts = append(parts, "--no-builtin-tools") + // An explicit empty selection excludes extension tools too. + parts = append(parts, "--tools ''") } else { parts = append(parts, "--tools "+shellQuote(strings.Join(tools, ","))) if excluded := piMCPExclusions(tools); excluded != "" { @@ -1122,6 +1129,9 @@ func (r PiRuntime) piExecModel(ctx context.Context, params RunParams, m *piManif if exitCode == piEditRepairTamperedExit && piEditRepairEnabled(m.Tools) { return piRunResult{exitCode: exitCode, modelSpec: modelSpec, guardErr: fmt.Errorf("pi edit-repair extension %s missing or modified in %s; refusing to run (was Bootstrap run, or did the agent change it?)", piEditRepairExtensionFile, r.ConfigDir())} } + if exitCode == piToolSelectionExit && m.Tools != nil { + return piRunResult{exitCode: exitCode, modelSpec: modelSpec, guardErr: fmt.Errorf("pi strict tool selection failed or selector changed; refusing inference")} + } if exitCode == piManifestTamperedExit { return piRunResult{exitCode: exitCode, modelSpec: modelSpec, guardErr: fmt.Errorf("the pi manifest at %s is not the one Bootstrap wrote; refusing to run because it configures the hook plan and the sub-agent children (did the agent or a rewritten .env change it?)", r.piManifestPath())} } @@ -1233,6 +1243,9 @@ func (r PiRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printe return -1, err } manifestSum := piManifestHash(params.SandboxName) + if manifestSum == "" && (m.Tools != nil || (m.Agent != nil && m.Agent.ToolSelector != "")) { + return -1, fmt.Errorf("pi strict tool selection requires the manifest digest for sandbox %s; run Bootstrap in the same process before Run", params.SandboxName) + } handler := params.OnEvent if handler == nil { diff --git a/internal/runtime/pi_run_test.go b/internal/runtime/pi_run_test.go index e72f9d00a1..e40d1d7f7d 100644 --- a/internal/runtime/pi_run_test.go +++ b/internal/runtime/pi_run_test.go @@ -102,7 +102,10 @@ func TestBuildPiRunCommand_Basic(t *testing.T) { // The guard runs before the agent-writable .env is sourced; the // runner-owned locations are re-pinned right after it. - assert.True(t, strings.HasPrefix(cmd, `cd '/sandbox/workspace/repo' && `+piBinaryPin()+` && `+piHooksGuard("/sandbox/pi-config/fullsend-hooks.js", "/sandbox/pi-config/fullsend-manifest.json")+` && `+piEnvLoad+` && `+piLoaderEnvUnset()+` && `+strings.Join(PiRuntime{}.EnvExports(), " && ")+` && export FULLSEND_PI_MANIFEST='/sandbox/pi-config/fullsend-manifest.json' && export FULLSEND_PI_HOOK_PYTHON="$FULLSEND_ENV_PYTHON" && export FULLSEND_PI_HOOK_PATH="$FULLSEND_TRUSTED_PATH" && export FULLSEND_PI_CHILD_BIN="$FULLSEND_PI_BIN" FULLSEND_PI_CHILD_NODE="$FULLSEND_PI_NODE" && export FULLSEND_RUNTIME=pi && export GOOGLE_CLOUD_LOCATION="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}" && unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_OAUTH_TOKEN ANTHROPIC_BASE_URL ANTHROPIC_VERTEX_BASE_URL && export GOOGLE_CLOUD_PROJECT="${ANTHROPIC_VERTEX_PROJECT_ID:-$GOOGLE_CLOUD_PROJECT}" && `+cliLaunch(piBinaryVar, piNodeVar)+` --print --mode json`), cmd) + assert.True(t, strings.HasPrefix(cmd, `cd '/sandbox/workspace/repo' && `+piBinaryPin()+` && `+piToolSelectionGuard("/sandbox/pi-config/fullsend-tools.js")+` && `+piHooksGuard("/sandbox/pi-config/fullsend-hooks.js", "/sandbox/pi-config/fullsend-manifest.json")+` && `+piEnvLoad), cmd) + afterEnv := strings.SplitN(cmd, piEnvLoad, 2) + require.Len(t, afterEnv, 2) + assert.Contains(t, afterEnv[1], "&& unset -f test [ command sha256sum cut && "+piToolSelectionGuard("/sandbox/pi-config/fullsend-tools.js")) // Gemini on Vertex needs GOOGLE_CLOUD_LOCATION; the fleet exports the // region as CLOUD_ML_REGION, so it is mirrored after .env is sourced. assert.Contains(t, cmd, `&& export GOOGLE_CLOUD_LOCATION="${GOOGLE_CLOUD_LOCATION:-$CLOUD_ML_REGION}"`) @@ -855,8 +858,8 @@ func TestBuildPiRunCommand_EmptyToolRestriction(t *testing.T) { t.Setenv("FULLSEND_PI_MODEL", "") m := &piManifest{Tools: []string{}} cmd := buildPiRunCommand(piTestParams(), m, nil, "") - assert.Contains(t, cmd, "--no-builtin-tools") - assert.NotContains(t, cmd, "--tools ") + assert.Contains(t, cmd, "--tools ''") + assert.NotContains(t, cmd, "--no-builtin-tools") } func TestBuildPiRunCommand_QuotesRepoDirAndModel(t *testing.T) { diff --git a/internal/runtime/pi_tool_selection.go b/internal/runtime/pi_tool_selection.go new file mode 100644 index 0000000000..e265827010 --- /dev/null +++ b/internal/runtime/pi_tool_selection.go @@ -0,0 +1,23 @@ +package runtime + +import ( + "crypto/sha256" + _ "embed" + "encoding/hex" + "fmt" +) + +const piToolSelectionExtensionFile = "fullsend-tools.js" +const piToolSelectionExit = 99 + +//go:embed pi_extension/fullsend-tools.js +var piToolSelectionExtensionJS []byte + +func piToolSelectionGuard(path string) string { + return fmt.Sprintf(`{ test -f %s && [ "$(command -p sha256sum %s | command -p cut -d' ' -f1)" = %s ] || { echo 'fullsend: pi tool selector missing or modified; refusing to run' >&2; exit %d; }; }`, shellQuote(path), shellQuote(path), shellQuote(piToolSelectionDigest()), piToolSelectionExit) +} + +func piToolSelectionDigest() string { + sum := sha256.Sum256(piToolSelectionExtensionJS) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/runtime/pi_tool_selection_test.go b/internal/runtime/pi_tool_selection_test.go new file mode 100644 index 0000000000..d2cd38d865 --- /dev/null +++ b/internal/runtime/pi_tool_selection_test.go @@ -0,0 +1,184 @@ +package runtime + +import ( + "context" + "encoding/json" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/ui" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPiExactNativeTools(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + input, tools, invalid []string + }{ + {name: "native, builtin alias and MCP", input: []string{"inspect_record", "Read", "inspect_record", "mcp__docs__*"}, tools: []string{"inspect_record", "read", "mcp__docs__*"}}, + {name: "reserved Pi names", input: []string{"read", "bash", "powershell", "codemode", "tool_search"}, tools: []string{}, invalid: []string{"read", "bash", "powershell", "codemode", "tool_search"}}, + {name: "malformed names", input: []string{"native*", "bad,name", "bad/name", "0bad", "-bad", "", "mcp__", "list_mcp_unknown"}, tools: []string{}, invalid: []string{"native*", "bad,name", "bad/name", "0bad", "-bad", "", "mcp__", "list_mcp_unknown"}}, + } { + t.Run(tc.name, func(t *testing.T) { + tools, invalid := piToolsFor(tc.input) + assert.Equal(t, tc.tools, tools) + assert.Equal(t, tc.invalid, invalid) + }) + } + assert.Equal(t, []string{"inspect_record"}, piNativeToolsFor([]string{"Bash", "Skill", "Agent", "inspect_record", "inspect_record", "native*"})) + child, unsupported := piPersonaTools([]string{"Read", "inspect_record"}) + assert.Equal(t, []string{"read"}, child) + assert.Equal(t, []string{"inspect_record"}, unsupported) +} + +func TestPiToolSelectorBootstrap(t *testing.T) { + work := t.TempDir() + store := filepath.Join(work, "store") + fakeOpenshellPi(t, filepath.Join(work, "openshell.log"), store, "/dev/null") + input := bootstrapInput{sandboxName: "native-tools-test", agentName: "assess", agentPath: writeAgentFile(t, "---\nname: assess\ntools: [inspect_record]\n---\nAssess the admitted target.")} + require.NoError(t, PiRuntime{}.Bootstrap(input)) + var manifest piManifest + require.NoError(t, json.Unmarshal(storedUpload(t, store, PiRuntime{}.piManifestPath()), &manifest)) + assert.True(t, manifest.StrictTools) + selector := PiRuntime{}.ConfigDir() + "/" + piToolSelectionExtensionFile + assert.Equal(t, []string{"inspect_record"}, manifest.NativeTools) + assert.Equal(t, []string{"inspect_record"}, manifest.Tools) + assert.Equal(t, piToolSelectionExtensionJS, storedUpload(t, store, selector)) + input.agentPath = writeAgentFile(t, "---\nname: assess\ntools: ['native*']\n---\nAssess.") + require.ErrorContains(t, PiRuntime{}.Bootstrap(input), "exact names") + input.agentPath = writeAgentFile(t, "---\nname: assess\ntools: [powershell]\n---\nAssess.") + require.ErrorContains(t, PiRuntime{}.Bootstrap(input), `reserved Pi tool name "powershell" has no supported Claude spelling`) + input.agentPath = writeAgentFile(t, "---\nname: assess\ntools: [read]\n---\nAssess.") + require.ErrorContains(t, PiRuntime{}.Bootstrap(input), `reserved Pi tool name "read": use Claude spelling "Read"`) +} + +func TestPiToolSelectorGuard(t *testing.T) { + t.Parallel() + if err := exec.Command("sh", "-c", "command -p sha256sum /dev/null && command -p cut -d' ' -f1 /dev/null").Run(); err != nil { + t.Skip("shell guard requires sha256sum and cut on the standard utility path") + } + file := filepath.Join(t.TempDir(), "selector.js") + guard := piToolSelectionGuard(file) + for _, bytes := range [][]byte{[]byte("modified"), piToolSelectionExtensionJS} { + require.NoError(t, os.WriteFile(file, bytes, 0o600)) + err := exec.Command("sh", "-c", guard).Run() + if string(bytes) == string(piToolSelectionExtensionJS) { + require.NoError(t, err) + } else { + var exit *exec.ExitError + require.ErrorAs(t, err, &exit) + assert.Equal(t, piToolSelectionExit, exit.ExitCode()) + } + } + require.NoError(t, os.Remove(file)) + require.Error(t, exec.Command("sh", "-c", guard).Run()) +} + +func TestBuildPiRunCommand_StrictNativeSelection(t *testing.T) { + // Activation derives from the explicit list, not an editable boolean. + m := &piManifest{NativeTools: []string{"inspect_record"}, Tools: []string{"inspect_record"}} + ext := piManifestExtension{Name: "native", Path: "/sandbox/pi-config/extensions/native"} + cmd := buildPiRunCommand(piTestParams(), m, []piManifestExtension{ext}, "manifest-digest") + assert.Contains(t, cmd, "--tools 'inspect_record'") + assert.Contains(t, cmd, piToolSelectionGuard(PiRuntime{}.ConfigDir()+"/"+piToolSelectionExtensionFile)) + assert.Greater(t, strings.Index(cmd, "-e '/sandbox/pi-config/fullsend-tools.js'"), strings.Index(cmd, "-e '/sandbox/pi-config/extensions/native'")) + assert.NotContains(t, cmd, "--no-builtin-tools") +} + +func TestPiRuntimeRun_TamperedToolSelectorFailsClosed(t *testing.T) { + t.Setenv("FULLSEND_PI_MODEL", "") + forgetPiManifestHash(t, "sb") + work := t.TempDir() + store := filepath.Join(work, "store") + fakeOpenshellPi(t, filepath.Join(work, "openshell.log"), store, "/dev/null") + // A selector failure must end the run rather than trigger model fallback. + require.NoError(t, PiRuntime{}.Bootstrap(bootstrapInput{ + sandboxName: "sb", agentPath: writeAgentFile(t, "---\nname: review\nmodel: opus\ntools: [inspect_record]\n---\nReview the PR."), agentName: "review", + })) + binDir := t.TempDir() + script := `#!/bin/sh +if [ "$2" = "exec" ]; then + for last; do :; done + case "$last" in + cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + store + `'/"$f"; exit $? ;; + *"exit 99"*) echo 'fullsend: pi tool selector missing or modified' >&2; exit 99 ;; + esac +fi +exit 0 +` + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + exit, err := PiRuntime{}.Run(context.Background(), RunParams{ + SandboxName: "sb", RepoDir: "/r", Timeout: 30 * time.Second, + OnEvent: func(AgentEvent) {}, + }, ui.New(os.Stderr), time.Now(), &RunMetrics{}) + assert.Equal(t, piToolSelectionExit, exit) + require.ErrorContains(t, err, "strict tool selection failed") + assert.NotContains(t, err.Error(), "Agent extension") + + forgetPiManifestHash(t, "sb") + exit, err = PiRuntime{}.Run(context.Background(), RunParams{ + SandboxName: "sb", RepoDir: "/r", Timeout: 30 * time.Second, + }, ui.New(os.Stderr), time.Now(), &RunMetrics{}) + assert.Equal(t, -1, exit) + require.ErrorContains(t, err, "run Bootstrap in the same process") +} + +func TestPiGatewayGuardWithExplicitTools(t *testing.T) { + params := piTestParams() + SetPiGatewayRun(params.SandboxName, &PiGatewayRun{}) + t.Cleanup(func() { SetPiGatewayRun(params.SandboxName, nil) }) + binDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte("#!/bin/sh\nexit 92\n"), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + result := (PiRuntime{}).piExecModel(context.Background(), params, &piManifest{Tools: []string{"read"}}, nil, + "manifest-digest", "gateway/test", time.Second, false, io.Discard, func(AgentEvent) {}, ui.New(io.Discard)) + assert.Equal(t, piGatewayConfigTamperedExit, result.exitCode) + require.ErrorContains(t, result.guardErr, PiInferenceGatewayLocalConfigFile) +} + +func TestPiExecModel_SelectorExitWithoutExplicitTools(t *testing.T) { + binDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte("#!/bin/sh\nexit 99\n"), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + result := (PiRuntime{}).piExecModel(context.Background(), piTestParams(), &piManifest{}, nil, + "", "openai/gpt-5", time.Second, false, io.Discard, func(AgentEvent) {}, ui.New(io.Discard)) + assert.Equal(t, piToolSelectionExit, result.exitCode) + assert.NoError(t, result.guardErr) +} + +func TestPiRuntimeRun_DefaultAgentRequiresManifestDigest(t *testing.T) { + t.Setenv("FULLSEND_PI_MODEL", "") + params := piTestParams() + forgetPiManifestHash(t, params.SandboxName) + work := t.TempDir() + store := filepath.Join(work, "store") + fakeOpenshellPi(t, filepath.Join(work, "openshell.log"), store, "/dev/null") + runtime := PiRuntime{} + require.NoError(t, runtime.Bootstrap(bootstrapInput{ + sandboxName: params.SandboxName, + agentPath: writeAgentFile(t, "---\nname: review\nmodel: opus\n---\nReview."), + agentName: "review", + })) + var manifest piManifest + require.NoError(t, json.Unmarshal(storedUpload(t, store, runtime.piManifestPath()), &manifest)) + require.Nil(t, manifest.Tools) + require.NotNil(t, manifest.Agent) + require.NotEmpty(t, manifest.Agent.ToolSelector) + + forgetPiManifestHash(t, params.SandboxName) + exit, err := runtime.Run(context.Background(), params, ui.New(io.Discard), time.Now(), &RunMetrics{}) + assert.Equal(t, -1, exit) + require.ErrorContains(t, err, "run Bootstrap in the same process") +} diff --git a/internal/runtime/testdata/pi-direct-mcp.mjs b/internal/runtime/testdata/pi-direct-mcp.mjs index de29869ac7..a5282bfc4f 100644 --- a/internal/runtime/testdata/pi-direct-mcp.mjs +++ b/internal/runtime/testdata/pi-direct-mcp.mjs @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { childArgs, childTools } from "../pi_extension/fullsend-agent.js"; -const [encoded, command, extension] = process.argv.slice(2); +const [encoded, command, extension, selectorPath, manifestPath, digest] = process.argv.slice(2); const agent = JSON.parse(encoded); assert.deepEqual(agent.tools, ["mcp__docs__*", "read"]); const serverWidePersona = agent.personas.docs.tools.includes("mcp__docs__*"); @@ -15,6 +15,7 @@ assert.equal(agent.declaredExtensions[0].name, "docs-plugin"); // The sandbox uploader's path is mapped back to its local fixture for this // offline process. All tool selections come from Bootstrap and Run rendering. agent.declaredExtensions[0].path = extension; +agent.toolSelector = selectorPath; // The fixture supplies an offline provider instead of sandbox inference adapters. agent.extensions = []; const home = mkdtempSync(join(tmpdir(), "fullsend-direct-")); @@ -22,7 +23,8 @@ try { agent.sessionsDir = home; const selection = command.match(/--tools '([^']*)'/); assert.ok(selection, command); - const env = {PATH: process.env.PATH, HOME: home, PI_CODING_AGENT_DIR: home, TEST_SNAPSHOT: join(home, "snapshot.json")}; + const env = {PATH: process.env.PATH, HOME: home, PI_CODING_AGENT_DIR: home, TEST_SNAPSHOT: join(home, "snapshot.json"), + FULLSEND_PI_MANIFEST: manifestPath, FULLSEND_PI_MANIFEST_SHA256: digest}; function run(args) { const result = spawnSync(process.env.FULLSEND_TEST_PI_BIN, args, {cwd: home, input: "search docs", encoding: "utf8", timeout: 45000, env}); assert.equal(result.error, undefined);