Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(devin): authenticate ACP sessions with the configured API key
VNATdev-opse1f1140f6670
diff --git a/server/drivers/acp/background-text.test.ts b/server/drivers/acp/background-text.test.tsindex cc14c463a1..089b331449 100644--- a/server/drivers/acp/background-text.test.ts+++ b/server/drivers/acp/background-text.test.ts@@ -16,7 +16,7 @@ import { GrokAgentDriver } from "./grok.ts";import { QwenAgentDriver } from "./qwen.ts";const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "testing", "fake-acp-cli.ts");-const ENV_KEYS = ["FAKE_ACP_MODE", "FAKE_ACP_DUMP", "FAKE_ACP_TEXT_REPLY", "FAKE_ACP_MODELS", "FAKE_ACP_SESSION_MODELS", "FAKE_ACP_MODEL_STICKS"];+const ENV_KEYS = ["FAKE_ACP_MODE", "FAKE_ACP_DUMP", "FAKE_ACP_TEXT_REPLY", "FAKE_ACP_MODELS", "FAKE_ACP_SESSION_MODELS", "FAKE_ACP_MODEL_STICKS", "FAKE_ACP_AUTH_METHOD", "FAKE_ACP_EXPECTED_API_KEY"];describe("ACP memory one-shot (generateMemoryText)", () => {let instance: ProviderInstance | undefined;@@ -158,6 +158,19 @@ describe("ACP memory one-shot (generateMemoryText)", () => {expect(existsSync(`${process.env.FAKE_ACP_DUMP}.prompts.jsonl`)).toBe(false);});+ it("sends authenticate with its _meta before the one-shot session/new", async () => {+ process.env.FAKE_ACP_MODE = "auth-required-api-key";+ process.env.FAKE_ACP_AUTH_METHOD = "devin-browser";+ process.env.FAKE_ACP_EXPECTED_API_KEY = "fixture-key";+ const engine = await create(createAcpDriver({+ ...support, pickAuthMethod: () => "devin-browser", authMeta: () => ({ api_key: "fixture-key" }),+ }));+ expect(await engine.generateMemoryText!("prompt")).toBe("[]");+ expect(JSON.parse(readFileSync(`${process.env.FAKE_ACP_DUMP}.authenticate.json`, "utf8"))).toEqual({+ methodId: "devin-browser", _meta: { api_key: "fixture-key" },+ });+ });+it("keeps the session's default when the engine can no longer route the bot's model", async () => {const resolveTurnModel = () => { throw new Error("model is no longer configured"); };await (await create(createAcpDriver({ ...support, resolveTurnModel }))).generateMemoryText!("prompt", { fallback: { model: "m-bot", refused: new Set<string>(), onRefused: () => {} } });diff --git a/server/drivers/acp/background-text.ts b/server/drivers/acp/background-text.tsindex a77f6359af..13423d6f3b 100644--- a/server/drivers/acp/background-text.ts+++ b/server/drivers/acp/background-text.ts@@ -79,6 +79,7 @@ export interface AcpOneShotInput {/** Model applied outside `selectModel` (e.g. via argv or `configure`), used for usage attribution once configured. */configuredModel?: string;pickAuthMethod: (methods: Array<{ id?: string }>) => string | null;+ authMeta?: Record<string, unknown>;authRequired: boolean | "if-requested";loginNote: string;/** Whether a session/new refusal asks for a sign-in; it then fails with `loginNote`. */@@ -216,7 +217,7 @@ export function runAcpOneShot(input: AcpOneShotInput): Promise<string> {const methodId = input.pickAuthMethod(methods);if (methodId) {try {- await request("authenticate", { methodId });+ await request("authenticate", { methodId, ...(input.authMeta ? { _meta: input.authMeta } : {}) });} catch {if (input.authRequired) throw new Error(input.loginNote);}diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 21d6a96a32..1333b07731 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -225,6 +225,8 @@ export interface AcpSupport extends AcpDriverHooks {): void;/** The authenticate methodId from initialize's authMethods; null skips authenticate. */pickAuthMethod(authMethods: Array<{ id?: string }>, env: Record<string, string | undefined>): string | null;+ /** Extra authenticate params, e.g. an API key the CLI does not read from the environment. Never logged. */+ authMeta?(env: Record<string, string | undefined>): Record<string, unknown> | undefined;/** "fail": abort if auth is missing/errors (subscription CLIs).* "fail-request": cached API credentials need no method, but a requested* OAuth login must succeed. "continue": proceed on an ambient login. */@@ -1095,8 +1097,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>: [];const methodId = support.pickAuthMethod(methods, spawnEnv);if (methodId) {+ const meta = support.authMeta?.(spawnEnv);try {- await session.host.once("authenticate", () => retryTransient(request, "authenticate", { methodId }, INIT_TIMEOUT));+ await session.host.once("authenticate", () => retryTransient(request, "authenticate", { methodId, ...(meta ? { _meta: meta } : {}) }, INIT_TIMEOUT));session.authenticated = true;} catch (error) {const failed = signIn.authenticateFailed(error, support.authFailure); if (failed) throw failed;@@ -1456,6 +1459,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>prompt,defaultModel: turnModel ?? catalog.models.default, model, ...(turnModel ? { configuredModel: turnModel } : {}),pickAuthMethod: (methods) => support.skipsAuthenticate?.(instanceId) ? null : support.pickAuthMethod(methods, spawnEnv),+ ...(support.authMeta && !support.skipsAuthenticate?.(instanceId) ? { authMeta: support.authMeta(spawnEnv) } : {}),authRequired: turnModel && skipSubscriptionAuthForLocalInject(options.model ?? options.fallback?.model) ? false : !support.skipsAuthenticate?.(instanceId) && (support.authFailure === "fail-request" ? "if-requested" : support.authFailure === "fail"),loginNote: support.loginNote, signInRefused: support.skipsAuthenticate?.(instanceId) && support.signInRequest ? (error) => { const refused = support.signInRequest!.rpcError(error, instanceId); if (refused) support.signInRequest!.required(instanceId); return refused; } : undefined,clientCapabilitiesMeta: support.clientCapabilitiesMeta,diff --git a/server/drivers/acp/custom-model-catalog.ts b/server/drivers/acp/custom-model-catalog.tsindex 19df5c3911..1ee280b52b 100644--- a/server/drivers/acp/custom-model-catalog.ts+++ b/server/drivers/acp/custom-model-catalog.ts@@ -32,6 +32,9 @@ export interface AcpDiscoveryOptions {default?: string;/** Sent as `clientCapabilities._meta` in initialize, as a turn session sends it, so both see the same model list. */clientCapabilitiesMeta?: Record<string, unknown>;+ /** Some CLIs refuse session/new until authenticate ran with a method they advertised. */+ authMethod?(methods: Array<{ id?: string }>, env: Record<string, string | undefined>): string | null;+ authMeta?(env: Record<string, string | undefined>): Record<string, unknown> | undefined;/** The picker label for an advertised model, given session/new's result verbatim. */label?(model: { id: string; label: string }, sessionNew: unknown): string;/** Close stdin and give the agent this many milliseconds to exit on its own, so it can release what it holds,@@ -224,6 +227,13 @@ export async function discoverAcpModels(...(discovery.clientCapabilitiesMeta ? { _meta: discovery.clientCapabilitiesMeta } : {}),},});+ const advertised = record(initialized);+ const methods: Array<{ id?: string }> = Array.isArray(advertised?.authMethods) ? advertised.authMethods as Array<{ id?: string }> : [];+ const methodId = discovery.authMethod?.(methods, env);+ if (methodId) {+ const meta = discovery.authMeta?.(env);+ await request("authenticate", { methodId, ...(meta ? { _meta: meta } : {}) });+ }const initial = await request("session/new", { cwd, mcpServers: [] });const rawSessionId = record(initial)?.sessionId;if (typeof rawSessionId !== "string" || !rawSessionId) throw new Error("ACP model discovery did not return a session.");diff --git a/server/drivers/acp/devin.test.ts b/server/drivers/acp/devin.test.tsindex f7cf5ae7a5..a07f424ddc 100644--- a/server/drivers/acp/devin.test.ts+++ b/server/drivers/acp/devin.test.ts@@ -188,6 +188,28 @@ describe("Devin ACP driver", () => {expect(catalog.options.map((option) => option.id)).toEqual(["agent-default", ...MODELS.split(",")]);});+ it("authenticates with the API key before model discovery's session/new", async () => {+ const dump = join(scratch, "discovery-auth.json");+ const rpc = join(scratch, "discovery-auth-rpc.json");+ const catalog = await resolveDevinModels({+ ...process.env, FAKE_ACP_MODELS: MODELS, FAKE_ACP_MODE: "auth-required-api-key", FAKE_ACP_AUTH_METHOD: "devin-browser",+ FAKE_ACP_EXPECTED_API_KEY: "engine-fixture-key", WINDSURF_API_KEY: "engine-fixture-key", FAKE_ACP_DUMP: dump, FAKE_ACP_RPC_DUMP: rpc,+ }, { cli: FAKE_CLI });+ expect(catalog.options.map((option) => option.id)).toEqual(["agent-default", ...MODELS.split(",")]);+ expect(JSON.parse(readFileSync(`${dump}.authenticate.json`, "utf8"))).toEqual({ methodId: "devin-browser", _meta: { api_key: "engine-fixture-key" } });+ const methods = JSON.parse(readFileSync(rpc, "utf8")) as string[];+ expect(methods.indexOf("authenticate")).toBeLessThan(methods.indexOf("session/new"));+ });++ it("fails discovery without calling authenticate when the CLI requires a key and none is available", async () => {+ const dump = join(scratch, "discovery-no-key.json");+ await expect(resolveDevinModels({+ ...process.env, FAKE_ACP_MODELS: MODELS, FAKE_ACP_MODE: "auth-required-api-key", FAKE_ACP_AUTH_METHOD: "devin-browser",+ FAKE_ACP_EXPECTED_API_KEY: "engine-fixture-key", FAKE_ACP_DUMP: dump,+ }, { cli: FAKE_CLI })).rejects.toThrow(/ACP model discovery/);+ expect(existsSync(`${dump}.authenticate.json`)).toBe(false);+ });+it("lists a catalog of more than 128 models (a Devin Pro account has 145) without switching to each one", async () => {const models = Array.from({ length: 145 }, (_, index) => `fixture-model-${index}`);const rpc = join(scratch, "discovery-rpc.json");@@ -221,6 +243,20 @@ describe("Devin ACP driver", () => {expect(prompts().at(-1)).toMatchObject({ model: "claude-sonnet-5-5" });});+ it("authenticates the turn session before prompting and keeps the key out of argv and events", async () => {+ const { instance, recorder } = await create({+ FAKE_ACP_MODE: "auth-required-api-key", FAKE_ACP_AUTH_METHOD: "devin-browser", FAKE_ACP_EXPECTED_API_KEY: "engine-fixture-key",+ });+ const { turnId } = await instance.adapter.sendTurn({ threadId: "devin-auth", text: "hello", model: "claude-sonnet-5-5", approvalMode: "ask" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ expect(JSON.parse(readFileSync(join(scratch, "launch.json.authenticate.json"), "utf8"))).toEqual({+ methodId: "devin-browser", _meta: { api_key: "engine-fixture-key" },+ });+ const launch = JSON.parse(readFileSync(join(scratch, "launch.json"), "utf8"));+ expect(JSON.stringify(launch.argv)).not.toContain("engine-fixture-key");+ expect(JSON.stringify(recorder.events)).not.toContain("engine-fixture-key");+ });+it("leaves Devin on its own default model, and bypasses permissions only under Full access", async () => {const { instance, recorder } = await create();const { turnId } = await instance.adapter.sendTurn({ threadId: "devin-full", text: "hello", model: "agent-default", approvalMode: "full" });diff --git a/server/drivers/acp/devin.ts b/server/drivers/acp/devin.tsindex d7eedfd633..90e029d3db 100644--- a/server/drivers/acp/devin.ts+++ b/server/drivers/acp/devin.ts@@ -23,6 +23,8 @@ const MODELS: ModelCatalog = { default: AGENT_DEFAULT.id, options: [AGENT_DEFAULconst SPAWN_ARGS = ["acp"];const SIGN_IN = "devin auth login";const API_KEY_ENV = "WINDSURF_API_KEY";+/** What initialize advertises on 3000.12.x; 3000.15+ keeps the method but refuses session/new until authenticate carries the key. */+const AUTH_METHOD = "devin-browser";const LOGIN_NOTE = `Devin is not signed in. Run ${SIGN_IN} in a terminal, or set ${API_KEY_ENV}, then check again.`;export const DEVIN_MODE = { ask: "accept-edits", full: "bypass" } as const;@@ -43,10 +45,25 @@ export function devinSignedIn(env: Record<string, string | undefined>, platform:return Boolean(env[API_KEY_ENV]?.trim()) || devinCredentialsFiles(env, platform).some((file) => existsSync(file));}+function devinAuthMethod(methods: Array<{ id?: string }>, env: Record<string, string | undefined>): string | null {+ if (!env[API_KEY_ENV]?.trim()) return null;+ const offered = methods.find((method) => method.id === AUTH_METHOD || String(method.id ?? "").startsWith("devin-"));+ return offered?.id ?? null;+}++/** The key goes to the CLI's authenticate request, never to argv, logs or events. */+function devinAuthMeta(env: Record<string, string | undefined>): Record<string, unknown> | undefined {+ const key = env[API_KEY_ENV]?.trim();+ return key ? { api_key: key } : undefined;+}+/** No exit grace: devin 3000.12.57 exits on EOF but orphans the MCP servers it started from its own config, which then* hold the discovery folder for seconds where the tree kill would have stopped them. A Devin Pro account advertises* 145 models, past discovery's default cap of 128; above 128 the per-model variant switches are skipped, as for OMP. */-const DISCOVERY: AcpDiscoveryOptions = { passthrough: AGENT_DEFAULT, variantLimit: 128, maxModels: 4096 };+const DISCOVERY: AcpDiscoveryOptions = {+ passthrough: AGENT_DEFAULT, variantLimit: 128, maxModels: 4096,+ authMethod: devinAuthMethod, authMeta: devinAuthMeta,+};export function resolveDevinModels(env: Record<string, string | undefined>, config: Pick<AcpConfig, "cli">): Promise<ModelCatalog> {return discoverAcpModels(env, config.cli, SPAWN_ARGS, DISCOVERY);@@ -114,7 +131,8 @@ const SUPPORT: AcpSupport = {resolveModelsOnCreate: false,selectModel: { configId: "model", agentDefault: AGENT_DEFAULT.id },modelVariants: true,- pickAuthMethod: () => null,+ pickAuthMethod: devinAuthMethod,+ authMeta: devinAuthMeta,authFailure: "continue",isAuthenticated: (env) => devinSignedIn(env),classifyError: classifyDevinError,diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex ae67d5f757..98b75b0f02 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -12,7 +12,9 @@// FAKE_ACP_MODE happy (default) | image | empty-reply | reasoning-only | exit-early | fail-after-text | crash-in-prompt// | abort-in-prompt (a sign-in link, then a TCMalloc CHECK line on stderr, then exit 134 as bubblewrap reports SIGABRT) | hang// | hang-initialize | unkeyed-tool | finished-tools (tool_call frames that arrive already completed or failed, one updated again)-// | no-auth | auth-required | permission | question+// | no-auth | auth-required | auth-required-api-key (session/new fails until authenticate carries+// _meta.api_key === FAKE_ACP_EXPECTED_API_KEY; the request is dumped to FAKE_ACP_DUMP.authenticate.json)+// | permission | question// | ask-question (a mid-prompt vendor question: FAKE_ACP_ASK_METHOD, default cursor/ask_question, params// FAKE_ACP_ASK_PARAMS; the client's reply is written to FAKE_ACP_ASK_ANSWER. FAKE_ACP_ASK_TIMING=with-result// settles the turn with the card open; after-result asks between turns)@@ -131,6 +133,7 @@ import { spawn } from "node:child_process";import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";const mode = process.env.FAKE_ACP_MODE ?? "happy";+let apiKeyAuthenticated = false;if (process.env.FAKE_ACP_START_FAILURE) {writeSync(2, `${process.env.FAKE_ACP_START_FAILURE}\n`);@@ -1071,11 +1074,19 @@ function handle(msg: any) {break;}case "authenticate":+ if (process.env.FAKE_ACP_DUMP) writeFileSync(`${process.env.FAKE_ACP_DUMP}.authenticate.json`, JSON.stringify(msg.params));if (failRpc(msg)) break;if (mode === "authenticate-failed") {out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "Login expired" } });break;}+ if (mode === "auth-required-api-key") {+ if (msg.params?._meta?.api_key !== (process.env.FAKE_ACP_EXPECTED_API_KEY ?? "")) {+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "Invalid API key" } });+ break;+ }+ apiKeyAuthenticated = true;+ }result(msg.id, {});break;case "_x.ai/mcp/list":@@ -1085,7 +1096,7 @@ function handle(msg: any) {break;case "session/new": {if (failRpc(msg)) break;- if (mode === "auth-required") {+ if (mode === "auth-required" || (mode === "auth-required-api-key" && !apiKeyAuthenticated)) {out({jsonrpc: "2.0",id: msg.id,