diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 35fcb16bc1a..e9d2c94b9fa 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -548,6 +548,15 @@ Activity-only reorderings wait for one second without further activity changes; new and removed tasks appear immediately. Titles, status, and live indicators stay current during that delay. +### OpenCode native runtime + +Paperclip Runner resolves the pinned OpenCode platform package installed with +Paperclip. On Apple Silicon and Intel Macs it runs the matching macOS binary; +on Linux x64 it runs the qualified baseline binary. No global OpenCode command +or dependency postinstall script is required. This also works when installation +scripts are disabled. The published server declares the same pinned dependency +as the source Runner package. + ## One-Command Local Run For a first-time local install, you can bootstrap and run in one command: diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-command.test.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-command.test.ts new file mode 100644 index 00000000000..d5db904c632 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-command.test.ts @@ -0,0 +1,60 @@ +import { chmod, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { afterEach, expect, it } from "vitest"; +import { resolvePinnedOpenCodeCommand } from "./opencode-server-driver.js"; + +const roots: string[] = []; +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); + +async function installed(layout: "source" | "standalone" | "vendored", platform: string, architecture: string, name: string) { + const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-opencode-install-"))); + roots.push(root); + const issuer = join(root, layout === "vendored" ? "dist/vendor/paperclip-runner/drivers/opencode/driver.js" + : layout === "source" ? "src/drivers/opencode/driver.ts" : "dist/drivers/opencode/driver.js"); + const wrapper = join(root, "node_modules/opencode-ai"); + const artifact = join(root, "node_modules", name); + const executable = join(artifact, "bin/opencode"); + await mkdir(dirname(issuer), { recursive: true }); + await mkdir(join(wrapper, "bin"), { recursive: true }); + await mkdir(dirname(executable), { recursive: true }); + await writeFile(join(wrapper, "package.json"), JSON.stringify({ name: "opencode-ai", version: "1.18.34", optionalDependencies: { [name]: "1.18.34" } })); + const placeholder = 'echo "postinstall was not run" >&2\nexit 1\n'; + await writeFile(join(wrapper, "bin/opencode.exe"), placeholder, { mode: 0o755 }); + await writeFile(join(artifact, "package.json"), JSON.stringify({ name, version: "1.18.34", os: [platform], cpu: [architecture] })); + await writeFile(executable, "#!/bin/sh\necho 1.18.34\n", { mode: 0o755 }); + return { issuer: pathToFileURL(issuer), wrapper, artifact, executable, root, placeholder }; +} + +it.each(["source", "standalone", "vendored"] as const)("resolves the platform binary in a %s install with postinstall skipped", async layout => { + for (const [platform, architecture, name] of [ + ["darwin", "arm64", "opencode-darwin-arm64"], + ["darwin", "x64", "opencode-darwin-x64-baseline"], + ["linux", "x64", "opencode-linux-x64-baseline"], + ] as const) { + const install = await installed(layout, platform, architecture, name); + expect(resolvePinnedOpenCodeCommand(install.issuer, { platform, architecture })).toBe(install.executable); + expect(await readFile(join(install.wrapper, "bin/opencode.exe"), "utf8")).toBe(install.placeholder); + } +}); + +it("rejects missing or mismatched qualified dependencies", async () => { + const install = await installed("vendored", "darwin", "arm64", "opencode-darwin-arm64"); + await writeFile(join(install.artifact, "package.json"), JSON.stringify({ name: "opencode-darwin-arm64", version: "1.18.17", os: ["darwin"], cpu: ["arm64"] })); + expect(() => resolvePinnedOpenCodeCommand(install.issuer, { platform: "darwin", architecture: "arm64" })).toThrow("identity mismatch"); + await rm(install.artifact, { recursive: true }); + expect(() => resolvePinnedOpenCodeCommand(install.issuer, { platform: "darwin", architecture: "arm64" })).toThrow("qualified platform dependency is missing"); + expect(() => resolvePinnedOpenCodeCommand(install.issuer, { platform: "win32", architecture: "x64" })).toThrow("not qualified"); +}); + +it("rejects executables outside the platform package or without execute permission", async () => { + const install = await installed("source", "darwin", "arm64", "opencode-darwin-arm64"); + await chmod(install.executable, 0o644); + expect(() => resolvePinnedOpenCodeCommand(install.issuer, { platform: "darwin", architecture: "arm64" })).toThrow("Pinned OpenCode runtime unavailable"); + await rm(install.executable); + const outside = join(install.root, "outside"); + await writeFile(outside, "#!/bin/sh\n", { mode: 0o755 }); + await symlink(outside, install.executable); + expect(() => resolvePinnedOpenCodeCommand(install.issuer, { platform: "darwin", architecture: "arm64" })).toThrow("escapes its qualified platform package"); +}); 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 fa95ea19b4d..81abbfd3f06 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -1,5 +1,7 @@ import { spawn, type ChildProcess } from "node:child_process"; import { randomBytes } from "node:crypto"; +import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs"; +import { createRequire } from "node:module"; import { chmod, mkdir, @@ -15,7 +17,7 @@ import { Agent as HttpAgent, createServer as createHttpServer, request as reques import { Agent as HttpsAgent, request as requestHttps } from "node:https"; import { getCACertificates } from "node:tls"; import { pipeline } from "node:stream/promises"; -import { dirname, join, resolve } from "node:path"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { CODEX_SKILLLESS_BASE_INSTRUCTIONS, @@ -83,6 +85,69 @@ export const QUALIFIED_OPENCODE_VERSION = "1.18.34" as const; export const QUALIFIED_OPENCODE_MODEL = "openrouter/deepseek/deepseek-v4-flash-0731" as const; +/** Resolve a declared, pinned native dependency without PATH or install fallback. */ +export function resolvePinnedOpenCodeCommand( + issuer: string | URL = import.meta.url, + target: { platform?: string; architecture?: string } = {}, +): string { + try { + const platform = target.platform ?? process.platform; + const architecture = target.architecture ?? process.arch; + const packageNames: Record = { + "linux-x64": ["opencode-linux-x64-baseline"], + "darwin-arm64": ["opencode-darwin-arm64"], + "darwin-x64": ["opencode-darwin-x64-baseline"], + }; + const candidates = packageNames[`${platform}-${architecture}`]; + if (!candidates) { + throw new Error("OpenCode native target is not qualified"); + } + const manifestPath = realpathSync(createRequire(issuer).resolve("opencode-ai/package.json")); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + if (manifest.name !== "opencode-ai" || manifest.version !== QUALIFIED_OPENCODE_VERSION) { + throw new Error(`OpenCode package version mismatch: expected opencode-ai@${QUALIFIED_OPENCODE_VERSION}`); + } + const dependencyRequire = createRequire(manifestPath); + for (const name of candidates) { + if (manifest.optionalDependencies?.[name] !== QUALIFIED_OPENCODE_VERSION) { + throw new Error("OpenCode platform dependency does not match its qualified version"); + } + let platformManifest: string; + try { + platformManifest = realpathSync(dependencyRequire.resolve(`${name}/package.json`)); + } catch (error) { + if (["MODULE_NOT_FOUND", "ENOENT"].includes((error as NodeJS.ErrnoException).code ?? "")) { + continue; + } + throw error; + } + const metadata = JSON.parse(readFileSync(platformManifest, "utf8")); + if (metadata.name !== name || metadata.version !== QUALIFIED_OPENCODE_VERSION + || !Array.isArray(metadata.os) || !metadata.os.includes(platform) + || !Array.isArray(metadata.cpu) || !metadata.cpu.includes(architecture)) { + throw new Error("OpenCode installed platform artifact identity mismatch"); + } + const root = dirname(platformManifest); + const executable = realpathSync(resolve(root, "bin/opencode")); + const inside = relative(root, executable); + if (!inside || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) { + throw new Error("OpenCode executable escapes its qualified platform package"); + } + if (!statSync(executable).isFile()) { + throw new Error("OpenCode executable is not a regular file"); + } + accessSync(executable, constants.X_OK); + return executable; + } + throw new Error("OpenCode qualified platform dependency is missing"); + } catch (error) { + throw new Error( + `Pinned OpenCode runtime unavailable: ${(error as Error).message}. Restore Paperclip's runtime dependencies.`, + { cause: error }, + ); + } +} + type DynamicToolHandler = (call: { tool: string; callId: string; @@ -2255,7 +2320,7 @@ async function startRuntime(input: { } input.options.commandLifecycle?.beforeSpawn(); child = spawn( - input.options.command ?? "opencode", + input.options.command ?? resolvePinnedOpenCodeCommand(), ["serve", "--hostname", "127.0.0.1", "--port", String(port)], { cwd: input.cwd, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index d8fed91521b..fd3c6da2148 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -1587,6 +1587,15 @@ it.each(["acpx-runtime-sidecar.cjs", "opencode-app-server-proxy.cjs"] as const)( }, ); +it("requires a remote OpenCode executable before resolving controller dependencies", () => { + expect(() => runnerdLaunchProfileInternals.resolveRunnerOpenCodeExecutable({ + runnerFilesystemRoot: "/provider-pack", + })).toThrow("OpenCode executable is missing from the provider pack"); + expect(runnerdLaunchProfileInternals.resolveRunnerOpenCodeExecutable({ + runnerFilesystemRoot: "/provider-pack", opencodeCommand: "/provider-pack/opencode", + })).toBe("/provider-pack/opencode"); +}); + it("derives the ACPX package authority only from the verified dist/cli layout", () => { const runnerPackageRoot = fileURLToPath(new URL("../..", import.meta.url)); expect( diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 4290d68d90b..08a8886f3b9 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1,3 +1,4 @@ +import { resolvePinnedOpenCodeCommand } from "../drivers/opencode/opencode-server-driver.js"; import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js"; import { admittedPiThinkingLevel, resolvePiThinkingLevel } from "../drivers/acpx/pi-thinking.js"; import { configuredEnvironment } from "../configured-environment.js"; @@ -3182,6 +3183,14 @@ function opencodeRunnerLaunchProfile( }; } +function resolveRunnerOpenCodeExecutable(options: RunnerdCodexTransportOptions): string { + if (options.opencodeCommand !== undefined) return options.opencodeCommand; + if (options.runnerFilesystemRoot) { + throw new Error("runner_remote_provider_artifact_incompatible: OpenCode executable is missing from the provider pack"); + } + return resolvePinnedOpenCodeCommand(); +} + function authorizedToolSet( tools: readonly Readonly>[], ): Record { @@ -4731,8 +4740,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { : undefined; const opencodeExecutable = provider === "opencode" - ? (this.options.opencodeCommand ?? - resolve(packageRoot, "node_modules/opencode-ai/bin/opencode.exe")) + ? resolveRunnerOpenCodeExecutable(this.options) : null; const runnerAcpxLaunchProfile = provider === "acpx" @@ -4757,9 +4765,9 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ) { const providerPaths = [ ["provider Node", providerNodeCommand], - ["OpenCode proxy", opencodeProxyPath], - ["ACPX sidecar", acpxSidecarPath], - ["OpenCode executable", opencodeExecutable ?? "opencode"], + ...(provider === "opencode" + ? [["OpenCode proxy", opencodeProxyPath], ["OpenCode executable", opencodeExecutable!]] as const + : [["ACPX sidecar", acpxSidecarPath]] as const), ] as const; for (const [label, candidate] of providerPaths) { if ( @@ -5358,8 +5366,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.options.providerNodeCommand ?? process.execPath; const opencodeExecutable = provider === "opencode" - ? (this.options.opencodeCommand ?? - resolve(packageRoot, "node_modules/opencode-ai/bin/opencode.exe")) + ? resolveRunnerOpenCodeExecutable(this.options) : null; const runnerAcpxLaunchProfile = provider === "acpx" @@ -7040,6 +7047,7 @@ export const runnerdLaunchProfileInternals = Object.freeze({ acpxProviderPackageAuthority, acpxRunnerLaunchProfile, resolveBuildOwnedCliArtifact, + resolveRunnerOpenCodeExecutable, maxOutboxBytes: RUNNERD_MAX_OUTBOX_BYTES, p0ReserveBytes: RUNNERD_P0_RESERVE_BYTES, }); diff --git a/server/package.json b/server/package.json index b0fa25129fe..3b1a969073f 100644 --- a/server/package.json +++ b/server/package.json @@ -97,6 +97,7 @@ "nice-grpc": "2.1.17", "nice-grpc-common": "2.0.4", "open": "^11.0.4", + "opencode-ai": "1.18.34", "pino": "^10.0.0", "pino-http": "^11.0.0", "pino-pretty": "^13.1.3", diff --git a/server/src/__tests__/server-package-build-script.test.ts b/server/src/__tests__/server-package-build-script.test.ts index 83b9ea8fa4c..64cbbf17ab2 100644 --- a/server/src/__tests__/server-package-build-script.test.ts +++ b/server/src/__tests__/server-package-build-script.test.ts @@ -103,6 +103,16 @@ describe("server package build script", () => { ); }); + it("ships the pinned OpenCode dependency resolved by the vendored Runner", () => { + const server = JSON.parse(readFileSync(packageJsonPath, "utf8")); + const runner = JSON.parse(readFileSync(new URL( + "../../../packages/paperclip-runner/package.json", import.meta.url, + ), "utf8")); + // createRequire resolution is dynamic and is not covered by the import scan. + expect(server.dependencies["opencode-ai"]).toBe("1.18.34"); + expect(server.dependencies["opencode-ai"]).toBe(runner.dependencies["opencode-ai"]); + }); + it("loads runner source when the source server starts before workspace builds", () => { const shim = readFileSync(runnerShimPath, "utf8");