mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Cloud starter-inference onboarding (`free_inference_1`) runs the first OpenCode agent inside a remote plugin Runner environment using a per-run server proxy (`PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`) instead of exposing the raw OpenRouter key. > - On remote plugin Runner environments, OpenCode runs failed immediately with OpenRouter HTTP 401 (`No cookie auth credentials found`) because the proxy URL and token never reached the sandbox. > - Three boundaries stripped the proxy credentials: `preparePluginRunnerCredentials` returned early when `managedAiCredentialIdentity` was absent, `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode` did not allow the proxy pair, and Rust `OPENCODE_PROVIDER_ENVIRONMENT_KEYS` in `codex_provider.rs` did not forward those keys. > - This pull request adds the `[PAPERCLIP_OPENROUTER_PROXY_URL, PAPERCLIP_OPENROUTER_PROXY_TOKEN]` pair across all three boundaries while keeping raw starter keys strictly server-side and failing closed on partial or ambiguous credentials. > - The benefit is that Cloud starter-inference OpenCode runs authenticate cleanly through the server proxy inside remote plugin Runner sandboxes. ## Linked Issues or Issue Description Refs #23401, #23427 **Summary** Transfer `PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN` through the plugin Runner credential boundary and Rust `runner-core` allowlist for Cloud starter-inference OpenCode runs. **Steps to Reproduce** 1. Create a Cloud starter-inference (`free_inference_1`) workspace running OpenCode in a remote plugin Runner environment. 2. Send a message in the onboarding chat. 3. Observe `APIError` HTTP 401 (`No cookie auth credentials found`) from OpenRouter because the sandbox OpenCode proxy received neither `PAPERCLIP_OPENROUTER_PROXY_URL` nor `OPENROUTER_API_KEY`. **Expected Behavior** The remote plugin Runner receives `{ PAPERCLIP_OPENROUTER_PROXY_URL, PAPERCLIP_OPENROUTER_PROXY_TOKEN }` via the `opencode` `provider-env` credential channel, forwards them to OpenCode, and routes inference through the server-side starter proxy. ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: Added `["PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN"]` to `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode`. - `packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs`: Added `"PAPERCLIP_OPENROUTER_PROXY_URL"` and `"PAPERCLIP_OPENROUTER_PROXY_TOKEN"` to `OPENCODE_PROVIDER_ENVIRONMENT_KEYS`. - `server/src/services/native-runtime/plugin-runner-credentials.ts`: Allowed `opencode` runs with both `PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN` to transfer that `provider-env` credential when `identity` is absent (using `"cloud-trial"` as `accountIdentity`). - `server/src/services/native-runtime/plugin-runner-credentials.test.ts`: Added regression coverage for transferring the Cloud starter proxy pair without a managed AI connection identity and failing closed on partial or ambiguous combinations. - `tests/runner-e2e/source-sdk-public-inputs.json`: Updated reviewed SDK public inputs pin for `packages/plugins/sdk/src/environment-tasks.ts`. ## Verification - `pnpm --filter @paperclipai/plugin-sdk build` — passed. - `pnpm --filter @paperclipai/plugin-sdk exec vitest run tests/environment-tasks.test.ts tests/environment-task-release-resume.test.ts` — passed (104/104 tests). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/plugin-runner-credential-names.test.ts` — passed (45/45 tests, verifying SDK allowlist, Runner TS allowlist, and Rust `codex_provider.rs` allowlist together). ## Risks - Low risk. Only the ephemeral per-run proxy URL and `pctrial_` token pair is allowed when both are present and non-empty; partial or mixed sets still fail closed in `environmentTaskCredentialSchema`, and raw OpenRouter keys never leave the server process. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## 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 - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge
103 lines
6.3 KiB
TypeScript
103 lines
6.3 KiB
TypeScript
import { realpath } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
|
|
import { hasUsableGrokAuthValue, parseGrokAuthPayload } from "@paperclipai/adapter-grok-local/server";
|
|
import {
|
|
ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS, environmentTaskCredentialSchema,
|
|
type PluginEnvironmentTaskCredential, type PluginEnvironmentTaskCredentialProvider,
|
|
} from "@paperclipai/plugin-sdk";
|
|
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
|
|
import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js";
|
|
|
|
const ANTIGRAVITY_SIGN_IN_ENV = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET";
|
|
|
|
interface PreparedPluginRunnerCredentials {
|
|
githubBroker?: { url: string; token: string };
|
|
accountIdentity?: string;
|
|
credential?: PluginEnvironmentTaskCredential;
|
|
writeback?: { mode: "live" | "on_stop"; requiresGoogleGeneration?: true };
|
|
onCredentials?: (snapshot: PluginEnvironmentTaskCredential) => Promise<void>;
|
|
}
|
|
|
|
/** Transfer only the selected account. Provider configuration stays at the dedicated provider boundary. */
|
|
export async function preparePluginRunnerCredentials(input: {
|
|
provider: string;
|
|
identity?: string;
|
|
accountIdentity?: string;
|
|
home?: string;
|
|
environment: NodeJS.ProcessEnv;
|
|
}): Promise<PreparedPluginRunnerCredentials> {
|
|
const github = input.environment.PAPERCLIP_GITHUB_BROKER_TOKEN ? { githubBroker: {
|
|
url: input.environment.PAPERCLIP_GITHUB_BROKER_URL ?? "",
|
|
token: input.environment.PAPERCLIP_GITHUB_BROKER_TOKEN,
|
|
} } : {};
|
|
const hasCloudTrialOpenRouterProxy =
|
|
input.provider === "opencode" &&
|
|
Boolean(input.environment.PAPERCLIP_OPENROUTER_PROXY_URL?.trim()) &&
|
|
Boolean(input.environment.PAPERCLIP_OPENROUTER_PROXY_TOKEN?.trim());
|
|
if (!input.identity && !hasCloudTrialOpenRouterProxy) return github;
|
|
const accountIdentity = input.accountIdentity ?? input.identity ?? "cloud-trial";
|
|
if (input.provider === "codex") {
|
|
if (!input.home) throw new Error("Plugin Runner selected credential home unavailable");
|
|
const hostAuthPath = join(await realpath(input.home), "auth.json");
|
|
const authJson = await readLocalAiCredentialFile(hostAuthPath);
|
|
const parsed = JSON.parse(authJson);
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Plugin Runner selected credential invalid");
|
|
const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "codex", content: authJson });
|
|
return { ...github, accountIdentity, credential, writeback: parsed.tokens ? { mode: "live" } : undefined,
|
|
onCredentials: async (snapshot: PluginEnvironmentTaskCredential) => {
|
|
if (snapshot.type !== "auth-file" || snapshot.provider !== "codex") throw new Error("Plugin Runner credential provider mismatch");
|
|
await copyBackCodexAuth({ hostAuthPath, readSandboxAuth: async () => Buffer.from(snapshot.content), log: () => {} });
|
|
},
|
|
};
|
|
}
|
|
if (input.provider === "grok" && !input.environment.XAI_API_KEY) {
|
|
if (input.environment.XAI_BASE_URL) throw new Error("Plugin Runner does not support the selected provider routing");
|
|
if (!input.home) throw new Error("Plugin Runner selected credential home unavailable");
|
|
const content = await readLocalAiCredentialFile(join(await realpath(input.home), "auth.json"));
|
|
let usable = false;
|
|
try {
|
|
const parsed = parseGrokAuthPayload(JSON.parse(content));
|
|
usable = parsed !== null && hasUsableGrokAuthValue(parsed.value);
|
|
} catch { /* Do not expose credential bytes through JSON parser errors. */ }
|
|
if (!usable) throw new Error("Plugin Runner selected credential invalid");
|
|
return { ...github, accountIdentity, writeback: { mode: "live" },
|
|
credential: environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "grok", content }) };
|
|
}
|
|
if (input.provider === "claude") {
|
|
if (input.environment.ANTHROPIC_BASE_URL || input.environment.ANTHROPIC_AUTH_TOKEN) {
|
|
throw new Error("Plugin Runner does not support the selected provider routing");
|
|
}
|
|
const environment = Object.fromEntries(["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"]
|
|
.flatMap(key => input.environment[key] ? [[key, input.environment[key]]] : []));
|
|
return { ...github, accountIdentity, credential: environmentTaskCredentialSchema.parse({ type: "claude-env", environment }) };
|
|
}
|
|
if (input.provider === "grok" || input.provider === "copilot" || input.provider === "opencode" || input.provider === "antigravity") {
|
|
const provider: PluginEnvironmentTaskCredentialProvider = input.provider;
|
|
if (provider === "grok") {
|
|
if (input.environment.XAI_BASE_URL) throw new Error("Plugin Runner does not support the selected provider routing");
|
|
}
|
|
if (provider === "antigravity") {
|
|
if (input.environment[ANTIGRAVITY_SIGN_IN_ENV]?.trim()) throw new Error("Plugin Runner selected credential unavailable");
|
|
if (!input.environment.GEMINI_API_KEY?.trim()) {
|
|
if (!input.home) throw new Error("Google Antigravity needs a Gemini API key or a saved Google sign-in.");
|
|
let authJson: string;
|
|
try {
|
|
authJson = sanitizeAntigravityCredential(await readLocalAiCredentialFile(join(await realpath(input.home), "antigravity-acp", "acp_token.json")));
|
|
} catch {
|
|
throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry.");
|
|
}
|
|
const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider, content: authJson });
|
|
return { ...github, accountIdentity, credential, writeback: { mode: "live", requiresGoogleGeneration: true } };
|
|
}
|
|
}
|
|
const names = new Set(provider === "antigravity" ? ["GEMINI_API_KEY"] : ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat());
|
|
const environment = Object.fromEntries([...names]
|
|
.flatMap(key => input.environment[key] ? [[key, input.environment[key]]] : []));
|
|
const credential = environmentTaskCredentialSchema.safeParse({ type: "provider-env", provider, environment });
|
|
if (!credential.success) throw new Error("Plugin Runner selected credential unavailable");
|
|
return { ...github, accountIdentity, credential: credential.data };
|
|
}
|
|
throw new Error("Plugin Runner does not support the selected credential provider");
|
|
}
|