Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Antigravity: a sign-in Google cannot confirm for a moment is not a sign-out
laijsg1e9d08cade37a
diff --git a/server/antigravity-auth-blip.e2e.test.ts b/server/antigravity-auth-blip.e2e.test.tsnew file mode 100644index 0000000000..5904f75d43--- /dev/null+++ b/server/antigravity-auth-blip.e2e.test.ts@@ -0,0 +1,118 @@+import { spawn, type ChildProcess } from "node:child_process";+import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";++import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";+import { antigravityTokenPath } from "./drivers/antigravity-acp.ts";+import { waitForExit } from "./testing/cleanup.ts";++const codex = { instanceId: "codex", model: "gpt-fake-default" };+const antigravity = { instanceId: "antigravity", model: "gemini-3.8-flash" };++it("a sign-in Google cannot confirm for a moment is not a sign-out", async () => {+ const fixture = await launchVerificationServer();+ const { dataDir, url, logPath } = fixture.info;+ let server: ChildProcess | undefined;+ const runtime = join(dataDir, "fake-antigravity");+ const failureFile = join(dataDir, "authenticate-failure.json");+ const rpcFile = join(dataDir, "antigravity-rpc.jsonl");+ const evidence: unknown[] = [{ url, dataDir }];+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": "application/json", origin: url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),+ });+ const value = await response.json() as any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(200);+ return value;+ };+ const control = async (...args: string[]) => {+ const result = await runControlOmb([...args, "--url", url]) as any;+ evidence.push({ command: args, result });+ return result;+ };+ const calls = (method: string): Array<{ pid: number }> => existsSync(rpcFile)+ ? readFileSync(rpcFile, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((call) => call.method === method)+ : [];+ try {+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ mkdirSync(runtime, { recursive: true });+ const fakeAcp = fileURLToPath(new URL("./testing/fake-acp-cli.ts", import.meta.url));+ for (const name of ["agy.ts", process.platform === "win32" ? "localharness_external.exe" : "localharness_external"]) {+ copyFileSync(fakeAcp, join(runtime, name));+ chmodSync(join(runtime, name), 0o755);+ }+ const token = antigravityTokenPath(antigravity.instanceId, dataDir);+ mkdirSync(dirname(token), { recursive: true });+ writeFileSync(token, "{}", { mode: 0o600 });+ const configPath = join(dataDir, "config.json");+ const config = JSON.parse(readFileSync(configPath, "utf8"));+ config.instances.antigravity = {+ driver: "antigravityAgent",+ config: { cli: join(runtime, "agy.ts") },+ environment: {+ FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: antigravity.model,+ FAKE_ACP_RPC_FAILURE_METHOD: "authenticate", FAKE_ACP_RPC_FAILURE_FILE: failureFile, FAKE_ACP_RPC_APPEND_FILE: rpcFile,+ },+ };+ config.instances.codex = { driver: "codex", config: { cli: fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url)) } };+ writeFileSync(configPath, JSON.stringify(config));+ const log = openSync(logPath, "a", 0o600);+ server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), stdio: ["ignore", log, log],+ });+ closeSync(log);+ await expect.poll(async () => {+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }+ }, { timeout: 20_000 }).toBe(true);+ const instance = async (id: string) => ((await api("GET", "/api/instances?fresh=1")).instances as any[]).find((entry) => entry.instanceId === id);+ await expect.poll(async () => (await instance("codex"))?.models.options.some((option: any) => option.id === codex.model), { timeout: 20_000 }).toBe(true);+ expect((await instance("antigravity"))?.snapshot.authenticated).toBe(true);++ const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };+ const starter = bots.find((bot) => bot.chiefOfStaff);+ if (starter) await api("PATCH", `/api/bots/${starter.id}`, { chiefOfStaff: false });+ const { bot } = await control("new-bot", "--name", "Kai");+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: antigravity, fallback: [codex] });+ const threadId = bot.activeTaskId;+ await api("PATCH", `/api/bots/${bot.id}/tasks/${threadId}`, { modelSelection: antigravity });+ const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];+ const lines = (all: any[]) => all.flatMap((message) => message.tool?.name ? [message.tool.name as string] : []);++ writeFileSync(failureFile, JSON.stringify({ code: -32603, message: "Failed to refresh token: network is unreachable" }));+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");+ await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "60");+ const first = await messages();+ evidence.push({ first });+ expect(lines(first).filter((line) => /signed out|needs a Google account/i.test(line)), "nothing says it signed out").toEqual([]);+ expect(lines(first).some((line) => line.includes("network is unreachable")), "the reason is shown").toBe(true);+ expect((await instance("antigravity"))?.snapshot.authenticated, "still signed in").toBe(true);+ const notices = ((await api("GET", "/api/notifications")).notifications as any[]).filter((entry) => entry.kind === "notice");+ expect(notices.map((entry) => entry.body).filter((body) => /signed out/i.test(body))).toEqual([]);++ rmSync(failureFile);+ const refused = calls("authenticate").map((call) => call.pid);+ expect(refused, "the runtime was asked to authenticate").not.toEqual([]);+ expect(calls("session/prompt"), "the refused process never got the prompt").toEqual([]);+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+ await expect.poll(() => refused.some(alive), { timeout: 15_000, message: "the refused process was stopped" }).toBe(false);+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Try again");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "60")).status).toBe("settled");+ const prompted = calls("session/prompt").map((call) => call.pid);+ expect(prompted, "the next turn ran on Antigravity").toHaveLength(1);+ expect(refused, "on a new process").not.toContain(prompted[0]);+ evidence.push({ second: await messages() });+ } finally {+ const evidencePath = `${logPath}.antigravity-auth-blip.json`;+ try {+ writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));+ } finally {+ await waitForExit(server, { signal: "SIGTERM" });+ await fixture.close();+ console.info(JSON.stringify({ logPath, evidencePath, fixtureRemoved: !existsSync(dataDir) }));+ }+ }+}, 240_000);diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex f163f26b07..329d635f98 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -1147,7 +1147,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>await session.host.once("authenticate", () => request("authenticate", { methodId }, INIT_TIMEOUT));session.authenticated = true;} catch (error) {- if (signIn.asked(error) || support.authFailure !== "continue") throw signIn.asked(error) ?? new Error(support.loginNote);+ const failed = signIn.authenticateFailed(error, support.authFailure); if (failed) throw failed;}} else if (support.authFailure === "fail") {throw new Error(support.loginNote);diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.tsindex 83eea38aec..05c51733df 100644--- a/server/drivers/acp/driver-hooks.ts+++ b/server/drivers/acp/driver-hooks.ts@@ -11,7 +11,8 @@ export interface AcpDriverHooks {* the agent reads itself, for an agent whose own file tool returns media as raw bytes (Antigravity). */mediaLinks?: boolean;/** An agent that asks for a sign-in no turn can give. Its turns fail at once with `loginNote`, its process is closed- * and `required` is told, instead of the turn waiting on a sign-in nobody sees. */+ * and `required` is told, instead of the turn waiting on a sign-in nobody sees. Only these say the account is signed+ * out: any other `authenticate` failure fails the turn as an ordinary startup error. */signInRequest?: {/** Whether a whole stderr line announces the request. */stderrLine(line: string): boolean;@@ -107,4 +108,12 @@ export class SignInRequests {this.#support.signInRequest.required(this.#instanceId);return this.#error();}++ authenticateFailed(error: unknown, authFailure: "fail" | "fail-request" | "continue"): Error | null {+ const asked = this.asked(error);+ if (asked) return asked;+ if (authFailure === "continue") return null;+ if (!this.#support.signInRequest) return new Error(this.#support.loginNote);+ return error instanceof Error ? error : new Error(String(error));+ }}diff --git a/server/drivers/acp/rpc-error.ts b/server/drivers/acp/rpc-error.tsindex c834af854c..8f37a92790 100644--- a/server/drivers/acp/rpc-error.ts+++ b/server/drivers/acp/rpc-error.ts@@ -1,7 +1,12 @@import { redactSecretsInText } from "../../redact.ts";/** The vendor's own message and the method we called, before redaction or any attached detail. */-const resumeRefusal = new WeakMap<object, { message: string; method: string }>();+const vendorFailures = new WeakMap<object, { message: string; method: string }>();++/** The vendor's own message, without the method and detail acpRpcError adds to what is shown. */+export function acpVendorMessage(error: unknown): string | undefined {+ return error && typeof error === "object" ? vendorFailures.get(error)?.message : undefined;+}/** Words around the id are case-insensitive. The captured id keeps the vendor's case. */const MISSING_SESSION_MESSAGE = /^\s*(?:invalid params:\s*)?session\s+"([^"]+)"\s+not found\b(?:\s*\(session\/(?:load|resume)\))?[\s.]*$/i;@@ -24,7 +29,7 @@ export function acpRpcError(value: any, method: string): Error {const diagnostic = `${detail && detail !== message ? `${message}: ${detail}` : message} (${context})`;const shown = redactSecretsInText(diagnostic);const error = new Error(shown.slice(0, 1500));- resumeRefusal.set(error, { message, method });+ vendorFailures.set(error, { message, method });return Object.assign(error, { code: value?.code, data, acpDiagnostic: shown,// -32603 is JSON-RPC's internal error; invalid params, unsupported methods and auth refusals keep the session.acpSessionFailure: value?.code === -32603,@@ -39,7 +44,7 @@ export function acpMissingSession(error: unknown, cursor: string): boolean {const fields = data as Record<string, unknown>;if (fields.sessionId === cursor && Object.keys(fields).length === 1) return true;}- const refusal = record ? resumeRefusal.get(record) : undefined;+ const refusal = record ? vendorFailures.get(record) : undefined;if (!refusal || (refusal.method !== "session/load" && refusal.method !== "session/resume")) return false;const named = refusal.message.match(MISSING_SESSION_MESSAGE);return named?.[1] === cursor;diff --git a/server/drivers/antigravity-sign-in.test.ts b/server/drivers/antigravity-sign-in.test.tsindex 713ac25e2d..628e356644 100644--- a/server/drivers/antigravity-sign-in.test.ts+++ b/server/drivers/antigravity-sign-in.test.ts@@ -22,6 +22,7 @@ import {probeAntigravityModels,verifyAntigravityBrowserHelper,} from "./antigravity-acp.ts";+import { acpRpcError } from "./acp/rpc-error.ts";import { AntigravityAuthController } from "./antigravity-auth.ts";import { resolveAntigravityRuntime } from "./antigravity-runtime.ts";import { AntigravityDriver, antigravitySignInError } from "./antigravity.ts";@@ -133,6 +134,28 @@ describe("a sign-in the runtime asks for in the middle of a turn", () => {expect((await instance.snapshot()).authenticated).toBe(false);}, 60_000);+ it.each([-32603, -32000])("keeps the account signed in when authenticate fails (%i) without asking for a sign-in", async (code) => {+ ensureDirs();+ const fake = fakeRuntime(runtimeSource(+ `reply(message.id, { error: { code: ${code}, message: "Failed to refresh token: network is unreachable" } });`,+ ));+ const instanceId = `antigravity-network-blip${code}`;+ storeToken(instanceId);+ const instance = await create(instanceId, fake.executable);+ const recorder = recordEvents(instance.adapter);+ const { turnId } = await instance.adapter.sendTurn({ threadId: "blip", text: "hello", cwd: fake.directory });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const events = recorder.events.filter((event) => event.turnId === turnId);+ expect(events).not.toContainEqual(expect.objectContaining({ message: LOGIN_NOTE }));+ expect(events).toContainEqual(expect.objectContaining({+ type: "runtime.error",+ message: expect.stringContaining("network is unreachable"),+ }));+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });+ expect(events.at(-1)).not.toMatchObject({ stopReason: "auth_required" });+ expect((await instance.snapshot()).authenticated).toBe(true);+ }, 60_000);+it("reads signed in again after a sign-in that succeeds without rewriting the stored token", async () => {ensureDirs();const fake = fakeRuntime();@@ -165,6 +188,30 @@ describe("a sign-in the runtime asks for in the middle of a turn", () => {expect(antigravitySignInError(error)).toBe(expected);});+ it.each([+ [{ code: -32000, message: "Request failed" }, false],+ [{ code: -32000, message: "Authentication service unavailable" }, false],+ [{ code: -32000, message: "Request failed", data: { trace: "x".repeat(2_500), details: "Please sign in again" } }, true],+ [{ code: -32000, message: "Authentication required" }, true],+ [{ code: -32000, message: "Authentication required", data: { network: "online" } }, true],+ [{ code: -32000, message: "Authentication failed: connection refused" }, false],+ [{ code: -32000, message: "Login check failed: socket hang up" }, false],+ [{ code: -32000, message: "Authentication failed: network is unreachable" }, false],+ [{ code: -32000, message: "Please sign in again", data: { details: "Previous refresh timed out" } }, true],+ [{ code: -32000, message: "Login expired" }, true],+ [{ code: -32000, message: "invalid_grant: Token has been expired or revoked." }, true],+ [{ code: -32000, message: "Failed to reauthenticate: connection refused" }, false],+ [{ code: -32000, message: "Please reauthenticate" }, true],+ [{ code: -32000, message: "Reauthentication required" }, true],+ [{ code: -32000, message: "Re-authentication required" }, true],+ [{ code: -32000, message: "Access token expired", data: { details: "refresh failed: network is unreachable" } }, false],+ [{ code: -32000, message: "Request failed", data: { details: "Authentication failed: connection refused" } }, false],+ [{ code: -32000, message: "Request failed", data: { reason: "Authentication failed: connection refused" } }, false],+ [{ code: -32000, message: "Request failed", data: { reason: "UNAUTHENTICATED" } }, true],+ ])("reads the runtime's own words, not the method OpenMausBot called (%j)", (answer, expected) => {+ expect(antigravitySignInError(acpRpcError(answer, "authenticate"))).toBe(expected);+ });+it("stops a model lookup the same way instead of waiting on a link nobody sees", async () => {const fake = fakeRuntime(runtimeSource(ASKS_FOR_SIGN_IN));const runtime = await resolveAntigravityRuntime(fake.executable);diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.tsindex 327967f0ea..f613a60e2b 100644--- a/server/drivers/antigravity.ts+++ b/server/drivers/antigravity.ts@@ -13,6 +13,8 @@ import type {SendTurnInput,} from "../contracts.ts";import { createAcpDriver, type AcpConfig, type AcpSupport } from "./acp/core.ts";+import { acpVendorMessage } from "./acp/rpc-error.ts";+import { classifyError } from "./retry.ts";import {antigravityClientInfo,antigravityProfileAuthenticated,@@ -85,13 +87,20 @@ export function antigravityUpdateFilter(): (update: Record<string, any>) => Reco}const SIGN_IN_WORDS = /\bauthenticat|\bunauthenticated\b|\bsign(?:ed)?[ -]?in\b|\blog(?:ged)?[ -]?in\b|\bcredentials?\b/iu;+const SIGN_IN_ASKED = /\bauthentication required\b|\bunauthenticated\b|\bnot (?:logged|signed)[ -]?in\b|\b(?:sign|log)[ -]?in again\b|\bplease (?:sign|log)[ -]?in\b|\blogin expired\b|\bplease re-?authenticate\b|\bre-?authentication required\b|\binvalid_grant\b|\b(?:credentials?|token) (?:has been |have been |was |were )?revoked\b/iu;+const UNREACHABLE = /\bnetwork\b|\bunreachable\b|\boffline\b/iu;-/** -32000 is ACP's `auth_required`, but an agent may reuse it for other failures; the text must agree. */+/** -32000 is ACP's `auth_required`, but an agent may reuse it for other failures, a sign-in service it cannot reach+ * among them. Words that ask for a sign-in decide; words that only mention one do unless the failure is one that passes. */export function antigravitySignInError(error: unknown): boolean {- const value = error as { code?: unknown; message?: unknown; data?: unknown } | null;+ const value = error as { code?: unknown; message?: unknown; data?: any } | null;if (value?.code !== -32000) return false;- const data = typeof value.data === "string" ? value.data : value.data && typeof value.data === "object" ? JSON.stringify(value.data) : "";- return SIGN_IN_WORDS.test(`${typeof value.message === "string" ? value.message : ""} ${data.slice(0, 2_000)}`);+ const data = value.data;+ const bounded = (fields: unknown[]) => fields.filter((field): field is string => typeof field === "string").map((field) => field.slice(0, 2_000)).join(" ");+ const reason = bounded([acpVendorMessage(error) ?? value.message, ...(typeof data === "string" ? [data] : [data?.details, data?.message, data?.reason, data?.error?.message])]);+ const whole = `${reason} ${bounded([data && typeof data === "object" ? JSON.stringify(data) : undefined])}`;+ if (SIGN_IN_ASKED.test(whole)) return true;+ return SIGN_IN_WORDS.test(whole) && !UNREACHABLE.test(reason) && !classifyError({ text: reason }).transient;}const managedAsset = resolveAntigravityReleaseAsset();diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 8f82018803..eb77503087 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -47,7 +47,7 @@// FAKE_ACP_RPC_DUMP this process's method list, rewritten after every request// FAKE_ACP_RPC_APPEND_FILE one {"pid","method","cwd"} line appended per request// FAKE_ACP_RPC_FAILURE_FILE JSON-RPC error for session/prompt; once read the process stays poisoned-// FAKE_ACP_RPC_FAILURE_METHOD initialize, session/new or session/prompt (default)+// FAKE_ACP_RPC_FAILURE_METHOD initialize, authenticate, session/new or session/prompt (default)// FAKE_ACP_RPC_FAILURE_GATE hold the error until this file exists// FAKE_ACP_RPC_FAILURE_AFTER_OUTPUT emit text and a tool result before failing// FAKE_ACP_RPC_FAILURE_AFTER_USAGE emit the scripted usage updates and FAKE_ACP_UPDATES_FILE's before failing@@ -1041,6 +1041,7 @@ function handle(msg: any) {break;}case "authenticate":+ if (failRpc(msg)) break;if (mode === "authenticate-failed") {out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "Login expired" } });break;