diff --git a/packages/adapter-utils/src/api-billing-type.test.ts b/packages/adapter-utils/src/api-billing-type.test.ts index 5804093cce9..4ec29b37a61 100644 --- a/packages/adapter-utils/src/api-billing-type.test.ts +++ b/packages/adapter-utils/src/api-billing-type.test.ts @@ -5,7 +5,9 @@ describe("verified API billing", () => { it.each([ ["openrouter", "OPENROUTER_API_KEY"], ["openai", "OPENAI_API_KEY"], ["anthropic", "ANTHROPIC_API_KEY"], ["deepseek", "DEEPSEEK_API_KEY"], - ])("classifies %s with its matching credential", (provider, key) => { + ["google", "GOOGLE_GENERATIVE_AI_API_KEY"], ["google", "GEMINI_API_KEY"], + ["xai", "XAI_API_KEY"], ["groq", "GROQ_API_KEY"], ["opencode", "OPENCODE_API_KEY"], + ])("classifies %s with its matching credential (%s)", (provider, key) => { expect(apiKeyBillingType(provider, { [key]: "fixture-key" })).toBe("metered_api"); }); it("recognizes Codex's key alias only for the Codex runtime", () => { @@ -14,7 +16,7 @@ describe("verified API billing", () => { expect(apiKeyBillingType("openai", env)).toBe("unknown"); expect(apiKeyBillingType("openrouter", env, "codex")).toBe("unknown"); }); - it.each(["openrouter", "openai", "constructor", "toString", null, "unsupported"]) ("does not infer billing for %s", provider => { + it.each(["openrouter", "openai", "google", "constructor", "toString", null, "unsupported"]) ("does not infer billing for %s", provider => { expect(apiKeyBillingType(provider, { ANTHROPIC_API_KEY: "unrelated-key", OPENAI_API_KEY: " " })).toBe("unknown"); }); }); diff --git a/packages/adapter-utils/src/api-billing-type.ts b/packages/adapter-utils/src/api-billing-type.ts index 28402cc4f45..0758d2b22f7 100644 --- a/packages/adapter-utils/src/api-billing-type.ts +++ b/packages/adapter-utils/src/api-billing-type.ts @@ -5,6 +5,10 @@ const API_KEY_NAMES: Readonly> = { openrouter: ["OPENROUTER_API_KEY"], anthropic: ["ANTHROPIC_API_KEY"], deepseek: ["DEEPSEEK_API_KEY"], + google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"], + xai: ["XAI_API_KEY"], + groq: ["GROQ_API_KEY"], + opencode: ["OPENCODE_API_KEY"], }; /** A model/provider name alone does not prove billing. Only a matching API diff --git a/packages/adapters/opencode-local/src/server/models.test.ts b/packages/adapters/opencode-local/src/server/models.test.ts index 0de89de8dd2..395c584a413 100644 --- a/packages/adapters/opencode-local/src/server/models.test.ts +++ b/packages/adapters/opencode-local/src/server/models.test.ts @@ -315,4 +315,28 @@ describe("openCode models", () => { await assertion; expect(spy).toHaveBeenCalledTimes(3); }); + + it("mirrors GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY during model discovery", async () => { + const spy = vi.spyOn(serverUtils, "runChildProcess").mockResolvedValueOnce({ + exitCode: 0, + signal: null, + timedOut: false, + stdout: "google/gemini-2.5-flash\n", + stderr: "", + pid: 1, + startedAt: new Date().toISOString(), + }); + + await expect( + discoverOpenCodeModels({ + env: { GEMINI_API_KEY: "gemini-discovery-key" }, + }), + ).resolves.toEqual([ + { id: "google/gemini-2.5-flash", label: "google/gemini-2.5-flash" }, + ]); + expect(spy.mock.calls[0]?.[3]?.env).toMatchObject({ + GEMINI_API_KEY: "gemini-discovery-key", + GOOGLE_GENERATIVE_AI_API_KEY: "gemini-discovery-key", + }); + }); }); diff --git a/packages/adapters/opencode-local/src/server/models.ts b/packages/adapters/opencode-local/src/server/models.ts index 3e576eaa20b..b6d8c1b3c6c 100644 --- a/packages/adapters/opencode-local/src/server/models.ts +++ b/packages/adapters/opencode-local/src/server/models.ts @@ -7,6 +7,7 @@ import { runChildProcess, } from "@paperclipai/adapter-utils/server-utils"; import { isValidOpenCodeModelId } from "../index.js"; +import { applyOpenCodeProviderEnvAliases } from "./runtime-config.js"; const MODELS_CACHE_TTL_MS = 60_000; const MODELS_DISCOVERY_TIMEOUT_MS = 20_000; @@ -159,13 +160,15 @@ export async function discoverOpenCodeModels( // image). Fall back to process.env.HOME. } // Prevent OpenCode from writing an opencode.json into the working directory. - const runtimeEnv = normalizeEnv( - ensurePathInEnv({ - ...process.env, - ...env, - ...(resolvedHome ? { HOME: resolvedHome } : {}), - OPENCODE_DISABLE_PROJECT_CONFIG: "true", - }), + const runtimeEnv = applyOpenCodeProviderEnvAliases( + normalizeEnv( + ensurePathInEnv({ + ...process.env, + ...applyOpenCodeProviderEnvAliases(env), + ...(resolvedHome ? { HOME: resolvedHome } : {}), + OPENCODE_DISABLE_PROJECT_CONFIG: "true", + }), + ), ); const maxAttempts = MODELS_DISCOVERY_RETRY_DELAYS_MS.length + 1; diff --git a/packages/adapters/opencode-local/src/server/runtime-config.test.ts b/packages/adapters/opencode-local/src/server/runtime-config.test.ts index de8d940743e..bdc017a4e3c 100644 --- a/packages/adapters/opencode-local/src/server/runtime-config.test.ts +++ b/packages/adapters/opencode-local/src/server/runtime-config.test.ts @@ -5,7 +5,7 @@ import { execFileSync, spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/adapter-utils/openrouter-attribution"; -import { prepareOpenCodeRuntimeConfig } from "./runtime-config.js"; +import { applyOpenCodeProviderEnvAliases, prepareOpenCodeRuntimeConfig } from "./runtime-config.js"; const cleanupPaths = new Set(); @@ -482,4 +482,37 @@ describe("prepareOpenCodeRuntimeConfig", () => { expect(config.provider.openrouter.options.headers["HTTP-Referer"]).toBe("https://paperclip.ing"); await prepared.cleanup(); }); + + it("mirrors GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY when absent or blank", async () => { + const configHome = await makeConfigHome(); + const prepared = await prepareOpenCodeRuntimeConfig({ + env: { XDG_CONFIG_HOME: configHome, GEMINI_API_KEY: "gemini-fixture-key" }, + config: { model: "google/gemini-2.5-flash" }, + }); + cleanupPaths.add(prepared.env.XDG_CONFIG_HOME); + expect(prepared.env.GEMINI_API_KEY).toBe("gemini-fixture-key"); + expect(prepared.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe("gemini-fixture-key"); + await prepared.cleanup(); + }); + + it("preserves explicit GOOGLE_GENERATIVE_AI_API_KEY and blank managed isolation", () => { + expect( + applyOpenCodeProviderEnvAliases({ + GEMINI_API_KEY: "gemini-key", + GOOGLE_GENERATIVE_AI_API_KEY: "explicit-google-key", + }), + ).toEqual({ + GEMINI_API_KEY: "gemini-key", + GOOGLE_GENERATIVE_AI_API_KEY: "explicit-google-key", + }); + expect( + applyOpenCodeProviderEnvAliases({ + GEMINI_API_KEY: "", + GOOGLE_GENERATIVE_AI_API_KEY: "", + }), + ).toEqual({ + GEMINI_API_KEY: "", + GOOGLE_GENERATIVE_AI_API_KEY: "", + }); + }); }); diff --git a/packages/adapters/opencode-local/src/server/runtime-config.ts b/packages/adapters/opencode-local/src/server/runtime-config.ts index 1b25d1e1dd0..f3bae796307 100644 --- a/packages/adapters/opencode-local/src/server/runtime-config.ts +++ b/packages/adapters/opencode-local/src/server/runtime-config.ts @@ -104,14 +104,36 @@ async function readJsonObject(filepath: string): Promise } } +/** + * OpenCode's built-in Google provider (@ai-sdk/google) reads + * GOOGLE_GENERATIVE_AI_API_KEY, whereas Paperclip's Google/Antigravity setup + * and managed connections supply GEMINI_API_KEY. Mirror a non-empty + * GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY when the latter is absent + * or empty, while leaving explicit blank managed isolation untouched. + */ +export function applyOpenCodeProviderEnvAliases( + env: Record, +): Record { + const geminiKey = env.GEMINI_API_KEY?.trim(); + const googleGenAiKey = env.GOOGLE_GENERATIVE_AI_API_KEY?.trim(); + if (!googleGenAiKey && geminiKey) { + return { + ...env, + GOOGLE_GENERATIVE_AI_API_KEY: geminiKey, + }; + } + return env; +} + export async function prepareOpenCodeRuntimeConfig(input: { env: Record; config: Record; sandboxToolOomPreference?: boolean; }): Promise { const skipPermissions = asBoolean(input.config.dangerouslySkipPermissions, true); + const aliasedEnv = applyOpenCodeProviderEnvAliases(input.env); - const sourceConfigDir = path.join(resolveXdgConfigHome(input.env), "opencode"); + const sourceConfigDir = path.join(resolveXdgConfigHome(aliasedEnv), "opencode"); const runtimeConfigHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-config-")); const runtimeConfigDir = path.join(runtimeConfigHome, "opencode"); const runtimeConfigPath = path.join(runtimeConfigDir, "opencode.json"); @@ -227,7 +249,7 @@ export async function prepareOpenCodeRuntimeConfig(input: { return { env: { - ...input.env, + ...aliasedEnv, XDG_CONFIG_HOME: runtimeConfigHome, ...(inlineContent ? { OPENCODE_CONFIG_CONTENT: inlineConfig ? JSON.stringify({ ...inlineConfig, provider: nextProvider }) : inlineContent } : {}), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs b/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs index 60f382cf522..0c18c436677 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs @@ -98,6 +98,13 @@ const OPENCODE_PROVIDER_ENVIRONMENT_KEYS: &[&str] = &[ "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY", "OPENROUTER_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "GOOGLE_GENERATIVE_AI_API_KEY", + "XAI_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", "PAPERCLIP_OPENCODE_PERMISSION_MODE", "PAPERCLIP_OPENCODE_RUNTIME_DIR", "PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs b/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs index 371617e6f16..52d7ab30274 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/configured_environment.rs @@ -49,15 +49,19 @@ const RESERVED: &[&str] = &[ "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", "ENV", + "GEMINI_API_KEY", "GH_ENTERPRISE_TOKEN", "GH_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "GITHUB_TOKEN", + "GOOGLE_GENERATIVE_AI_API_KEY", + "GROQ_API_KEY", "HOME", "KIMI_API_KEY", "NODE_OPTIONS", "NODE_PATH", "OPENAI_API_KEY", + "OPENCODE_API_KEY", "OPENROUTER_API_KEY", "PAPERCLIP_ACPX_CREDENTIAL_BINDING", "PAPERCLIP_AGENT_ID", diff --git a/packages/paperclip-runner/src/configured-environment.ts b/packages/paperclip-runner/src/configured-environment.ts index 0fa4d86d969..7806cf1568a 100644 --- a/packages/paperclip-runner/src/configured-environment.ts +++ b/packages/paperclip-runner/src/configured-environment.ts @@ -40,7 +40,8 @@ export const GENERATED_RUNTIME_ENVIRONMENT_KEYS: ReadonlySet = new Set([ export const PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS: readonly string[] = [ "OPENAI_API_KEY", "CODEX_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", - "AWS_BEARER_TOKEN_BEDROCK", "OPENROUTER_API_KEY", "XAI_API_KEY", "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", + "AWS_BEARER_TOKEN_BEDROCK", "OPENROUTER_API_KEY", "GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY", + "XAI_API_KEY", "GROQ_API_KEY", "OPENCODE_API_KEY", "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", "COPILOT_GITHUB_TOKEN", "KIMI_API_KEY", "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "PAPERCLIP_GIT_TOKEN", ]; diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index 95cc417f4a1..5c74550d132 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -4933,6 +4933,10 @@ const runnerExplicitProviderEnvironmentKeys = [ "PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", "PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", + "GEMINI_API_KEY", + "GOOGLE_GENERATIVE_AI_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", "XAI_API_KEY", "AWS_REGION", "AWS_DEFAULT_REGION", 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 141bcb0891b..cc8d05a47c5 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 @@ -1202,6 +1202,81 @@ 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); + const geminiKey = "synthetic-direct-gemini-key"; + const openaiKey = "synthetic-unrelated-openai-key"; + const openrouterKey = "synthetic-unrelated-openrouter-key"; + const command = join(root, "direct-key-probe.mjs"); + await writeFile(command, [ + `#!${process.execPath}`, + 'import { writeFile } from "node:fs/promises";', + 'import { join } from "node:path";', + 'await writeFile(join(process.env.XDG_DATA_HOME, "direct-keys.json"), JSON.stringify({', + ' gemini: process.env.GEMINI_API_KEY ?? null,', + ' googleGenAi: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? null,', + ' 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" }); + } + }); + 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 f357a1235a0..641dd392e7f 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -381,6 +381,9 @@ export class OpenCodeServerDriver implements HarnessDriver { this.#options.environment?.OPENROUTER_API_KEY, this.#options.environment?.PAPERCLIP_AI_PROVIDER_KEY, this.#options.environment?.PAPERCLIP_OPENROUTER_PROXY_TOKEN, + ...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS.map( + (key) => this.#options.environment?.[key], + ), ]), }; } @@ -2716,6 +2719,21 @@ async function startRuntime(input: { const identityValues = identityKey ? [identityKey, JSON.stringify(identityKey).slice(1, -1), ...identityKey.split(/\r?\n/).filter(line => line && !line.startsWith("-----"))] : []; 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, providerEnvironment); const sensitiveValues = [ ...identityValues, ...Object.entries(taskEnvironment).flatMap(([key, value]) => @@ -2726,18 +2744,23 @@ async function startRuntime(input: { providerEnvironment.OPENROUTER_API_KEY, providerEnvironment.PAPERCLIP_AI_PROVIDER_KEY, providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN, + ...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS.map(key => providerEnvironment[key]), + ...Object.values(directProviderEnvironment), ].filter((value): value is string => Boolean(value)); input.trace?.addSensitiveValues(sensitiveValues); - // 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. + // 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. 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, {}), - secrets: configuredSecretEnvironment(input.options.environment), + environment: sanitizedEnvironment(input.options.environment, directProviderEnvironment), + secrets: [ + ...configuredSecretEnvironment(input.options.environment), + ...Object.entries(directProviderEnvironment).map(([name, value]) => ({ name, value })), + ], }).catch(async error => { await bridge.close().catch(() => {}); await removeIsolatedHome(isolatedHome).catch(() => {}); @@ -2754,18 +2777,6 @@ async function startRuntime(input: { externalDirectories[`${root}/**`] = "allow"; } if (instructionRoot) externalDirectories[`${instructionRoot}/**`] = "allow"; - 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 providerProxy = providerRoute ? await startOpenCodeProviderProxy(providerRoute.baseUrl, providerRoute.key, providerModelId, providerEnvironment, input.onUpstreamServed, outputCustody?.values ?? []).catch(async error => { await bridge.close().catch(() => {}); @@ -2870,6 +2881,7 @@ async function startRuntime(input: { const environment = sanitizedEnvironment( input.options.environment, { + ...directProviderEnvironment, HOME: isolatedHome, XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome, @@ -3402,6 +3414,43 @@ 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, +): Record { + if (!modelProvider) 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, @@ -3548,7 +3597,7 @@ function redact( } return redacted .replace( - /(OPENROUTER_API_KEY|authorization|password|token|secret)\s*[:=]\s*[^\s,}\]]+/gi, + /([A-Z0-9_]*API_KEY|authorization|password|token|secret)\s*[:=]\s*[^\s,}\]]+/gi, "$1=[REDACTED]", ) .slice(0, 8_192); 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 6aafeb14e28..c144f407c16 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -3096,6 +3096,52 @@ it("passes only the Anthropic credential to Claude Managed runnerd", () => { expect(environment.DATABASE_URL).toBeUndefined(); }); +it("forwards direct OpenCode provider API keys without leaking Paperclip controller credentials", () => { + const environment = createCapabilityRunnerdProviderEnvironment({ + provider: "opencode", + options: { + provider: "opencode", + environment: { + PATH: "/bin", + OPENROUTER_API_KEY: "openrouter-canary", + OPENAI_API_KEY: "openai-canary", + ANTHROPIC_API_KEY: "anthropic-canary", + GEMINI_API_KEY: "gemini-canary", + GOOGLE_GENERATIVE_AI_API_KEY: "google-genai-canary", + XAI_API_KEY: "xai-canary", + GROQ_API_KEY: "groq-canary", + OPENCODE_API_KEY: "opencode-canary", + PAPERCLIP_API_KEY: "must-not-reach-provider", + DATABASE_URL: "must-not-reach-provider", + }, + }, + identity: { + runnerInstanceId: "runner-1", + environmentLeaseId: "lease-1", + runId: "run-1", + normalizedSessionId: "session-1", + turnId: "turn-1", + itemId: "item-1", + }, + codexHome: "/isolated/codex-home", + runtimeContextPath: "/isolated/runtime-context.json", + hasRuntimeContext: false, + }); + expect(environment).toMatchObject({ + PATH: "/bin", + OPENROUTER_API_KEY: "openrouter-canary", + OPENAI_API_KEY: "openai-canary", + ANTHROPIC_API_KEY: "anthropic-canary", + GEMINI_API_KEY: "gemini-canary", + GOOGLE_GENERATIVE_AI_API_KEY: "google-genai-canary", + XAI_API_KEY: "xai-canary", + GROQ_API_KEY: "groq-canary", + OPENCODE_API_KEY: "opencode-canary", + }); + expect(environment.PAPERCLIP_API_KEY).toBeUndefined(); + expect(environment.DATABASE_URL).toBeUndefined(); +}); + it("uses file-backed AWS workload identity without forwarding access keys or Paperclip tokens", () => { const environment = createCapabilityRunnerdProviderEnvironment({ provider: "aws_agentcore", diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 312a063efb4..7806ca12117 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -4044,6 +4044,13 @@ export const OPEN_CODE_RUNNER_ENVIRONMENT_KEYS = new Set([ "WINDIR", "RUST_BACKTRACE", "OPENROUTER_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "GOOGLE_GENERATIVE_AI_API_KEY", + "XAI_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", "PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN", ]); diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index ebdf0950379..a22367f0e83 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -59,7 +59,18 @@ export type PluginEnvironmentTaskConfiguredEnvironment = z.infer; export type PluginEnvironmentTaskCredentialProvider = keyof typeof ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS; diff --git a/packages/shared/src/ai-connections.ts b/packages/shared/src/ai-connections.ts index f4107ef6a07..aa3ba735761 100644 --- a/packages/shared/src/ai-connections.ts +++ b/packages/shared/src/ai-connections.ts @@ -97,7 +97,7 @@ export const AI_CONNECTION_CAPABILITIES: Record< methods: { api_key: { adapters: ["copilot_runtime"], envKey: "COPILOT_GITHUB_TOKEN" } }, }, google: { name: "Google", methods: { - api_key: { adapters: ["gemini_local", "pi_local", "antigravity_runtime"], envKey: "GEMINI_API_KEY" }, + api_key: { adapters: ["gemini_local", "pi_local", "opencode_local", "antigravity_runtime"], envKey: "GEMINI_API_KEY" }, subscription: { adapters: ["antigravity_runtime"], envKey: "GEMINI_HOME" }, } }, anthropic: { @@ -107,14 +107,14 @@ export const AI_CONNECTION_CAPABILITIES: Record< adapters: ["claude_local"], envKey: "CLAUDE_CODE_OAUTH_TOKEN", }, - api_key: { adapters: ["claude_local", "pi_local"], envKey: "ANTHROPIC_API_KEY" }, + api_key: { adapters: ["claude_local", "pi_local", "opencode_local"], envKey: "ANTHROPIC_API_KEY" }, }, }, openai: { name: "OpenAI", methods: { subscription: { adapters: ["codex_local"], envKey: "CODEX_HOME" }, - api_key: { adapters: ["codex_local", "pi_local"], envKey: "OPENAI_API_KEY" }, + api_key: { adapters: ["codex_local", "pi_local", "opencode_local"], envKey: "OPENAI_API_KEY" }, }, }, openrouter: { @@ -127,7 +127,7 @@ export const AI_CONNECTION_CAPABILITIES: Record< name: "Grok", methods: { subscription: { adapters: ["grok_local"], envKey: "GROK_HOME" }, - api_key: { adapters: ["grok_local"], envKey: "XAI_API_KEY" }, + api_key: { adapters: ["grok_local", "opencode_local"], envKey: "XAI_API_KEY" }, }, }, }; @@ -158,8 +158,8 @@ export function isAiConnectionCompatible( : requirement.method ? [methods[requirement.method]] : []; return ( candidates.some((method) => method?.adapters.includes(adapterType)) && - (requirement.provider !== "openrouter" || - (typeof model === "string" && model.startsWith("openrouter/"))) + ((adapterType !== "opencode_local" && requirement.provider !== "openrouter") || + (typeof model === "string" && model.startsWith(`${requirement.provider}/`))) ); } export type AiConnectionUnavailableReason = diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts index 92cbbfb031b..5aea39fc234 100644 --- a/packages/shared/src/validators/agent.ts +++ b/packages/shared/src/validators/agent.ts @@ -296,6 +296,7 @@ export const testAdapterEnvironmentSchema = z.object({ OPENAI_API_KEY: z.string().max(16384), OPENROUTER_API_KEY: z.string().max(16384), GEMINI_API_KEY: z.string().max(16384), + GOOGLE_GENERATIVE_AI_API_KEY: z.string().max(16384), XAI_API_KEY: z.string().max(16384), GROQ_API_KEY: z.string().max(16384), OPENCODE_API_KEY: z.string().max(16384), diff --git a/server/src/__tests__/agent-test-environment-routes.test.ts b/server/src/__tests__/agent-test-environment-routes.test.ts index d4c2db91cd7..71bed0429a3 100644 --- a/server/src/__tests__/agent-test-environment-routes.test.ts +++ b/server/src/__tests__/agent-test-environment-routes.test.ts @@ -21,7 +21,7 @@ const mockSecretService = vi.hoisted(() => ({ normalizeAdapterConfigForPersistence: vi.fn(async (_companyId: string, config: Record) => config), resolveAdapterConfigForRuntime: vi.fn(async (_companyId: string, config: Record) => ({ config })), collectMissingRuntimeBindings: vi.fn(async () => [] as Array>), - resolveEnvBindings: vi.fn(async () => ({ + resolveEnvBindings: vi.fn(async (_companyId: string, _env: Record) => ({ env: {} as Record, secretKeys: new Set(), manifest: [], @@ -761,7 +761,7 @@ describe("agent test-environment route", () => { expect(testEnvironmentSpy).not.toHaveBeenCalled(); }); - it.each(["CURSOR_API_KEY", "KIMI_MODEL_API_KEY", "ZAI_API_KEY", "KIMI_API_KEY", "MINIMAX_API_KEY"])("accepts %s as a probe-only credential", async (key) => { + it.each(["CURSOR_API_KEY", "KIMI_MODEL_API_KEY", "ZAI_API_KEY", "KIMI_API_KEY", "MINIMAX_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"])("accepts %s as a probe-only credential", async (key) => { const app = await createApp(); const res = await request(app) .post("/api/companies/company-1/adapters/external_test/test-environment") @@ -771,6 +771,61 @@ describe("agent test-environment route", () => { expect(testEnvironmentSpy.mock.calls[0]?.[0].config.env).toEqual({ [key]: "probe-only-key" }); }); + it("strips stale secret refs overridden by testCredentials before persistence and runtime secret resolution", async () => { + const { HttpError } = await import("../errors.js"); + const staleSecretId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const envId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; + mockEnvironmentService.getById.mockResolvedValue({ + id: envId, + companyId: "company-1", + name: "Local", + driver: "local", + status: "active", + config: {}, + envVars: { + GEMINI_API_KEY: { type: "secret_ref", secretId: staleSecretId, version: "latest" }, + GOOGLE_GENERATIVE_AI_API_KEY: { type: "secret_ref", secretId: staleSecretId, version: "latest" }, + KEEP_ENV: { type: "plain", value: "keep-env-value" }, + }, + }); + mockSecretService.normalizeAdapterConfigForPersistence.mockImplementation(async (_companyId, config) => { + const env = (config.env ?? {}) as Record; + if ("GEMINI_API_KEY" in env || "GOOGLE_GENERATIVE_AI_API_KEY" in env) throw new HttpError(404, "Secret not found"); + return config; + }); + mockSecretService.resolveAdapterConfigForRuntime.mockImplementation(async (_companyId, config) => { + const env = (config.env ?? {}) as Record; + if ("GEMINI_API_KEY" in env || "GOOGLE_GENERATIVE_AI_API_KEY" in env) throw new HttpError(404, "Secret not found"); + return { config }; + }); + mockSecretService.resolveEnvBindings.mockImplementation(async (_companyId, env) => { + if ("GEMINI_API_KEY" in env || "GOOGLE_GENERATIVE_AI_API_KEY" in env) throw new HttpError(404, "Secret not found"); + return { env: { KEEP_ENV: "keep-env-value" }, secretKeys: new Set(), manifest: [] }; + }); + const app = await createApp(); + + const res = await request(app) + .post("/api/companies/company-1/adapters/external_test/test-environment") + .send({ + environmentId: envId, + adapterConfig: { + env: { + GEMINI_API_KEY: { type: "secret_ref", secretId: staleSecretId, version: "latest" }, + GOOGLE_GENERATIVE_AI_API_KEY: { type: "secret_ref", secretId: staleSecretId, version: "latest" }, + OTHER_PLAIN: "other-value", + }, + }, + testCredentials: { GEMINI_API_KEY: "fresh-gemini-key" }, + }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(testEnvironmentSpy.mock.calls[0]?.[0].config.env).toEqual({ + KEEP_ENV: "keep-env-value", + OTHER_PLAIN: "other-value", + GEMINI_API_KEY: "fresh-gemini-key", + }); + }); + it("maps the Hermes gateway probe key without passing it to persistence", async () => { const { registerServerAdapter, getServerAdapter, unregisterServerAdapter } = await import("../adapters/index.js"); const previous = getServerAdapter("hermes_gateway"); diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index a2fe7762869..b61cdc89902 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -109,6 +109,44 @@ describe("managed AI connections", () => { await expect(prepareManagedAiRuntime(db, { ...piInput, config: { ...piInput.config, env: { PAPERCLIP_PI_PROVIDERS: "{}" } } })).rejects.toThrow("routing is incompatible"); }); + it.each([ + { adapterType: "opencode_local", config: { model: "google/gemini-2.5-flash" } }, + { adapterType: "paperclip_runner", config: { provider: "opencode", model: "google/gemini-2.5-flash" } }, + ] as const)("prepares OpenCode ($adapterType) with an Antigravity Google API key in both GEMINI_API_KEY and GOOGLE_GENERATIVE_AI_API_KEY", async ({ adapterType, config }) => { + const owner = `opencode-google-${adapterType}`; + await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); + const token = "fixture-antigravity-gemini-key"; + const account = await service.save(companyId, owner, { + provider: "google", + method: "api_key", + ownership: "personal", + name: owner, + apiKey: token, + allAgents: true, + agentIds: [], + }, token); + const runtime = await prepareManagedAiRuntime(db, { + companyId, + agentId, + responsibleUserId: owner, + adapterType, + binding: { provider: "google", method: "api_key", mode: "delegated", ...account }, + config: { ...config, env: { OPENAI_API_KEY: "stale-openai", OPENROUTER_API_KEY: "stale-openrouter" } }, + }); + try { + expect(runtime.config.env).toMatchObject({ + GEMINI_API_KEY: token, + GOOGLE_GENERATIVE_AI_API_KEY: token, + OPENCODE_DISABLE_PROJECT_CONFIG: "true", + OPENAI_API_KEY: "", + OPENROUTER_API_KEY: "", + }); + expect(runtime.attribution).toMatchObject({ connectionId: account.connectionId, grantId: account.grantId, provider: "google", method: "api_key" }); + } finally { + await runtime.cleanup(); + } + }); + it.each([200, 401])("reverifies native Pi OpenRouter keys without requiring the Legacy Pi CLI (HTTP %s)", async status => { const owner = `pi-adoption-${status}`; await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); diff --git a/server/src/__tests__/ai-provider-routing.test.ts b/server/src/__tests__/ai-provider-routing.test.ts index c5f520a715d..fbe276877a5 100644 --- a/server/src/__tests__/ai-provider-routing.test.ts +++ b/server/src/__tests__/ai-provider-routing.test.ts @@ -28,6 +28,13 @@ describe("provider routing", () => { expect(isAiConnectionCompatible({ provider, method: "subscription", mode: "responsible_user" }, "pi_local", `${provider}/model`)).toBe(true); expect(isAiConnectionCompatible({ provider, method: "api_key" }, "pi_local", "different/model")).toBe(false); }); + it.each(["openai", "anthropic", "google", "xai", "openrouter"] as const)("accepts OpenCode %s API keys only for matching models and rejects subscriptions", provider => { + expect(isAiConnectionCompatible({ provider, method: "api_key" }, "opencode_local", `${provider}/model`)).toBe(true); + expect(isAiConnectionCompatible({ provider, method: "api_key" }, "paperclip_runner", `${provider}/model`, "opencode")).toBe(true); + expect(isAiConnectionCompatible({ provider, method: "subscription" }, "opencode_local", `${provider}/model`)).toBe(false); + expect(isAiConnectionCompatible({ provider, method: "subscription", mode: "responsible_user" }, "opencode_local", `${provider}/model`)).toBe(true); + expect(isAiConnectionCompatible({ provider, method: "api_key" }, "opencode_local", "different/model")).toBe(false); + }); it.each([ "https://user:secret@gateway.example/v1", "https://gateway.example/v1?key=secret", diff --git a/server/src/__tests__/opencode-local-adapter-environment.test.ts b/server/src/__tests__/opencode-local-adapter-environment.test.ts index 2a0e44a2745..b9717136698 100644 --- a/server/src/__tests__/opencode-local-adapter-environment.test.ts +++ b/server/src/__tests__/opencode-local-adapter-environment.test.ts @@ -99,4 +99,77 @@ describe("opencode_local environment diagnostics", () => { await fs.rm(binDir, { recursive: true, force: true }); } }, 10_000); + + it("maps GEMINI_API_KEY to GOOGLE_GENERATIVE_AI_API_KEY for OpenCode probes and respects blank managed isolation", async () => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-env-gemini-cwd-")); + const binDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-env-gemini-bin-")); + const fakeOpencode = path.join(binDir, "opencode"); + const script = [ + "#!/bin/sh", + "if [ \"$1\" = \"models\" ]; then", + " echo 'google/gemini-2.5-flash'", + " exit 0", + "fi", + "if [ -z \"$GOOGLE_GENERATIVE_AI_API_KEY\" ]; then", + " echo 'Google Generative AI API key is missing. Pass it using the apiKey parameter or the GOOGLE_GENERATIVE_AI_API_KEY environment variable.' 1>&2", + " exit 1", + "fi", + "if [ \"$GOOGLE_GENERATIVE_AI_API_KEY\" != \"explicit-gemini-key\" ]; then", + " echo \"unexpected key: $GOOGLE_GENERATIVE_AI_API_KEY\" 1>&2", + " exit 1", + "fi", + "printf '{\"type\":\"text\",\"part\":{\"text\":\"hello\"}}\n'", + "exit 0", + "", + ].join("\n"); + const prevGemini = process.env.GEMINI_API_KEY; + const prevGoogleGenAi = process.env.GOOGLE_GENERATIVE_AI_API_KEY; + process.env.GEMINI_API_KEY = "ambient-gemini-key"; + process.env.GOOGLE_GENERATIVE_AI_API_KEY = "ambient-google-gen-ai-key"; + + try { + await fs.writeFile(fakeOpencode, script, { mode: 0o755 }); + + const direct = await testEnvironment({ + companyId: "company-1", + adapterType: "opencode_local", + config: { + command: fakeOpencode, + cwd, + model: "google/gemini-2.5-flash", + env: { + GEMINI_API_KEY: "explicit-gemini-key", + XDG_CONFIG_HOME: path.join(cwd, "config"), + }, + }, + }); + expect(direct.status).toBe("pass"); + expect(direct.checks.some((check) => check.code === "opencode_hello_probe_passed")).toBe(true); + + const isolated = await testEnvironment({ + companyId: "company-1", + adapterType: "opencode_local", + config: { + command: fakeOpencode, + cwd, + model: "google/gemini-2.5-flash", + managedAiConnection: true, + env: { + GEMINI_API_KEY: "", + GOOGLE_GENERATIVE_AI_API_KEY: "", + XDG_CONFIG_HOME: path.join(cwd, "config-isolated"), + }, + }, + }); + expect(isolated.status).not.toBe("pass"); + expect(isolated.checks.some((check) => check.code === "opencode_hello_probe_auth_required")).toBe(true); + } finally { + if (prevGemini === undefined) delete process.env.GEMINI_API_KEY; + else process.env.GEMINI_API_KEY = prevGemini; + if (prevGoogleGenAi === undefined) delete process.env.GOOGLE_GENERATIVE_AI_API_KEY; + else process.env.GOOGLE_GENERATIVE_AI_API_KEY = prevGoogleGenAi; + await fs.rm(cwd, { recursive: true, force: true }); + await fs.rm(binDir, { recursive: true, force: true }); + } + }, 15_000); }); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 59b34569f12..f04ab7c4b20 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -2371,9 +2371,17 @@ export function agentRoutes( claude_local: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"], codex_local: ["OPENAI_API_KEY", "CODEX_API_KEY"], grok_local: ["XAI_API_KEY"], - // OpenCode reaches its models through OpenRouter, the provider account - // AI connections bind for opencode_local. - opencode_local: ["OPENROUTER_API_KEY"], + // OpenCode reaches its models through provider API keys configured as env vars. + opencode_local: [ + "OPENROUTER_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "GOOGLE_GENERATIVE_AI_API_KEY", + "XAI_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", + ], }; function isInheritableCredentialReference(value: unknown): value is Record { @@ -3512,9 +3520,29 @@ export function agentRoutes( res.json(pluginRunnerAiConnectionRequiredTestResult(type, preconfiguredTestHome)); return; } + const testCredentialKeys = new Set(Object.keys(req.body.testCredentials ?? {})); + if (testCredentialKeys.has("GEMINI_API_KEY")) testCredentialKeys.add("GOOGLE_GENERATIVE_AI_API_KEY"); + if (testCredentialKeys.has("GOOGLE_GENERATIVE_AI_API_KEY")) testCredentialKeys.add("GEMINI_API_KEY"); + const adapterConfigForSecretResolution = (() => { + if (testCredentialKeys.size === 0) return adapterConfigForTest; + const next: Record = { ...adapterConfigForTest }; + if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) { + const filteredEnv = Object.fromEntries( + Object.entries(next.env as Record).filter( + ([key]) => !testCredentialKeys.has(key), + ), + ); + if (Object.keys(filteredEnv).length > 0) next.env = filteredEnv; + else delete next.env; + } + if (type === "hermes_gateway" && testCredentialKeys.has("API_SERVER_KEY")) { + delete next.apiKey; + } + return next; + })(); const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( companyId, - adapterConfigForTest, + adapterConfigForSecretResolution, { strictMode: strictSecretsMode, adapterType: type }, ); // Prospective, non-persisted config: resolve the acting user's own user @@ -3554,7 +3582,7 @@ export function agentRoutes( const selectedEnvironment = await environmentsSvc.getById(requestedEnvironmentId); const environmentEnv = Object.fromEntries( Object.entries(aiBinding ? stripAiAuthBindings(selectedEnvironment?.envVars) : parseObject(selectedEnvironment?.envVars)).filter( - ([key]) => !isForbiddenConfigEnvKey(key), + ([key]) => !isForbiddenConfigEnvKey(key) && !testCredentialKeys.has(key), ), ); if (Object.keys(environmentEnv).length > 0) { diff --git a/server/src/services/agent-ai-connection-default.ts b/server/src/services/agent-ai-connection-default.ts index c7585da9a2f..4a6ae3cfa36 100644 --- a/server/src/services/agent-ai-connection-default.ts +++ b/server/src/services/agent-ai-connection-default.ts @@ -11,7 +11,7 @@ import { // A config copied from another provider can retain unrelated keys. const PROVIDER_AUTH_ENV_KEYS: Record = { github: ["COPILOT_GITHUB_TOKEN"], - google: ["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL"], + google: ["GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL"], anthropic: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CONFIG_DIR", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"], openai: ["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_HOME", "OPENAI_BASE_URL"], openrouter: ["OPENROUTER_API_KEY", "OPENCODE_AUTH_JSON", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "PAPERCLIP_OPENCODE_PROVIDERS"], @@ -39,11 +39,14 @@ export function defaultAiConnectionForHire( // the new agent. Never silently replace an incompatible pool with local auth. // OpenCode also supports explicitly configured providers whose models are // outside the managed OpenRouter catalog. Their auth still takes precedence. - const childProvider = adapterType === "opencode_local" - || (adapterType === "paperclip_runner" && config.provider === "opencode") - ? "openrouter" - : AI_PROVIDERS.find((provider) => - compatible({ provider, method: "api_key", mode: "responsible_user" })); + const matchedProvider = AI_PROVIDERS.find((provider) => + compatible({ provider, method: "api_key", mode: "responsible_user" })); + const childProvider = matchedProvider ?? ( + adapterType === "opencode_local" + || (adapterType === "paperclip_runner" && config.provider === "opencode") + ? "openrouter" + : undefined + ); return childProvider && hasChildAuth(childProvider) ? undefined : inherited.data; } if (inherited.data.mode !== "delegated" && compatible(inherited.data)) { diff --git a/server/src/services/ai-auth-failure.test.ts b/server/src/services/ai-auth-failure.test.ts index 08892d1dab3..8d7aceebb8d 100644 --- a/server/src/services/ai-auth-failure.test.ts +++ b/server/src/services/ai-auth-failure.test.ts @@ -16,11 +16,15 @@ describe("AI authentication failure recovery", () => { ["paperclip_runner", { provider: "acpx", acpxAgent: "claude" }, "anthropic"], ["paperclip_runner", { provider: "acpx", acpxAgent: "grok" }, "xai"], ["opencode_local", { model: "openrouter/model" }, "openrouter"], + ["opencode_local", { model: "google/gemini-2.5-flash" }, "google"], + ["opencode_local", { model: "anthropic/claude" }, "anthropic"], + ["opencode_local", { model: "openai/gpt-5" }, "openai"], + ["opencode_local", { model: "xai/grok-4" }, "xai"], ] as const)("maps %s %j to %s", (adapter, config, provider) => { expect(aiBindingForAuthRecovery(adapter, config)).toMatchObject({ provider, mode: "responsible_user" }); }); it("does not guess a provider for unsupported harnesses or routes", () => { - expect(aiBindingForAuthRecovery("opencode_local", { model: "anthropic/claude" })).toBeUndefined(); + expect(aiBindingForAuthRecovery("opencode_local", { model: "zai/glm-5" })).toBeUndefined(); expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "acpx", acpxAgent: "custom" })).toBeUndefined(); }); it("offers Google's supported API-key method for Gemini recovery", () => { diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.ts index ee49c4631f9..02c60eebd25 100644 --- a/server/src/services/ai-connection-runtime.ts +++ b/server/src/services/ai-connection-runtime.ts @@ -54,7 +54,7 @@ export const AI_AUTH_ENV_KEYS = [ "COPILOT_GITHUB_TOKEN", "PAPERCLIP_AI_PROVIDER_KEY", "PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_CODEX_PROVIDERS", "PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN", - "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GOOGLE_GENAI_USE_VERTEXAI", + "GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GOOGLE_GENAI_USE_VERTEXAI", "GEMINI_HOME", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", "HERMES_HOME", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_SHARED_CREDENTIALS_FILE", "AWS_CONFIG_FILE", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", "ANTHROPIC_BEDROCK_BASE_URL", "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", @@ -67,6 +67,8 @@ export const AI_AUTH_ENV_KEYS = [ "OPENROUTER_API_KEY", "XAI_API_KEY", "GROK_API_KEY", + "GROQ_API_KEY", + "OPENCODE_API_KEY", "CODEX_HOME", "GROK_HOME", "CLAUDE_CONFIG_DIR", @@ -354,6 +356,11 @@ export async function prepareManagedAiRuntime( provider: { openrouter: { options: { apiKey: value, headers: OPENROUTER_ATTRIBUTION_HEADERS } } }, }); env.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; + } else if (!routing && harness === "opencode_local" && selection.attribution.method === "api_key") { + if (input.binding.provider === "google") { + env.GOOGLE_GENERATIVE_AI_API_KEY = value; + } + env.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; } if (!routing && input.binding.provider === "google" && harness === "gemini_local") { // Gemini headless CLI requires an explicit auth choice even with an API key. diff --git a/server/src/services/native-runtime/plugin-runner-credentials.test.ts b/server/src/services/native-runtime/plugin-runner-credentials.test.ts index 819229b7bd0..37a1bb2f71e 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.test.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.test.ts @@ -123,6 +123,14 @@ describe("plugin Runner provider environment credentials", () => { ["grok", { XAI_API_KEY: "fixture-xai" }], ["copilot", { COPILOT_GITHUB_TOKEN: "fixture-copilot" }], ["opencode", { OPENROUTER_API_KEY: "fixture-openrouter" }], + ["opencode", { GEMINI_API_KEY: "fixture-gemini" }], + ["opencode", { GOOGLE_GENERATIVE_AI_API_KEY: "fixture-google-genai" }], + ["opencode", { GEMINI_API_KEY: "fixture-gemini", GOOGLE_GENERATIVE_AI_API_KEY: "fixture-gemini" }], + ["opencode", { OPENAI_API_KEY: "fixture-openai" }], + ["opencode", { ANTHROPIC_API_KEY: "fixture-anthropic" }], + ["opencode", { XAI_API_KEY: "fixture-xai" }], + ["opencode", { GROQ_API_KEY: "fixture-groq" }], + ["opencode", { OPENCODE_API_KEY: "fixture-opencode" }], ["opencode", { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }], ] as const)("transfers only the selected %s variables", async (provider, environment) => { const transfer = await preparePluginRunnerCredentials({ provider, identity: "revision", accountIdentity: "account", @@ -154,6 +162,7 @@ describe("plugin Runner provider environment credentials", () => { ["opencode", { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1" }], ["opencode", { PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }], ["opencode", { OPENROUTER_API_KEY: "fixture-openrouter", PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }], + ["opencode", { GEMINI_API_KEY: "fixture-gemini", OPENAI_API_KEY: "fixture-openai" }], ["opencode", { OPENROUTER_API_KEY: "fixture\0value" }], ] as const)("fails closed for an incomplete or ambiguous %s credential", async (provider, environment) => { const result = preparePluginRunnerCredentials({ provider, identity: "revision", environment: { ...blanks, ...environment } }); diff --git a/ui/src/components/ai-connections/AiConnectionField.tsx b/ui/src/components/ai-connections/AiConnectionField.tsx index e2c247162e2..ae56d945cec 100644 --- a/ui/src/components/ai-connections/AiConnectionField.tsx +++ b/ui/src/components/ai-connections/AiConnectionField.tsx @@ -108,10 +108,14 @@ export function AiConnectionField({ routerAdapterType?: string; onUseHarnessAuth?: () => void; }) { - const piProvider = adapterType === "pi_local" ? model?.split("/")[0] : undefined; - const provider = adapterType === "pi_local" && ["anthropic", "openai", "google", "openrouter"].includes(piProvider ?? "") - ? piProvider as AiProvider - : adapterType === "pi_local" && value && value.mode !== "router" ? value.provider : aiProviderForAdapter(adapterType); + const multiProviderHarness = adapterType === "pi_local" || adapterType === "opencode_local"; + const supportedMultiProviders = adapterType === "opencode_local" + ? ["anthropic", "openai", "google", "openrouter", "xai"] + : ["anthropic", "openai", "google", "openrouter"]; + const modelProvider = multiProviderHarness ? model?.split("/")[0] : undefined; + const provider = multiProviderHarness && supportedMultiProviders.includes(modelProvider ?? "") + ? modelProvider as AiProvider + : multiProviderHarness && value && value.mode !== "router" ? value.provider : aiProviderForAdapter(adapterType); const returnFocus = useRef(null); const restoreFocus = (event: Event) => { event.preventDefault(); returnFocus.current?.focus(); }; const [adopting, setAdopting] = useState(false); @@ -170,9 +174,12 @@ export function AiConnectionField({ selectDefault.reset(); setConnecting(true); }; - const method: AiAuthMethod = (value && value.mode !== "router" && value.mode !== "responsible_user" ? value.method : undefined) - ?? accounts.data?.connections.find((account) => account.provider === provider && account.isDefault)?.method - ?? (provider === "openrouter" || provider === "google" || provider === "github" ? "api_key" : "subscription"); + const apiKeyOnlyHarness = adapterType === "pi_local" || adapterType === "opencode_local"; + const method: AiAuthMethod = apiKeyOnlyHarness + ? "api_key" + : (value && value.mode !== "router" && value.mode !== "responsible_user" ? value.method : undefined) + ?? accounts.data?.connections.find((account) => account.provider === provider && account.isDefault)?.method + ?? (provider === "openrouter" || provider === "google" || provider === "github" ? "api_key" : "subscription"); const compatiblePools = agentId ? accounts.data?.pools?.filter(pool => pool.enabled && pool.members.some(member => isAiConnectionCompatible(member.binding, routerAdapterType ?? adapterType, member.profile.model, member.profile.provider, member.profile.acpxAgent))) ?? [] : []; if (!provider) return null; if (legacy && !value && !adopting) @@ -306,7 +313,7 @@ export function AiConnectionField({ companyId={companyId} provider={provider} initialMethod={reconnecting?.method ?? method} - fixedMethod={Boolean(reconnecting)} + fixedMethod={Boolean(reconnecting) || apiKeyOnlyHarness} connectionId={reconnecting?.id} name={reconnecting?.name ?? `My ${provider === "anthropic" ? "Claude" : provider === "openai" ? "OpenAI" : provider === "xai" ? "Grok" : provider === "google" ? "Antigravity" : provider === "github" ? "GitHub Copilot" : "OpenRouter"} ${method === "subscription" ? "subscription" : "API"}`} ownership="personal" diff --git a/ui/src/components/ai-connections/AiConnectionSelect.test.tsx b/ui/src/components/ai-connections/AiConnectionSelect.test.tsx index bbd7d7479eb..cfe5e771db6 100644 --- a/ui/src/components/ai-connections/AiConnectionSelect.test.tsx +++ b/ui/src/components/ai-connections/AiConnectionSelect.test.tsx @@ -62,6 +62,29 @@ it.each(["anthropic", "openai", "google", "openrouter"] as const)("offers %s API expect(options.some(option => option.textContent?.includes("Supported API account"))).toBe(true); }); +it.each(["anthropic", "openai", "google", "xai", "openrouter"] as const)("offers %s API accounts for OpenCode before a model is chosen", async provider => { + const options = await openConnections({ adapterType: "opencode_local", connections: [{ + id: "key", grantId: "grant", companyId: "company", provider, method: "api_key", + name: "Supported OpenCode API account", ownership: "shared", status: "connected", + }] }); + expect(options.some(option => option.textContent?.includes("Supported OpenCode API account"))).toBe(true); +}); + +it("offers Antigravity API keys for Google OpenCode models and rejects Antigravity subscriptions", async () => { + const connections = [ + { id: "google-key", grantId: "grant-key", companyId: "company", provider: "google" as const, method: "api_key" as const, + name: "Antigravity API key", ownership: "shared" as const, status: "connected" as const }, + { id: "google-sub", grantId: "grant-sub", companyId: "company", provider: "google" as const, method: "subscription" as const, + name: "Antigravity OAuth", ownership: "shared" as const, status: "connected" as const }, + ]; + const googleOptions = await openConnections({ adapterType: "opencode_local", model: "google/gemini-2.5-flash", connections }); + expect(googleOptions.some(option => option.textContent?.includes("Antigravity API key"))).toBe(true); + expect(googleOptions.some(option => option.textContent?.includes("Antigravity OAuth"))).toBe(false); + + const openaiOptions = await openConnections({ adapterType: "opencode_local", model: "openai/gpt-5", connections }); + expect(openaiOptions.some(option => option.textContent?.includes("Antigravity API key"))).toBe(false); +}); + it("uses the actual default account's sign-in method for harness compatibility", async () => { const options = await openConnections({ adapterType: "gemini_local", requirement: { companyId: "company", provider: "google" }, connections: [{ id: "google", grantId: "grant", companyId: "company", provider: "google", method: "subscription", diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index a271ed5b737..eb593065746 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -57,8 +57,11 @@ import { environmentDisplayLabel } from "@/lib/managed-sandbox-environment"; import { buildNewAgentRuntimeConfig } from "@/lib/new-agent-runtime-config"; import { PROVIDER_ENV_KEYS, + applySetupCredentialConfig, + resolveSetupCredentialBinding, storeProviderApiKey, storeOrganizationApiKey, + type SetupCredentialBinding, } from "@/lib/provider-credential"; import { defaultCreateValues } from "../agent-config-defaults"; import { ModelDropdown } from "../AgentConfigForm"; @@ -387,23 +390,19 @@ function Setup({ const savedOrganizationKey = companySecrets.data?.find( (entry) => entry.key === envKey && entry.status === "active", ); - const selectedBinding = - adapterType === "cursor_cloud" - ? nativeCursorCloud ? providerBinding : null - : (providerBinding ?? - (savedOrganizationKey - ? { - type: "secret_ref" as const, - secretId: savedOrganizationKey.id, - version: "latest" as const, - } - : savedKey - ? { - type: "user_secret_ref" as const, - key: envKey, - version: "latest" as const, - } - : null)); + const selectedBinding = resolveSetupCredentialBinding({ + adapterType, + nativeCursorCloud, + apiKey, + providerBinding: + providerBinding && typeof providerBinding === "object" && "type" in providerBinding + && (providerBinding.type === "secret_ref" || providerBinding.type === "user_secret_ref") + ? (providerBinding as SetupCredentialBinding) + : null, + savedOrganizationSecretId: savedOrganizationKey?.id ?? null, + hasSavedUserKey: Boolean(savedKey), + envKey, + }); const usingKimiApi = adapterType === "kimi_local" && Boolean(apiKey.trim() || selectedBinding); const cloud = Boolean(useCloudInstance()); @@ -519,10 +518,20 @@ function Setup({ config.model = model; config.env = { ...((saved.env as object) ?? {}), ...((config.env as object) ?? {}) }; } - if (!aiBinding && !nextConnection?.aiConnection && hasCredentialField && binding) { - if (adapterType === "hermes_gateway") config.apiKey = binding; - else - config.env = { ...((config.env as object) ?? {}), [envKey]: binding }; + if (!aiBinding && !nextConnection?.aiConnection && hasCredentialField) { + applySetupCredentialConfig(config, { + adapterType, + envKey, + apiKey, + binding: + binding && typeof binding === "object" && "type" in binding + && (binding.type === "secret_ref" || binding.type === "user_secret_ref") + ? (binding as SetupCredentialBinding) + : null, + multiProvider, + isSetupDraft: created?.pauseReason === "setup", + providerEnvKeys: providerKeys, + }); } if (adapterType === "cursor_cloud") Object.assign(config, { diff --git a/ui/src/lib/provider-credential.test.ts b/ui/src/lib/provider-credential.test.ts new file mode 100644 index 00000000000..9c2c062e4fc --- /dev/null +++ b/ui/src/lib/provider-credential.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from "vitest"; +import { + applySetupCredentialConfig, + resolveSetupCredentialBinding, +} from "./provider-credential"; + +describe("provider credential setup helpers", () => { + it("ignores auto-selected organization or personal secrets when an explicit raw API key is entered", () => { + expect( + resolveSetupCredentialBinding({ + adapterType: "opencode_local", + nativeCursorCloud: false, + apiKey: "AIza-explicit-key", + providerBinding: { + type: "secret_ref", + secretId: "stale-org-secret", + version: "latest", + }, + savedOrganizationSecretId: "org-secret-1", + hasSavedUserKey: true, + envKey: "GEMINI_API_KEY", + }), + ).toBeNull(); + }); + + it("falls back to explicit binding, then org secret, then personal secret when raw API key is blank", () => { + expect( + resolveSetupCredentialBinding({ + adapterType: "opencode_local", + nativeCursorCloud: false, + apiKey: " ", + providerBinding: null, + savedOrganizationSecretId: "org-secret-1", + hasSavedUserKey: true, + envKey: "GEMINI_API_KEY", + }), + ).toEqual({ + type: "secret_ref", + secretId: "org-secret-1", + version: "latest", + }); + + expect( + resolveSetupCredentialBinding({ + adapterType: "opencode_local", + nativeCursorCloud: false, + apiKey: "", + providerBinding: null, + savedOrganizationSecretId: null, + hasSavedUserKey: true, + envKey: "GEMINI_API_KEY", + }), + ).toEqual({ + type: "user_secret_ref", + key: "GEMINI_API_KEY", + version: "latest", + }); + }); + + it("strips stale provider secret refs and Google aliases when testing a raw API key on a multi-provider setup draft", () => { + const config: Record = { + model: "google/gemini-2.5-flash", + env: { + OPENROUTER_API_KEY: { + type: "secret_ref", + secretId: "deleted-openrouter-secret", + version: "latest", + }, + GEMINI_API_KEY: { + type: "secret_ref", + secretId: "stale-gemini-secret", + version: "latest", + }, + GOOGLE_GENERATIVE_AI_API_KEY: { + type: "secret_ref", + secretId: "stale-google-genai-secret", + version: "latest", + }, + CUSTOM_FLAG: "keep-me", + }, + }; + + applySetupCredentialConfig(config, { + adapterType: "opencode_local", + envKey: "GEMINI_API_KEY", + apiKey: "AIza-explicit-key", + binding: null, + multiProvider: true, + isSetupDraft: true, + }); + + expect(config.env).toEqual({ CUSTOM_FLAG: "keep-me" }); + }); + + it("removes the env object completely when all stale provider refs are cleared", () => { + const config: Record = { + model: "google/gemini-2.5-flash", + env: { + OPENROUTER_API_KEY: { + type: "secret_ref", + secretId: "deleted-openrouter-secret", + version: "latest", + }, + }, + }; + + applySetupCredentialConfig(config, { + adapterType: "opencode_local", + envKey: "GEMINI_API_KEY", + apiKey: "AIza-explicit-key", + binding: null, + multiProvider: true, + isSetupDraft: true, + }); + + expect(config).toEqual({ model: "google/gemini-2.5-flash" }); + }); + + it("replaces stale other-provider bindings and Google aliases when applying a saved binding on a multi-provider draft", () => { + const config: Record = { + model: "google/gemini-2.5-flash", + env: { + OPENROUTER_API_KEY: { + type: "secret_ref", + secretId: "old-openrouter-secret", + version: "latest", + }, + GOOGLE_GENERATIVE_AI_API_KEY: { + type: "secret_ref", + secretId: "old-google-genai-secret", + version: "latest", + }, + }, + }; + + applySetupCredentialConfig(config, { + adapterType: "opencode_local", + envKey: "GEMINI_API_KEY", + apiKey: "", + binding: { + type: "secret_ref", + secretId: "gemini-org-secret", + version: "latest", + }, + multiProvider: true, + isSetupDraft: true, + }); + + expect(config.env).toEqual({ + GEMINI_API_KEY: { + type: "secret_ref", + secretId: "gemini-org-secret", + version: "latest", + }, + }); + }); +}); diff --git a/ui/src/lib/provider-credential.ts b/ui/src/lib/provider-credential.ts index 5ef857679e3..cba1a5696cb 100644 --- a/ui/src/lib/provider-credential.ts +++ b/ui/src/lib/provider-credential.ts @@ -10,6 +10,11 @@ export const PROVIDER_ENV_KEYS: Record = { opencode: "OPENCODE_API_KEY", }; +const PROVIDER_ENV_KEY_ALIASES: Readonly> = { + GEMINI_API_KEY: ["GOOGLE_GENERATIVE_AI_API_KEY"], + GOOGLE_GENERATIVE_AI_API_KEY: ["GEMINI_API_KEY"], +}; + /** New organization credentials get a distinct key; never rotate another agent's secret. */ export async function storeOrganizationApiKey( companyId: string, @@ -66,3 +71,111 @@ export async function storeProviderApiKey( remove, }; } + +export type SetupCredentialBinding = + | { type: "secret_ref"; secretId: string; version: "latest" | number } + | { type: "user_secret_ref"; key: string; version: "latest" | number }; + +/** + * Resolve which saved secret binding (if any) applies during agent setup. + * An explicit raw API key entered by the user always overrides any auto-selected + * organization or personal secret so testing/saving never fails on an unused + * or inaccessible secret ref. + */ +export function resolveSetupCredentialBinding(input: { + adapterType: string; + nativeCursorCloud: boolean; + apiKey: string; + providerBinding: SetupCredentialBinding | null; + savedOrganizationSecretId?: string | null; + hasSavedUserKey?: boolean; + envKey: string; +}): SetupCredentialBinding | null { + if (input.apiKey.trim().length > 0) return null; + if (input.adapterType === "cursor_cloud") { + return input.nativeCursorCloud ? input.providerBinding : null; + } + if (input.providerBinding) return input.providerBinding; + if (input.savedOrganizationSecretId) { + return { + type: "secret_ref", + secretId: input.savedOrganizationSecretId, + version: "latest", + }; + } + if (input.hasSavedUserKey) { + return { + type: "user_secret_ref", + key: input.envKey, + version: "latest", + }; + } + return null; +} + +/** + * Apply or clear setup credential bindings on an adapterConfig draft. + * When a raw API key is being tested or saved, remove any stale saved binding + * for `envKey` (and stale other-provider bindings on multi-provider setup drafts) + * so probe requests do not validate dead secret references. + */ +export function applySetupCredentialConfig( + config: Record, + input: { + adapterType: string; + envKey: string; + apiKey: string; + binding: SetupCredentialBinding | null; + multiProvider: boolean; + isSetupDraft: boolean; + providerEnvKeys?: Record; + }, +): void { + const hasRawApiKey = input.apiKey.trim().length > 0; + const currentEnv: Record = + config.env && typeof config.env === "object" && !Array.isArray(config.env) + ? { ...(config.env as Record) } + : {}; + let envTouched = false; + + if (input.multiProvider && input.isSetupDraft && (hasRawApiKey || input.binding)) { + const providerKeySet = new Set(Object.values(input.providerEnvKeys ?? PROVIDER_ENV_KEYS)); + for (const key of [...providerKeySet]) { + for (const alias of PROVIDER_ENV_KEY_ALIASES[key] ?? []) { + providerKeySet.add(alias); + } + } + for (const key of providerKeySet) { + if (key === input.envKey) continue; + if (key in currentEnv) { + delete currentEnv[key]; + envTouched = true; + } + } + } + + if (hasRawApiKey) { + if (input.adapterType === "hermes_gateway") { + delete config.apiKey; + } else { + for (const key of [input.envKey, ...(PROVIDER_ENV_KEY_ALIASES[input.envKey] ?? [])]) { + if (key in currentEnv) { + delete currentEnv[key]; + envTouched = true; + } + } + } + } else if (input.binding) { + if (input.adapterType === "hermes_gateway") { + config.apiKey = input.binding; + } else { + currentEnv[input.envKey] = input.binding; + envTouched = true; + } + } + + if (envTouched) { + if (Object.keys(currentEnv).length > 0) config.env = currentEnv; + else delete config.env; + } +}