Files
PaperClipAI/packages/paperclip-runner/src/drivers/runtime-context-materializer.ts
T
Nicky LeachandClaude Fable 5.2 0aaab644fe refactor(runner): remove the direct assigned-gateway path (#21311)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent reaches the tools of its app connections through an MCP
gateway.
> - Before #21274, some native harnesses got the gateway URL and a
bearer token and connected to the gateway directly. The Runner has code
for that: an HTTP MCP server for ACPX providers, a server entry in the
Codex `config.toml`, a server entry in the OpenCode config, and the
lists that pass the three `PAPERCLIP_NATIVE_MCP_*` variables to a
sidecar.
> - #21274 gives each native harness its gateway tools through the PRP
relay. Core removes the three variables from each Runner environment.
The direct code path gets no binding.
> - Code that cannot run still needs maintenance, and it can still put a
token in a provider process if a variable arrives by another way.
> - This pull request deletes the direct path from the Runner.
> - The benefit is one path for assigned gateway tools, and no Runner
code that can give a gateway token to a provider.

## Linked Issues or Issue Description

No public issue exists. The issue is described here.

This pull request is in a stack. Its base branch is
`fix/keep-quiet-claude-provider-between-turns` (#21293). It depends on
#21274, which is the bottom of the stack. On `master` without #21274,
the direct path is still in use.

**What existing behavior does this improve?**

The Runner code that connects a provider directly to the assigned MCP
gateway.

**Subsystem affected**

Paperclip Runner: the TypeScript drivers and the Rust `runner-core`
environment lists.

**Current behavior**

After #21274, Core never gives `PAPERCLIP_NATIVE_MCP_NAME`,
`PAPERCLIP_NATIVE_MCP_URL` or `PAPERCLIP_NATIVE_MCP_TOKEN` to a Runner.
The Runner still has the code that reads them and configures a direct
gateway server for ACPX providers, Codex and OpenCode.

**Proposed behavior**

The Runner has no code that reads the three variables to configure a
provider. If the variables are in the environment of a Runner, no
provider environment, sidecar, Codex `config.toml` or OpenCode config
gets them.

**Reason and benefit**

Less code, one path, and no way for a gateway token to reach a provider
process through the Runner.

## What Changed

- Deleted `packages/paperclip-runner/src/drivers/native-mcp.ts`
(`nativeMcpLaunchBinding`).
- `drivers/acpx/runtime-host.ts`: removed the native gateway server
entry and the name conflict check. The admission gate keeps its message.
A run with a binding id is admitted when the sidecar uses the PRP
transport with its tool bridge, as the production sidecar always does.
- `drivers/acpx/environment.ts`: the name and the URL are not in the
provider allowlist.
- `drivers/runtime-context-materializer.ts` and
`live/runnerd-codex-transport.ts`: the Codex home functions have no
`nativeMcp` parameter. The sidecar token pass-through is gone.
- `drivers/opencode/opencode-server-driver.ts`: removed the read of the
binding, its trace redaction value, and the gateway server entry in the
OpenCode config.
- `drivers/stdio-mcp.ts` and `runner-core/src/stdio_mcp.rs`: removed the
reservation of the gateway server name. No gateway server exists, so no
name can conflict. The names `paperclip` and `paperclip_runner_*` stay
reserved.
- `runner-core/src/acpx_sidecar_transport.rs` and `codex_provider.rs`:
the three variables are not in the pass-through lists.
- `control-plane/durable-prp-control-plane.ts`: the three variables are
not in the platform environment list.
- `packages/paperclip-runner/README.md`: the text about direct callers
and assigned servers.
- Kept: the three names stay in the reserved lists
(`src/configured-environment.ts`,
`runner-core/src/configured_environment.rs`). A user cannot configure
them. Tests in both languages now check all three names.
- No server code changed. The relay needs the gateway token and URL on
the control plane.

23 files, 73 lines added and 211 lines removed.

## State saved by the previous release

- This pull request changes no persisted shape. The provider server
lists, the launch profile digests, the protocol versions and the sidecar
contract are the same as with #21274.
- A Runner or sidecar that the previous release started keeps its own
code until its run ends, as #21274 describes.
- A kept Codex home that has the old gateway server in `config.toml` is
written again at the next start and at a recovery of the same run. A
test covers this.
- If the old variables reach a new Runner, no provider gets them. Tests
cover this for ACPX, Codex and OpenCode.

## Verification

From `packages/paperclip-runner`:

- `npx vitest run src/drivers/acpx/runtime-host.test.ts
src/live/runnerd-codex-transport.test.ts
src/drivers/acpx/environment.test.ts
src/drivers/opencode/opencode-server-driver.test.ts
src/live/runnerd-codex-transport-warm-attachment.test.ts
src/drivers/runtime-context-materializer.test.ts
src/drivers/agent-observability.test.ts src/drivers/stdio-mcp.test.ts
src/control-plane/durable-prp-control-plane.test.ts
src/configured-environment.test.ts`: `10 passed (10)` files, `807
passed` tests.
- `npx tsc --noEmit -p tsconfig.json` and `-p tsconfig.test.json`: no
errors.
- `cargo fmt --manifest-path runner/Cargo.toml --all -- --check`: no
changes.
- `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`:
20 passed. `cargo test -p paperclip-runner-core --lib`: 639 passed, 4
ignored.

Tests that failed with the old code and pass now:

- `runtime-host.test.ts`: "admits a relayed … run with a binding id and
ignores a previous-release gateway binding", for Claude, Codex and
Cursor.
- `runnerd-codex-transport.test.ts`: "drops a previous-release gateway
binding from the … runner environment", for ACPX Claude, Codex, Pi,
Cursor, Copilot and Kimi, and for OpenCode.
- `opencode-server-driver.test.ts`: the OpenCode config has only the
task bridge.
- `runnerd-codex-transport-warm-attachment.test.ts`: a restored Codex
home has no gateway server and no gateway credential in `config.toml`.
- `environment.test.ts`: a provider environment has none of the three
variables.
- Rust
`previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar`:
a Runner that starts with the old variables gives none of them to the
sidecar, for five agents.

Mutation check: with the three names put back in the Rust pass-through
list, the Rust test fails.

Not run: a live run with a real provider. Not run: `pnpm verify` and the
full suite. CI supplies that coverage.

## Risks

- **This pull request is safe only after #21274.** The stack order keeps
that.
- **A developer who sets the three variables by hand for
`eval-session`** no longer gets direct gateway tools. No document
describes that use.
- **The warm attachment test uses the staged Runner binary from
preflight.** That binary does not have the Rust changes of this pull
request. The Codex path of that test does not use the changed lists.
- The evidence that no entry point supplies a binding comes from a read
of the code: Core removes the variables before it builds each Runner
environment, and a native run cannot use the in-process path.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the
change, reviewed the diff, and ran the verification and a mutation check
again.
- Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with
tool use (shell, file edits, local test runs), traced each code path and
wrote the change and the tests.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 13:33:47 -08:00

412 lines
15 KiB
TypeScript

import { isOpenRouterUrl, openRouterCodexHeaders } from "./openrouter-attribution.js";
import { randomUUID } from "node:crypto";
import { constants } from "node:fs";
import {
chmod,
cp,
lstat,
mkdir,
open,
readdir,
rename,
rm,
writeFile,
} from "node:fs/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { parse as parseToml } from "smol-toml";
import { codexObservabilityToml } from "./agent-observability.js";
import type { NativeRuntimeContextSnapshot } from "../contracts/runtime-context.js";
async function assertSafeTree(root: string, child = ""): Promise<void> {
const directory = child ? join(root, child) : root;
const directoryStat = await lstat(directory);
if (directoryStat.isSymbolicLink()) {
throw new Error(
`runtime context asset contains a symlink: ${child || "."}`,
);
}
if (!directoryStat.isDirectory()) {
throw new Error("runtime context asset root must be a directory");
}
for (const entry of await readdir(directory, { withFileTypes: true })) {
const childRelative = child ? `${child}/${entry.name}` : entry.name;
const stat = await lstat(join(root, childRelative));
if (stat.isSymbolicLink()) {
throw new Error(
`runtime context asset contains a symlink: ${childRelative}`,
);
}
if (stat.isDirectory()) await assertSafeTree(root, childRelative);
else if (!stat.isFile()) {
throw new Error(
`runtime context asset contains an unsupported file: ${childRelative}`,
);
}
}
}
function safeMaterializationTarget(root: string, runtimeName: string): string {
const segments = runtimeName.split("/");
if (
runtimeName.startsWith("/")
|| runtimeName.includes("\\")
|| runtimeName.includes("\0")
|| segments.some((segment) => /[<>:"|?*\u0000-\u001f\u007f]/u.test(segment))
|| segments.some((segment) => !segment || segment === "." || segment === "..")
|| segments.some((segment) => !segment.replace(/[ .]+$/u, ""))
|| segments.some(isWin32ReservedPathSegment)
) {
throw new Error("runtime context skill name must be a safe relative path");
}
const target = resolve(root, runtimeName);
const relation = relative(resolve(root), target);
if (
relation === ""
|| relation === ".."
|| relation.startsWith(`..${sep}`)
|| isAbsolute(relation)
) {
throw new Error("runtime context skill name must stay inside the skills home");
}
return target;
}
function isWin32ReservedPathSegment(segment: string): boolean {
const basename = segment
.normalize("NFC")
.split(".", 1)[0]!
.replace(/[ .]+$/u, "")
.toUpperCase();
return /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9¹²³]|LPT[1-9¹²³])$/u.test(
basename,
);
}
function portableRuntimeNameKey(runtimeName: string): string {
// Skill assignments must remain unambiguous when the same context is moved
// between the case-sensitive Linux runner and the case-insensitive default
// filesystems on macOS or Windows. NFC also catches composed/decomposed
// aliases, while per-segment trimming matches Win32's treatment of trailing
// dots and spaces before either spelling reaches the staging tree.
return runtimeName
.normalize("NFC")
.split("/")
.map((segment) => segment.replace(/[ .]+$/u, ""))
.join("/")
.toLowerCase();
}
async function protectStagedTree(root: string): Promise<void> {
const rootHandle = await open(
root,
constants.O_RDONLY
| (constants.O_NOFOLLOW ?? 0)
| (constants.O_DIRECTORY ?? 0),
);
try {
const opened = await rootHandle.stat();
if (!opened.isDirectory()) {
throw new Error("staged runtime context root must be a directory");
}
for (const entry of await readdir(root, { withFileTypes: true })) {
const child = join(root, entry.name);
if (entry.isDirectory()) {
await protectStagedTree(child);
continue;
}
const childHandle = await open(
child,
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
);
try {
const openedChild = await childHandle.stat();
if (!openedChild.isFile()) {
throw new Error("staged runtime context asset must be a regular file");
}
await childHandle.chmod(openedChild.mode & 0o555);
} finally {
await childHandle.close();
}
}
// Seal directories only after their descendants. Traversal needs execute
// permission, but provider processes must not be able to rewrite assigned
// skills after the immutable snapshot has been published.
await rootHandle.chmod(0o555);
} finally {
await rootHandle.close();
}
}
async function unprotectMaterializedTree(root: string): Promise<void> {
const rootHandle = await open(
root,
constants.O_RDONLY
| (constants.O_NOFOLLOW ?? 0)
| (constants.O_DIRECTORY ?? 0),
);
try {
const opened = await rootHandle.stat();
if (!opened.isDirectory()) {
throw new Error("materialized runtime context root must be a directory");
}
// Restore directory mutation before descending so every child can be
// unlinked. Handles plus O_NOFOLLOW keep cleanup inside the sealed tree.
await rootHandle.chmod(0o700);
for (const entry of await readdir(root, { withFileTypes: true })) {
const child = join(root, entry.name);
if (entry.isDirectory()) {
await unprotectMaterializedTree(child);
continue;
}
const childHandle = await open(
child,
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
);
try {
const openedChild = await childHandle.stat();
if (!openedChild.isFile()) {
throw new Error("materialized runtime context asset must be a regular file");
}
await childHandle.chmod(0o600);
} finally {
await childHandle.close();
}
}
} finally {
await rootHandle.close();
}
}
async function removeMaterializedTree(
skillsHome: string,
removeTree: (path: string) => Promise<void>,
): Promise<void> {
const exists = await lstat(skillsHome).then(
() => true,
(error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return false;
throw error;
},
);
if (!exists) return;
await unprotectMaterializedTree(skillsHome);
await removeTree(skillsHome);
}
/** Removes a previously sealed skills snapshot at an explicit lifecycle boundary. */
export async function releaseMaterializedNativeRuntimeSkills(
skillsHome: string,
): Promise<void> {
await removeMaterializedTree(
skillsHome,
(path) => rm(path, { recursive: true, force: true }),
);
}
export async function materializeNativeRuntimeSkills(
context: NativeRuntimeContextSnapshot | null,
skillsHome: string,
dependencies: {
/** Internal test seam for failed staging cleanup coverage. */
removeTree?: (path: string) => Promise<void>;
/** Internal test seam for publication failure coverage. */
renameTree?: (source: string, destination: string) => Promise<void>;
} = {},
): Promise<void> {
const removeTree =
dependencies.removeTree ??
((path: string) => rm(path, { recursive: true, force: true }));
const renameTree = dependencies.renameTree ?? rename;
if (context) {
const runtimeNames = new Set<string>();
for (const skill of context.skills) {
safeMaterializationTarget(skillsHome, skill.runtimeName);
const runtimeName = portableRuntimeNameKey(skill.runtimeName);
if (runtimeNames.has(runtimeName)) {
throw new Error("runtime context skill names must not overlap");
}
runtimeNames.add(runtimeName);
}
for (const runtimeName of runtimeNames) {
const segments = runtimeName.split("/");
for (let length = 1; length < segments.length; length += 1) {
if (runtimeNames.has(segments.slice(0, length).join("/"))) {
throw new Error("runtime context skill names must not overlap");
}
}
}
for (const skill of context.skills) {
await assertSafeTree(skill.bundle.rootPath);
}
}
const skillsHomeExists = await lstat(skillsHome).then(
() => true,
(error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return false;
throw error;
},
);
if (skillsHomeExists) {
throw new Error(
"runtime context skills home must be a fresh destination",
);
}
const parent = dirname(skillsHome);
const nonce = randomUUID();
const stagingHome = join(parent, `.paperclip-skills-staging-${nonce}`);
await mkdir(parent, { recursive: true, mode: 0o700 });
await chmod(parent, 0o700);
await mkdir(stagingHome, { mode: 0o700 });
try {
for (const skill of context?.skills ?? []) {
const target = safeMaterializationTarget(stagingHome, skill.runtimeName);
await cp(skill.bundle.rootPath, target, {
recursive: true,
force: false,
errorOnExist: true,
dereference: false,
verbatimSymlinks: true,
});
await assertSafeTree(target);
await protectStagedTree(target);
}
// The caller supplies a new isolated home for each provider launch. Never
// move an existing assignment out of its canonical path: a failed bounded
// rollback cannot portably guarantee that name is restored on every
// filesystem. Publication therefore targets only a fresh destination.
await renameTree(stagingHome, skillsHome);
} catch (error) {
// Cleanup is best effort and must not replace the publication failure that
// explains why no runtime snapshot was installed.
await removeMaterializedTree(stagingHome, removeTree).catch(() => undefined);
throw error;
}
}
async function readSourceCodexAuth(sourceAuth: string): Promise<Buffer | null> {
const handle = await open(
sourceAuth,
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT" || error.code === "ELOOP") return null;
throw error;
});
if (!handle) return null;
try {
const stat = await handle.stat();
if (!stat.isFile()) return null;
if (stat.size > 1024 * 1024) {
throw new Error("source Codex auth file exceeds the 1 MiB limit");
}
return await handle.readFile();
} finally {
await handle.close();
}
}
/** Copy only Paperclip's value-free provider projection, never host tools or hooks. */
async function managedCodexProviderConfig(sourceHome?: string | null): Promise<string> {
if (!sourceHome?.trim()) return "";
const source = await readSourceCodexAuth(join(sourceHome, "config.toml"));
if (!source) return "";
let parsed;
try { parsed = parseToml(source.toString("utf8")); } catch { return ""; }
if (parsed.model_provider !== "paperclip") return "";
const providers = parsed.model_providers as Record<string, unknown> | undefined;
const provider = providers?.paperclip as Record<string, unknown> | undefined;
if (!provider || typeof provider.base_url !== "string" || provider.wire_api !== "responses"
|| provider.requires_openai_auth !== false
|| (provider.env_key !== undefined && provider.env_key !== "PAPERCLIP_AI_PROVIDER_KEY")) {
throw new Error("Invalid managed Codex provider configuration");
}
const url = new URL(provider.base_url);
if (url.username || url.password || url.search || url.hash
|| (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) {
throw new Error("Invalid managed Codex provider URL");
}
return `model_provider = "paperclip"\n[model_providers.paperclip]\nname = "Paperclip connection"\nbase_url = ${JSON.stringify(provider.base_url)}\nwire_api = "responses"\nrequires_openai_auth = false\n${provider.env_key ? 'env_key = "PAPERCLIP_AI_PROVIDER_KEY"\n' : ""}${isOpenRouterUrl(provider.base_url) ? openRouterCodexHeaders() : ""}`;
}
export async function prepareIsolatedCodexHome(input: {
observability?: import("./agent-observability.js").ProviderObservabilityLaunch;
context: NativeRuntimeContextSnapshot | null;
codexHome: string;
sourceCodexHome?: string | null;
apiKey?: string | null;
}): Promise<void> {
await materializeNativeRuntimeSkills(
input.context,
join(input.codexHome, "skills"),
);
const providerConfig = await managedCodexProviderConfig(input.sourceCodexHome);
await writeIsolatedCodexConfig(input, providerConfig);
await writeIsolatedCodexAuth(input, providerConfig);
}
async function writeIsolatedCodexConfig(input: CodexAuthInput, providerConfig: string): Promise<void> {
const configPath = join(input.codexHome, "config.toml");
await mkdir(input.codexHome, { recursive: true, mode: 0o700 });
await chmod(input.codexHome, 0o700);
const temporaryConfig = join(input.codexHome, `.config-${randomUUID()}.tmp`);
try {
await writeFile(temporaryConfig, [
'cli_auth_credentials_store = "file"',
providerConfig,
codexObservabilityToml(input.observability?.otelConfig),
// Codex shell snapshots serialize the provider process environment. The
// native runner injects short-lived provider and MCP bindings, so a
// snapshot would turn ephemeral credentials into durable session state.
"[features]",
"shell_snapshot = false",
"",
].join("\n"), { mode: 0o600, flag: "wx" });
await rename(temporaryConfig, configPath);
await chmod(configPath, 0o600);
} finally { await rm(temporaryConfig, { force: true }); }
}
type CodexAuthInput = {
codexHome: string;
sourceCodexHome?: string | null;
apiKey?: string | null;
observability?: import("./agent-observability.js").ProviderObservabilityLaunch;
};
export async function prepareIsolatedCodexRecoveryHome(input: CodexAuthInput): Promise<void> {
const providerConfig = await managedCodexProviderConfig(input.sourceCodexHome);
await writeIsolatedCodexConfig(input, providerConfig);
await writeIsolatedCodexAuth(input, providerConfig);
}
async function writeIsolatedCodexAuth(input: CodexAuthInput, providerConfig: string): Promise<void> {
await mkdir(input.codexHome, { recursive: true, mode: 0o700 });
const targetAuth = join(input.codexHome, "auth.json");
await rm(targetAuth, { force: true });
if (providerConfig) return;
const apiKey = input.apiKey?.trim();
if (apiKey) {
// The pinned Codex app-server authenticates API-key automation through its
// login cache rather than the CLI-only CODEX_API_KEY path. Keep this file
// owner-only in the disposable session home.
await writeFile(
targetAuth,
JSON.stringify({ OPENAI_API_KEY: apiKey }),
{ mode: 0o600 },
);
await chmod(targetAuth, 0o600);
return;
}
const sourceHome = input.sourceCodexHome?.trim();
if (!sourceHome) return;
const sourceAuth = await readSourceCodexAuth(join(sourceHome, "auth.json"));
if (!sourceAuth) return;
await writeFile(targetAuth, sourceAuth, { mode: 0o600 });
await chmod(targetAuth, 0o600);
}