Files
PaperClipAI/packages/paperclip-runner/src/drivers/runtime-context-materializer.ts
T
DottaandPaperclip 9f7057e122 feat(connections): configure custom model providers across agent harnesses (#14970)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use a harness, a model, and a credential to run tasks.
> - Connections already store credentials and control who can use them.
> - Custom providers also need an endpoint and a supported API format.
> - A per-agent endpoint would duplicate credentials and access rules.
> - This pull request stores routing on the connection and projects it
into the harness.
> - Isolated credentials and protocol checks keep the selected
connection authoritative.

## Linked Issues or Issue Description

Refs #37, #13083, #14104, #14565, #12692.

#14016 is a reference only. This PR has its own schema, vault
persistence, routing validation, runtime projection, and tests. None of
the five commits in #14016 is an ancestor of this branch. We do not
depend on or plan to merge it. #14967 addresses task-pinned account
pools. #14422 addresses another provider integration.

This is the first of two linked PRs. Merge this connection change before
#15341, which refines agent setup and adds the qualification harness.
The split keeps each review below 100 changed files. Provider catalog
entries have usable setup forms in this PR. Local browser subscription
sign-in is included.

## What Changed

- Store non-secret routing metadata on AI connections. Vault provider
API keys, including Bedrock bearer API keys. Reject general AWS access
keys.
- Enforce company, owner, human audience, agent access, connection
status, and protocol checks before resolving credentials. Keep reconnect
destinations immutable and retain connection identity during key
rotation.
- Project OpenRouter and compatible custom endpoints into Codex, Claude,
OpenCode, and local Hermes. Carry these settings through both legacy and
native runner transports. Clear conflicting host credentials and redact
keys from diagnostics.
- Preserve older OpenRouter accounts and native personal defaults. Add
Google API-key accounts and migration `0306` for the two
provider-default constraints.
- Run local Claude and Codex subscription sign-in behind the existing
browser sign-in card. Use private attempt homes and owner-bound
completion instead of a copied terminal command.
- Seed isolated Gemini authentication and preserve OpenCode workspace
permissions. Keep the selected connection authoritative. The independent
Gemini and Grok workflow fixes are in #15341.
- Keep native OpenCode custom gateway keys in a runner-owned
selected-model proxy; the harness config contains only a session-scoped
capability. Honor runtime outgoing proxy and certificate settings.
Preserve streamed responses and revoke the proxy on close or startup
failure.
- Allow ordinary members to connect native personal accounts before an
agent exists.
- Repair routed accounts from task cards using the saved provider
destination, protocol, model aliases, and connection identity.
- Add provider catalog definitions, model discovery, pinned logos, and
complete native and routed setup forms. Allow a personal routed
connection before a new agent exists. Keep endpoint authentication keys
out of Hermes terminal children.
- Recover cancelled or restarted browser sign-in with a clear restart
action. Support no-auth endpoints without a vault credential. Add
isolation and recovery regressions and runtime documentation.

## Verification

- Updated with `origin/master` at `22a3ea341`. Migration `0306` follows
the new master migration and passes migration and snapshot checks.
- The integrated connection regressions passed 152 tests and 50 native
OpenCode driver tests, including key-free child-shell configuration
reads, authenticated/no-auth forwarding, streaming, model/path
restrictions, cancellation, outgoing proxy routing, and NO_PROXY bypass.
Provider setup has 14 passing tests. The pinned real OpenCode 1.18.34
executable also completed a turn through the proxy against a local
synthetic provider; the reusable key was absent from its config. A
second real-executable smoke passed with an HTTPS CONNECT proxy and
runtime-specific synthetic certificate trust. Certificate-file and
certificate-directory regressions pass.
- Task-card repair passed 48 tests, including OpenRouter, Bedrock, and
custom gateway reconnect cases. UI typecheck and token gates passed.
- The prior core regression set passed 133 tests across new-agent setup,
provider forms, browser sign-in, routing projection, and connection
authorization. Token gates and UI typecheck passed.
- Full workspace typecheck and production build passed again after the
latest integration and credential-proxy fix. The merged deterministic
runner E2E suite passed 1,400 Vitest tests and 128 Node tests.
- Full workspace typecheck passed on the prior linked combined
implementation. Production build, Storybook build, 1,316 browser-harness
Vitest tests, and 128 Node tests passed. Head `9d964c8d9` includes the
latest master integration and regenerated migration. This exact head
passed 54 remote checks with four expected skips and Greptile 5/5; no
review threads remain open. An unchanged server fixture had a random
six-character issue-prefix collision on its first attempt. All 245 tests
passed locally and the single CI retry passed.
- A provider-free terminal check used the cited supported Hermes source
and dummy keys. Gateway and OpenRouter terminal children could not read
the selected key.
- The broad local Vitest attempt passed 15,442 tests but was not green.
It had an embedded-Postgres startup failure, an HTTP logger timeout, an
origin socket error, and a browser cancellation wait timeout. The
cancellation wait was corrected. The relevant connection tests and the
full origin test file passed separately. Latest-head CI must pass before
merge.
- Prior credential-backed acceptance exercised task creation, tool use,
artifact delivery, completion, and context-dependent follow-up. Claude
legacy and native runners passed Bedrock with `us-east-1` and
`us.anthropic.claude-sonnet-4-6`.
- Historical local qualification retained 43 passing API/gateway cells
out of 46. Those attempts span earlier builds. They do not qualify this
exact commit or staging. All subscription combinations and staging
remain unqualified.
- Verify native subscription and API-key setup. Connect a regular
provider catalog row. Verify an incompatible harness and a changed
reconnect URL are rejected. Use #15341 for the complete browser
campaign.

## Risks

- Migration `0306` changes two check constraints. It preserves rows and
is safe to reapply. It takes normal constraint-change locks.
- Credential projection touches several harnesses. CLI upgrades can
change provider configuration and session behavior.
- The native OpenCode proxy adds a loopback hop, pins requests to the
selected model, limits request bodies to 16 MiB, rejects redirects, and
expires at session close. It prevents reusable keys in the child
configuration; it is not an OS isolation boundary against a process
debugger running as the same user.
- Custom endpoints must be reachable from the agent environment. Saving
a connection does not prove connectivity. Bedrock keys require rotation
before expiry.
- Gemini CLI 0.58.0 has an upstream ACP new-file error conversion
defect. Provider overloads and an unresolved follow-up timeout also
affect live Gemini qualification. We have not patched the installed CLI
or marked those cases as passing.
- OpenClaw Gateway, Hermes Gateway, Claude Managed, AWS AgentCore,
Process, HTTP, and legacy ACPX local are excluded. Vertex, ambient AWS
identity, arbitrary auth headers, and custom routing for other harnesses
are excluded.
- These PRs do not establish production or staging qualification for
every provider and login method.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, repository tools, code
execution, and browser testing. The exact deployment model ID and
context window size were not exposed in this session.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-06 13:29:03 -05:00

394 lines
14 KiB
TypeScript

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 type { NativeRuntimeContextSnapshot } from "../contracts/runtime-context.js";
import type { NativeMcpLaunchBinding } from "./native-mcp.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' : ""}`;
}
export async function prepareIsolatedCodexHome(input: {
context: NativeRuntimeContextSnapshot | null;
codexHome: string;
sourceCodexHome?: string | null;
nativeMcp?: NativeMcpLaunchBinding | null;
apiKey?: string | null;
}): Promise<void> {
await materializeNativeRuntimeSkills(
input.context,
join(input.codexHome, "skills"),
);
const providerConfig = await managedCodexProviderConfig(input.sourceCodexHome);
const configPath = join(input.codexHome, "config.toml");
await rm(configPath, { force: true });
await writeFile(configPath, [
providerConfig,
// 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",
"",
...(input.nativeMcp
? [
`[mcp_servers.${JSON.stringify(input.nativeMcp.name)}]`,
`url = ${JSON.stringify(input.nativeMcp.url)}`,
// This endpoint is Paperclip's authenticated policy gateway, not an
// upstream server. It enforces connection grants and human approvals
// for every operation; the provider must deliver calls to that gate.
'default_tools_approval_mode = "approve"',
`http_headers = { Authorization = ${JSON.stringify(`Bearer ${input.nativeMcp.token}`)} }`,
"",
]
: []),
].join("\n"), { mode: 0o600 });
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);
}