Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(antigravity): route OAuth refresh and usage quota through instance proxy and upgrade UA to 2.33.0
frank8ai4811bc1297c5
diff --git a/server/drivers/antigravity-account.test.ts b/server/drivers/antigravity-account.test.tsindex 4519b1c433..921586e99b 100644--- a/server/drivers/antigravity-account.test.ts+++ b/server/drivers/antigravity-account.test.ts@@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { antigravityAccount } from "./antigravity-account.ts";+import { antigravityAccount, createProxiedFetch } from "./antigravity-account.ts";let home: string;let path: string;@@ -63,3 +63,9 @@ it.each(["offline", "denied", "bad-token", "bad-email"])("keeps lookup failure nexpect(await antigravityAccount(path)).toBeUndefined();expect(fetcher).toHaveBeenCalledTimes(calls);});++it("supports proxyUrl and creates proxied fetch correctly", async () => {+ const customFetch = createProxiedFetch("http://127.0.0.1:30082");+ expect(typeof customFetch).toBe("function");+ expect(createProxiedFetch()).toBe(fetch);+});diff --git a/server/drivers/antigravity-account.ts b/server/drivers/antigravity-account.tsindex 96fe23f519..cf38d90538 100644--- a/server/drivers/antigravity-account.ts+++ b/server/drivers/antigravity-account.ts@@ -1,37 +1,51 @@import { createHash } from "node:crypto";import { readFile, stat } from "node:fs/promises";+import { ProxyAgent, fetch as undiciFetch } from "undici";type Identity = { email: string; method: "login" } | undefined;const identities = new Map<string, { fingerprint: string; expires: number; result: Promise<Identity> }>();+export type AccessFetch = (url: string, init: { method?: "POST"; headers?: Record<string, string>; body?: string | URLSearchParams; redirect: "error" | "manual"; signal: AbortSignal }) => Promise<Pick<Response, "ok" | "json">>;++/** Returns a fetch function that routes traffic through an HTTP/HTTPS proxy via undici ProxyAgent.+ * If proxyUrl is empty, falls back to globalThis.fetch. */+export function createProxiedFetch(proxyUrl?: string): AccessFetch {+ if (!proxyUrl) return fetch as unknown as AccessFetch;+ const agent = new ProxyAgent(proxyUrl);+ return (async (url: string, init: any) => {+ return undiciFetch(url, { ...init, dispatcher: agent });+ }) as unknown as AccessFetch;+}+/** The official ACP file stores refresh credentials, not the account email.- * Resolve display identity through Google only; never expose or rewrite tokens. */-export async function antigravityAccount(tokenPath: string): Promise<Identity> {+ * Resolve display identity through Google only; never expose or rewrite tokens.+ * When proxyUrl is provided, network calls strictly route through the instance's designated proxy. */+export async function antigravityAccount(tokenPath: string, proxyUrl?: string): Promise<Identity> {try {const info = await stat(tokenPath);if (!info.isFile() || info.size > 1024 * 1024) return undefined;const raw = await readFile(tokenPath, "utf8");const fingerprint = createHash("sha256").update(raw).digest("hex");- const cached = identities.get(tokenPath);+ const cacheKey = proxyUrl ? tokenPath + "#" + proxyUrl : tokenPath;+ const cached = identities.get(cacheKey);if (cached?.fingerprint === fingerprint && cached.expires > Date.now()) return cached.result;const credentials = JSON.parse(raw);if (!credentials || !["client_id", "client_secret", "refresh_token"].every((key) => typeof credentials[key] === "string" && credentials[key].length > 0)) return undefined;const entry = { fingerprint, expires: Date.now() + 60_000, result: Promise.resolve<Identity>(undefined) };- entry.result = lookup(credentials).then((account) => {+ entry.result = lookup(credentials, proxyUrl).then((account) => {if (account) entry.expires = Date.now() + 60 * 60_000;return account;});if (identities.size >= 128) identities.delete(identities.keys().next().value!);- identities.set(tokenPath, entry);+ identities.set(cacheKey, entry);return entry.result;} catch {- identities.delete(tokenPath);+ identities.delete(proxyUrl ? tokenPath + "#" + proxyUrl : tokenPath);return undefined;}}export interface AntigravityStoredSignIn { client_id: string; client_secret: string; refresh_token: string }-type AccessFetch = (url: string, init: { method?: "POST"; headers?: Record<string, string>; body?: string | URLSearchParams; redirect: "error" | "manual"; signal: AbortSignal }) => Promise<Pick<Response, "ok" | "json">>;/** A short-lived access token for the stored sign-in, from Google only. The token stays in memory: it is never logged,* written or returned to a client. Undefined when Google refuses or cannot be reached. */@@ -52,17 +66,18 @@ export async function refreshAntigravityAccess(return { accessToken: token.access_token, expiresInSeconds: typeof token.expires_in === "number" && token.expires_in > 0 ? token.expires_in : null };}-async function lookup(credentials: AntigravityStoredSignIn): Promise<Identity> {+async function lookup(credentials: AntigravityStoredSignIn, proxyUrl?: string): Promise<Identity> {try {const signal = AbortSignal.timeout(3_000);- const access = await refreshAntigravityAccess(credentials, signal);+ const fetcher = proxyUrl ? createProxiedFetch(proxyUrl) : fetch;+ const access = await refreshAntigravityAccess(credentials, signal, fetcher as AccessFetch);if (!access) return undefined;- const identity = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {- headers: { Authorization: `Bearer ${access.accessToken}` }, redirect: "error", signal,+ const identity = await fetcher("https://www.googleapis.com/oauth2/v3/userinfo", {+ headers: { Authorization: "Bearer " + access.accessToken }, redirect: "error", signal,});if (!identity.ok) return undefined;const user = await identity.json() as { email?: unknown };- if (typeof user.email !== "string" || user.email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(user.email)) return undefined;+ if (typeof user.email !== "string" || user.email.length > 254 || !/^[^s@]+@[^s@]+.[^s@]+$/.test(user.email)) return undefined;return { email: user.email, method: "login" };} catch {// Identity lookup failure must not mark a working engine as signed out.diff --git a/server/drivers/antigravity-usage-limits.test.ts b/server/drivers/antigravity-usage-limits.test.tsindex 68b0ccf658..9ea55011f2 100644--- a/server/drivers/antigravity-usage-limits.test.ts+++ b/server/drivers/antigravity-usage-limits.test.ts@@ -78,7 +78,7 @@ function fixture(options: FixtureOptions = {}) {}expect(init.headers.Authorization).toBe("Bearer access-token");expect(JSON.parse(init.body!)).toEqual({ project: "project-id" });- expect(init.headers["User-Agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);+ expect(init.headers["User-Agent"]).toMatch(/^antigravity\/hub\/2\.33\.0 /);const host = new URL(url).host;return url.endsWith(":retrieveUserQuotaSummary")? respond(options.summaryByHost?.[host] ?? options.summary ?? summary, options.summaryStatusByHost?.[host] ?? options.summaryStatus ?? 200)diff --git a/server/drivers/antigravity-usage-limits.ts b/server/drivers/antigravity-usage-limits.tsindex a75d97a2cb..7ddc9dcf31 100644--- a/server/drivers/antigravity-usage-limits.ts+++ b/server/drivers/antigravity-usage-limits.ts@@ -20,7 +20,7 @@ import { refreshAntigravityAccess } from "./antigravity-account.ts";export const ANTIGRAVITY_USAGE_LIMITS = true;export function antigravityUserAgent(platform: NodeJS.Platform, architecture: string): string {- return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;+ return `antigravity/hub/2.33.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;}const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";@@ -247,6 +247,7 @@ export interface AntigravityUsageDeps {fetch: PlanFetch;now?: () => number;timeoutMs?: number;+ proxyUrl?: string;}/** `work`, or a rejection once `signal` aborts: a request that ignores its signal does not hold the others' answers. */diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.tsindex 931bbd7bf1..ed4bada5a9 100644--- a/server/drivers/antigravity.ts+++ b/server/drivers/antigravity.ts@@ -192,7 +192,7 @@ const support: AcpSupport = {state: "available",version: runtime.version,authenticated: await antigravityProfileAuthenticated(profile),- account: await antigravityAccount(profile.tokenPath),+ account: await antigravityAccount(profile.tokenPath, profile.environment?.HTTPS_PROXY || profile.environment?.HTTP_PROXY || env?.HTTPS_PROXY || env?.HTTP_PROXY),};} catch (error) {return { state: "unavailable", reason: error instanceof Error ? error.message : String(error) };diff --git a/server/plan-usage.ts b/server/plan-usage.tsindex 4906f972f6..aa20b896b5 100644--- a/server/plan-usage.ts+++ b/server/plan-usage.ts@@ -8,6 +8,7 @@ import type { InstanceConfigMap } from "./contracts.ts";import { resolveClaudeConfigDir } from "./drivers/claude.ts";import { codexHome } from "./drivers/codex-identity.ts";import { antigravityPlanUsage } from "./drivers/antigravity-usage-limits.ts";+import { createProxiedFetch } from "./drivers/antigravity-account.ts";import { harnessHome, sealedFixture } from "./env-path.ts";export type PlanDriver = "claude" | "codex" | "grok" | "opencode" | "antigravity";@@ -919,7 +920,14 @@ function okRow(account: PlanAccount, windows: PlanWindows): PlanProviderRow {async function fetchProvider(account: PlanAccount, deps: PlanUsageDeps): Promise<PlanProviderRow | null> { // null: OpenCode, in every fleet, with no key of its ownlet credential: PlanCredential;- if (account.driver === "antigravity") { const windows = await antigravityPlanUsage(account.id, deps); return windows && okRow(account, windows); } // null: no sign-in, or Google gave nothing+ if (account.driver === "antigravity") {+ const proxyUrl = account.environment?.HTTPS_PROXY || account.environment?.HTTP_PROXY;+ const effectiveDeps = proxyUrl && deps.fetch === fetch+ ? { ...deps, fetch: createProxiedFetch(proxyUrl) as any, proxyUrl }+ : { ...deps, proxyUrl };+ const windows = await antigravityPlanUsage(account.id, effectiveDeps);+ return windows && okRow(account, windows);+ } // null: no sign-in, or Google gave nothingtry {credential = await deps.credentials.read(account);} catch {