fix(opencode): fix API key env/secret resolution and support Antigravity connector

- Strip probe-overridden credential keys (including symmetric GEMINI_API_KEY /
  GOOGLE_GENERATIVE_AI_API_KEY aliases) from adapterConfig and environment
  envVars before secret persistence and runtime resolution in test-environment.
- Prefer an explicit pasted API key over auto-selected organization secrets in
  NewAgentSetup, and clear stale provider refs when switching credentials.
- Alias GEMINI_API_KEY to GOOGLE_GENERATIVE_AI_API_KEY and pass direct provider
  API keys across legacy opencode_local, native paperclip-runner (TS and Rust),
  and Plugin Runner environments, while redacting provider keys in output custody.
- Enable API-key AI connections (including the Google / Antigravity connector)
  for opencode_local with provider-to-model compatibility checks and isolated
  runtime environment preparation.

Fixes #23359
Refs #23370

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
cryppadottaandPaperclip committed 2026-12-01 15:53:11 +00:00
1 parent ea56320e10
commit 486ab99f71
31 files changed
+908 -82

No files matched your search

@@ -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");
});
});
@@ -5,6 +5,10 @@ const API_KEY_NAMES: Readonly<Record<string, readonly string[]>> = {
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
@@ -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",
});
});
});
@@ -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;
@@ -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<string>();
@@ -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: "",
});
});
});
@@ -104,14 +104,36 @@ async function readJsonObject(filepath: string): Promise<Record<string, unknown>
}
}
/**
* 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<string, string>,
): Record<string, string> {
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<string, string>;
config: Record<string, unknown>;
sandboxToolOomPreference?: boolean;
}): Promise<PreparedOpenCodeRuntimeConfig> {
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 } : {}),
@@ -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",
@@ -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",
@@ -40,7 +40,8 @@ export const GENERATED_RUNTIME_ENVIRONMENT_KEYS: ReadonlySet<string> = 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",
];
@@ -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",
@@ -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";
@@ -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<Record<string, readonly string[]>> = {
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<string, string> {
if (!modelProvider) return {};
const keys = OPENCODE_DIRECT_PROVIDER_ENV_MAP[modelProvider];
if (!keys) return {};
const resolved: Record<string, string> = {};
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<string, string>,
@@ -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);
@@ -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",
@@ -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",
]);
+12 -1
View File
@@ -59,7 +59,18 @@ export type PluginEnvironmentTaskConfiguredEnvironment = z.infer<typeof environm
export const ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS = {
grok: [["XAI_API_KEY"]],
copilot: [["COPILOT_GITHUB_TOKEN"]],
opencode: [["OPENROUTER_API_KEY"], ["PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_AI_PROVIDER_KEY"]],
opencode: [
["OPENROUTER_API_KEY"],
["PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_AI_PROVIDER_KEY"],
["GEMINI_API_KEY"],
["GOOGLE_GENERATIVE_AI_API_KEY"],
["GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
["OPENAI_API_KEY"],
["ANTHROPIC_API_KEY"],
["XAI_API_KEY"],
["GROQ_API_KEY"],
["OPENCODE_API_KEY"],
],
antigravity: [["GEMINI_API_KEY"], ["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]],
} as const satisfies Record<string, readonly (readonly string[])[]>;
export type PluginEnvironmentTaskCredentialProvider = keyof typeof ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS;
+6 -6
View File
@@ -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 =
+1
View File
@@ -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),
@@ -21,7 +21,7 @@ const mockSecretService = vi.hoisted(() => ({
normalizeAdapterConfigForPersistence: vi.fn(async (_companyId: string, config: Record<string, unknown>) => config),
resolveAdapterConfigForRuntime: vi.fn(async (_companyId: string, config: Record<string, unknown>) => ({ config })),
collectMissingRuntimeBindings: vi.fn(async () => [] as Array<Record<string, unknown>>),
resolveEnvBindings: vi.fn(async () => ({
resolveEnvBindings: vi.fn(async (_companyId: string, _env: Record<string, unknown>) => ({
env: {} as Record<string, string>,
secretKeys: new Set<string>(),
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<string, unknown>;
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<string, unknown>;
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<string>(), 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");
@@ -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" });
@@ -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",
@@ -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);
});
+33 -5
View File
@@ -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<string, unknown> {
@@ -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<string, unknown> = { ...adapterConfigForTest };
if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) {
const filteredEnv = Object.fromEntries(
Object.entries(next.env as Record<string, unknown>).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) {
@@ -11,7 +11,7 @@ import {
// A config copied from another provider can retain unrelated keys.
const PROVIDER_AUTH_ENV_KEYS: Record<AiProvider, readonly string[]> = {
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)) {
+5 -1
View File
@@ -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", () => {
+8 -1
View File
@@ -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.
@@ -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 } });
@@ -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<HTMLElement | null>(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"
@@ -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",
+30 -21
View File
@@ -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, {
+157
View File
@@ -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<string, unknown> = {
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<string, unknown> = {
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<string, unknown> = {
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",
},
});
});
});
+113
View File
@@ -10,6 +10,11 @@ export const PROVIDER_ENV_KEYS: Record<string, string> = {
opencode: "OPENCODE_API_KEY",
};
const PROVIDER_ENV_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
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<string, unknown>,
input: {
adapterType: string;
envKey: string;
apiKey: string;
binding: SetupCredentialBinding | null;
multiProvider: boolean;
isSetupDraft: boolean;
providerEnvKeys?: Record<string, string>;
},
): void {
const hasRawApiKey = input.apiKey.trim().length > 0;
const currentEnv: Record<string, unknown> =
config.env && typeof config.env === "object" && !Array.isArray(config.env)
? { ...(config.env as Record<string, unknown>) }
: {};
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;
}
}