From 5590c19fd601fc2df492dc301002b16a2aa095c5 Mon Sep 17 00:00:00 2001 From: cryppadotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:08:24 +0000 Subject: [PATCH] fix(opencode): proxy direct provider keys via runner loopback broker --- .../opencode/opencode-server-driver.test.ts | 420 ++++++++++--- .../opencode/opencode-server-driver.ts | 216 +------ .../src/drivers/opencode/provider-proxy.ts | 578 ++++++++++++++++++ .../runner-e2e/source-sdk-public-inputs.json | 6 +- 4 files changed, 949 insertions(+), 271 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts 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 bd45147c22e..f750c4216a6 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 @@ -38,6 +38,7 @@ import type { PrpEvent } from "../../protocol/replay-contract.js"; import { OpenCodeServerDriver, openCodeServerDriverInternals, + resolvePinnedOpenCodeCommand, } from "./opencode-server-driver.js"; const upstreamTransport = vi.hoisted(() => ({ endpoint: "", urls: [] as string[] })); @@ -1203,12 +1204,36 @@ describe("OpenCodeServerDriver", () => { } }); - it("forwards active direct provider API keys with Gemini aliasing, isolates unrelated keys, and redacts them", async () => { - const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-direct-keys-")); - roots.push(root); + it("keeps direct Google provider keys out of OpenCode env and proxies Gemini requests with session-scoped auth", async () => { + await chmod(fixture, 0o755); const geminiKey = "synthetic-direct-gemini-key"; + const explicitGenAiKey = "synthetic-explicit-google-genai-key"; const openaiKey = "synthetic-unrelated-openai-key"; const openrouterKey = "synthetic-unrelated-openrouter-key"; + let redirect = false; + const received: Array<{ apiKey: string | undefined; body: unknown }> = []; + const upstream = createHttpServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", chunk => chunks.push(Buffer.from(chunk))); + request.on("end", () => { + if (redirect) { + response.writeHead(307, { location: "https://attacker.invalid/v1beta" }).end(); + return; + } + received.push({ + apiKey: typeof request.headers["x-goog-api-key"] === "string" ? request.headers["x-goog-api-key"] : undefined, + body: JSON.parse(Buffer.concat(chunks).toString("utf8")), + }); + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ candidates: [] })); + }); + }); + await new Promise(resolve => upstream.listen(0, "127.0.0.1", resolve)); + const address = upstream.address(); + if (!address || typeof address === "string") throw new Error("Could not bind mock upstream"); + upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`; + upstreamTransport.urls = []; + const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-direct-keys-")); + roots.push(root); const command = join(root, "direct-key-probe.mjs"); await writeFile(command, [ `#!${process.execPath}`, @@ -1220,71 +1245,91 @@ describe("OpenCodeServerDriver", () => { ' openai: process.env.OPENAI_API_KEY ?? null,', ' openrouter: process.env.OPENROUTER_API_KEY ?? null,', '}));', - 'process.stderr.write(`direct key diagnostic: ${process.env.GOOGLE_GENERATIVE_AI_API_KEY}\n`);', `await import(${JSON.stringify(fixture)});`, ].join("\n"), { mode: 0o755 }); - const diagnostics: string[] = []; - const driver = new OpenCodeServerDriver({ - model: "google/gemini-2.5-flash", - command, - runtimeDirectory: root, - environment: { - PATH: process.env.PATH, - GEMINI_API_KEY: geminiKey, - OPENAI_API_KEY: openaiKey, - OPENROUTER_API_KEY: openrouterKey, - }, - onDiagnostic: message => diagnostics.push(message), - }); - const session = await driver.openSession({ runId: "direct-google", normalizedSessionId: "direct-google", workingDirectory: root }); - try { - const observed = JSON.parse(await readFile(join(root, "direct-google", "data", "direct-keys.json"), "utf8")); - expect(observed).toEqual({ - gemini: geminiKey, - googleGenAi: geminiKey, - openai: null, - openrouter: null, - }); - const configText = await readFile(join(root, "direct-google", "config", "opencode", "opencode.json"), "utf8"); - expect(configText).not.toContain(geminiKey); - expect(diagnostics.join("\n")).toContain("direct key diagnostic: [REDACTED]"); - expect(diagnostics.join("\n")).not.toContain(geminiKey); - } finally { - await session.close({ reason: "test" }); - } - - const explicitGenAiKey = "synthetic-explicit-google-genai-key"; - const explicitDriver = new OpenCodeServerDriver({ - model: "google/gemini-2.5-flash", - command, - runtimeDirectory: root, - environment: { - PATH: process.env.PATH, - GEMINI_API_KEY: geminiKey, - GOOGLE_GENERATIVE_AI_API_KEY: explicitGenAiKey, - }, - }); - const explicitSession = await explicitDriver.openSession({ runId: "direct-google-explicit", normalizedSessionId: "direct-google-explicit", workingDirectory: root }); - try { - const observed = JSON.parse(await readFile(join(root, "direct-google-explicit", "data", "direct-keys.json"), "utf8")); - expect(observed).toEqual({ - gemini: geminiKey, - googleGenAi: explicitGenAiKey, - openai: null, - openrouter: null, - }); - } finally { - await explicitSession.close({ reason: "test" }); - } - - // Omitting environment must never leak ambient host direct provider keys. const previousGemini = process.env.GEMINI_API_KEY; const previousGoogleGenAi = process.env.GOOGLE_GENERATIVE_AI_API_KEY; const previousOpenAi = process.env.OPENAI_API_KEY; - process.env.GEMINI_API_KEY = "ambient-host-gemini-key"; - process.env.GOOGLE_GENERATIVE_AI_API_KEY = "ambient-host-google-genai-key"; - process.env.OPENAI_API_KEY = "ambient-host-openai-key"; try { + const driver = new OpenCodeServerDriver({ + model: "google/gemini-2.5-flash", + command, + runtimeDirectory: root, + environment: { + PATH: process.env.PATH, + GEMINI_API_KEY: geminiKey, + OPENAI_API_KEY: openaiKey, + OPENROUTER_API_KEY: openrouterKey, + }, + }); + const session = await driver.openSession({ runId: "direct-google", normalizedSessionId: "direct-google", workingDirectory: root }); + let googleProxyUrl = ""; + try { + const observed = JSON.parse(await readFile(join(root, "direct-google", "data", "direct-keys.json"), "utf8")); + expect(observed).toEqual({ + gemini: null, + googleGenAi: null, + openai: null, + openrouter: null, + }); + const configText = await readFile(join(root, "direct-google", "config", "opencode", "opencode.json"), "utf8"); + expect(configText).not.toContain(geminiKey); + const config = JSON.parse(configText); + const { baseURL, apiKey } = config.provider.google.options; + expect(config.provider.google.npm).toBeUndefined(); + expect(baseURL).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1beta$/); + expect(apiKey).not.toBe(geminiKey); + googleProxyUrl = `${baseURL}/models/gemini-2.5-flash:streamGenerateContent?alt=sse`; + const payload = { contents: [{ role: "user", parts: [{ text: "hello" }] }] }; + expect((await fetch(googleProxyUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(401); + expect((await fetch(`${baseURL}/models/wrong-model:streamGenerateContent?alt=sse`, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404); + expect((await fetch(`${baseURL}/models/gemini-2.5-flash:streamGenerateContent?key=injected`, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404); + expect((await fetch(googleProxyUrl, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(200); + expect(received).toEqual([{ apiKey: geminiKey, body: payload }]); + expect(upstreamTransport.urls).toEqual(["https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"]); + redirect = true; + expect((await fetch(googleProxyUrl, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(502); + redirect = false; + } finally { + await session.close({ reason: "test" }); + } + await expect(fetch(googleProxyUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })).rejects.toThrow(); + + // Explicit GOOGLE_GENERATIVE_AI_API_KEY takes precedence over GEMINI_API_KEY. + received.length = 0; + upstreamTransport.urls = []; + const explicitDriver = new OpenCodeServerDriver({ + model: "google/gemini-2.5-flash", + command, + runtimeDirectory: root, + environment: { + PATH: process.env.PATH, + GEMINI_API_KEY: geminiKey, + GOOGLE_GENERATIVE_AI_API_KEY: explicitGenAiKey, + }, + }); + const explicitSession = await explicitDriver.openSession({ runId: "direct-google-explicit", normalizedSessionId: "direct-google-explicit", workingDirectory: root }); + try { + const observed = JSON.parse(await readFile(join(root, "direct-google-explicit", "data", "direct-keys.json"), "utf8")); + expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null }); + const config = JSON.parse(await readFile(join(root, "direct-google-explicit", "config", "opencode", "opencode.json"), "utf8")); + const { baseURL, apiKey } = config.provider.google.options; + const response = await fetch(`${baseURL}/models/gemini-2.5-flash:generateContent`, { + method: "POST", + headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, + body: JSON.stringify({ contents: [] }), + }); + expect(response.status).toBe(200); + expect(received).toEqual([{ apiKey: explicitGenAiKey, body: { contents: [] } }]); + expect(upstreamTransport.urls).toEqual(["https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"]); + } finally { + await explicitSession.close({ reason: "test" }); + } + + // Omitting environment must never leak ambient host direct provider keys or start a proxy from them. + process.env.GEMINI_API_KEY = "ambient-host-gemini-key"; + process.env.GOOGLE_GENERATIVE_AI_API_KEY = "ambient-host-google-genai-key"; + process.env.OPENAI_API_KEY = "ambient-host-openai-key"; const ambientDriver = new OpenCodeServerDriver({ model: "google/gemini-2.5-flash", command, @@ -1297,18 +1342,14 @@ describe("OpenCodeServerDriver", () => { }); try { const observed = JSON.parse(await readFile(join(root, "direct-google-no-ambient", "data", "direct-keys.json"), "utf8")); - expect(observed).toEqual({ - gemini: null, - googleGenAi: null, - openai: null, - openrouter: null, - }); + expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null }); + const config = JSON.parse(await readFile(join(root, "direct-google-no-ambient", "config", "opencode", "opencode.json"), "utf8")); + expect(config.provider.google.options).toBeUndefined(); } finally { await ambientSession.close({ reason: "test" }); } - // Runnerd environment sanitization must strip conflicting host Google keys - // so an explicit run GEMINI_API_KEY wins over an ambient host GOOGLE_GENERATIVE_AI_API_KEY. + // Runnerd environment sanitization strips conflicting host Google keys so an explicit run GEMINI_API_KEY wins. const sanitizedConflicting = createSanitizedOpenCodeRunnerEnvironment({ PATH: process.env.PATH, GEMINI_API_KEY: geminiKey, @@ -1322,6 +1363,7 @@ describe("OpenCodeServerDriver", () => { expect(sanitizedAmbientOnly.GOOGLE_GENERATIVE_AI_API_KEY).toBeUndefined(); expect(sanitizedAmbientOnly.OPENAI_API_KEY).toBeUndefined(); + received.length = 0; const conflictingDriver = new OpenCodeServerDriver({ model: "google/gemini-2.5-flash", command, @@ -1335,25 +1377,251 @@ describe("OpenCodeServerDriver", () => { }); try { const observed = JSON.parse(await readFile(join(root, "direct-google-host-conflict", "data", "direct-keys.json"), "utf8")); - expect(observed).toEqual({ - gemini: geminiKey, - googleGenAi: geminiKey, - openai: null, - openrouter: null, - }); + expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null }); + const config = JSON.parse(await readFile(join(root, "direct-google-host-conflict", "config", "opencode", "opencode.json"), "utf8")); + const { baseURL, apiKey } = config.provider.google.options; + expect((await fetch(`${baseURL}/models/gemini-2.5-flash:streamGenerateContent?alt=sse`, { + method: "POST", + headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, + body: JSON.stringify({ contents: [] }), + })).status).toBe(200); + expect(received).toEqual([{ apiKey: geminiKey, body: { contents: [] } }]); } finally { await conflictingSession.close({ reason: "test" }); } } finally { + upstreamTransport.endpoint = ""; if (previousGemini === undefined) delete process.env.GEMINI_API_KEY; else process.env.GEMINI_API_KEY = previousGemini; if (previousGoogleGenAi === undefined) delete process.env.GOOGLE_GENERATIVE_AI_API_KEY; else process.env.GOOGLE_GENERATIVE_AI_API_KEY = previousGoogleGenAi; if (previousOpenAi === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = previousOpenAi; + await new Promise(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); }); } }); + it.each([ + { + provider: "anthropic", + model: "claude-sonnet-4-5", + envKey: "ANTHROPIC_API_KEY", + secret: "synthetic-anthropic-key", + requestPath: "/messages", + expectedUpstreamUrl: "https://api.anthropic.com/v1/messages", + authHeader: "x-api-key", + extraHeaders: { "anthropic-version": "2023-06-01", "anthropic-beta": "structured-outputs-2025-11-13" }, + }, + { + provider: "openai", + model: "gpt-5", + envKey: "OPENAI_API_KEY", + secret: "synthetic-openai-key", + requestPath: "/responses", + expectedUpstreamUrl: "https://api.openai.com/v1/responses", + authHeader: "authorization", + extraHeaders: {}, + }, + { + provider: "xai", + model: "grok-3", + envKey: "XAI_API_KEY", + secret: "synthetic-xai-key", + requestPath: "/chat/completions", + expectedUpstreamUrl: "https://api.x.ai/v1/chat/completions", + authHeader: "authorization", + extraHeaders: {}, + }, + { + provider: "groq", + model: "llama-3.3-70b-versatile", + envKey: "GROQ_API_KEY", + secret: "synthetic-groq-key", + requestPath: "/chat/completions", + expectedUpstreamUrl: "https://api.groq.com/openai/v1/chat/completions", + authHeader: "authorization", + extraHeaders: {}, + }, + { + provider: "opencode", + model: "big-pickle", + envKey: "OPENCODE_API_KEY", + secret: "synthetic-opencode-key", + requestPath: "/chat/completions", + expectedUpstreamUrl: "https://opencode.ai/zen/v1/chat/completions", + authHeader: "authorization", + extraHeaders: { "x-opencode-client": "cli" }, + }, + ] as const)("proxies direct $provider requests through a runner-owned loopback broker without exposing $envKey to the child", async ({ + provider, + model, + envKey, + secret, + requestPath, + expectedUpstreamUrl, + authHeader, + extraHeaders, + }) => { + await chmod(fixture, 0o755); + const received: Array<{ headers: Record; body: unknown }> = []; + const upstream = createHttpServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", chunk => chunks.push(Buffer.from(chunk))); + request.on("end", () => { + received.push({ headers: request.headers, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) }); + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: "ok" })); + }); + }); + await new Promise(resolve => upstream.listen(0, "127.0.0.1", resolve)); + const address = upstream.address(); + if (!address || typeof address === "string") throw new Error("Could not bind mock upstream"); + upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`; + upstreamTransport.urls = []; + const root = await mkdtemp(join(tmpdir(), `paperclip-opencode-${provider}-proxy-`)); + roots.push(root); + let session: Awaited> | undefined; + try { + const driver = new OpenCodeServerDriver({ + model: `${provider}/${model}`, + command: fixture, + runtimeDirectory: root, + environment: { PATH: process.env.PATH, [envKey]: secret }, + }); + session = await driver.openSession({ runId: provider, normalizedSessionId: provider, workingDirectory: root }); + const configText = await readFile(join(root, provider, "config", "opencode", "opencode.json"), "utf8"); + expect(configText).not.toContain(secret); + const envText = await readFile(join(root, provider, "data", "fake-environment.json"), "utf8"); + expect(JSON.parse(envText).keys).not.toContain(envKey); + expect(envText).not.toContain(secret); + const config = JSON.parse(configText); + const { baseURL, apiKey } = config.provider[provider].options; + expect(baseURL).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1$/); + expect(apiKey).not.toBe(secret); + const authHeaders = authHeader === "authorization" + ? { Authorization: `Bearer ${apiKey}` } + : { [authHeader]: apiKey }; + const url = `${baseURL}${requestPath}`; + const payload = { model, messages: [{ role: "user", content: "hi" }] }; + expect((await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(401); + expect((await fetch(url, { method: "POST", headers: { ...authHeaders, "Content-Type": "application/json" }, body: JSON.stringify({ ...payload, model: "wrong-model" }) })).status).toBe(400); + expect((await fetch(`${baseURL}/models`, { method: "POST", headers: { ...authHeaders, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404); + expect((await fetch(url, { method: "POST", headers: { ...authHeaders, ...extraHeaders, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(200); + expect(upstreamTransport.urls).toEqual([expectedUpstreamUrl]); + expect(received).toHaveLength(1); + expect(received[0]?.headers[authHeader]).toBe(authHeader === "authorization" ? `Bearer ${secret}` : secret); + for (const [headerName, headerValue] of Object.entries(extraHeaders)) { + expect(received[0]?.headers[headerName]).toBe(headerValue); + } + } finally { + await session?.close({ reason: "test" }); + upstreamTransport.endpoint = ""; + await new Promise(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); }); + } + }); + + it("runs the pinned OpenCode bash tool without exposing the direct Gemini key while authenticating model calls", async () => { + const geminiKey = "synthetic-pinned-runtime-gemini-key-secret"; + const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-pinned-shell-")); + const workspace = await mkdtemp(join(tmpdir(), "paperclip-opencode-pinned-workspace-")); + roots.push(root, workspace); + let mainTurns = 0; + const observedUpstreamApiKeys: Array = []; + const observedShellPayloads: string[] = []; + const upstream = createHttpServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", chunk => chunks.push(Buffer.from(chunk))); + request.on("end", () => { + const rawBody = Buffer.concat(chunks).toString("utf8"); + observedUpstreamApiKeys.push( + typeof request.headers["x-goog-api-key"] === "string" ? request.headers["x-goog-api-key"] : undefined, + ); + const sse = (data: unknown) => `data: ${JSON.stringify(data)}\n\n`; + if (rawBody.includes("You are a title generator")) { + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end(sse({ + candidates: [{ content: { role: "model", parts: [{ text: "Env check" }] }, finishReason: "STOP" }], + usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 2, totalTokenCount: 7 }, + })); + return; + } + mainTurns += 1; + if (mainTurns === 1) { + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end(sse({ + candidates: [{ + content: { + role: "model", + parts: [{ + functionCall: { + name: "bash", + args: { + command: 'node -e "const fs = require(\x27fs\x27); const out = { gemini: process.env.GEMINI_API_KEY ?? null, googleGenAi: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? null, envHasSecret: Object.values(process.env).some(v => String(v).includes(\x27synthetic-pinned-runtime-gemini-key-secret\x27)), configHasSecret: fs.readFileSync(process.env.XDG_CONFIG_HOME + \x27/opencode/opencode.json\x27, \x27utf8\x27).includes(\x27synthetic-pinned-runtime-gemini-key-secret\x27) }; fs.writeFileSync(\x27shell-env-proof.json\x27, JSON.stringify(out)); console.log(JSON.stringify(out));"', + description: "Verify direct Gemini key is absent from shell env and config", + }, + }, + }], + }, + finishReason: "STOP", + }], + usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5, totalTokenCount: 15 }, + })); + return; + } + observedShellPayloads.push(rawBody); + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end(sse({ + candidates: [{ + content: { role: "model", parts: [{ text: "Shell environment verified without provider key." }] }, + finishReason: "STOP", + }], + usageMetadata: { promptTokenCount: 15, candidatesTokenCount: 8, totalTokenCount: 23 }, + })); + }); + }); + await new Promise(resolve => upstream.listen(0, "127.0.0.1", resolve)); + const address = upstream.address(); + if (!address || typeof address === "string") throw new Error("Could not bind mock Gemini upstream"); + upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`; + upstreamTransport.urls = []; + let session: Awaited> | undefined; + try { + const driver = new OpenCodeServerDriver({ + model: "google/gemini-2.5-flash", + command: resolvePinnedOpenCodeCommand(), + runtimeDirectory: root, + environment: { + PATH: process.env.PATH, + GEMINI_API_KEY: geminiKey, + }, + }); + session = await driver.openSession({ + runId: "pinned-google-shell", + normalizedSessionId: "pinned-google-shell", + workingDirectory: workspace, + }); + await session.startTurn({ message: { role: "user", text: "Check shell environment." } }); + await collectTurnEvents(session.events()); + const proof = JSON.parse(await readFile(join(workspace, "shell-env-proof.json"), "utf8")); + expect(proof).toEqual({ + gemini: null, + googleGenAi: null, + envHasSecret: false, + configHasSecret: false, + }); + expect(mainTurns).toBeGreaterThanOrEqual(2); + expect(observedUpstreamApiKeys.length).toBeGreaterThanOrEqual(2); + expect(observedUpstreamApiKeys.every(key => key === geminiKey)).toBe(true); + expect(upstreamTransport.urls.every(url => + url === "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse" + )).toBe(true); + expect(observedShellPayloads.length).toBeGreaterThanOrEqual(1); + } finally { + await session?.close({ reason: "pinned shell isolation test complete" }); + upstreamTransport.endpoint = ""; + await new Promise(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); }); + } + }, 30_000); + it("passes OpenRouter's stream through unchanged and records the host that served it on the turn's usage", async () => { await chmod(fixture, 0o755); const model = "deepseek/deepseek-v4.1-flash-1017"; 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 48287e5b672..8b8b76bd52f 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -1,4 +1,4 @@ -import { isOpenRouterUrl, OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js"; +import { OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js"; import { spawn, type ChildProcess } from "node:child_process"; import { resolveCompletionContinuation } from "../completion-continuation.js"; import { createHash, randomBytes } from "node:crypto"; @@ -17,15 +17,10 @@ import { } from "node:fs/promises"; import { createServer } from "node:net"; import { constants as osConstants } from "node:os"; -import { Agent as HttpAgent, createServer as createHttpServer, request as requestHttp, type IncomingMessage } from "node:http"; -import { Agent as HttpsAgent, request as requestHttps } from "node:https"; -import { getCACertificates } from "node:tls"; -import { pipeline } from "node:stream/promises"; import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { parseOpenCodeReasoningMode, type OpenCodeReasoningMode } from "./reasoning-mode.js"; -import { attributeUnsupportedToolMedia } from "./tool-media-attribution.js"; -import { createUpstreamServedTap, type UpstreamServed } from "./upstream-served.js"; +import { type UpstreamServed } from "./upstream-served.js"; import { openCodeProviderFailure } from "./provider-failure.js"; import { startOpenCodeMemoryKillProbe, @@ -40,7 +35,12 @@ import { annotateOmittedProviderText, parseOpenCodeSseFrames } from "./sse-frame import { githubCredentialEnvironment } from "../../github-credential-environment.js"; 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 { prepareOpenCodeOutputCustody } from "./output-custody.js"; +import { + OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS, + resolveOpenCodeProviderRoute, + startOpenCodeProviderProxy, +} from "./provider-proxy.js"; import { CODEX_SKILLLESS_BASE_INSTRUCTIONS, @@ -2541,127 +2541,6 @@ class OpenCodeHarnessSession implements HarnessSession { } } -/** Retain the reusable gateway key in the runner; the harness gets a session-scoped capability. */ -async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: string, environment: NodeJS.ProcessEnv, onServed?: (served: UpstreamServed | null) => void, secretValues: readonly string[] = []) { - const upstreamUrl = new URL(`${baseUrl.replace(/\/+$/, "")}/chat/completions`); - const token = randomBytes(32).toString("base64url"); - // Agent-local settings keep one runtime's transport configuration out of other sessions. - const proxyEnv = { - HTTP_PROXY: environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY, - HTTPS_PROXY: environment.https_proxy ?? environment.HTTPS_PROXY ?? environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY, - NO_PROXY: environment.no_proxy ?? environment.NO_PROXY, - }; - const ca = [...getCACertificates("default")]; - if (environment.SSL_CERT_FILE) ca.push(await readFile(environment.SSL_CERT_FILE, "utf8")); - if (environment.SSL_CERT_DIR) { - for (const entry of await readdir(environment.SSL_CERT_DIR, { withFileTypes: true })) { - if (!entry.isDirectory()) { - const certificate = await readFile(join(environment.SSL_CERT_DIR, entry.name), "utf8"); - if (certificate.includes("-----BEGIN CERTIFICATE-----")) ca.push(certificate); - } - } - } - const agent = upstreamUrl.protocol === "https:" ? new HttpsAgent({ proxyEnv, ca }) : new HttpAgent({ proxyEnv }); - const controllers = new Set(); - const server = createHttpServer((request, response) => { - const controller = new AbortController(); - controllers.add(controller); - response.once("close", () => controller.abort()); - void (async () => { - if (request.headers.authorization !== `Bearer ${token}`) { - response.writeHead(401).end(); - return; - } - if (request.method !== "POST" || request.url !== "/v1/chat/completions") { - response.writeHead(404).end(); - return; - } - const chunks: Buffer[] = []; - let bytes = 0; - for await (const chunk of request) { - bytes += chunk.length; - if (bytes > 16 * 1024 * 1024) { - response.writeHead(413).end(); - return; - } - chunks.push(Buffer.from(chunk)); - } - let body = Buffer.concat(chunks); - let payload: Record; - try { payload = JSON.parse(body.toString("utf8")); } - catch { response.writeHead(400).end(); return; } - if (!payload || typeof payload !== "object" || payload.model !== model || - ["models", "route", "plugins", "transforms"].some(field => Object.hasOwn(payload, field))) { - response.writeHead(400).end(); - return; - } - // Keep OpenCode's unreadable-media notice attributed to the tool result - // instead of a synthetic user message the model mistakes for the person. - if (attributeUnsupportedToolMedia(payload)) body = Buffer.from(JSON.stringify(payload), "utf8"); - // Defense in depth: no configured secret value leaves for the model. - if (secretValues.length > 0) { - const redacted = redactOpenCodeModelRequest(body, secretValues, payload); - if (redacted) body = redacted; - } - let served: UpstreamServed | null = null; - try { - const upstream = await new Promise((resolve, reject) => { - const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(upstreamUrl, { - method: "POST", - agent, - headers: { ...(isOpenRouterUrl(baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}), "Content-Type": "application/json", "Content-Length": body.length, ...(key ? { Authorization: `Bearer ${key}` } : {}) }, - signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]), - }, resolve); - outgoing.once("error", reject); - outgoing.end(body); - }); - // Never forward authentication to a redirect destination. - const status = upstream.statusCode ?? 502; - if (status >= 300 && status < 400) { - upstream.destroy(); - throw new Error("Provider redirects are not supported"); - } - const headers: Record = {}; - for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) { - const value = upstream.headers[name]; - if (typeof value === "string") headers[name] = value; - } - response.writeHead(status, headers); - if (onServed && status >= 200 && status < 300) { - await pipeline(upstream, createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"], - onServed: value => { served = value; } }), response); - } else await pipeline(upstream, response); - } finally { - try { onServed?.(served); } catch { /* Recording never affects the response. */ } - } - })().catch(() => { - if (!response.headersSent) response.writeHead(502).end("Provider request failed"); - else response.destroy(); - }).finally(() => controllers.delete(controller)); - }); - try { - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); }); - }); - } catch (error) { agent.destroy(); throw error; } - const address = server.address(); - if (!address || typeof address === "string") { - server.close(); - agent.destroy(); - throw new Error("Could not bind OpenCode provider proxy"); - } - return { - baseURL: `http://127.0.0.1:${address.port}/v1`, - token, - close: async () => { - for (const controller of controllers) controller.abort(); - agent.destroy(); - await new Promise((resolve) => { server.close(() => resolve()); server.closeAllConnections(); }); - }, - }; -} - async function startRuntime(input: { options: OpenCodeServerDriverOptions; root: string; @@ -2721,19 +2600,11 @@ async function startRuntime(input: { const providerEnvironment = input.options.environment ?? process.env; const [modelProvider, ...modelIdParts] = input.options.model.split("/"); const providerModelId = modelIdParts.join("/"); - const providerRoute = modelProvider === "openrouter" - ? providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL - ? { - baseUrl: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL, - key: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN ?? "", - } - : { baseUrl: "https://openrouter.ai/api/v1", key: providerEnvironment.OPENROUTER_API_KEY ?? "" } - : modelProvider === "paperclip" && input.options.environment?.PAPERCLIP_AI_PROVIDER_URL - ? { baseUrl: input.options.environment.PAPERCLIP_AI_PROVIDER_URL, key: input.options.environment.PAPERCLIP_AI_PROVIDER_KEY ?? "" } - : null; - const directProviderEnvironment = providerRoute - ? {} - : resolveDirectOpenCodeProviderEnvironment(modelProvider, input.options.environment); + const providerRoute = resolveOpenCodeProviderRoute( + modelProvider, + input.options.environment, + providerEnvironment, + ); const sensitiveValues = [ ...identityValues, ...Object.entries(taskEnvironment).flatMap(([key, value]) => @@ -2744,23 +2615,20 @@ async function startRuntime(input: { providerEnvironment.OPENROUTER_API_KEY, providerEnvironment.PAPERCLIP_AI_PROVIDER_KEY, providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN, + providerRoute?.key, ...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS.map(key => input.options.environment?.[key]), - ...Object.values(directProviderEnvironment), ].filter((value): value is string => Boolean(value)); input.trace?.addSensitiveValues(sensitiveValues); - // Configured secrets and direct provider API keys must never reach OpenCode's - // captured tool output, its session store, or the model. Prepared before - // launch; a launch that cannot protect them does not start. + // Configured secrets must never reach OpenCode's captured tool output, its + // session store, or the model. Prepared before launch; a launch that cannot + // protect them does not start. const outputCustody = await prepareOpenCodeOutputCustody({ 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, directProviderEnvironment), - secrets: [ - ...configuredSecretEnvironment(input.options.environment), - ...Object.entries(directProviderEnvironment).map(([name, value]) => ({ name, value })), - ], + environment: sanitizedEnvironment(input.options.environment, {}), + secrets: configuredSecretEnvironment(input.options.environment), }).catch(async error => { await bridge.close().catch(() => {}); await removeIsolatedHome(isolatedHome).catch(() => {}); @@ -2778,7 +2646,7 @@ async function startRuntime(input: { } if (instructionRoot) externalDirectories[`${instructionRoot}/**`] = "allow"; const providerProxy = providerRoute - ? await startOpenCodeProviderProxy(providerRoute.baseUrl, providerRoute.key, providerModelId, providerEnvironment, input.onUpstreamServed, outputCustody?.values ?? []).catch(async error => { + ? await startOpenCodeProviderProxy(providerRoute, providerModelId, providerEnvironment, input.onUpstreamServed, outputCustody?.values ?? []).catch(async error => { await bridge.close().catch(() => {}); await removeIsolatedHome(isolatedHome).catch(() => {}); throw error; @@ -2828,8 +2696,10 @@ async function startRuntime(input: { [modelProvider!]: { ...(modelProvider === "openrouter" ? { options: { headers: OPENROUTER_ATTRIBUTION_HEADERS } } : {}), ...(providerProxy ? { - npm: "@ai-sdk/openai-compatible", - name: modelProvider === "openrouter" ? "OpenRouter" : "Paperclip connection", + ...(providerRoute?.overrideOpenAiCompatible ? { + npm: "@ai-sdk/openai-compatible", + name: providerRoute.overrideOpenAiCompatible.name, + } : {}), options: { ...(modelProvider === "openrouter" ? { headers: OPENROUTER_ATTRIBUTION_HEADERS } : {}), baseURL: providerProxy.baseURL, @@ -2881,7 +2751,6 @@ async function startRuntime(input: { const environment = sanitizedEnvironment( input.options.environment, { - ...directProviderEnvironment, HOME: isolatedHome, XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome, @@ -3414,43 +3283,6 @@ async function* parseSse( } } -const OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS = [ - "GOOGLE_GENERATIVE_AI_API_KEY", - "GEMINI_API_KEY", - "OPENAI_API_KEY", - "ANTHROPIC_API_KEY", - "XAI_API_KEY", - "GROQ_API_KEY", - "OPENCODE_API_KEY", -] as const; - -const OPENCODE_DIRECT_PROVIDER_ENV_MAP: Readonly> = { - google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"], - openai: ["OPENAI_API_KEY"], - anthropic: ["ANTHROPIC_API_KEY"], - xai: ["XAI_API_KEY"], - groq: ["GROQ_API_KEY"], - opencode: ["OPENCODE_API_KEY"], -}; - -function resolveDirectOpenCodeProviderEnvironment( - modelProvider: string | undefined, - source: NodeJS.ProcessEnv | undefined, -): Record { - if (!modelProvider || !source) return {}; - const keys = OPENCODE_DIRECT_PROVIDER_ENV_MAP[modelProvider]; - if (!keys) return {}; - const resolved: Record = {}; - for (const key of keys) { - const value = source[key]?.trim(); - if (value) resolved[key] = value; - } - if (modelProvider === "google" && !resolved.GOOGLE_GENERATIVE_AI_API_KEY && resolved.GEMINI_API_KEY) { - resolved.GOOGLE_GENERATIVE_AI_API_KEY = resolved.GEMINI_API_KEY; - } - return resolved; -} - function sanitizedEnvironment( source: NodeJS.ProcessEnv | undefined, overrides: Record, diff --git a/packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts b/packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts new file mode 100644 index 00000000000..7287ee06127 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts @@ -0,0 +1,578 @@ +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import { + Agent as HttpAgent, + createServer as createHttpServer, + request as requestHttp, + type IncomingHttpHeaders, + type IncomingMessage, +} from "node:http"; +import { Agent as HttpsAgent, request as requestHttps } from "node:https"; +import { join } from "node:path"; +import { pipeline } from "node:stream/promises"; +import { getCACertificates } from "node:tls"; + +import { isOpenRouterUrl, OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js"; +import { redactOpenCodeModelRequest } from "./output-custody.js"; +import { attributeUnsupportedToolMedia } from "./tool-media-attribution.js"; +import { createUpstreamServedTap, type UpstreamServed } from "./upstream-served.js"; + +export const OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS = [ + "GOOGLE_GENERATIVE_AI_API_KEY", + "GEMINI_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "XAI_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", +] as const; + +export type OpenCodeProviderProtocol = + | "openai_compatible_gateway" + | "google" + | "anthropic" + | "openai" + | "xai" + | "groq" + | "opencode"; + +export interface OpenCodeProviderRoute { + protocol: OpenCodeProviderProtocol; + baseUrl: string; + key: string; + localBasePath: "/v1" | "/v1beta"; + overrideOpenAiCompatible?: { + name: string; + }; +} + +export interface OpenCodeProviderProxy { + baseURL: string; + token: string; + close(): Promise; +} + +const DIRECT_PROVIDER_DEFAULTS: Readonly< + Record< + Exclude, + { + baseUrl: string; + localBasePath: "/v1" | "/v1beta"; + envKeys: readonly string[]; + } + > +> = { + google: { + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + localBasePath: "/v1beta", + envKeys: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"], + }, + anthropic: { + baseUrl: "https://api.anthropic.com/v1", + localBasePath: "/v1", + envKeys: ["ANTHROPIC_API_KEY"], + }, + openai: { + baseUrl: "https://api.openai.com/v1", + localBasePath: "/v1", + envKeys: ["OPENAI_API_KEY"], + }, + xai: { + baseUrl: "https://api.x.ai/v1", + localBasePath: "/v1", + envKeys: ["XAI_API_KEY"], + }, + groq: { + baseUrl: "https://api.groq.com/openai/v1", + localBasePath: "/v1", + envKeys: ["GROQ_API_KEY"], + }, + opencode: { + baseUrl: "https://opencode.ai/zen/v1", + localBasePath: "/v1", + envKeys: ["OPENCODE_API_KEY"], + }, +}; + +export function resolveOpenCodeProviderRoute( + modelProvider: string | undefined, + explicitEnvironment: NodeJS.ProcessEnv | undefined, + providerEnvironment: NodeJS.ProcessEnv, +): OpenCodeProviderRoute | null { + if (!modelProvider) return null; + if (modelProvider === "openrouter") { + if (providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL) { + return { + protocol: "openai_compatible_gateway", + baseUrl: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL, + key: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN ?? "", + localBasePath: "/v1", + overrideOpenAiCompatible: { name: "OpenRouter" }, + }; + } + return { + protocol: "openai_compatible_gateway", + baseUrl: "https://openrouter.ai/api/v1", + key: providerEnvironment.OPENROUTER_API_KEY ?? "", + localBasePath: "/v1", + overrideOpenAiCompatible: { name: "OpenRouter" }, + }; + } + if (modelProvider === "paperclip" && explicitEnvironment?.PAPERCLIP_AI_PROVIDER_URL) { + return { + protocol: "openai_compatible_gateway", + baseUrl: explicitEnvironment.PAPERCLIP_AI_PROVIDER_URL, + key: explicitEnvironment.PAPERCLIP_AI_PROVIDER_KEY ?? "", + localBasePath: "/v1", + overrideOpenAiCompatible: { name: "Paperclip connection" }, + }; + } + if (!explicitEnvironment) return null; + if (!Object.hasOwn(DIRECT_PROVIDER_DEFAULTS, modelProvider)) return null; + const protocol = modelProvider as Exclude; + const spec = DIRECT_PROVIDER_DEFAULTS[protocol]; + let key = ""; + for (const envKey of spec.envKeys) { + const candidate = explicitEnvironment[envKey]?.trim(); + if (candidate) { + key = candidate; + break; + } + } + if (!key) return null; + return { + protocol, + baseUrl: spec.baseUrl, + key, + localBasePath: spec.localBasePath, + }; +} + +type ProxyAuthMode = "bearer" | "x-api-key" | "x-goog-api-key"; + +function secretEquals(actual: string | undefined, expected: string): boolean { + if (typeof actual !== "string") return false; + const left = Buffer.from(actual, "utf8"); + const right = Buffer.from(expected, "utf8"); + return left.length === right.length && timingSafeEqual(left, right); +} + +function headerString(headers: IncomingHttpHeaders, name: string): string | undefined { + const value = headers[name]; + return typeof value === "string" ? value : undefined; +} + +function verifyProxyAuth( + protocol: OpenCodeProviderProtocol, + headers: IncomingHttpHeaders, + token: string, +): ProxyAuthMode | null { + const expectedBearer = `Bearer ${token}`; + switch (protocol) { + case "openai_compatible_gateway": + case "openai": + case "xai": + case "groq": + return secretEquals(headerString(headers, "authorization"), expectedBearer) ? "bearer" : null; + case "google": + return secretEquals(headerString(headers, "x-goog-api-key"), token) ? "x-goog-api-key" : null; + case "anthropic": + return secretEquals(headerString(headers, "x-api-key"), token) ? "x-api-key" : null; + case "opencode": + if (secretEquals(headerString(headers, "authorization"), expectedBearer)) return "bearer"; + if (secretEquals(headerString(headers, "x-api-key"), token)) return "x-api-key"; + if (secretEquals(headerString(headers, "x-goog-api-key"), token)) return "x-goog-api-key"; + return null; + } +} + +interface MatchedUpstreamRequest { + upstreamSuffix: string; + requirePayloadModel: boolean; + rejectGatewayOverrides: boolean; + rewriteUnsupportedToolMedia: boolean; + forwardAnthropicHeaders: boolean; + forwardOpenCodeHeaders: boolean; +} + +function matchProviderProxyRequest( + protocol: OpenCodeProviderProtocol, + rawUrl: string | undefined, + model: string, +): MatchedUpstreamRequest | null { + if (!rawUrl || !rawUrl.startsWith("/")) return null; + let parsed: URL; + try { + parsed = new URL(rawUrl, "http://127.0.0.1"); + } catch { + return null; + } + const encodedModel = encodeURIComponent(model); + const { pathname, search } = parsed; + switch (protocol) { + case "openai_compatible_gateway": + if (rawUrl !== "/v1/chat/completions") return null; + return { + upstreamSuffix: "/chat/completions", + requirePayloadModel: true, + rejectGatewayOverrides: true, + rewriteUnsupportedToolMedia: true, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + case "google": { + const streamPath = `/v1beta/models/${encodedModel}:streamGenerateContent`; + const generatePath = `/v1beta/models/${encodedModel}:generateContent`; + if (pathname === streamPath && (search === "" || search === "?alt=sse")) { + return { + upstreamSuffix: `/models/${encodedModel}:streamGenerateContent${search}`, + requirePayloadModel: false, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + } + if (pathname === generatePath && search === "") { + return { + upstreamSuffix: `/models/${encodedModel}:generateContent`, + requirePayloadModel: false, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + } + return null; + } + case "anthropic": + if (pathname !== "/v1/messages" || search !== "") return null; + return { + upstreamSuffix: "/messages", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: true, + forwardOpenCodeHeaders: false, + }; + case "openai": + case "xai": + if (search !== "") return null; + if (pathname === "/v1/responses") { + return { + upstreamSuffix: "/responses", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + } + if (pathname === "/v1/chat/completions") { + return { + upstreamSuffix: "/chat/completions", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: true, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + } + return null; + case "groq": + if (pathname !== "/v1/chat/completions" || search !== "") return null; + return { + upstreamSuffix: "/chat/completions", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: true, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: false, + }; + case "opencode": { + if (pathname === "/v1/chat/completions" && search === "") { + return { + upstreamSuffix: "/chat/completions", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: true, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: true, + }; + } + if (pathname === "/v1/responses" && search === "") { + return { + upstreamSuffix: "/responses", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: true, + }; + } + if (pathname === "/v1/messages" && search === "") { + return { + upstreamSuffix: "/messages", + requirePayloadModel: true, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: true, + forwardOpenCodeHeaders: true, + }; + } + const streamPath = `/v1/models/${encodedModel}:streamGenerateContent`; + const generatePath = `/v1/models/${encodedModel}:generateContent`; + if (pathname === streamPath && (search === "" || search === "?alt=sse")) { + return { + upstreamSuffix: `/models/${encodedModel}:streamGenerateContent${search}`, + requirePayloadModel: false, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: true, + }; + } + if (pathname === generatePath && search === "") { + return { + upstreamSuffix: `/models/${encodedModel}:generateContent`, + requirePayloadModel: false, + rejectGatewayOverrides: false, + rewriteUnsupportedToolMedia: false, + forwardAnthropicHeaders: false, + forwardOpenCodeHeaders: true, + }; + } + return null; + } + } +} + +function buildUpstreamHeaders(input: { + route: OpenCodeProviderRoute; + authMode: ProxyAuthMode; + matched: MatchedUpstreamRequest; + incomingHeaders: IncomingHttpHeaders; + contentLength: number; +}): Record { + const headers: Record = { + ...(isOpenRouterUrl(input.route.baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}), + "Content-Type": "application/json", + "Content-Length": input.contentLength, + }; + if (input.route.key) { + if (input.authMode === "bearer") headers.Authorization = `Bearer ${input.route.key}`; + else if (input.authMode === "x-api-key") headers["x-api-key"] = input.route.key; + else if (input.authMode === "x-goog-api-key") headers["x-goog-api-key"] = input.route.key; + } + if (input.matched.forwardAnthropicHeaders) { + for (const name of ["anthropic-version", "anthropic-beta"]) { + const value = headerString(input.incomingHeaders, name); + if (value) headers[name] = value; + } + } + if (input.matched.forwardOpenCodeHeaders) { + for (const name of ["x-opencode-client", "x-opencode-project", "x-opencode-request", "x-opencode-session"]) { + const value = headerString(input.incomingHeaders, name); + if (value) headers[name] = value; + } + } + return headers; +} + +/** Retain reusable gateway and direct provider API keys in the runner; the harness receives only a session-scoped capability. */ +export async function startOpenCodeProviderProxy( + route: OpenCodeProviderRoute, + model: string, + environment: NodeJS.ProcessEnv, + onServed?: (served: UpstreamServed | null) => void, + secretValues: readonly string[] = [], +): Promise { + const normalizedBaseUrl = route.baseUrl.replace(/\/+$/, ""); + const baseOriginUrl = new URL(normalizedBaseUrl); + const token = randomBytes(32).toString("base64url"); + // Agent-local settings keep one runtime's transport configuration out of other sessions. + const proxyEnv = { + HTTP_PROXY: environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY, + HTTPS_PROXY: + environment.https_proxy ?? + environment.HTTPS_PROXY ?? + environment.http_proxy ?? + environment.HTTP_PROXY ?? + environment.all_proxy ?? + environment.ALL_PROXY, + NO_PROXY: environment.no_proxy ?? environment.NO_PROXY, + }; + const ca = [...getCACertificates("default")]; + if (environment.SSL_CERT_FILE) ca.push(await readFile(environment.SSL_CERT_FILE, "utf8")); + if (environment.SSL_CERT_DIR) { + for (const entry of await readdir(environment.SSL_CERT_DIR, { withFileTypes: true })) { + if (!entry.isDirectory()) { + const certificate = await readFile(join(environment.SSL_CERT_DIR, entry.name), "utf8"); + if (certificate.includes("-----BEGIN CERTIFICATE-----")) ca.push(certificate); + } + } + } + const agent = + baseOriginUrl.protocol === "https:" ? new HttpsAgent({ proxyEnv, ca }) : new HttpAgent({ proxyEnv }); + const controllers = new Set(); + const server = createHttpServer((request, response) => { + const controller = new AbortController(); + controllers.add(controller); + response.once("close", () => controller.abort()); + void (async () => { + const authMode = verifyProxyAuth(route.protocol, request.headers, token); + if (!authMode) { + response.writeHead(401).end(); + return; + } + if (request.method !== "POST") { + response.writeHead(404).end(); + return; + } + const matched = matchProviderProxyRequest(route.protocol, request.url, model); + if (!matched) { + response.writeHead(404).end(); + return; + } + const upstreamUrl = new URL(`${normalizedBaseUrl}${matched.upstreamSuffix}`); + if (upstreamUrl.origin !== baseOriginUrl.origin) { + response.writeHead(404).end(); + return; + } + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of request) { + bytes += chunk.length; + if (bytes > 16 * 1024 * 1024) { + response.writeHead(413).end(); + return; + } + chunks.push(Buffer.from(chunk)); + } + let body = Buffer.concat(chunks); + let payload: Record; + try { + payload = JSON.parse(body.toString("utf8")); + } catch { + response.writeHead(400).end(); + return; + } + if (!payload || typeof payload !== "object" || Array.isArray(payload)) { + response.writeHead(400).end(); + return; + } + if (matched.requirePayloadModel && payload.model !== model) { + response.writeHead(400).end(); + return; + } + if ( + matched.rejectGatewayOverrides && + ["models", "route", "plugins", "transforms"].some((field) => Object.hasOwn(payload, field)) + ) { + response.writeHead(400).end(); + return; + } + // Keep OpenCode's unreadable-media notice attributed to the tool result + // instead of a synthetic user message the model mistakes for the person. + if (matched.rewriteUnsupportedToolMedia && attributeUnsupportedToolMedia(payload)) { + body = Buffer.from(JSON.stringify(payload), "utf8"); + } + // Defense in depth: no configured secret value leaves for the model. + if (secretValues.length > 0) { + const redacted = redactOpenCodeModelRequest(body, secretValues, payload); + if (redacted) body = redacted; + } + let served: UpstreamServed | null = null; + try { + const upstream = await new Promise((resolve, reject) => { + const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)( + upstreamUrl, + { + method: "POST", + agent, + headers: buildUpstreamHeaders({ + route, + authMode, + matched, + incomingHeaders: request.headers, + contentLength: body.length, + }), + signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]), + }, + resolve, + ); + outgoing.once("error", reject); + outgoing.end(body); + }); + // Never forward authentication to a redirect destination. + const status = upstream.statusCode ?? 502; + if (status >= 300 && status < 400) { + upstream.destroy(); + throw new Error("Provider redirects are not supported"); + } + const headers: Record = {}; + for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) { + const value = upstream.headers[name]; + if (typeof value === "string") headers[name] = value; + } + response.writeHead(status, headers); + if (onServed && status >= 200 && status < 300) { + await pipeline( + upstream, + createUpstreamServedTap({ + contentType: headers["content-type"], + contentEncoding: headers["content-encoding"], + onServed: (value) => { + served = value; + }, + }), + response, + ); + } else { + await pipeline(upstream, response); + } + } finally { + try { + onServed?.(served); + } catch { + /* Recording never affects the response. */ + } + } + })() + .catch(() => { + if (!response.headersSent) response.writeHead(502).end("Provider request failed"); + else response.destroy(); + }) + .finally(() => controllers.delete(controller)); + }); + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + server.off("error", reject); + resolve(); + }); + }); + } catch (error) { + agent.destroy(); + throw error; + } + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + agent.destroy(); + throw new Error("Could not bind OpenCode provider proxy"); + } + return { + baseURL: `http://127.0.0.1:${address.port}${route.localBasePath}`, + token, + close: async () => { + for (const controller of controllers) controller.abort(); + agent.destroy(); + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + }, + }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 7c0dc5a22fe..6e58f421777 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,7 +13,7 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "d8ff7e00e98c02e671fe60fb7f7eda887a34371b", + "packages/plugins/sdk/src/environment-tasks.ts": "a2752f33aa44c0a546e5459a5db8b42923428e84", "packages/plugins/sdk/src/host-client-factory.ts": "8f76d518b4b43a41436b516cb2929165611bd483", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", @@ -65,7 +65,7 @@ "packages/shared/src/aggregator-apps.ts": "2a69a54ee0cb305170275b6f4e97689c107defb1", "packages/shared/src/ai-connection-router.ts": "9fbd89c385a4d5827bc68e1c7f6a66e00453d413", "packages/shared/src/ai-connection-usage.ts": "4b51573ee92f8a2ae0f80dd15288a0e59b4dddc7", - "packages/shared/src/ai-connections.ts": "f4107ef6a07c070b7ad04d64bf16d50135a3950a", + "packages/shared/src/ai-connections.ts": "aa3ba73576179f54f998dcd2634ce579f71620c7", "packages/shared/src/ai-provider-routing.ts": "e1f1fdefc23c76efe425e937852e61fe028cccc1", "packages/shared/src/analytics-consent.test.ts": "0c69d867d4f108cb57c07b4e71633e058cb7506b", "packages/shared/src/analytics-consent.ts": "00c4bfbd24ac3a288a68caae52468dfcd26df3e7", @@ -503,7 +503,7 @@ "packages/shared/src/validators/adapter-skills.ts": "ae43f7b180f632d5f54dfa821b8dc5ef6c6aa53d", "packages/shared/src/validators/agent-commentary.ts": "8242c5b28a77131aefdc00c873ad84c6c6736e4b", "packages/shared/src/validators/agent.test.ts": "b15ce4e96097e807de7e52ca174139dd51e0d9c9", - "packages/shared/src/validators/agent.ts": "92cbbfb031bd0e592083e2deb6f961bd5f31a574", + "packages/shared/src/validators/agent.ts": "5aea39fc234af1a1960fca0607b584e8b1da9ff7", "packages/shared/src/validators/app-definition.ts": "87a60e50f386c8f836d1c5a1576b75a50bc719a2", "packages/shared/src/validators/approval.test.ts": "051d29b27400fdd1e311466587b276264cf072e4", "packages/shared/src/validators/approval.ts": "b8fd4da39568e3b70b767266196ea5303efeef25",