diff --git a/packages/paperclip-runner/scripts/qualify-opencode-runtime.test.mjs b/packages/paperclip-runner/scripts/qualify-opencode-runtime.test.mjs index 90434353727..aa6cddda0ff 100644 --- a/packages/paperclip-runner/scripts/qualify-opencode-runtime.test.mjs +++ b/packages/paperclip-runner/scripts/qualify-opencode-runtime.test.mjs @@ -154,6 +154,7 @@ for (const custody of [false, true]) { timeout: 90_000, }, async (t) => { const { prepareOpenCodeOutputCustody } = await import("../dist/drivers/opencode/output-custody.js"); + const { markOpenCodeConfigDependenciesInstalled } = await import("../dist/drivers/opencode/config-dependencies.js"); const secret = `synthetic-qualification-secret-${Date.now().toString(36)}`; const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-custody-")); const workspace = join(root, "workspace"); @@ -189,6 +190,9 @@ for (const custody of [false, true]) { await once(provider, "listening"); const configHome = join(root, "config"); await mkdir(join(configHome, "opencode"), { recursive: true }); + // As every Runner launch does: without this, OpenCode installs its plugin + // package with npm inside `opencode serve` and stops answering requests. + await markOpenCodeConfigDependenciesInstalled(join(configHome, "opencode")); const env = { PATH: `${dirname(process.execPath)}:${process.env.PATH ?? "/usr/bin:/bin"}`, HOME: root, XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: join(root, "data"), XDG_CACHE_HOME: join(root, "cache"), @@ -203,7 +207,7 @@ for (const custody of [false, true]) { }; if (custody) { const prepared = await prepareOpenCodeOutputCustody({ directory: join(root, "custody"), binDirectory: join(root, "bin"), - configDirectory: join(configHome, "opencode"), environment: env, secrets: [{ name: "QUALIFY_SECRET", value: secret }] }); + environment: env, secrets: [{ name: "QUALIFY_SECRET", value: secret }] }); Object.assign(config, prepared.config); Object.assign(env, prepared.environment); } diff --git a/packages/paperclip-runner/src/drivers/opencode/config-dependencies.test.ts b/packages/paperclip-runner/src/drivers/opencode/config-dependencies.test.ts new file mode 100644 index 00000000000..98768153ad4 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/config-dependencies.test.ts @@ -0,0 +1,73 @@ +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { markOpenCodeConfigDependenciesInstalled, OPENCODE_CONFIG_DEPENDENCY } from "./config-dependencies.js"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function configDirectory() { + const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-config-")); + roots.push(root); + return root; +} + +// OpenCode reads a missing or unreadable file as an empty object. +const readJson = async (path: string): Promise> => { + try { return JSON.parse(await readFile(path, "utf8")); } catch { return {}; } +}; + +/** + * OpenCode 1.18.34's `Npm.install` decision for a config directory, which it + * calls with `add: ["@opencode-ai/plugin"]` on every project bootstrap. True + * means OpenCode runs npm's Arborist inside `opencode serve`. + */ +async function openCodeWouldInstallConfigDependencies(directory: string): Promise { + const exists = await stat(join(directory, "node_modules")).then(() => true, () => false); + if (!exists) return true; + const fields = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + const manifest = await readJson(join(directory, "package.json")); + const root = (await readJson(join(directory, "package-lock.json"))).packages?.[""] ?? {}; + const wanted = new Set([...fields.flatMap((field) => Object.keys(manifest[field] ?? {})), OPENCODE_CONFIG_DEPENDENCY]); + const locked = new Set(fields.flatMap((field) => Object.keys(root[field] ?? {}))); + return [...wanted].some((name) => !locked.has(name)); +} + +describe("OpenCode config dependencies", () => { + it("stops OpenCode from installing its plugin package into a fresh config directory", async () => { + const directory = await configDirectory(); + expect(await openCodeWouldInstallConfigDependencies(directory)).toBe(true); + + await markOpenCodeConfigDependenciesInstalled(directory); + + expect(await openCodeWouldInstallConfigDependencies(directory)).toBe(false); + expect((await stat(join(directory, "package-lock.json"))).mode & 0o777).toBe(0o600); + }); + + it("is repeatable and keeps a lock that a completed install already wrote", async () => { + const directory = await configDirectory(); + await mkdir(join(directory, "node_modules")); + const installed = `${JSON.stringify({ name: "opencode", lockfileVersion: 3, packages: { "": { dependencies: { [OPENCODE_CONFIG_DEPENDENCY]: "1.18.34" } } } }, null, 2)}\n`; + await writeFile(join(directory, "package-lock.json"), installed); + + await markOpenCodeConfigDependenciesInstalled(directory); + await markOpenCodeConfigDependenciesInstalled(directory); + + expect(await readFile(join(directory, "package-lock.json"), "utf8")).toBe(installed); + expect(await openCodeWouldInstallConfigDependencies(directory)).toBe(false); + }); + + it("replaces a lock that would still make OpenCode install, such as one left by an interrupted install", async () => { + const directory = await configDirectory(); + await mkdir(join(directory, "node_modules")); + await writeFile(join(directory, "package-lock.json"), "{\"lockfileVersion\":3,\"packages\":{\"\":{}}}"); + expect(await openCodeWouldInstallConfigDependencies(directory)).toBe(true); + + await markOpenCodeConfigDependenciesInstalled(directory); + + expect(await openCodeWouldInstallConfigDependencies(directory)).toBe(false); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/opencode/config-dependencies.ts b/packages/paperclip-runner/src/drivers/opencode/config-dependencies.ts new file mode 100644 index 00000000000..a1399358f35 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/config-dependencies.ts @@ -0,0 +1,46 @@ +import { randomBytes } from "node:crypto"; +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +/** + * When OpenCode bootstraps a project it installs `@opencode-ai/plugin` into + * its global config directory, even when no plugin is configured. OpenCode + * 1.18 runs that install with npm's Arborist inside the `opencode serve` + * process: it downloads about 100 MB of packages into a fresh npm cache and + * keeps OpenCode's event loop busy while it allocates. OpenCode then stops + * answering, and a sandbox with an 8 GiB limit can reach it within a minute. + * + * OpenCode skips the install when the directory has `node_modules` and a + * `package-lock.json` whose root entry lists every dependency it would add. + * The runner pins OpenCode and loads only local plugin files, which import + * nothing from that package, so the dependency is recorded as installed. + */ +export const OPENCODE_CONFIG_DEPENDENCY = "@opencode-ai/plugin"; + +const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"] as const; + +function listsDependency(lock: unknown): boolean { + if (!lock || typeof lock !== "object") return false; + const root = (lock as { packages?: Record }).packages?.[""]; + if (!root || typeof root !== "object") return false; + return DEPENDENCY_FIELDS.some((field) => { + const dependencies = (root as Record)[field]; + return Boolean(dependencies && typeof dependencies === "object" && OPENCODE_CONFIG_DEPENDENCY in dependencies); + }); +} + +/** Record OpenCode's config dependency as installed so OpenCode does not install it at startup. */ +export async function markOpenCodeConfigDependenciesInstalled(configDirectory: string): Promise { + await mkdir(join(configDirectory, "node_modules"), { recursive: true, mode: 0o700 }); + const lockPath = join(configDirectory, "package-lock.json"); + const existing = await readFile(lockPath, "utf8").then( + (text) => { try { return JSON.parse(text) as unknown; } catch { return null; } }, + (error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; }, + ); + // Keep a lock that already satisfies OpenCode, including one a completed install wrote. + if (listsDependency(existing)) return; + const lock = { lockfileVersion: 3, packages: { "": { dependencies: { [OPENCODE_CONFIG_DEPENDENCY]: "*" } } } }; + const temporary = `${lockPath}.${process.pid}.${randomBytes(6).toString("hex")}`; + await writeFile(temporary, `${JSON.stringify(lock)}\n`, { mode: 0o600 }); + await rename(temporary, lockPath); +} diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts index 759441e366f..9e22a1cec43 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts @@ -481,6 +481,27 @@ describe("OpenCodeServerDriver", () => { } }); + it("records OpenCode's plugin package as installed so OpenCode does not run npm at startup", async () => { + await chmod(fixture, 0o755); + const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-config-dependencies-")); + roots.push(root); + // No configured secret: output custody stays off, as for most agents. + const driver = new OpenCodeServerDriver({ + model: "openrouter/test-model", command: fixture, runtimeDirectory: root, environment: { PATH: process.env.PATH }, + }); + const session = await driver.openSession({ runId: "dependencies", normalizedSessionId: "dependencies", workingDirectory: root }); + try { + const configDirectory = join(root, "dependencies", "config", "opencode"); + const config = JSON.parse(await readFile(join(configDirectory, "opencode.json"), "utf8")); + expect(config.plugin).toEqual([]); + expect((await stat(join(configDirectory, "node_modules"))).isDirectory()).toBe(true); + const lock = JSON.parse(await readFile(join(configDirectory, "package-lock.json"), "utf8")); + expect(lock.packages[""].dependencies).toHaveProperty("@opencode-ai/plugin"); + } finally { + await session.close({ reason: "test" }); + } + }); + it("protects configured secrets in OpenCode output across controller and runner cutovers in one saved session", async () => { await chmod(fixture, 0o755); const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-output-custody-")); diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts index 3e29f425557..7155c666901 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -47,6 +47,7 @@ import { githubCredentialEnvironment } from "../../github-credential-environment import { configuredOpenCodeEnvironment } from "./environment.js"; import { CONFIGURED_ENVIRONMENT_KEYS, SECRET_ENVIRONMENT_KEYS, configuredSecretEnvironment } from "../../configured-environment.js"; import { prepareOpenCodeOutputCustody, redactOpenCodeModelRequest } from "./output-custody.js"; +import { markOpenCodeConfigDependenciesInstalled } from "./config-dependencies.js"; import { CODEX_SKILLLESS_BASE_INSTRUCTIONS, @@ -2728,6 +2729,9 @@ async function startRuntime(input: { mkdir(dataHome, { recursive: true, mode: 0o700 }), mkdir(cacheHome, { recursive: true, mode: 0o700 }), ]); + // Without this, OpenCode installs its plugin package with npm inside + // `opencode serve` at startup, which can fill the sandbox's memory. + await markOpenCodeConfigDependenciesInstalled(join(configHome, "opencode")); // HOME contains a read-only skill snapshot, whose destination must be fresh. // Keep OpenCode's XDG data stable for provider-session recovery while giving // every launch (including retries and recovery) a new isolated HOME. @@ -2777,7 +2781,6 @@ async function startRuntime(input: { directory: join(isolatedHome, ".paperclip-output-custody"), // Shared by every session of this runtime so the wrapper is written once. binDirectory: join(resolve(input.options.runtimeDirectory), "output-custody"), - configDirectory: join(configHome, "opencode"), environment: sanitizedEnvironment(input.options.environment, {}), secrets: configuredSecretEnvironment(input.options.environment), }).catch(async error => { diff --git a/packages/paperclip-runner/src/drivers/opencode/output-custody.test.ts b/packages/paperclip-runner/src/drivers/opencode/output-custody.test.ts index f794b51675a..cc9851d1e91 100644 --- a/packages/paperclip-runner/src/drivers/opencode/output-custody.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/output-custody.test.ts @@ -30,7 +30,7 @@ async function prepared(secrets = [{ name: "PUBLISHING_API_KEY", value: SECRET } const environment = { PATH: process.env.PATH, PUBLISHING_API_KEY: SECRET, PLAIN_SETTING: PLAIN, MULTILINE_KEY: "-----BEGIN KEY-----\nline-one-material\nline-two-material\n-----END KEY-----" }; const custody = await prepareOpenCodeOutputCustody({ - directory: join(root, "launch"), binDirectory: join(root, "bin"), configDirectory: join(root, "config"), + directory: join(root, "launch"), binDirectory: join(root, "bin"), environment, secrets, }); return { root, environment, custody }; @@ -126,7 +126,7 @@ describe("OpenCode output custody", () => { it("keeps the executable wrapper byte-identical across launches", async () => { const first = await prepared(); const second = await prepareOpenCodeOutputCustody({ - directory: join(first.root, "launch-2"), binDirectory: join(first.root, "bin"), configDirectory: join(first.root, "config"), + directory: join(first.root, "launch-2"), binDirectory: join(first.root, "bin"), environment: first.environment, secrets: [{ name: "PUBLISHING_API_KEY", value: SECRET }], }); expect(second!.config.shell).toBe(first.custody!.config.shell); @@ -161,7 +161,7 @@ describe("secrets custody cannot protect", () => { const root = await mkdtemp(join(tmpdir(), "paperclip-output-custody-short-")); roots.push(root); await expect(prepareOpenCodeOutputCustody({ - directory: join(root, "launch"), binDirectory: join(root, "bin"), configDirectory: join(root, "config"), + directory: join(root, "launch"), binDirectory: join(root, "bin"), environment: { PATH: process.env.PATH, SHORT_SECRET: value }, secrets: [{ name: "SHORT_SECRET", value }], })).rejects.toMatchObject({ code: "opencode_output_custody_unavailable" }); }); diff --git a/packages/paperclip-runner/src/drivers/opencode/output-custody.ts b/packages/paperclip-runner/src/drivers/opencode/output-custody.ts index 42807c1c3e8..e17a201233a 100644 --- a/packages/paperclip-runner/src/drivers/opencode/output-custody.ts +++ b/packages/paperclip-runner/src/drivers/opencode/output-custody.ts @@ -267,14 +267,12 @@ async function writeStable(path: string, content: string, mode: number): Promise * Prepare output custody for one OpenCode launch, or return null when no * configured secret needs it. `directory` must be fresh for this launch; * `binDirectory` is stable across launches and holds the executable wrapper. - * `configDirectory` is OpenCode's global config directory: OpenCode waits for - * a dependency install there before it loads any plugin, so it is marked as - * already installed to keep that install off the first tool call. + * The launch records OpenCode's config dependency as installed before it + * starts OpenCode, so the plugin does not wait for an install. */ export async function prepareOpenCodeOutputCustody(input: { directory: string; binDirectory: string; - configDirectory: string; environment: NodeJS.ProcessEnv; secrets: ReadonlyArray<{ name: string; value: string }>; platform?: NodeJS.Platform; @@ -300,17 +298,11 @@ export async function prepareOpenCodeOutputCustody(input: { await Promise.all([ mkdir(bin, { recursive: true, mode: 0o700 }), mkdir(input.directory, { recursive: true, mode: 0o700 }), - mkdir(join(input.configDirectory, "node_modules"), { recursive: true, mode: 0o700 }), ]); await Promise.all([ writeStable(filter, OUTPUT_CUSTODY_AWK, 0o600), writeStable(shell, wrapperFor(filter), 0o700), writeFile(plugin, OUTPUT_CUSTODY_PLUGIN, { mode: 0o600 }), - writeFile( - join(input.configDirectory, "package-lock.json"), - `${JSON.stringify({ lockfileVersion: 3, packages: { "": { dependencies: { "@opencode-ai/plugin": "*" } } } })}\n`, - { mode: 0o600, flag: "wx" }, - ).catch((error: NodeJS.ErrnoException) => { if (error.code !== "EEXIST") throw error; }), ]); return { config: { shell, plugin: [`file://${plugin}`] },