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

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments

## Linked Issues or Issue Description

- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)

## What Changed

- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
03dc341957 --check` — passed (`changed:
false`, 602 inputs)
- GitHub CI on `03dc341957`: all 95 checks green (`MERGEABLE` / `CLEAN`)
— `ci / verify` ([run
47315344108](https://github.com/paperclipai/paperclip/actions/runs/47315344108)),
`ci / e2e`, `Verify Paperclip Runner` (static checks, Rust, Vitest
package & native server suites), `Runner Windows` ([run
47315343800](https://github.com/paperclipai/paperclip/actions/runs/47315343800)),
`Runner image` (`amd64` + `arm64`, [run
47315343840](https://github.com/paperclipai/paperclip/actions/runs/47315343840)),
`macOS OpenCode SSH runtime` ([run
47315343817](https://github.com/paperclipai/paperclip/actions/runs/47315343817)),
`Verify serialized server suites` (1/9–9/9), `Superagent Security Scan`,
`Greptile Review` (5/5), `Paperclip Review` (5/5), `Socket Security`,
and `security/snyk` passed.
- Local verification gap: `cargo` is not installed in this container;
Rust checks (`typecheck:rust` / `test:rust`) ran and passed in GitHub CI
(`verify_paperclip_runner`).

## Risks

- Low to moderate risk. No database schema or migration changes are
included.
- Touches provider credential allowlists in both TypeScript and Rust
(`codex_provider.rs`, `configured_environment.rs`), the runner-owned
loopback proxy for direct OpenCode providers, and secret-stripping logic
in `POST /companies/:companyId/adapters/:type/test-environment`. Parity
between TypeScript and Rust allowlists is enforced by
`plugin-runner-credential-names.test.ts`, and Rust build/test checks
pass in CI.
- `opencode_local` AI connection compatibility enforces that the
selected model prefix matches the connected provider (for example,
`google/...` for a Google/Antigravity API-key connection). Existing
`openrouter/...` connections remain compatible.

## Model Used

- Google Gemini (Antigravity agent runtime) with reasoning, repository
code navigation, shell execution, and automated test verification.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-04 12:20:32 -06:00
1 parent 01ecbadbf1
commit cfe5042378
38 files changed
+2106 -226

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,58 @@ 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",
});
});
it("does not repopulate an explicitly blanked GOOGLE_GENERATIVE_AI_API_KEY from ambient GEMINI_API_KEY", async () => {
vi.stubEnv("GEMINI_API_KEY", "ambient-host-gemini-key");
vi.stubEnv("GOOGLE_GENERATIVE_AI_API_KEY", "ambient-host-google-key");
const spy = vi.spyOn(serverUtils, "runChildProcess").mockResolvedValue({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "google/gemini-2.5-flash\n",
stderr: "",
pid: 1,
startedAt: new Date().toISOString(),
});
try {
await discoverOpenCodeModels({
env: { GOOGLE_GENERATIVE_AI_API_KEY: "" },
});
expect(spy.mock.calls[0]?.[3]?.env?.GOOGLE_GENERATIVE_AI_API_KEY).toBe("");
await discoverOpenCodeModels({
env: { GEMINI_API_KEY: "explicit-run-gemini-key" },
});
expect(spy.mock.calls[1]?.[3]?.env).toMatchObject({
GEMINI_API_KEY: "explicit-run-gemini-key",
GOOGLE_GENERATIVE_AI_API_KEY: "explicit-run-gemini-key",
});
} finally {
vi.unstubAllEnvs();
}
});
});
@@ -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,10 +160,16 @@ export async function discoverOpenCodeModels(
// image). Fall back to process.env.HOME.
}
// Prevent OpenCode from writing an opencode.json into the working directory.
// Apply Google alias independently to host and explicit envs before merging so
// an explicit blank GOOGLE_GENERATIVE_AI_API_KEY cannot be repopulated by an
// ambient host GEMINI_API_KEY, while an explicit GEMINI_API_KEY still overrides
// an ambient host GOOGLE_GENERATIVE_AI_API_KEY.
const aliasedHostEnv = applyOpenCodeProviderEnvAliases(normalizeEnv(process.env));
const aliasedExplicitEnv = applyOpenCodeProviderEnvAliases(env);
const runtimeEnv = normalizeEnv(
ensurePathInEnv({
...process.env,
...env,
...aliasedHostEnv,
...aliasedExplicitEnv,
...(resolvedHome ? { HOME: resolvedHome } : {}),
OPENCODE_DISABLE_PROJECT_CONFIG: "true",
}),
@@ -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 } : {}),
@@ -100,6 +100,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_RUNNER_HARNESS_STATE_DIR",
@@ -49,15 +49,21 @@ const RESERVED: &[&str] = &[
"CURSOR_API_KEY",
"CURSOR_AUTH_TOKEN",
"ENV",
"GEMINI_API_KEY",
"GH_ENTERPRISE_TOKEN",
"GH_TOKEN",
"GITHUB_ENTERPRISE_TOKEN",
"GITHUB_TOKEN",
"GOOGLE_API_KEY",
"GOOGLE_GENERATIVE_AI_API_KEY",
"GROK_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",
@@ -240,6 +246,8 @@ mod tests {
"[\"PAPERCLIP_RUNTIME_NOTIFICATION_CONTEXT\"]",
"[\"PAPERCLIP_RUNTIME_NOTIFICATION_HELPER\"]",
"[\"OPENAI_API_KEY\"]",
"[\"GOOGLE_API_KEY\"]",
"[\"GROK_API_KEY\"]",
"[\"KIMI_API_KEY\"]",
"[\"PAPERCLIP_NATIVE_MCP_NAME\"]",
"[\"PAPERCLIP_NATIVE_MCP_URL\"]",
@@ -89,6 +89,21 @@ describe("configured environment authority", () => {
expect(createSanitizedAcpxSpawnInput(selected, "pi").env.KIMI_API_KEY).toBe("selected-kimi-secret");
});
it("reserves Google and Grok provider credentials from generic task projections", () => {
const projected = configuredEnvironmentProjection({
GEMINI_API_KEY: "selected-gemini-secret",
GOOGLE_API_KEY: "selected-google-secret",
GOOGLE_GENERATIVE_AI_API_KEY: "selected-google-genai-secret",
GROK_API_KEY: "selected-grok-secret",
CUSTOM_FLAG: "allowed",
});
expect(projected.GEMINI_API_KEY).toBeUndefined();
expect(projected.GOOGLE_API_KEY).toBeUndefined();
expect(projected.GOOGLE_GENERATIVE_AI_API_KEY).toBeUndefined();
expect(projected.GROK_API_KEY).toBeUndefined();
expect(JSON.parse(projected[CONFIGURED_ENVIRONMENT_KEYS]!)).toEqual(["CUSTOM_FLAG"]);
});
it("does not accept an ambient projection in the provider or shell policy", () => {
vi.stubEnv(CONFIGURED_ENVIRONMENT_KEYS, JSON.stringify(["PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"]));
vi.stubEnv("PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", "ambient-secret");
@@ -98,7 +113,7 @@ describe("configured environment authority", () => {
} finally { vi.unstubAllEnvs(); }
});
it.each(["not-json", "[1]", '["NODE_OPTIONS"]', '["PAPERCLIP_API_KEY"]', '["PAPERCLIP_RUNNER_BOOTSTRAP_TICKET"]', '["OPENAI_API_KEY"]', '["KIMI_API_KEY"]', '["PAPERCLIP_NATIVE_MCP_NAME"]', '["PAPERCLIP_NATIVE_MCP_URL"]', '["PAPERCLIP_NATIVE_MCP_TOKEN"]', '["LD_PRELOAD"]', '["bad=name"]', '["CUSTOM","CUSTOM"]', '["MISSING"]'])
it.each(["not-json", "[1]", '["NODE_OPTIONS"]', '["PAPERCLIP_API_KEY"]', '["PAPERCLIP_RUNNER_BOOTSTRAP_TICKET"]', '["OPENAI_API_KEY"]', '["GOOGLE_API_KEY"]', '["GROK_API_KEY"]', '["KIMI_API_KEY"]', '["PAPERCLIP_NATIVE_MCP_NAME"]', '["PAPERCLIP_NATIVE_MCP_URL"]', '["PAPERCLIP_NATIVE_MCP_TOKEN"]', '["LD_PRELOAD"]', '["bad=name"]', '["CUSTOM","CUSTOM"]', '["MISSING"]'])
("rejects malformed or reserved projection %s", raw => {
expect(() => configuredEnvironment({ [CONFIGURED_ENVIRONMENT_KEYS]: raw })).toThrow("Invalid configured environment");
});
@@ -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_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY",
"XAI_API_KEY", "GROK_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",
];
@@ -4940,6 +4940,10 @@ const runnerExplicitProviderEnvironmentKeys = [
"PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET",
"PAPERCLIP_ACPX_AUTH_JSON_FILE",
"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",
@@ -111,19 +111,22 @@ it("leaves no unchanged OAuth handoff after failed admission or an API-key sessi
});
it("keeps the selected key while removing conflicting explicitly projected Google auth and runtime controls", () => {
const source = configuredEnvironmentProjection({
const projected = configuredEnvironmentProjection({
GEMINI_API_KEY: "selected-key", GOOGLE_API_KEY: "other-key", GOOGLE_APPLICATION_CREDENTIALS: "/foreign/adc.json",
GOOGLE_GENAI_USE_VERTEXAI: "true", GOOGLE_CLOUD_PROJECT: "foreign-project", GEMINI_HOME: "/foreign/home",
AGY_LLM_GATEWAY_URL: "https://foreign.invalid", ANTIGRAVITY_HARNESS_PATH: "/foreign/helper",
CLOUDSDK_CONFIG: "/foreign/cloud", AGY_ACP_FORCE_FILE_STORAGE: "0", TASK_INPUT: "retained",
});
expect(projected.GEMINI_API_KEY).toBeUndefined();
expect(projected.GOOGLE_API_KEY).toBeUndefined();
const source = { ...projected, GEMINI_API_KEY: "selected-key" };
const env = createSanitizedAcpxSpawnInput(source, "antigravity").env;
expect(env.GEMINI_API_KEY).toBe("selected-key");
expect(env.TASK_INPUT).toBe("retained");
for (const name of Object.keys(source)) {
if (/^(?:GOOGLE_|GEMINI_|AGY_|ANTIGRAVITY_|CLOUDSDK_)/.test(name) && name !== "GEMINI_API_KEY") expect(env[name]).toBeUndefined();
}
expect(JSON.parse(env.PAPERCLIP_CONFIGURED_ENV_KEYS!)).toEqual(["GEMINI_API_KEY", "TASK_INPUT"]);
expect(JSON.parse(env.PAPERCLIP_CONFIGURED_ENV_KEYS!)).toEqual(["TASK_INPUT"]);
});
it("does not borrow an ambient Gemini key", () => {
@@ -32,11 +32,13 @@ import {
import { createCodexTaskEnvelope } from "../../contracts/codex.js";
import { PRP_BLOCKER_ALREADY_REPORTED_MESSAGE, PRP_RESULT_ALREADY_ACCEPTED_MESSAGE } from "../../contracts/completion-result.js";
import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironmentProjection } from "../../configured-environment.js";
import { createSanitizedOpenCodeRunnerEnvironment } from "../../live/runnerd-codex-transport.js";
import { localIntegrityBoundaryGolden } from "../../../test-support/local-integrity-boundary-golden.js";
import type { PrpEvent } from "../../protocol/replay-contract.js";
import {
OpenCodeServerDriver,
openCodeServerDriverInternals,
resolvePinnedOpenCodeCommand,
} from "./opencode-server-driver.js";
import { harnessStateSessionDirectoryName } from "../harness-state-directory.js";
@@ -1300,6 +1302,436 @@ describe("OpenCodeServerDriver", () => {
}
});
it("keeps direct Google provider keys out of OpenCode env and proxies Gemini requests with session-scoped auth", async () => {
await chmod(fixture, 0o755);
const geminiKey = "synthetic-direct-gemini-key";
const explicitGenAiKey = "synthetic-explicit-google-genai-key";
const openaiKey = "synthetic-unrelated-openai-key";
const openrouterKey = "synthetic-unrelated-openrouter-key";
let redirect = false;
const received: Array<{ apiKey: string | undefined; body: unknown }> = [];
const upstream = createHttpServer((request, response) => {
const chunks: Buffer[] = [];
request.on("data", chunk => chunks.push(Buffer.from(chunk)));
request.on("end", () => {
if (redirect) {
response.writeHead(307, { location: "https://attacker.invalid/v1beta" }).end();
return;
}
received.push({
apiKey: typeof request.headers["x-goog-api-key"] === "string" ? request.headers["x-goog-api-key"] : undefined,
body: JSON.parse(Buffer.concat(chunks).toString("utf8")),
});
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ candidates: [] }));
});
});
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (!address || typeof address === "string") throw new Error("Could not bind mock upstream");
upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`;
upstreamTransport.urls = [];
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-direct-keys-"));
roots.push(root);
const command = join(root, "direct-key-probe.mjs");
await writeFile(command, [
`#!${process.execPath}`,
'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,',
'}));',
`await import(${JSON.stringify(fixture)});`,
].join("\n"), { mode: 0o755 });
const previousGemini = process.env.GEMINI_API_KEY;
const previousGoogleGenAi = process.env.GOOGLE_GENERATIVE_AI_API_KEY;
const previousOpenAi = process.env.OPENAI_API_KEY;
const previousOpenRouter = process.env.OPENROUTER_API_KEY;
try {
const driver = new OpenCodeServerDriver({
model: "google/gemini-2.5-flash",
command,
runtimeDirectory: root,
environment: {
PATH: process.env.PATH,
GEMINI_API_KEY: geminiKey,
OPENAI_API_KEY: openaiKey,
OPENROUTER_API_KEY: openrouterKey,
},
});
const session = await driver.openSession({ runId: "direct-google", normalizedSessionId: "direct-google", workingDirectory: root });
let googleProxyUrl = "";
try {
const observed = JSON.parse(await readFile(join(root, "direct-google", "data", "direct-keys.json"), "utf8"));
expect(observed).toEqual({
gemini: null,
googleGenAi: null,
openai: null,
openrouter: null,
});
const configText = await readFile(join(root, "direct-google", "config", "opencode", "opencode.json"), "utf8");
expect(configText).not.toContain(geminiKey);
const config = JSON.parse(configText);
const { baseURL, apiKey } = config.provider.google.options;
expect(config.provider.google.npm).toBeUndefined();
expect(baseURL).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1beta$/);
expect(apiKey).not.toBe(geminiKey);
googleProxyUrl = `${baseURL}/models/gemini-2.5-flash:streamGenerateContent?alt=sse`;
const payload = { contents: [{ role: "user", parts: [{ text: "hello" }] }] };
expect((await fetch(googleProxyUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(401);
expect((await fetch(`${baseURL}/models/wrong-model:streamGenerateContent?alt=sse`, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404);
expect((await fetch(`${baseURL}/models/gemini-2.5-flash:streamGenerateContent?key=injected`, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404);
expect((await fetch(googleProxyUrl, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(200);
expect(received).toEqual([{ apiKey: geminiKey, body: payload }]);
expect(upstreamTransport.urls).toEqual(["https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"]);
redirect = true;
expect((await fetch(googleProxyUrl, { method: "POST", headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(502);
redirect = false;
} finally {
await session.close({ reason: "test" });
}
await expect(fetch(googleProxyUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })).rejects.toThrow();
// Explicit GOOGLE_GENERATIVE_AI_API_KEY takes precedence over GEMINI_API_KEY.
received.length = 0;
upstreamTransport.urls = [];
const explicitDriver = new OpenCodeServerDriver({
model: "google/gemini-2.5-flash",
command,
runtimeDirectory: root,
environment: {
PATH: process.env.PATH,
GEMINI_API_KEY: geminiKey,
GOOGLE_GENERATIVE_AI_API_KEY: explicitGenAiKey,
},
});
const explicitSession = await explicitDriver.openSession({ runId: "direct-google-explicit", normalizedSessionId: "direct-google-explicit", workingDirectory: root });
try {
const observed = JSON.parse(await readFile(join(root, "direct-google-explicit", "data", "direct-keys.json"), "utf8"));
expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null });
const config = JSON.parse(await readFile(join(root, "direct-google-explicit", "config", "opencode", "opencode.json"), "utf8"));
const { baseURL, apiKey } = config.provider.google.options;
const response = await fetch(`${baseURL}/models/gemini-2.5-flash:generateContent`, {
method: "POST",
headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" },
body: JSON.stringify({ contents: [] }),
});
expect(response.status).toBe(200);
expect(received).toEqual([{ apiKey: explicitGenAiKey, body: { contents: [] } }]);
expect(upstreamTransport.urls).toEqual(["https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"]);
} finally {
await explicitSession.close({ reason: "test" });
}
// Omitting environment must never leak ambient host direct provider keys or start a proxy from them.
process.env.GEMINI_API_KEY = "ambient-host-gemini-key";
process.env.GOOGLE_GENERATIVE_AI_API_KEY = "ambient-host-google-genai-key";
process.env.OPENAI_API_KEY = "ambient-host-openai-key";
process.env.OPENROUTER_API_KEY = "ambient-host-openrouter-key";
const ambientDriver = new OpenCodeServerDriver({
model: "google/gemini-2.5-flash",
command,
runtimeDirectory: root,
});
const ambientSession = await ambientDriver.openSession({
runId: "direct-google-no-ambient",
normalizedSessionId: "direct-google-no-ambient",
workingDirectory: root,
});
try {
const observed = JSON.parse(await readFile(join(root, "direct-google-no-ambient", "data", "direct-keys.json"), "utf8"));
expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null });
const config = JSON.parse(await readFile(join(root, "direct-google-no-ambient", "config", "opencode", "opencode.json"), "utf8"));
expect(config.provider.google.options).toBeUndefined();
} finally {
await ambientSession.close({ reason: "test" });
}
// Runnerd environment sanitization strips conflicting host Google keys so an explicit run GEMINI_API_KEY wins.
const sanitizedConflicting = createSanitizedOpenCodeRunnerEnvironment({
PATH: process.env.PATH,
GEMINI_API_KEY: geminiKey,
});
expect(sanitizedConflicting.GEMINI_API_KEY).toBe(geminiKey);
expect(sanitizedConflicting.GOOGLE_GENERATIVE_AI_API_KEY).toBeUndefined();
expect(sanitizedConflicting.OPENAI_API_KEY).toBeUndefined();
expect(sanitizedConflicting.OPENROUTER_API_KEY).toBeUndefined();
const sanitizedAmbientOnly = createSanitizedOpenCodeRunnerEnvironment(undefined);
expect(sanitizedAmbientOnly.GEMINI_API_KEY).toBeUndefined();
expect(sanitizedAmbientOnly.GOOGLE_GENERATIVE_AI_API_KEY).toBeUndefined();
expect(sanitizedAmbientOnly.OPENAI_API_KEY).toBeUndefined();
expect(sanitizedAmbientOnly.OPENROUTER_API_KEY).toBeUndefined();
const sanitizedExplicitOpenRouter = createSanitizedOpenCodeRunnerEnvironment({
PATH: process.env.PATH,
OPENROUTER_API_KEY: openrouterKey,
});
expect(sanitizedExplicitOpenRouter.OPENROUTER_API_KEY).toBe(openrouterKey);
received.length = 0;
const conflictingDriver = new OpenCodeServerDriver({
model: "google/gemini-2.5-flash",
command,
runtimeDirectory: root,
environment: sanitizedConflicting,
});
const conflictingSession = await conflictingDriver.openSession({
runId: "direct-google-host-conflict",
normalizedSessionId: "direct-google-host-conflict",
workingDirectory: root,
});
try {
const observed = JSON.parse(await readFile(join(root, "direct-google-host-conflict", "data", "direct-keys.json"), "utf8"));
expect(observed).toEqual({ gemini: null, googleGenAi: null, openai: null, openrouter: null });
const config = JSON.parse(await readFile(join(root, "direct-google-host-conflict", "config", "opencode", "opencode.json"), "utf8"));
const { baseURL, apiKey } = config.provider.google.options;
expect((await fetch(`${baseURL}/models/gemini-2.5-flash:streamGenerateContent?alt=sse`, {
method: "POST",
headers: { "x-goog-api-key": apiKey, "Content-Type": "application/json" },
body: JSON.stringify({ contents: [] }),
})).status).toBe(200);
expect(received).toEqual([{ apiKey: geminiKey, body: { contents: [] } }]);
} finally {
await conflictingSession.close({ reason: "test" });
}
} finally {
upstreamTransport.endpoint = "";
if (previousGemini === undefined) delete process.env.GEMINI_API_KEY;
else process.env.GEMINI_API_KEY = previousGemini;
if (previousGoogleGenAi === undefined) delete process.env.GOOGLE_GENERATIVE_AI_API_KEY;
else process.env.GOOGLE_GENERATIVE_AI_API_KEY = previousGoogleGenAi;
if (previousOpenAi === undefined) delete process.env.OPENAI_API_KEY;
else process.env.OPENAI_API_KEY = previousOpenAi;
if (previousOpenRouter === undefined) delete process.env.OPENROUTER_API_KEY;
else process.env.OPENROUTER_API_KEY = previousOpenRouter;
await new Promise<void>(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); });
}
});
it.each([
{
provider: "anthropic",
model: "claude-sonnet-4-5",
envKey: "ANTHROPIC_API_KEY",
secret: "synthetic-anthropic-key",
requestPath: "/messages",
expectedUpstreamUrl: "https://api.anthropic.com/v1/messages",
authHeader: "x-api-key",
extraHeaders: { "anthropic-version": "2023-06-01", "anthropic-beta": "structured-outputs-2025-11-13" },
},
{
provider: "openai",
model: "gpt-5",
envKey: "OPENAI_API_KEY",
secret: "synthetic-openai-key",
requestPath: "/responses",
expectedUpstreamUrl: "https://api.openai.com/v1/responses",
authHeader: "authorization",
extraHeaders: {},
},
{
provider: "xai",
model: "grok-3",
envKey: "XAI_API_KEY",
secret: "synthetic-xai-key",
requestPath: "/chat/completions",
expectedUpstreamUrl: "https://api.x.ai/v1/chat/completions",
authHeader: "authorization",
extraHeaders: {},
},
{
provider: "groq",
model: "llama-3.3-70b-versatile",
envKey: "GROQ_API_KEY",
secret: "synthetic-groq-key",
requestPath: "/chat/completions",
expectedUpstreamUrl: "https://api.groq.com/openai/v1/chat/completions",
authHeader: "authorization",
extraHeaders: {},
},
{
provider: "opencode",
model: "big-pickle",
envKey: "OPENCODE_API_KEY",
secret: "synthetic-opencode-key",
requestPath: "/chat/completions",
expectedUpstreamUrl: "https://opencode.ai/zen/v1/chat/completions",
authHeader: "authorization",
extraHeaders: { "x-opencode-client": "cli" },
},
] as const)("proxies direct $provider requests through a runner-owned loopback broker without exposing $envKey to the child", async ({
provider,
model,
envKey,
secret,
requestPath,
expectedUpstreamUrl,
authHeader,
extraHeaders,
}) => {
await chmod(fixture, 0o755);
const received: Array<{ headers: Record<string, string | string[] | undefined>; body: unknown }> = [];
const upstream = createHttpServer((request, response) => {
const chunks: Buffer[] = [];
request.on("data", chunk => chunks.push(Buffer.from(chunk)));
request.on("end", () => {
received.push({ headers: request.headers, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) });
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: "ok" }));
});
});
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (!address || typeof address === "string") throw new Error("Could not bind mock upstream");
upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`;
upstreamTransport.urls = [];
const root = await mkdtemp(join(tmpdir(), `paperclip-opencode-${provider}-proxy-`));
roots.push(root);
let session: Awaited<ReturnType<OpenCodeServerDriver["openSession"]>> | undefined;
try {
const driver = new OpenCodeServerDriver({
model: `${provider}/${model}`,
command: fixture,
runtimeDirectory: root,
environment: { PATH: process.env.PATH, [envKey]: secret },
});
session = await driver.openSession({ runId: provider, normalizedSessionId: provider, workingDirectory: root });
const configText = await readFile(join(root, provider, "config", "opencode", "opencode.json"), "utf8");
expect(configText).not.toContain(secret);
const envText = await readFile(join(root, provider, "data", "fake-environment.json"), "utf8");
expect(JSON.parse(envText).keys).not.toContain(envKey);
expect(envText).not.toContain(secret);
const config = JSON.parse(configText);
const { baseURL, apiKey } = config.provider[provider].options;
expect(baseURL).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1$/);
expect(apiKey).not.toBe(secret);
const authHeaders = authHeader === "authorization"
? { Authorization: `Bearer ${apiKey}` }
: { [authHeader]: apiKey };
const url = `${baseURL}${requestPath}`;
const payload = { model, messages: [{ role: "user", content: "hi" }] };
expect((await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(401);
expect((await fetch(url, { method: "POST", headers: { ...authHeaders, "Content-Type": "application/json" }, body: JSON.stringify({ ...payload, model: "wrong-model" }) })).status).toBe(400);
expect((await fetch(`${baseURL}/models`, { method: "POST", headers: { ...authHeaders, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(404);
expect((await fetch(url, { method: "POST", headers: { ...authHeaders, ...extraHeaders, "Content-Type": "application/json" }, body: JSON.stringify(payload) })).status).toBe(200);
expect(upstreamTransport.urls).toEqual([expectedUpstreamUrl]);
expect(received).toHaveLength(1);
expect(received[0]?.headers[authHeader]).toBe(authHeader === "authorization" ? `Bearer ${secret}` : secret);
for (const [headerName, headerValue] of Object.entries(extraHeaders)) {
expect(received[0]?.headers[headerName]).toBe(headerValue);
}
} finally {
await session?.close({ reason: "test" });
upstreamTransport.endpoint = "";
await new Promise<void>(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); });
}
});
it("runs the pinned OpenCode bash tool without exposing the direct Gemini key while authenticating model calls", async () => {
const geminiKey = "synthetic-pinned-runtime-gemini-key-secret";
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-pinned-shell-"));
const workspace = await mkdtemp(join(tmpdir(), "paperclip-opencode-pinned-workspace-"));
roots.push(root, workspace);
let mainTurns = 0;
const observedUpstreamApiKeys: Array<string | undefined> = [];
const observedShellPayloads: string[] = [];
const upstream = createHttpServer((request, response) => {
const chunks: Buffer[] = [];
request.on("data", chunk => chunks.push(Buffer.from(chunk)));
request.on("end", () => {
const rawBody = Buffer.concat(chunks).toString("utf8");
observedUpstreamApiKeys.push(
typeof request.headers["x-goog-api-key"] === "string" ? request.headers["x-goog-api-key"] : undefined,
);
const sse = (data: unknown) => `data: ${JSON.stringify(data)}\n\n`;
if (rawBody.includes("You are a title generator")) {
response.writeHead(200, { "content-type": "text/event-stream" });
response.end(sse({
candidates: [{ content: { role: "model", parts: [{ text: "Env check" }] }, finishReason: "STOP" }],
usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 2, totalTokenCount: 7 },
}));
return;
}
mainTurns += 1;
if (mainTurns === 1) {
response.writeHead(200, { "content-type": "text/event-stream" });
response.end(sse({
candidates: [{
content: {
role: "model",
parts: [{
functionCall: {
name: "bash",
args: {
command: 'node -e "const fs = require(\x27fs\x27); const out = { gemini: process.env.GEMINI_API_KEY ?? null, googleGenAi: process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? null, envHasSecret: Object.values(process.env).some(v => String(v).includes(\x27synthetic-pinned-runtime-gemini-key-secret\x27)), configHasSecret: fs.readFileSync(process.env.XDG_CONFIG_HOME + \x27/opencode/opencode.json\x27, \x27utf8\x27).includes(\x27synthetic-pinned-runtime-gemini-key-secret\x27) }; fs.writeFileSync(\x27shell-env-proof.json\x27, JSON.stringify(out)); console.log(JSON.stringify(out));"',
description: "Verify direct Gemini key is absent from shell env and config",
},
},
}],
},
finishReason: "STOP",
}],
usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5, totalTokenCount: 15 },
}));
return;
}
observedShellPayloads.push(rawBody);
response.writeHead(200, { "content-type": "text/event-stream" });
response.end(sse({
candidates: [{
content: { role: "model", parts: [{ text: "Shell environment verified without provider key." }] },
finishReason: "STOP",
}],
usageMetadata: { promptTokenCount: 15, candidatesTokenCount: 8, totalTokenCount: 23 },
}));
});
});
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (!address || typeof address === "string") throw new Error("Could not bind mock Gemini upstream");
upstreamTransport.endpoint = `http://127.0.0.1:${address.port}`;
upstreamTransport.urls = [];
let session: Awaited<ReturnType<OpenCodeServerDriver["openSession"]>> | undefined;
try {
const driver = new OpenCodeServerDriver({
model: "google/gemini-2.5-flash",
command: resolvePinnedOpenCodeCommand(),
runtimeDirectory: root,
environment: {
PATH: process.env.PATH,
GEMINI_API_KEY: geminiKey,
},
});
session = await driver.openSession({
runId: "pinned-google-shell",
normalizedSessionId: "pinned-google-shell",
workingDirectory: workspace,
});
await session.startTurn({ message: { role: "user", text: "Check shell environment." } });
await collectTurnEvents(session.events());
const proof = JSON.parse(await readFile(join(workspace, "shell-env-proof.json"), "utf8"));
expect(proof).toEqual({
gemini: null,
googleGenAi: null,
envHasSecret: false,
configHasSecret: false,
});
expect(mainTurns).toBeGreaterThanOrEqual(2);
expect(observedUpstreamApiKeys.length).toBeGreaterThanOrEqual(2);
expect(observedUpstreamApiKeys.every(key => key === geminiKey)).toBe(true);
expect(upstreamTransport.urls.every(url =>
url === "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
)).toBe(true);
expect(observedShellPayloads.length).toBeGreaterThanOrEqual(1);
} finally {
await session?.close({ reason: "pinned shell isolation test complete" });
upstreamTransport.endpoint = "";
await new Promise<void>(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); });
}
}, 30_000);
it("passes OpenRouter's stream through unchanged and records the host that served it on the turn's usage", async () => {
await chmod(fixture, 0o755);
const model = "deepseek/deepseek-v4.1-flash-1017";
@@ -1,4 +1,4 @@
import { isOpenRouterUrl, OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js";
import { OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js";
import { ensurePrivateDirectory, harnessStateSessionDirectoryName, isInside, prepareHarnessStateSessionRoot, resolveHarnessStateDirectory } from "../harness-state-directory.js";
import { spawn, type ChildProcess } from "node:child_process";
import { resolveCompletionContinuation } from "../completion-continuation.js";
@@ -18,15 +18,10 @@ import {
} from "node:fs/promises";
import { createServer } from "node:net";
import { constants as osConstants } from "node:os";
import { Agent as HttpAgent, createServer as createHttpServer, request as requestHttp, type IncomingMessage } from "node:http";
import { Agent as HttpsAgent, request as requestHttps } from "node:https";
import { getCACertificates } from "node:tls";
import { pipeline } from "node:stream/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { parseOpenCodeReasoningMode, type OpenCodeReasoningMode } from "./reasoning-mode.js";
import { attributeUnsupportedToolMedia } from "./tool-media-attribution.js";
import { createUpstreamServedTap, type UpstreamServed } from "./upstream-served.js";
import { type UpstreamServed } from "./upstream-served.js";
import { openCodeProviderFailure } from "./provider-failure.js";
import {
startOpenCodeMemoryKillProbe,
@@ -36,7 +31,6 @@ import {
} from "./memory-kill-evidence.js";
import { createOpenCodeCompanyObservability } from "./company-observability.js";
import {
createOpenCodeProviderTrafficMeter,
type OpenCodeProviderTrafficEvidence,
type OpenCodeProviderTrafficMeter,
} from "./provider-traffic.js";
@@ -46,7 +40,12 @@ import { annotateOmittedProviderText, parseOpenCodeSseFrames } from "./sse-frame
import { githubCredentialEnvironment } from "../../github-credential-environment.js";
import { configuredOpenCodeEnvironment } from "./environment.js";
import { CONFIGURED_ENVIRONMENT_KEYS, SECRET_ENVIRONMENT_KEYS, configuredSecretEnvironment } from "../../configured-environment.js";
import { prepareOpenCodeOutputCustody, redactOpenCodeModelRequest } from "./output-custody.js";
import { prepareOpenCodeOutputCustody } from "./output-custody.js";
import {
OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS,
resolveOpenCodeProviderRoute,
startOpenCodeProviderProxy,
} from "./provider-proxy.js";
import { markOpenCodeConfigDependenciesInstalled } from "./config-dependencies.js";
import {
@@ -399,6 +398,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],
),
]),
};
}
@@ -2572,135 +2574,6 @@ class OpenCodeHarnessSession implements HarnessSession {
}
}
/** Retain the reusable gateway key in the runner; the harness gets a session-scoped capability. */
async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: string, environment: NodeJS.ProcessEnv, onServed?: (served: UpstreamServed | null) => void, secretValues: readonly string[] = []) {
const upstreamUrl = new URL(`${baseUrl.replace(/\/+$/, "")}/chat/completions`);
const token = randomBytes(32).toString("base64url");
// Byte and request counts only, so a killed OpenCode can be compared with its model traffic.
const traffic = createOpenCodeProviderTrafficMeter();
// Agent-local settings keep one runtime's transport configuration out of other sessions.
const proxyEnv = {
HTTP_PROXY: environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY,
HTTPS_PROXY: environment.https_proxy ?? environment.HTTPS_PROXY ?? environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY,
NO_PROXY: environment.no_proxy ?? environment.NO_PROXY,
};
const ca = [...getCACertificates("default")];
if (environment.SSL_CERT_FILE) ca.push(await readFile(environment.SSL_CERT_FILE, "utf8"));
if (environment.SSL_CERT_DIR) {
for (const entry of await readdir(environment.SSL_CERT_DIR, { withFileTypes: true })) {
if (!entry.isDirectory()) {
const certificate = await readFile(join(environment.SSL_CERT_DIR, entry.name), "utf8");
if (certificate.includes("-----BEGIN CERTIFICATE-----")) ca.push(certificate);
}
}
}
const agent = upstreamUrl.protocol === "https:" ? new HttpsAgent({ proxyEnv, ca }) : new HttpAgent({ proxyEnv });
const controllers = new Set<AbortController>();
const server = createHttpServer((request, response) => {
const controller = new AbortController();
controllers.add(controller);
response.once("close", () => controller.abort());
void (async () => {
if (request.headers.authorization !== `Bearer ${token}`) {
response.writeHead(401).end();
return;
}
if (request.method !== "POST" || request.url !== "/v1/chat/completions") {
response.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of request) {
bytes += chunk.length;
if (bytes > 16 * 1024 * 1024) {
response.writeHead(413).end();
return;
}
chunks.push(Buffer.from(chunk));
}
let body = Buffer.concat(chunks);
let payload: Record<string, unknown>;
try { payload = JSON.parse(body.toString("utf8")); }
catch { response.writeHead(400).end(); return; }
if (!payload || typeof payload !== "object" || payload.model !== model ||
["models", "route", "plugins", "transforms"].some(field => Object.hasOwn(payload, field))) {
response.writeHead(400).end();
return;
}
// Keep OpenCode's unreadable-media notice attributed to the tool result
// instead of a synthetic user message the model mistakes for the person.
if (attributeUnsupportedToolMedia(payload)) body = Buffer.from(JSON.stringify(payload), "utf8");
// Defense in depth: no configured secret value leaves for the model.
if (secretValues.length > 0) {
const redacted = redactOpenCodeModelRequest(body, secretValues, payload);
if (redacted) body = redacted;
}
let served: UpstreamServed | null = null;
const metered = traffic.startRequest(body.length);
// A response OpenCode stops reading (for example, because it was killed) stays visible as interrupted.
let responseCompleted = false;
try {
const upstream = await new Promise<IncomingMessage>((resolve, reject) => {
const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(upstreamUrl, {
method: "POST",
agent,
headers: { ...(isOpenRouterUrl(baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}), "Content-Type": "application/json", "Content-Length": body.length, ...(key ? { Authorization: `Bearer ${key}` } : {}) },
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]),
}, resolve);
outgoing.once("error", reject);
outgoing.end(body);
});
// Never forward authentication to a redirect destination.
const status = upstream.statusCode ?? 502;
if (status >= 300 && status < 400) {
upstream.destroy();
throw new Error("Provider redirects are not supported");
}
const headers: Record<string, string> = {};
for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) {
const value = upstream.headers[name];
if (typeof value === "string") headers[name] = value;
}
response.writeHead(status, headers);
if (onServed && status >= 200 && status < 300) {
await pipeline(upstream, metered.counter(), createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"],
onServed: value => { served = value; } }), response);
} else await pipeline(upstream, metered.counter(), response);
responseCompleted = true;
} finally {
metered.end(responseCompleted);
try { onServed?.(served); } catch { /* Recording never affects the response. */ }
}
})().catch(() => {
if (!response.headersSent) response.writeHead(502).end("Provider request failed");
else response.destroy();
}).finally(() => controllers.delete(controller));
});
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); });
});
} catch (error) { agent.destroy(); throw error; }
const address = server.address();
if (!address || typeof address === "string") {
server.close();
agent.destroy();
throw new Error("Could not bind OpenCode provider proxy");
}
return {
baseURL: `http://127.0.0.1:${address.port}/v1`,
token,
traffic,
close: async () => {
for (const controller of controllers) controller.abort();
agent.destroy();
await new Promise<void>((resolve) => { server.close(() => resolve()); server.closeAllConnections(); });
},
};
}
async function startRuntime(input: {
options: OpenCodeServerDriverOptions;
root: string;
@@ -2762,6 +2635,13 @@ 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 = resolveOpenCodeProviderRoute(
modelProvider,
input.options.environment,
providerEnvironment,
);
const sensitiveValues = [
...identityValues,
...Object.entries(taskEnvironment).flatMap(([key, value]) =>
@@ -2772,6 +2652,8 @@ async function startRuntime(input: {
providerEnvironment.OPENROUTER_API_KEY,
providerEnvironment.PAPERCLIP_AI_PROVIDER_KEY,
providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN,
providerRoute?.key,
...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS.map(key => input.options.environment?.[key]),
].filter((value): value is string => Boolean(value));
input.trace?.addSensitiveValues(sensitiveValues);
// Configured secrets must never reach OpenCode's captured tool output, its
@@ -2799,20 +2681,8 @@ 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 startOpenCodeProviderProxy(providerRoute, providerModelId, providerEnvironment, input.onUpstreamServed, outputCustody?.values ?? []).catch(async error => {
await bridge.close().catch(() => {});
await removeIsolatedHome(isolatedHome).catch(() => {});
throw error;
@@ -2862,8 +2732,10 @@ async function startRuntime(input: {
[modelProvider!]: {
...(modelProvider === "openrouter" ? { options: { headers: OPENROUTER_ATTRIBUTION_HEADERS } } : {}),
...(providerProxy ? {
npm: "@ai-sdk/openai-compatible",
name: modelProvider === "openrouter" ? "OpenRouter" : "Paperclip connection",
...(providerRoute?.overrideOpenAiCompatible ? {
npm: "@ai-sdk/openai-compatible",
name: providerRoute.overrideOpenAiCompatible.name,
} : {}),
options: {
...(modelProvider === "openrouter" ? { headers: OPENROUTER_ATTRIBUTION_HEADERS } : {}),
baseURL: providerProxy.baseURL,
@@ -3615,7 +3487,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);
@@ -0,0 +1,586 @@
import { randomBytes, timingSafeEqual } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import {
Agent as HttpAgent,
createServer as createHttpServer,
request as requestHttp,
type IncomingHttpHeaders,
type IncomingMessage,
} from "node:http";
import { Agent as HttpsAgent, request as requestHttps } from "node:https";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import { getCACertificates } from "node:tls";
import { isOpenRouterUrl, OPENROUTER_ATTRIBUTION_HEADERS } from "../openrouter-attribution.js";
import { redactOpenCodeModelRequest } from "./output-custody.js";
import {
createOpenCodeProviderTrafficMeter,
type OpenCodeProviderTrafficMeter,
} from "./provider-traffic.js";
import { attributeUnsupportedToolMedia } from "./tool-media-attribution.js";
import { createUpstreamServedTap, type UpstreamServed } from "./upstream-served.js";
export type OpenCodeProviderProtocol =
| "openai_compatible_gateway"
| "google"
| "anthropic"
| "openai"
| "xai"
| "groq"
| "opencode";
export interface OpenCodeProviderRoute {
protocol: OpenCodeProviderProtocol;
baseUrl: string;
key: string;
localBasePath: "/v1" | "/v1beta";
overrideOpenAiCompatible?: {
name: string;
};
}
export interface OpenCodeProviderProxy {
baseURL: string;
token: string;
traffic: OpenCodeProviderTrafficMeter;
close(): Promise<void>;
}
const DIRECT_PROVIDER_DEFAULTS: Readonly<
Record<
Exclude<OpenCodeProviderProtocol, "openai_compatible_gateway">,
{
baseUrl: string;
localBasePath: "/v1" | "/v1beta";
envKeys: readonly string[];
}
>
> = {
google: {
baseUrl: "https://generativelanguage.googleapis.com/v1beta",
localBasePath: "/v1beta",
envKeys: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
},
anthropic: {
baseUrl: "https://api.anthropic.com/v1",
localBasePath: "/v1",
envKeys: ["ANTHROPIC_API_KEY"],
},
openai: {
baseUrl: "https://api.openai.com/v1",
localBasePath: "/v1",
envKeys: ["OPENAI_API_KEY"],
},
xai: {
baseUrl: "https://api.x.ai/v1",
localBasePath: "/v1",
envKeys: ["XAI_API_KEY"],
},
groq: {
baseUrl: "https://api.groq.com/openai/v1",
localBasePath: "/v1",
envKeys: ["GROQ_API_KEY"],
},
opencode: {
baseUrl: "https://opencode.ai/zen/v1",
localBasePath: "/v1",
envKeys: ["OPENCODE_API_KEY"],
},
};
export const OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS: readonly string[] = Object.values(
DIRECT_PROVIDER_DEFAULTS,
).flatMap((spec) => spec.envKeys);
export function resolveOpenCodeProviderRoute(
modelProvider: string | undefined,
explicitEnvironment: NodeJS.ProcessEnv | undefined,
providerEnvironment: NodeJS.ProcessEnv,
): OpenCodeProviderRoute | null {
if (!modelProvider) return null;
if (modelProvider === "openrouter") {
if (providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL) {
return {
protocol: "openai_compatible_gateway",
baseUrl: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL,
key: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN ?? "",
localBasePath: "/v1",
overrideOpenAiCompatible: { name: "OpenRouter" },
};
}
return {
protocol: "openai_compatible_gateway",
baseUrl: "https://openrouter.ai/api/v1",
key: providerEnvironment.OPENROUTER_API_KEY ?? "",
localBasePath: "/v1",
overrideOpenAiCompatible: { name: "OpenRouter" },
};
}
if (modelProvider === "paperclip" && explicitEnvironment?.PAPERCLIP_AI_PROVIDER_URL) {
return {
protocol: "openai_compatible_gateway",
baseUrl: explicitEnvironment.PAPERCLIP_AI_PROVIDER_URL,
key: explicitEnvironment.PAPERCLIP_AI_PROVIDER_KEY ?? "",
localBasePath: "/v1",
overrideOpenAiCompatible: { name: "Paperclip connection" },
};
}
if (!explicitEnvironment) return null;
if (!Object.hasOwn(DIRECT_PROVIDER_DEFAULTS, modelProvider)) return null;
const protocol = modelProvider as Exclude<OpenCodeProviderProtocol, "openai_compatible_gateway">;
const spec = DIRECT_PROVIDER_DEFAULTS[protocol];
let key = "";
for (const envKey of spec.envKeys) {
const candidate = explicitEnvironment[envKey]?.trim();
if (candidate) {
key = candidate;
break;
}
}
if (!key) return null;
return {
protocol,
baseUrl: spec.baseUrl,
key,
localBasePath: spec.localBasePath,
};
}
type ProxyAuthMode = "bearer" | "x-api-key" | "x-goog-api-key";
function secretEquals(actual: string | undefined, expected: string): boolean {
if (typeof actual !== "string") return false;
const left = Buffer.from(actual, "utf8");
const right = Buffer.from(expected, "utf8");
return left.length === right.length && timingSafeEqual(left, right);
}
function headerString(headers: IncomingHttpHeaders, name: string): string | undefined {
const value = headers[name];
return typeof value === "string" ? value : undefined;
}
function verifyProxyAuth(
protocol: OpenCodeProviderProtocol,
headers: IncomingHttpHeaders,
token: string,
): ProxyAuthMode | null {
const expectedBearer = `Bearer ${token}`;
switch (protocol) {
case "openai_compatible_gateway":
case "openai":
case "xai":
case "groq":
return secretEquals(headerString(headers, "authorization"), expectedBearer) ? "bearer" : null;
case "google":
return secretEquals(headerString(headers, "x-goog-api-key"), token) ? "x-goog-api-key" : null;
case "anthropic":
return secretEquals(headerString(headers, "x-api-key"), token) ? "x-api-key" : null;
case "opencode":
if (secretEquals(headerString(headers, "authorization"), expectedBearer)) return "bearer";
if (secretEquals(headerString(headers, "x-api-key"), token)) return "x-api-key";
if (secretEquals(headerString(headers, "x-goog-api-key"), token)) return "x-goog-api-key";
return null;
}
}
interface MatchedUpstreamRequest {
upstreamSuffix: string;
requirePayloadModel: boolean;
rejectGatewayOverrides: boolean;
rewriteUnsupportedToolMedia: boolean;
forwardAnthropicHeaders: boolean;
forwardOpenCodeHeaders: boolean;
}
function matchProviderProxyRequest(
protocol: OpenCodeProviderProtocol,
rawUrl: string | undefined,
model: string,
): MatchedUpstreamRequest | null {
if (!rawUrl || !rawUrl.startsWith("/")) return null;
let parsed: URL;
try {
parsed = new URL(rawUrl, "http://127.0.0.1");
} catch {
return null;
}
const encodedModel = encodeURIComponent(model);
const { pathname, search } = parsed;
switch (protocol) {
case "openai_compatible_gateway":
if (rawUrl !== "/v1/chat/completions") return null;
return {
upstreamSuffix: "/chat/completions",
requirePayloadModel: true,
rejectGatewayOverrides: true,
rewriteUnsupportedToolMedia: true,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
case "google": {
const streamPath = `/v1beta/models/${encodedModel}:streamGenerateContent`;
const generatePath = `/v1beta/models/${encodedModel}:generateContent`;
if (pathname === streamPath && (search === "" || search === "?alt=sse")) {
return {
upstreamSuffix: `/models/${encodedModel}:streamGenerateContent${search}`,
requirePayloadModel: false,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
}
if (pathname === generatePath && search === "") {
return {
upstreamSuffix: `/models/${encodedModel}:generateContent`,
requirePayloadModel: false,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
}
return null;
}
case "anthropic":
if (pathname !== "/v1/messages" || search !== "") return null;
return {
upstreamSuffix: "/messages",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: true,
forwardOpenCodeHeaders: false,
};
case "openai":
case "xai":
if (search !== "") return null;
if (pathname === "/v1/responses") {
return {
upstreamSuffix: "/responses",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
}
if (pathname === "/v1/chat/completions") {
return {
upstreamSuffix: "/chat/completions",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: true,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
}
return null;
case "groq":
if (pathname !== "/v1/chat/completions" || search !== "") return null;
return {
upstreamSuffix: "/chat/completions",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: true,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: false,
};
case "opencode": {
if (pathname === "/v1/chat/completions" && search === "") {
return {
upstreamSuffix: "/chat/completions",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: true,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: true,
};
}
if (pathname === "/v1/responses" && search === "") {
return {
upstreamSuffix: "/responses",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: true,
};
}
if (pathname === "/v1/messages" && search === "") {
return {
upstreamSuffix: "/messages",
requirePayloadModel: true,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: true,
forwardOpenCodeHeaders: true,
};
}
const streamPath = `/v1/models/${encodedModel}:streamGenerateContent`;
const generatePath = `/v1/models/${encodedModel}:generateContent`;
if (pathname === streamPath && (search === "" || search === "?alt=sse")) {
return {
upstreamSuffix: `/models/${encodedModel}:streamGenerateContent${search}`,
requirePayloadModel: false,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: true,
};
}
if (pathname === generatePath && search === "") {
return {
upstreamSuffix: `/models/${encodedModel}:generateContent`,
requirePayloadModel: false,
rejectGatewayOverrides: false,
rewriteUnsupportedToolMedia: false,
forwardAnthropicHeaders: false,
forwardOpenCodeHeaders: true,
};
}
return null;
}
}
}
function buildUpstreamHeaders(input: {
route: OpenCodeProviderRoute;
authMode: ProxyAuthMode;
matched: MatchedUpstreamRequest;
incomingHeaders: IncomingHttpHeaders;
contentLength: number;
}): Record<string, string | number> {
const headers: Record<string, string | number> = {
...(isOpenRouterUrl(input.route.baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}),
"Content-Type": "application/json",
"Content-Length": input.contentLength,
};
if (input.route.key) {
if (input.authMode === "bearer") headers.Authorization = `Bearer ${input.route.key}`;
else if (input.authMode === "x-api-key") headers["x-api-key"] = input.route.key;
else if (input.authMode === "x-goog-api-key") headers["x-goog-api-key"] = input.route.key;
}
if (input.matched.forwardAnthropicHeaders) {
for (const name of ["anthropic-version", "anthropic-beta"]) {
const value = headerString(input.incomingHeaders, name);
if (value) headers[name] = value;
}
}
if (input.matched.forwardOpenCodeHeaders) {
for (const name of ["x-opencode-client", "x-opencode-project", "x-opencode-request", "x-opencode-session"]) {
const value = headerString(input.incomingHeaders, name);
if (value) headers[name] = value;
}
}
return headers;
}
/** Retain reusable gateway and direct provider API keys in the runner; the harness receives only a session-scoped capability. */
export async function startOpenCodeProviderProxy(
route: OpenCodeProviderRoute,
model: string,
environment: NodeJS.ProcessEnv,
onServed?: (served: UpstreamServed | null) => void,
secretValues: readonly string[] = [],
): Promise<OpenCodeProviderProxy> {
const normalizedBaseUrl = route.baseUrl.replace(/\/+$/, "");
const baseOriginUrl = new URL(normalizedBaseUrl);
const token = randomBytes(32).toString("base64url");
// Byte and request counts only, so a killed OpenCode can be compared with its model traffic.
const traffic = createOpenCodeProviderTrafficMeter();
// Agent-local settings keep one runtime's transport configuration out of other sessions.
const proxyEnv = {
HTTP_PROXY: environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY,
HTTPS_PROXY:
environment.https_proxy ??
environment.HTTPS_PROXY ??
environment.http_proxy ??
environment.HTTP_PROXY ??
environment.all_proxy ??
environment.ALL_PROXY,
NO_PROXY: environment.no_proxy ?? environment.NO_PROXY,
};
const ca = [...getCACertificates("default")];
if (environment.SSL_CERT_FILE) ca.push(await readFile(environment.SSL_CERT_FILE, "utf8"));
if (environment.SSL_CERT_DIR) {
for (const entry of await readdir(environment.SSL_CERT_DIR, { withFileTypes: true })) {
if (!entry.isDirectory()) {
const certificate = await readFile(join(environment.SSL_CERT_DIR, entry.name), "utf8");
if (certificate.includes("-----BEGIN CERTIFICATE-----")) ca.push(certificate);
}
}
}
const agent =
baseOriginUrl.protocol === "https:" ? new HttpsAgent({ proxyEnv, ca }) : new HttpAgent({ proxyEnv });
const controllers = new Set<AbortController>();
const server = createHttpServer((request, response) => {
const controller = new AbortController();
controllers.add(controller);
response.once("close", () => controller.abort());
void (async () => {
const authMode = verifyProxyAuth(route.protocol, request.headers, token);
if (!authMode) {
response.writeHead(401).end();
return;
}
if (request.method !== "POST") {
response.writeHead(404).end();
return;
}
const matched = matchProviderProxyRequest(route.protocol, request.url, model);
if (!matched) {
response.writeHead(404).end();
return;
}
const upstreamUrl = new URL(`${normalizedBaseUrl}${matched.upstreamSuffix}`);
if (upstreamUrl.origin !== baseOriginUrl.origin) {
response.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of request) {
bytes += chunk.length;
if (bytes > 16 * 1024 * 1024) {
response.writeHead(413).end();
return;
}
chunks.push(Buffer.from(chunk));
}
let body = Buffer.concat(chunks);
let payload: Record<string, unknown>;
try {
payload = JSON.parse(body.toString("utf8"));
} catch {
response.writeHead(400).end();
return;
}
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
response.writeHead(400).end();
return;
}
if (matched.requirePayloadModel && payload.model !== model) {
response.writeHead(400).end();
return;
}
if (
matched.rejectGatewayOverrides &&
["models", "route", "plugins", "transforms"].some((field) => Object.hasOwn(payload, field))
) {
response.writeHead(400).end();
return;
}
// Keep OpenCode's unreadable-media notice attributed to the tool result
// instead of a synthetic user message the model mistakes for the person.
if (matched.rewriteUnsupportedToolMedia && attributeUnsupportedToolMedia(payload)) {
body = Buffer.from(JSON.stringify(payload), "utf8");
}
// Defense in depth: no configured secret value leaves for the model.
if (secretValues.length > 0) {
const redacted = redactOpenCodeModelRequest(body, secretValues, payload);
if (redacted) body = redacted;
}
let served: UpstreamServed | null = null;
const metered = traffic.startRequest(body.length);
// A response OpenCode stops reading (for example, because it was killed) stays visible as interrupted.
let responseCompleted = false;
try {
const upstream = await new Promise<IncomingMessage>((resolve, reject) => {
const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(
upstreamUrl,
{
method: "POST",
agent,
headers: buildUpstreamHeaders({
route,
authMode,
matched,
incomingHeaders: request.headers,
contentLength: body.length,
}),
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]),
},
resolve,
);
outgoing.once("error", reject);
outgoing.end(body);
});
// Never forward authentication to a redirect destination.
const status = upstream.statusCode ?? 502;
if (status >= 300 && status < 400) {
upstream.destroy();
throw new Error("Provider redirects are not supported");
}
const headers: Record<string, string> = {};
for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) {
const value = upstream.headers[name];
if (typeof value === "string") headers[name] = value;
}
response.writeHead(status, headers);
if (onServed && status >= 200 && status < 300) {
await pipeline(
upstream,
metered.counter(),
createUpstreamServedTap({
contentType: headers["content-type"],
contentEncoding: headers["content-encoding"],
onServed: (value) => {
served = value;
},
}),
response,
);
} else {
await pipeline(upstream, metered.counter(), response);
}
responseCompleted = true;
} finally {
metered.end(responseCompleted);
try {
onServed?.(served);
} catch {
/* Recording never affects the response. */
}
}
})()
.catch(() => {
if (!response.headersSent) response.writeHead(502).end("Provider request failed");
else response.destroy();
})
.finally(() => controllers.delete(controller));
});
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.off("error", reject);
resolve();
});
});
} catch (error) {
agent.destroy();
throw error;
}
const address = server.address();
if (!address || typeof address === "string") {
server.close();
agent.destroy();
throw new Error("Could not bind OpenCode provider proxy");
}
return {
baseURL: `http://127.0.0.1:${address.port}${route.localBasePath}`,
token,
traffic,
close: async () => {
for (const controller of controllers) controller.abort();
agent.destroy();
await new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
});
},
};
}
@@ -26,7 +26,11 @@ describe("OpenCode provider proxy traffic", () => {
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (!address || typeof address === "string") throw new Error("Missing fixture address");
const proxy = await startOpenCodeProviderProxy(`http://127.0.0.1:${address.port}/v1`, "", "team/model", {});
const proxy = await startOpenCodeProviderProxy(
{ protocol: "openai_compatible_gateway", baseUrl: `http://127.0.0.1:${address.port}/v1`, key: "", localBasePath: "/v1" },
"team/model",
{},
);
const request = (content: string) => {
const body = JSON.stringify({ model: "team/model", stream: true, messages: [{ role: "user", content }] });
return { body, response: fetch(`${proxy.baseURL}/chat/completions`, {
@@ -79,7 +83,11 @@ describe("OpenCode provider proxy traffic", () => {
});
it("does not count a request the proxy rejects before calling the provider", async () => {
const proxy = await startOpenCodeProviderProxy("http://127.0.0.1:9/v1", "", "team/model", {});
const proxy = await startOpenCodeProviderProxy(
{ protocol: "openai_compatible_gateway", baseUrl: "http://127.0.0.1:9/v1", key: "", localBasePath: "/v1" },
"team/model",
{},
);
try {
const response = await fetch(`${proxy.baseURL}/chat/completions`, {
method: "POST", headers: { Authorization: `Bearer ${proxy.token}`, "Content-Type": "application/json" },
@@ -3099,6 +3099,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",
@@ -12,6 +12,7 @@ export { createRunnerdCodexAppServerArgs, resolveRunnerdAcpxPermissionMode, trus
import { applyProviderObservabilityEnvironment, redactObservabilityDiagnostic } from "../drivers/agent-observability.js";
import type { RunnerExecutionDriver } from "../control-plane/runner-execution-driver.js";
import { resolvePinnedOpenCodeCommand } from "../drivers/opencode/opencode-server-driver.js";
import { OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS } from "../drivers/opencode/provider-proxy.js";
import { bindAcpxCandidateAdmission, isAntigravityNativeTarget, parseAcpxCandidateAdmission, type AcpxCandidateAdmission, type AcpxCandidateStartupAdmission } from "../drivers/acpx/candidate-admission.js";
import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js";
import { resolveClaudeEffort, admittedClaudeEffort } from "../drivers/acpx/claude-effort.js";
@@ -4051,11 +4052,12 @@ export const OPEN_CODE_RUNNER_ENVIRONMENT_KEYS = new Set([
"WINDIR",
"RUST_BACKTRACE",
"OPENROUTER_API_KEY",
...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS,
"PAPERCLIP_OPENROUTER_PROXY_URL",
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
]);
function createSanitizedOpenCodeRunnerEnvironment(
export function createSanitizedOpenCodeRunnerEnvironment(
source: NodeJS.ProcessEnv | undefined,
): NodeJS.ProcessEnv {
const candidate = { ...process.env, ...source };
@@ -4065,6 +4067,8 @@ function createSanitizedOpenCodeRunnerEnvironment(
"PAPERCLIP_AGENT_PRIVATE_KEY",
"PAPERCLIP_OPENROUTER_PROXY_URL",
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
"OPENROUTER_API_KEY",
...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS,
]) {
delete candidate[key];
if (source?.[key] !== undefined) candidate[key] = source[key];
@@ -63,6 +63,14 @@ export const ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS = {
["OPENROUTER_API_KEY"],
["PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_AI_PROVIDER_KEY"],
["PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN"],
["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[])[]>;
+23 -6
View File
@@ -82,6 +82,23 @@ export function aiConnectionSourceSlug(
return metadata.success ? aiConnectionCatalogSlug(metadata.data.provider, metadata.data.routing) : null;
}
/** OpenCode provider -> environment variable keys (ordered by precedence). */
export const OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS = {
openrouter: ["OPENROUTER_API_KEY"],
google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
anthropic: ["ANTHROPIC_API_KEY"],
openai: ["OPENAI_API_KEY"],
xai: ["XAI_API_KEY"],
groq: ["GROQ_API_KEY"],
opencode: ["OPENCODE_API_KEY"],
} as const satisfies Readonly<Record<string, readonly string[]>>;
export type OpenCodeCredentialProvider = keyof typeof OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS;
export const OPENCODE_CREDENTIAL_ENV_KEYS: readonly string[] = Object.values(
OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS,
).flat();
/** Existing integrations only. This table describes compatibility, never routing. */
export const AI_CONNECTION_CAPABILITIES: Record<
AiProvider,
@@ -97,7 +114,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 +124,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 +144,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 +175,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),
@@ -636,4 +636,57 @@ describeEmbeddedPostgres("hired agent provider credential inheritance", () => {
expect(detailsText).not.toContain("adapterConfig");
expect(detailsText).not.toContain("CLAUDE_CODE_OAUTH_TOKEN");
});
it("treats OpenCode Google alias keys as one credential and permits child direct provider secret refs", async () => {
const companyId = await seedCompany();
const parentSecret = await createCompanySecret(companyId, "parent-google-genai-key");
const childSecret = await createCompanySecret(companyId, "child-gemini-key");
const parent = await seedParentAgent(companyId, "opencode_local", {
GOOGLE_GENERATIVE_AI_API_KEY: secretRef(parentSecret.id),
});
const res = await hire(agentActor(companyId, parent.id), companyId, {
name: "OpenCode Google Child",
role: "engineer",
adapterType: "opencode_local",
adapterConfig: {
model: "google/gemini-2.5-flash",
env: { GEMINI_API_KEY: secretRef(childSecret.id) },
},
});
expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(childEnvOf(res).GEMINI_API_KEY).toMatchObject({ type: "secret_ref", secretId: childSecret.id });
expect(childEnvOf(res).GOOGLE_GENERATIVE_AI_API_KEY).toBeUndefined();
});
it("inherits only the matching OpenCode provider credential from a multi-provider parent", async () => {
const companyId = await seedCompany();
const geminiSecret = await createCompanySecret(companyId, "parent-gemini-key");
const openaiSecret = await createCompanySecret(companyId, "parent-openai-key");
const parent = await seedParentAgent(companyId, "opencode_local", {
GEMINI_API_KEY: secretRef(geminiSecret.id),
OPENAI_API_KEY: secretRef(openaiSecret.id),
});
const googleRes = await hire(agentActor(companyId, parent.id), companyId, {
name: "OpenCode Matching Google Child",
role: "engineer",
adapterType: "opencode_local",
adapterConfig: { model: "google/gemini-2.5-flash" },
});
expect(googleRes.status, JSON.stringify(googleRes.body)).toBe(201);
expect(childEnvOf(googleRes).GEMINI_API_KEY).toMatchObject({ type: "secret_ref", secretId: geminiSecret.id });
expect(childEnvOf(googleRes).OPENAI_API_KEY).toBeUndefined();
const unrelatedRes = await hire(agentActor(companyId, parent.id), companyId, {
name: "OpenCode Unrelated Provider Child",
role: "engineer",
adapterType: "opencode_local",
adapterConfig: { model: "anthropic/claude-sonnet-4-5" },
});
expect(unrelatedRes.status, JSON.stringify(unrelatedRes.body)).toBe(201);
expect(childEnvOf(unrelatedRes).GEMINI_API_KEY).toBeUndefined();
expect(childEnvOf(unrelatedRes).OPENAI_API_KEY).toBeUndefined();
});
});
@@ -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");
@@ -24,6 +24,7 @@ import { quotaCredentialRecoveryPath, quotaCredentialRecovery, quotaCredentialHa
import { reconcileRetainedAiCleanup, retainAiCredentialCleanup } from "../services/retained-ai-credential-cleanup.js";
import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js";
import { aiConnectionService } from "../services/ai-connections.js";
import { defaultAiConnectionForHire } from "../services/agent-ai-connection-default.js";
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { syncConnectionCredentialBindings } from "../services/connection-credential-bindings.js";
import * as codexAdapter from "@paperclipai/adapter-codex-local/server";
@@ -109,6 +110,94 @@ 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("defaults OpenCode hires to the model-matching API-key connection while honoring direct and custom auth overrides", () => {
const manager = { provider: "openai", method: "api_key", mode: "responsible_user" } as const;
const router = { mode: "router", connectionId: randomUUID() } as const;
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash" }, manager)).toEqual({
provider: "google",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("paperclip_runner", { provider: "opencode", model: "anthropic/claude-sonnet-4-5" }, manager)).toEqual({
provider: "anthropic",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GEMINI_API_KEY: "explicit" } }, manager)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GOOGLE_GENERATIVE_AI_API_KEY: "explicit" } }, manager)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "anthropic/claude-sonnet-4-5", env: { PAPERCLIP_OPENCODE_PROVIDERS: "{}" } }, router)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "anthropic/claude-sonnet-4-5", env: { OPENCODE_AUTH_JSON: "{}" } }, router)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "groq/llama-3.3-70b-versatile", env: { GROQ_API_KEY: "explicit" } }, router)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GEMINI_API_KEY: { type: "user_secret_ref", key: "GEMINI_API_KEY", version: "latest" } } }, manager)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GEMINI_API_KEY: { type: "secret_ref", secretId: randomUUID(), version: "latest" } } }, manager)).toBeUndefined();
expect(defaultAiConnectionForHire("opencode_local", { model: "anthropic/claude-sonnet-4-5", env: { OPENCODE_AUTH_JSON: { type: "user_secret_ref", key: "OPENCODE_AUTH_JSON", version: "latest" } } }, router)).toBeUndefined();
expect(defaultAiConnectionForHire("codex_local", { model: "gpt-5", env: { OPENAI_API_KEY: { type: "user_secret_ref", key: "OPENAI_API_KEY", version: "latest" } } }, manager)).toBeUndefined();
// Non-OpenCode provider config keys and blank values must not drop inherited OpenCode connections.
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GOOGLE_GEMINI_BASE_URL: "https://generativelanguage.example.test" } }, manager)).toEqual({
provider: "google",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GOOGLE_API_KEY: "bare-google-key" } }, manager)).toEqual({
provider: "google",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GEMINI_API_KEY: "", GOOGLE_GENERATIVE_AI_API_KEY: { type: "plain", value: " " } } }, manager)).toEqual({
provider: "google",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GEMINI_API_KEY: { type: "user_secret_ref", key: " " } } }, manager)).toEqual({
provider: "google",
method: "api_key",
mode: "responsible_user",
});
expect(defaultAiConnectionForHire("opencode_local", { model: "anthropic/claude-sonnet-4-5", env: { ANTHROPIC_BASE_URL: "https://proxy.example.test", CLAUDE_CONFIG_DIR: "/tmp/claude" } }, router)).toEqual(router);
expect(defaultAiConnectionForHire("opencode_local", { model: "openai/gpt-5", env: { OPENAI_BASE_URL: "https://proxy.example.test", CODEX_HOME: "/tmp/codex" } }, router)).toEqual(router);
expect(defaultAiConnectionForHire("opencode_local", { model: "google/gemini-2.5-flash", env: { GOOGLE_API_KEY: "bare-google-key", GOOGLE_GEMINI_BASE_URL: "https://proxy.example.test" } }, router)).toEqual(router);
});
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);
});
@@ -1,10 +1,16 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { OPENCODE_CREDENTIAL_ENV_KEYS } from "@paperclipai/shared";
import { ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS } from "@paperclipai/plugin-sdk";
import {
PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS,
configuredEnvironmentProjection,
} from "../../../packages/paperclip-runner/src/configured-environment.js";
import {
ACPX_CREDENTIAL_BINDING_ENV, ACPX_CREDENTIAL_NAMES, createAcpxCredentialBinding, createAcpxSidecarHostEnvironment, createSanitizedAcpxSpawnInput,
} from "../../../packages/paperclip-runner/src/drivers/acpx/environment.js";
import { OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS } from "../../../packages/paperclip-runner/src/drivers/opencode/provider-proxy.js";
import { OPEN_CODE_RUNNER_ENVIRONMENT_KEYS } from "../../../packages/paperclip-runner/src/live/runnerd-codex-transport.js";
const runnerSource = (file: string) =>
@@ -15,6 +21,7 @@ const rustAcpxCredentialNames = (agent: string) =>
names(new RegExp(`"${agent}" => &\\[([^\\]]*)\\]`, "u").exec(acpxSidecar)?.[1]);
const rustCandidateAgents = names(/if matches!\(agent, ([^)]*)\) \{[^}]*keys\.push\("PAPERCLIP_ACPX_CREDENTIAL_BINDING"\)/u.exec(acpxSidecar)?.[1]);
const rustOpenCodeNames = names(/const OPENCODE_PROVIDER_ENVIRONMENT_KEYS: &\[&str\] = &\[([^\]]*)\];/u.exec(runnerSource("codex_provider.rs"))?.[1]);
const rustConfiguredReservedNames = names(/const RESERVED: &\[&str\] = &\[([^\]]*)\];/u.exec(runnerSource("configured_environment.rs"))?.[1]);
const acpxAgents = Object.keys(ACPX_CREDENTIAL_NAMES) as (keyof typeof ACPX_CREDENTIAL_NAMES)[];
const providers = Object.entries(ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS);
@@ -56,10 +63,36 @@ describe("plugin Runner provider credential names", () => {
}
});
it("keeps OpenCode and reserved provider credential lists synchronized across shared, SDK, TS Runner, and Rust Runner", () => {
const internalProxyEnvKeys = new Set([
"PAPERCLIP_AI_PROVIDER_URL",
"PAPERCLIP_AI_PROVIDER_KEY",
"PAPERCLIP_OPENROUTER_PROXY_URL",
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
]);
const sdkOpenCodeKeys = [...new Set(ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode.flat())]
.filter((name) => !internalProxyEnvKeys.has(name))
.sort();
const sharedOpenCodeKeys = [...new Set(OPENCODE_CREDENTIAL_ENV_KEYS)].sort();
const proxyOpenCodeKeys = [...new Set(["OPENROUTER_API_KEY", ...OPENCODE_DIRECT_PROVIDER_API_KEY_ENV_KEYS])].sort();
expect(sharedOpenCodeKeys).toEqual(sdkOpenCodeKeys);
expect(proxyOpenCodeKeys).toEqual(sharedOpenCodeKeys);
for (const name of sharedOpenCodeKeys) {
expect(OPEN_CODE_RUNNER_ENVIRONMENT_KEYS.has(name), `${name} in OPEN_CODE_RUNNER_ENVIRONMENT_KEYS`).toBe(true);
expect(rustOpenCodeNames, `${name} in Rust OPENCODE_PROVIDER_ENVIRONMENT_KEYS`).toContain(name);
expect(PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS, `${name} in TS PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS`).toContain(name);
}
for (const name of PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS) {
expect(rustConfiguredReservedNames, `${name} in Rust configured_environment::RESERVED`).toContain(name);
}
});
it("still strips Google and Gemini routing variables from the Antigravity process", () => {
const routing = { GOOGLE_API_KEY: "fixture-google", GOOGLE_APPLICATION_CREDENTIALS: "/controller/private/adc.json",
GOOGLE_CLOUD_PROJECT: "fixture-project", GOOGLE_GEMINI_BASE_URL: "https://router.example.test", GEMINI_HOME: "/controller/private/gemini" };
const environment = { GEMINI_API_KEY: "fixture-gemini", ...routing, PAPERCLIP_CONFIGURED_ENV_KEYS: JSON.stringify(Object.keys(routing)) };
const projectedRouting = configuredEnvironmentProjection(routing);
expect(projectedRouting.GOOGLE_API_KEY).toBeUndefined();
const environment = { ...projectedRouting, GEMINI_API_KEY: "fixture-gemini", GOOGLE_API_KEY: "fixture-google" };
const binding = createAcpxCredentialBinding(environment, "antigravity", "session");
const host = createAcpxSidecarHostEnvironment({ ...environment, [ACPX_CREDENTIAL_BINDING_ENV]: binding }, "antigravity", "session");
const spawned = createSanitizedAcpxSpawnInput(host, "antigravity").env;
+72 -7
View File
@@ -40,6 +40,8 @@ import { listOpenRouterModels } from "../services/openrouter-models.js";
import { withManagedAiProbe, stripAiAuthBindings } from "../services/ai-connection-runtime.js";
import {
ADAPTER_AUTH_MISSING_CHECK_CODE,
OPENCODE_CREDENTIAL_ENV_KEYS,
OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS,
aiConnectionBindingSchema,
aiConnectionMetadataSchema,
aiRoutingModel,
@@ -2370,9 +2372,8 @@ 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: OPENCODE_CREDENTIAL_ENV_KEYS,
};
function isInheritableCredentialReference(value: unknown): value is Record<string, unknown> {
@@ -2424,10 +2425,50 @@ export function agentRoutes(
claudeCredentialKeys.some((key) => existingEnv[key] !== undefined);
if (childHasClaudeCredential) return noInheritance;
let keysToInherit: readonly string[] = credentialKeys;
if (harness === "opencode_local") {
// If the hire already supplies any OpenCode provider credential (including
// either Google alias key), inherit none so parent keys cannot override or
// conflict with the child's chosen provider.
const childHasOpenCodeCredential =
existingEnv !== null &&
credentialKeys.some((key) => existingEnv[key] !== undefined);
if (childHasOpenCodeCredential) return noInheritance;
const parentProviderGroups = Object.entries(OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS)
.filter(([, keys]) => keys.some((key) => isInheritableCredentialReference(parentEnv[key])));
if (parentProviderGroups.length === 0) return noInheritance;
const childModelProvider = asNonEmptyString(adapterConfig.model)?.split("/")[0]?.trim().toLowerCase();
const parentModelProvider = asNonEmptyString(asRecord(parent.adapterConfig)?.model)?.split("/")[0]?.trim().toLowerCase();
const matchedChildGroup = childModelProvider
? parentProviderGroups.find(([provider]) => provider === childModelProvider)
: undefined;
if (matchedChildGroup) {
keysToInherit = matchedChildGroup[1];
} else if (childModelProvider) {
// The hire explicitly chose a model provider the parent holds no
// credential for; do not copy an unrelated provider key.
return noInheritance;
} else {
const matchedParentGroup = parentModelProvider
? parentProviderGroups.find(([provider]) => provider === parentModelProvider)
: undefined;
if (matchedParentGroup) {
keysToInherit = matchedParentGroup[1];
} else if (parentProviderGroups.length === 1) {
keysToInherit = parentProviderGroups[0]![1];
} else {
// Ambiguous multi-provider parent with no model to disambiguate.
return noInheritance;
}
}
}
const nextEnv: Record<string, unknown> = { ...(existingEnv ?? {}) };
let inheritedFixedClaudeOAuthBinding = false;
let changed = false;
for (const key of credentialKeys) {
for (const key of keysToInherit) {
if (existingEnv && existingEnv[key] !== undefined) continue;
const parentValue = parentEnv[key];
if (!isInheritableCredentialReference(parentValue)) continue;
@@ -2748,7 +2789,11 @@ export function agentRoutes(
...INHERITABLE_AGENT_CREDENTIAL_ENV_KEYS,
gemini_local: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
kimi_local: ["KIMI_MODEL_API_KEY"],
opencode_local: ["PAPERCLIP_OPENCODE_PROVIDERS", "OPENCODE_AUTH_JSON"],
opencode_local: [
...INHERITABLE_AGENT_CREDENTIAL_ENV_KEYS.opencode_local,
"PAPERCLIP_OPENCODE_PROVIDERS",
"OPENCODE_AUTH_JSON",
],
};
const POOL_AUTH_OVERRIDE_ENV_KEYS = [
"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "PAPERCLIP_OPENCODE_PROVIDERS", "OPENCODE_AUTH_JSON",
@@ -3512,9 +3557,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 +3619,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) {
@@ -1,5 +1,6 @@
import {
AI_PROVIDERS,
OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS,
aiRuntimeConnectionBindingSchema,
isAiConnectionCompatible,
type AiConnectionBinding,
@@ -11,13 +12,40 @@ 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"],
openrouter: ["OPENROUTER_API_KEY"],
xai: ["XAI_API_KEY", "GROK_API_KEY", "GROK_HOME", "XAI_BASE_URL"],
};
// OpenCode custom provider/config auth overrides apply across all OpenCode model providers.
const OPENCODE_CUSTOM_AUTH_ENV_KEYS = [
"OPENCODE_AUTH_JSON",
"OPENCODE_CONFIG_CONTENT",
"OPENCODE_CONFIG",
"OPENCODE_CONFIG_DIR",
"PAPERCLIP_OPENCODE_PROVIDERS",
] as const;
function hasNonEmptyEnvBinding(value: unknown): boolean {
if (typeof value === "string") return value.trim().length > 0;
if (value && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
if (record.type === "plain") return typeof record.value === "string" && record.value.trim().length > 0;
if (record.type === "secret_ref") return typeof record.secretId === "string" && record.secretId.trim().length > 0;
if (record.type === "user_secret_ref") return typeof record.key === "string" && record.key.trim().length > 0;
}
return false;
}
function openCodeModelProvider(model: unknown): string | undefined {
if (typeof model !== "string") return undefined;
const slash = model.indexOf("/");
if (slash <= 0) return undefined;
return model.slice(0, slash).trim().toLowerCase() || undefined;
}
/** A hire inherits a connection choice, never its manager's credentials or identity. */
export function defaultAiConnectionForHire(
adapterType: string,
@@ -30,8 +58,20 @@ export function defaultAiConnectionForHire(
// Unmanaged parents keep their existing login and credential-reference paths.
if (!inherited.success) return undefined;
const env = config.env && typeof config.env === "object" ? config.env as Record<string, unknown> : {};
const isOpenCode =
adapterType === "opencode_local"
|| (adapterType === "paperclip_runner" && config.provider === "opencode");
const hasOpenCodeChildAuth = (provider: string | undefined) => {
if (OPENCODE_CUSTOM_AUTH_ENV_KEYS.some((key) => hasNonEmptyEnvBinding(env[key]))) return true;
const keys = provider && Object.hasOwn(OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS, provider)
? OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS[provider as keyof typeof OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS]
: undefined;
return keys ? keys.some((key) => hasNonEmptyEnvBinding(env[key])) : false;
};
const hasChildAuth = (provider: AiProvider) =>
PROVIDER_AUTH_ENV_KEYS[provider].some((key) => env[key] !== undefined);
isOpenCode
? hasOpenCodeChildAuth(provider)
: PROVIDER_AUTH_ENV_KEYS[provider].some((key) => hasNonEmptyEnvBinding(env[key]));
const withChildAuthPrecedence = (binding: AiConnectionBinding) =>
hasChildAuth(binding.provider) ? undefined : binding;
if (inherited.data.mode === "router") {
@@ -39,11 +79,13 @@ 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" }));
if (isOpenCode) {
return hasOpenCodeChildAuth(openCodeModelProvider(config.model) ?? "openrouter")
? undefined
: inherited.data;
}
const childProvider = AI_PROVIDERS.find((provider) =>
compatible({ provider, method: "api_key", mode: "responsible_user" }));
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" }],
["opencode", { PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1", PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
] as const)("transfers only the selected %s variables", async (provider, environment) => {
@@ -166,6 +174,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", { PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1" }],
["opencode", { PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
["opencode", { OPENROUTER_API_KEY: "fixture-openrouter", PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1", PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
@@ -13,7 +13,7 @@
"packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb",
"packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8",
"packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4",
"packages/plugins/sdk/src/environment-tasks.ts": "3762ed8d25c8c1b63853e33c0e5646669b2cea7c",
"packages/plugins/sdk/src/environment-tasks.ts": "fb61d830ea05ac0f92bfd5ab017026aef93abe61",
"packages/plugins/sdk/src/host-client-factory.ts": "8f76d518b4b43a41436b516cb2929165611bd483",
"packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a",
"packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f",
@@ -65,7 +65,7 @@
"packages/shared/src/aggregator-apps.ts": "2a69a54ee0cb305170275b6f4e97689c107defb1",
"packages/shared/src/ai-connection-router.ts": "9fbd89c385a4d5827bc68e1c7f6a66e00453d413",
"packages/shared/src/ai-connection-usage.ts": "4b51573ee92f8a2ae0f80dd15288a0e59b4dddc7",
"packages/shared/src/ai-connections.ts": "f4107ef6a07c070b7ad04d64bf16d50135a3950a",
"packages/shared/src/ai-connections.ts": "13819a7d1f09f1a157c36a4c1856352acaebb197",
"packages/shared/src/ai-provider-routing.ts": "e1f1fdefc23c76efe425e937852e61fe028cccc1",
"packages/shared/src/analytics-consent.test.ts": "0c69d867d4f108cb57c07b4e71633e058cb7506b",
"packages/shared/src/analytics-consent.ts": "00c4bfbd24ac3a288a68caae52468dfcd26df3e7",
@@ -504,7 +504,7 @@
"packages/shared/src/validators/adapter-skills.ts": "ae43f7b180f632d5f54dfa821b8dc5ef6c6aa53d",
"packages/shared/src/validators/agent-commentary.ts": "8242c5b28a77131aefdc00c873ad84c6c6736e4b",
"packages/shared/src/validators/agent.test.ts": "b15ce4e96097e807de7e52ca174139dd51e0d9c9",
"packages/shared/src/validators/agent.ts": "92cbbfb031bd0e592083e2deb6f961bd5f31a574",
"packages/shared/src/validators/agent.ts": "5aea39fc234af1a1960fca0607b584e8b1da9ff7",
"packages/shared/src/validators/app-definition.ts": "87a60e50f386c8f836d1c5a1576b75a50bc719a2",
"packages/shared/src/validators/approval.test.ts": "051d29b27400fdd1e311466587b276264cf072e4",
"packages/shared/src/validators/approval.ts": "b8fd4da39568e3b70b767266196ea5303efeef25",
@@ -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)
@@ -302,7 +309,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";
@@ -397,23 +400,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());
@@ -530,10 +529,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;
}
}