Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(antigravity): a quota or upstream failure fails the turn with the usage-limit notice (#6087)
Milind Soni2a7a81d59737
diff --git a/NOTICE b/NOTICEindex 24682ae610..478e7cb685 100644--- a/NOTICE+++ b/NOTICE@@ -6,8 +6,8 @@ Version 2.0, with the consent of all contributors whose copyright wasincorporated before the transition.The Google Antigravity ACP integration adapts release, installation, profile,-authentication, sign-out, session setup, and runtime temporary-folder behavior-from T3 Code, Copyright 2026 T3 Tools Inc., used under the MIT License+authentication, sign-out, session setup, turn-outcome, and runtime+temporary-folder behavior from T3 Code, Copyright 2026 T3 Tools Inc., used under the MIT License(third_party/t3-code/LICENSE).Selected-text citation matching adapts T3 Code's assistant citation selection,diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex c3d80259ab..379326729d 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -1390,7 +1390,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>}if (variant !== undefined && requestedVariantOption().currentValue !== variant) {throw new Error(`${support.displayName} changed variant before the prompt`);- }+ } const promptOutcome = await support.promptOutcome?.(instanceId, sessionId);if (state.settled || state.stopped || session.closing) throw new Error("turn stopped");state.promptSent = true;if (!support.promptUnreachedModel) acknowledge();@@ -1452,7 +1452,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>: {}),});}- const reason = result?.stopReason;+ const reason = result?.stopReason, reported = await promptOutcome?.(result); if (reported) throw reported;if (reason === "end_turn") settle(threadId, session, true, null);else if (reason === "cancelled" || state.stopped) settle(threadId, session, true, "cancelled");else {diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.tsindex ee2ccec607..6618ebc360 100644--- a/server/drivers/acp/driver-hooks.ts+++ b/server/drivers/acp/driver-hooks.ts@@ -18,6 +18,9 @@ export interface AcpDriverHooks {processStarted?(child: ChildProcess, instanceId: string): void;/** Extra session/new, session/load and session/resume parameters, from the agent's initialize answer. */sessionSetupParams?(initializeResult: unknown): Record<string, unknown>;+ /** Called before each session/prompt. The check it returns gets that prompt's result and names the failure the agent+ * reported as an ordinary reply, which then fails the turn. Neither may throw. */+ promptOutcome?(instanceId: string, sessionId: string): Promise<(result: unknown) => Promise<Error | undefined>>;}const MAX_LINE_CHARS = 64 * 1024;diff --git a/server/drivers/acp/failure-words.ts b/server/drivers/acp/failure-words.tsindex 715f071a66..58b34f53d7 100644--- a/server/drivers/acp/failure-words.ts+++ b/server/drivers/acp/failure-words.ts@@ -22,8 +22,21 @@ function mcpStartFailure(message: string, provider: string) {return server === "composio" ? noticeFailure("chat.notice.acpMcpAppsFailed", { provider }) : noticeFailure("chat.notice.acpMcpServerFailed", { server, provider });}+/** A failure the agent reported as an ordinary reply, already in the words the person reads. */+export class AcpReportedFailure extends Error {+ readonly facts: { message: string; text?: ServerText; limitResetsAt?: number };+ readonly acpUsageLimit: boolean;++ constructor(facts: { message: string; text?: ServerText; limitResetsAt?: number }, usageLimit: boolean) {+ super(facts.message);+ this.facts = facts;+ this.acpUsageLimit = usageLimit;+ }+}+export function acpRuntimeFailure(error: unknown, provider: string, account?: { message?: string; text?: ServerText }) {if (account?.message !== undefined) return { message: account.message, text: account.text };+ if (error instanceof AcpReportedFailure) return error.facts;const message = error instanceof Error ? error.message : String(error);// Account wording, when given, wins over the MCP rewrite.const mcp = account?.text ? null : mcpStartFailure(message, provider);diff --git a/server/drivers/antigravity-turn-outcome.test.ts b/server/drivers/antigravity-turn-outcome.test.tsnew file mode 100644index 0000000000..f76147ee05--- /dev/null+++ b/server/drivers/antigravity-turn-outcome.test.ts@@ -0,0 +1,251 @@+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:+// - apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts (the error+// payload fixtures and the cases of the two reader tests).+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";++import { ensureDirs } from "../config.ts";+import type { ProviderInstance } from "../contracts.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { recordEvents } from "../testing/events.ts";+import { antigravityTokenPath } from "./antigravity-acp.ts";+import { antigravityLimitFacts, antigravityQuotaFamily, watchAntigravityPromptOutcome } from "./antigravity-turn-outcome.ts";+import { AntigravityDriver } from "./antigravity.ts";++const USER_INPUT = 14;+const PLANNER_RESPONSE = 15;+const TOOL = 8;+const ERROR_MESSAGE = 17;+const NAME = "Google Gemini (Antigravity)";+const USAGE_LIMIT = `This ${NAME} account has reached its usage limit. Wait for it to reset, or switch this bot to another AI.`;++// Error-step payloads trimmed from Antigravity 1.4.5 against a local Gemini endpoint.+const errorText = (error: string) =>+ `\n$Agent execution terminated due to error.\u0012agent executor error: ${error}: ${error}\n(1) attached stack trace\n -- stack trace:`;+// An unparsable reset timestamp must not hide the reset delay, nor a retry delay outrank it.+const QUOTA_ERROR = errorText(+ "Error 429, Message: Quota exhausted for test model., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.RetryInfo retryDelay:42s] map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:soon] reason:QUOTA_EXHAUSTED]]",+);+const RATE_LIMIT_ERROR = errorText(+ "Error 429, Message: Resource has been exhausted (e.g. check quota)., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:cloudcode-pa.googleapis.com reason:RATE_LIMIT_EXCEEDED] map[@type:type.googleapis.com/google.rpc.RetryInfo retryDelay:42s]]",+);+const INVALID_ARGUMENT_ERROR = errorText("Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []");+const UNAVAILABLE_ERROR = errorText("Error 503, Message: The service is currently unavailable., Status: UNAVAILABLE, Details: []");+const TIMESTAMP_ERROR = errorText(+ "Error 429, Message: Quota exhausted., Status: RESOURCE_EXHAUSTED, Details: [map[metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-20T10:00:00Z] reason:QUOTA_EXHAUSTED]]",+);+// The model's reply quoting the agent's quota notice is an ordinary planner response.+const QUOTED_NOTICE = "Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.";++const scratch: string[] = [];+const instances: ProviderInstance[] = [];++function profile(): { directory: string; conversations: string } {+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-outcome-"));+ scratch.push(directory);+ const conversations = join(directory, "antigravity-acp", "conversations");+ mkdirSync(conversations, { recursive: true });+ return { directory, conversations };+}++function append(file: string, steps: ReadonlyArray<readonly [number, string]>): void {+ const database = new DatabaseSync(file);+ try {+ database.exec("CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)");+ const insert = database.prepare("INSERT INTO steps (step_type, step_payload) VALUES (?, ?)");+ for (const [type, payload] of steps) insert.run(type, Buffer.from(payload));+ } finally {+ database.close();+ }+}++afterEach(async () => {+ for (const instance of instances.splice(0)) await instance.dispose();+ while (scratch.length) await removeTempDir(scratch.pop()!);+});++describe("watchAntigravityPromptOutcome", () => {+ it("fails only turns whose own steps end in an upstream error", async () => {+ const { directory, conversations } = profile();+ const sessionId = "e6aba774-5472-4277-b6ee-27b2e05570a7";+ const turn = async (steps: ReadonlyArray<readonly [number, string]>, result: object = { stopReason: "end_turn" }) => {+ const check = await watchAntigravityPromptOutcome(NAME, directory, sessionId, () => 0);+ if (steps.length) append(join(conversations, `${sessionId}.db`), steps);+ return check(result);+ };+ const input = "Run the fixture.";+ const reply = "FIXTURE_OK";++ // The first prompt creates the session log.+ expect(await turn([[USER_INPUT, input], [PLANNER_RESPONSE, reply]])).toBeUndefined();+ const quota = await turn([[USER_INPUT, input], [ERROR_MESSAGE, QUOTA_ERROR]]);+ expect(quota).toMatchObject({ acpUsageLimit: true, facts: { limitResetsAt: 3_600_000, text: { key: "chat.notice.usageLimitResets" } } });+ expect(quota!.message).toMatch(new RegExp(`^This ${NAME.replace(/[()]/g, "\\$&")} account has reached its usage limit, which resets .+\\. Until then, switch this bot to another AI\\.$`));+ // A turn that adds no step is not failed by the error step the turn before it left.+ expect(await turn([])).toBeUndefined();+ // The earlier error step is outside this turn.+ expect(await turn([[USER_INPUT, input], [PLANNER_RESPONSE, QUOTED_NOTICE]], { stopReason: "end_turn", usage: { inputTokens: 42, outputTokens: 3, totalTokens: 54 } }))+ .toBeUndefined();+ expect(await turn([[USER_INPUT, input], [ERROR_MESSAGE, RATE_LIMIT_ERROR]])).toMatchObject({ acpUsageLimit: true, facts: { limitResetsAt: 42_000 } });+ const stamped = async (stamp: string, at: number) => {+ const check = await watchAntigravityPromptOutcome(NAME, directory, sessionId, () => at);+ append(join(conversations, `${sessionId}.db`), [[USER_INPUT, input], [ERROR_MESSAGE, TIMESTAMP_ERROR.replace("2026-11-20T10:00:00Z", stamp)]]);+ return (await check({ stopReason: "end_turn" }))!.facts.limitResetsAt;+ };+ const day = 24 * 3_600_000, noon = Date.parse("2026-11-18T12:00:00Z");+ expect(await stamped("2026-11-20T10:00:00Z", noon)).toBe(Date.parse("2026-11-20T10:00:00Z"));+ expect(await stamped("2026-11-26T12:00:00Z", noon)).toBe(noon + 8 * day);+ // A reset that is past, too far off, or no time at all falls back to the delay beside it (an hour).+ for (const stamp of ["2001-01-01T00:00:00Z", "2026-11-18T12:00:00Z", "2026-11-26T12:00:01Z", "+275760-09-13T00:00:00Z", "5", "soon"]) {+ expect(await stamped(stamp, noon)).toBe(noon + 3_600_000);+ }+ const delayed = async (delay: string) => {+ const check = await watchAntigravityPromptOutcome(NAME, directory, sessionId, () => noon);+ append(join(conversations, `${sessionId}.db`), [[USER_INPUT, input], [ERROR_MESSAGE, QUOTA_ERROR.replace("quotaResetDelay:3600s", `quotaResetDelay:${delay}`)]]);+ return (await check({ stopReason: "end_turn" }))!.facts.limitResetsAt;+ };+ expect(await delayed("192h")).toBe(noon + 8 * day);+ for (const delay of ["99999999h", "193h", "0s"]) expect(await delayed(delay)).toBeUndefined();+ const invalid = await turn([[USER_INPUT, input], [ERROR_MESSAGE, INVALID_ARGUMENT_ERROR]]);+ expect(invalid).toMatchObject({ acpUsageLimit: false, message: `${NAME} stopped with an error (HTTP 400; ${NAME} says: "Request contains an invalid argument").` });+ expect(invalid!.facts.limitResetsAt).toBeUndefined();+ expect((await turn([[USER_INPUT, input], [ERROR_MESSAGE, UNAVAILABLE_ERROR]]))!.message)+ .toBe(`${NAME} had a temporary server problem (HTTP 503; ${NAME} says: "The service is currently unavailable"). Try again in a few minutes.`);+ expect(await turn([[USER_INPUT, input], [ERROR_MESSAGE, "no api error here"]])).toMatchObject({ acpUsageLimit: false, message: `${NAME} stopped with an error.` });+ // A completed tool keeps its usage, and the turn still fails.+ expect(await turn([[USER_INPUT, input], [PLANNER_RESPONSE, reply], [TOOL, reply], [ERROR_MESSAGE, QUOTA_ERROR]], { stopReason: "end_turn", usage: { inputTokens: 40, outputTokens: 5 } }))+ .toMatchObject({ acpUsageLimit: true });+ expect(await turn([[USER_INPUT, input], [PLANNER_RESPONSE, reply]])).toBeUndefined();+ // The agent maps the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.+ const refusal = await turn([], { stopReason: "refusal" });+ expect(refusal).toMatchObject({ acpUsageLimit: true, message: USAGE_LIMIT });+ expect(refusal!.facts.limitResetsAt).toBeUndefined();+ });++ it.skipIf(process.platform === "win32")("reads only this session's own unlinked log, and keeps a typed refusal", async () => {+ const { directory, conversations } = profile();+ const own = "e6aba774-5472-4277-b6ee-27b2e05570a7";+ const peer = "0d9c2b4e-1111-4222-8333-944455556666";++ // own.db links to a peer session; the peer's new error step is not this turn's.+ append(join(conversations, `${peer}.db`), [[USER_INPUT, "peer"]]);+ symlinkSync(join(conversations, `${peer}.db`), join(conversations, `${own}.db`));+ const linked = await watchAntigravityPromptOutcome(NAME, directory, own);+ append(join(conversations, `${peer}.db`), [[ERROR_MESSAGE, QUOTA_ERROR]]);+ expect(await linked({ stopReason: "end_turn" })).toBeUndefined();+ expect(await linked({ stopReason: "refusal" })).toMatchObject({ acpUsageLimit: true });++ // An unreadable log gives no evidence, but the agent's typed refusal still fails the turn.+ rmSync(join(conversations, `${own}.db`));+ writeFileSync(join(conversations, `${own}.db`), "not a database");+ const corrupt = await watchAntigravityPromptOutcome(NAME, directory, own);+ expect(await corrupt({ stopReason: "end_turn" })).toBeUndefined();+ expect(await corrupt({ stopReason: "refusal" })).toMatchObject({ acpUsageLimit: true, message: USAGE_LIMIT });+ });++ it("does not load a step that is no error, or an error step too large to read quickly", async () => {+ const { directory, conversations } = profile();+ const file = join(conversations, "big.db");+ const huge = "x".repeat(2 * 1024 * 1024);+ const turn = async (steps: ReadonlyArray<readonly [number, string]>) => {+ const check = await watchAntigravityPromptOutcome(NAME, directory, "big", () => 0);+ append(file, steps);+ return check({ stopReason: "end_turn" });+ };+ expect(await turn([[USER_INPUT, "hello"], [PLANNER_RESPONSE, huge]])).toBeUndefined();+ // The error step is the evidence; its text is not read, so the failure names no reason and no reset.+ const failure = await turn([[USER_INPUT, "hello"], [ERROR_MESSAGE, QUOTA_ERROR + huge]]);+ expect(failure).toMatchObject({ acpUsageLimit: false, message: `${NAME} stopped with an error.` });+ });++ it("holds only the models that share the quota that ran out", () => {+ expect(["gemini-3.8-flash", "gemini-4-argon", "gemini-4-argon-high", "gemini-carbon-2", "claude-sonnet-5", "gpt-6", "agy-model"].map(antigravityQuotaFamily))+ .toEqual(["gemini", "gemini-argon", "gemini-argon", "gemini-carbon", "shared", "shared", "shared"]);+ const known = ["gemini-3.8-flash", "gemini-3.8-pro", "gemini-4-argon", "claude-sonnet-5", "gpt-6"];+ expect(antigravityLimitFacts("claude-sonnet-5", known)).toEqual({ limit: "model", limitModels: ["claude-sonnet-5", "gpt-6"] });+ expect(antigravityLimitFacts("gemini-3.8-flash-high", known)).toEqual({ limit: "model", limitModels: ["gemini-3.8-flash-high", "gemini-3.8-flash", "gemini-3.8-pro"] });+ expect(antigravityLimitFacts("gemini-4-argon", known)).toEqual({ limit: "model", limitModels: ["gemini-4-argon"] });+ expect(antigravityLimitFacts(undefined, known)).toEqual({ limit: "model" });+ });++ it("gives no failure for a session id that is no file name, a missing profile, or a log replaced during the prompt", async () => {+ const { directory, conversations } = profile();+ expect(await (await watchAntigravityPromptOutcome(NAME, directory, "../escape"))({ stopReason: "end_turn" })).toBeUndefined();+ expect(await (await watchAntigravityPromptOutcome(NAME, join(directory, "absent"), "session"))({ stopReason: "end_turn" })).toBeUndefined();+ const file = join(conversations, "session.db");+ append(file, [[USER_INPUT, "first"]]);+ const check = await watchAntigravityPromptOutcome(NAME, directory, "session");+ rmSync(file);+ append(join(conversations, "other.db"), [[USER_INPUT, "hold the inode"]]);+ append(file, [[USER_INPUT, "second"], [USER_INPUT, "third"], [ERROR_MESSAGE, QUOTA_ERROR]]);+ expect(await check({ stopReason: "end_turn" })).toBeUndefined();+ });+});++describe("an Antigravity turn whose reply was an upstream failure", () => {+ const TESTING = join(dirname(fileURLToPath(import.meta.url)), "..", "testing");++ async function instance(instanceId: string, steps: Array<[number, string]> | null) {+ ensureDirs();+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-outcome-"));+ scratch.push(directory);+ const executable = join(directory, "fake-antigravity.ts");+ const harness = join(directory, process.platform === "win32" ? "localharness_external.exe" : "localharness_external");+ copyFileSync(join(TESTING, "fake-acp-cli.ts"), executable);+ copyFileSync(join(TESTING, "fake-acp-cli.ts"), harness);+ if (process.platform !== "win32") for (const file of [executable, harness]) chmodSync(file, 0o755);+ const token = antigravityTokenPath(instanceId);+ mkdirSync(dirname(token), { recursive: true });+ writeFileSync(token, "{}", { mode: 0o600 });+ const stepsFile = join(directory, "steps.json");+ if (steps) writeFileSync(stepsFile, JSON.stringify(steps));+ const created = await AntigravityDriver.create({+ instanceId, displayName: "Antigravity", enabled: true,+ config: { cli: executable, fullAuto: false },+ environment: { FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "gemini-3.8-flash", FAKE_ACP_AGENT_NAME: "Google Antigravity", FAKE_ACP_AGENT_VERSION: "1.4.5", FAKE_ACP_AGY_STEPS_FILE: stepsFile },+ });+ instances.push(created);+ return { created, directory, stepsFile };+ }++ it("shows the usage limit with its reset, and the next turn answers once the limit is gone", async () => {+ const { created, directory, stepsFile } = await instance("antigravity-outcome-quota", [[USER_INPUT, "hello"], [ERROR_MESSAGE, QUOTA_ERROR]]);+ const recorder = recordEvents(created.adapter);+ const before = Date.now();+ const { turnId } = await created.adapter.sendTurn({ threadId: "quota", text: "hello", model: "gemini-3.8-flash", approvalMode: "full", cwd: directory });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const events = recorder.events.filter((event) => event.turnId === turnId);+ const error = events.find((event) => event.type === "runtime.error") as { message: string; limit?: string; limitModels?: string[]; limitResetsAt?: number; text?: { key: string } };+ expect(error.message).toMatch(/account has reached its usage limit, which resets .+\. Until then, switch this bot to another AI\.$/);+ // The quota is that model family's, not the account's: the account's other models are not held.+ expect(error).toMatchObject({ limit: "model", limitModels: expect.arrayContaining(["gemini-3.8-flash"]), text: { key: "chat.notice.usageLimitResets" } });+ expect(error.limitModels!.every((model) => model.startsWith("gemini-"))).toBe(true);+ expect(error.limitResetsAt).toBeGreaterThanOrEqual(before + 3_600_000);+ expect(error.limitResetsAt).toBeLessThanOrEqual(Date.now() + 3_600_000);+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });++ writeFileSync(stepsFile, JSON.stringify([[USER_INPUT, "again"], [PLANNER_RESPONSE, "fine"]]));+ const next = await created.adapter.sendTurn({ threadId: "quota", text: "again", approvalMode: "full", cwd: directory });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === next.turnId);+ const later = recorder.events.filter((event) => event.turnId === next.turnId);+ expect(later.some((event) => event.type === "runtime.error")).toBe(false);+ expect(later.at(-1)).toMatchObject({ type: "turn.completed", ok: true });+ }, 90_000);++ it("leaves a normal reply, and a runtime that keeps no log, alone", async () => {+ for (const [instanceId, steps] of [["antigravity-outcome-fine", [[USER_INPUT, "hello"], [PLANNER_RESPONSE, "fine"]]], ["antigravity-outcome-no-log", null]] as const) {+ const { created, directory } = await instance(instanceId, steps as Array<[number, string]> | null);+ const recorder = recordEvents(created.adapter);+ const { turnId } = await created.adapter.sendTurn({ threadId: instanceId, text: "hello", approvalMode: "full", cwd: directory });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const events = recorder.events.filter((event) => event.turnId === turnId);+ expect(events.some((event) => event.type === "runtime.error")).toBe(false);+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });+ }+ }, 90_000);+});diff --git a/server/drivers/antigravity-turn-outcome.ts b/server/drivers/antigravity-turn-outcome.tsnew file mode 100644index 0000000000..b0d1c3770f--- /dev/null+++ b/server/drivers/antigravity-turn-outcome.ts@@ -0,0 +1,213 @@+// Whether an Antigravity turn that ended like a normal reply was an upstream failure, read from the runtime's own+// session log.+//+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:+// - apps/server/src/provider/acp/AntigravityTurnOutcome.ts (the error step,+// the quota and reset patterns, and the before and after reads of the+// session's own unlinked log);+// - apps/server/src/provider/acp/AntigravityProfilePaths.ts (the proof that+// no component of a path below the profile is a link).+// The failure is a plain error for the shared ACP runtime to throw, worded as every engine's usage limit is. A reset+// time is taken only inside the coming eight days, and a log or step too large to read quickly is not read.+import type { Stats } from "node:fs";+import { lstat, realpath } from "node:fs/promises";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";++import { AcpReportedFailure } from "./acp/failure-words.ts";+import { engineFailure } from "./engine-errors.ts";++// CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.+const ERROR_STEP_TYPE = 17;+// The harness error text leads the payload; a Go stack trace follows it.+const MAX_ERROR_PAYLOAD_BYTES = 16_384;+// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.+const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;+const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;+const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;+const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;+// google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset.+const RETRY_DELAY = /\bretryDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;+const GO_DURATION_PART = /(\d+(?:\.\d+)?)(ns|us|µs|μs|ms|h|m|s)/g;+const GO_DURATION_UNIT_MS: Record<string, number> = {+ ns: 1e-6,+ us: 1e-3,+ µs: 1e-3,+ μs: 1e-3,+ ms: 1,+ s: 1_000,+ m: 60_000,+ h: 3_600_000,+};+const NATIVE_SESSION_ID = /^[\w-]+$/;+// A log or an error step past these sizes is not read: the turn then ends as the runtime reported it.+const MAX_LOG_BYTES = 256 * 1024 * 1024;+const MAX_STEP_BYTES = 1024 * 1024;+// Google's longest window is a week; a reset further off, or not in the future, is not a reset time.+const MAX_RESET_AHEAD_MS = 8 * 24 * 3_600_000;+const CONVERSATION_SEGMENTS = ["antigravity-acp", "conversations"];++interface LastStep {+ type: number;+ payload: Uint8Array | null;+}++export type AntigravityPromptCheck = (result: unknown) => Promise<AcpReportedFailure | undefined>;++/** Proves a native runtime entry is at its literal path below the canonical profile: every component exists with the+ * expected type and none is a link. A link could point at another session's database under the same profile. */+async function managedPath(+ profileRoot: string,+ segments: readonly string[],+ kind: "file" | "directory",+): Promise<{ path: string; info: Stats } | undefined> {+ let current = profileRoot;+ let info: Stats | undefined;+ for (const [index, segment] of segments.entries()) {+ current = join(current, segment);+ info = await lstat(current).catch(() => undefined);+ const expectFile = kind === "file" && index === segments.length - 1;+ if (info === undefined || info.isSymbolicLink() || (expectFile ? !info.isFile() : !info.isDirectory())) return undefined;+ }+ if (info === undefined) return undefined;+ return (await realpath(current).catch(() => undefined)) === current ? { path: current, info } : undefined;+}++function readSteps<A>(file: string, read: (database: DatabaseSync) => A): A | undefined {+ const database = new DatabaseSync(file, { readOnly: true });+ try {+ database.exec("PRAGMA busy_timeout = 100");+ const hasSteps = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'").get() !== undefined;+ return hasSteps ? read(database) : undefined;+ } finally {+ database.close();+ }+}++function lastStepIndex(database: DatabaseSync): number {+ const index = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx;+ return typeof index === "number" ? index : -1;+}++// `length()` reads a blob's size from its record header; `substr()` loads the whole blob, so it runs only for an+// error step of a size worth loading.+const lastStepAfter = (index: number) => (database: DatabaseSync): LastStep | undefined => {+ const row = database.prepare("SELECT idx, step_type AS type, length(step_payload) AS bytes FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1").get(index);+ if (typeof row?.type !== "number") return undefined;+ if (row.type !== ERROR_STEP_TYPE || typeof row.bytes !== "number" || row.bytes > MAX_STEP_BYTES) return { type: row.type, payload: null };+ const payload = database.prepare("SELECT substr(step_payload, 1, ?) AS payload FROM steps WHERE idx = ?").get(MAX_ERROR_PAYLOAD_BYTES, row.idx)?.payload;+ return { type: row.type, payload: payload instanceof Uint8Array ? payload : null };+};++function resetAtFrom(text: string, now: number): number | undefined {+ const within = (at: number) => Number.isFinite(at) && at > now && at <= now + MAX_RESET_AHEAD_MS;+ const timestamp = RESET_TIMESTAMP.exec(text)?.[1];+ // A bare number is no timestamp, though Date.parse reads "5" as a year.+ const at = timestamp === undefined || !/^\d{4}-\d{2}-\d{2}T/u.test(timestamp) ? Number.NaN : Date.parse(timestamp);+ if (within(at)) return at;+ const delay = RESET_DELAY.exec(text)?.[1] ?? RETRY_DELAY.exec(text)?.[1];+ if (delay === undefined) return undefined;+ let delayMs = 0;+ for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0);+ const after = Math.round(now + delayMs);+ return within(after) ? after : undefined;+}++/** Which of the account's separately metered allowances a model draws on: Gemini's own, a separately metered Gemini+ * family, or the one every other model shares. */+export function antigravityQuotaFamily(model: string): string {+ if (!/^gemini-/iu.test(model)) return "shared";+ return /(?:^|-)argon(?:-|$)/iu.test(model) ? "gemini-argon" : /(?:^|-)carbon(?:-|$)/iu.test(model) ? "gemini-carbon" : "gemini";+}++/** A quota belongs to one allowance, not the account: it holds the models that draw on the same one as `model`, and+ * leaves the account's other models running. */+export function antigravityLimitFacts(model: string | undefined, known: Iterable<string>): { limit: "model"; limitModels?: string[] } {+ if (!model) return { limit: "model" };+ const family = antigravityQuotaFamily(model);+ return { limit: "model", limitModels: [...new Set([model, ...[...known].filter((id) => antigravityQuotaFamily(id) === family)])] };+}++function usageLimit(provider: string, text: string, now: number, timeZone?: string): AcpReportedFailure {+ const resetsAt = resetAtFrom(text, now);+ const failure = engineFailure(provider, "", { kind: "usage_limit", status: null, resetsAt, timeZone })!;+ return new AcpReportedFailure({ ...failure, ...(resetsAt === undefined ? {} : { limitResetsAt: resetsAt }) }, true);+}++/** The failure a prompt's result and the last step it added stand for; undefined for a normal reply. */+export function antigravityTurnFailure(+ provider: string,+ stopReason: unknown,+ step: LastStep | undefined,+ now: number,+ timeZone?: string,+): AcpReportedFailure | undefined {+ const errorText = step?.type === ERROR_STEP_TYPE ? new TextDecoder().decode(step.payload ?? new Uint8Array()) : undefined;+ // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.+ if (errorText === undefined && stopReason !== "refusal") return undefined;+ const text = errorText ?? "";+ const apiError = API_ERROR.exec(text);+ if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) return usageLimit(provider, text, now, timeZone);+ if (apiError === null) return new AcpReportedFailure(engineFailure(provider, "", { kind: "refused", status: null })!, false);+ const [, httpStatus, message, status] = apiError;+ if (httpStatus === "429" || status === "RESOURCE_EXHAUSTED") return usageLimit(provider, text, now, timeZone);+ const http = Number(httpStatus);+ return new AcpReportedFailure(engineFailure(provider, message!.trim(), { kind: http >= 500 ? "server" : "refused", status: http })!, false);+}++/**+ * Antigravity reports an upstream API failure as a chat message and `end_turn`. Its session log ends that turn with an+ * error step, so the check reads only steps the current prompt added, read-only, from this session's own unlinked+ * database. Without that evidence a typed `refusal` still fails the turn. Call it before `session/prompt`; it never+ * throws.+ */+export async function watchAntigravityPromptOutcome(+ provider: string,+ profileDirectory: string,+ sessionId: string,+ now: () => number = Date.now,+): Promise<AntigravityPromptCheck> {+ const stopReasonOf = (result: unknown) => (result as { stopReason?: unknown } | null)?.stopReason;+ const typedOnly: AntigravityPromptCheck = async (result) => antigravityTurnFailure(provider, stopReasonOf(result), undefined, now());+ if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;+ const segments = [...CONVERSATION_SEGMENTS, `${sessionId}.db`];+ const before = await (async () => {+ const root = await realpath(profileDirectory).catch(() => undefined);+ if (root === undefined) return undefined;+ if ((await managedPath(root, CONVERSATION_SEGMENTS, "directory")) === undefined) return undefined;+ const database = await managedPath(root, segments, "file");+ // A path that exists but fails the proof is a link or other foreign entry.+ if (database === undefined) {+ const present = await lstat(join(root, ...segments)).then(() => true, () => false);+ return present ? undefined : { root, identity: undefined, startIndex: -1 };+ }+ return { root, identity: database.info, startIndex: undefined };+ })().catch(() => undefined);+ if (before === undefined) return typedOnly;+ let startIndex = before.startIndex;+ if (startIndex === undefined) {+ if ((before.identity?.size ?? 0) > MAX_LOG_BYTES) return typedOnly;+ try {+ startIndex = readSteps(join(before.root, ...segments), lastStepIndex) ?? -1;+ } catch {+ return typedOnly;+ }+ }+ const from = startIndex;+ return async (result) => {+ // The same file as before the prompt, or one this prompt created, still unlinked.+ const after = await managedPath(before.root, segments, "file").catch(() => undefined);+ const sameFile = after !== undefined+ && (before.identity === undefined || (after.info.dev === before.identity.dev && after.info.ino === before.identity.ino));+ let step: LastStep | undefined;+ if (sameFile && after.info.size <= MAX_LOG_BYTES) {+ try {+ step = readSteps(after.path, lastStepAfter(from));+ } catch {+ step = undefined;+ }+ }+ return antigravityTurnFailure(provider, stopReasonOf(result), step, now());+ };+}diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.tsindex 1cf2fb62d3..217108a9a9 100644--- a/server/drivers/antigravity.ts+++ b/server/drivers/antigravity.ts@@ -27,6 +27,7 @@ import {validateAntigravityRuntime,verifyAntigravityBrowserHelper,} from "./antigravity-acp.ts";+import { antigravityLimitFacts, watchAntigravityPromptOutcome } from "./antigravity-turn-outcome.ts";import { AntigravityAuthController } from "./antigravity-auth.ts";import {antigravityManagedInstallAvailable,@@ -71,6 +72,8 @@ export function antigravitySignInError(error: unknown): boolean {const managedAsset = resolveAntigravityReleaseAsset();const runtimeProcesses = new AntigravityProcesses();+/** Every model id an account here has been offered, beside the bundled catalog's. */+const offeredModels = new Set<string>();const support: AcpSupport = {driverKind: "antigravityAgent",@@ -116,11 +119,13 @@ const support: AcpSupport = {const runtime = await resolveAntigravityRuntime(config.cli, env);const profile = await prepareAntigravityProfile({ instanceId, runtime, baseEnv: env });if (!(await antigravityProfileAuthenticated(profile))) throw new Error(support.loginNote);- return probeAntigravityModels({+ const catalog = await probeAntigravityModels({runtime,profile,fallbackDefault: currentEngineCatalog("antigravity").default,});+ for (const option of catalog.options) offeredModels.add(option.id);+ return catalog;},pickAuthMethod: (methods) => methods.some((method) => method.id === "oauth-personal")@@ -136,6 +141,9 @@ const support: AcpSupport = {},processStarted: (child, instanceId) => runtimeProcesses.track(instanceId, child),sessionSetupParams: antigravitySessionSetup,+ // One model family's quota is not the account's: Gemini and the models that share another allowance keep running.+ limitFacts: (_text, model) => antigravityLimitFacts(model, [...support.models.options.map((option) => option.id), ...offeredModels]),+ promptOutcome: (instanceId, sessionId) => watchAntigravityPromptOutcome(support.displayName, antigravityProfileDirectory(instanceId), sessionId),requireAuthenticationBeforeSpawn: true,isAuthenticated: async (env, config, instanceId) => {try {diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 0fcad07db2..67374a4c95 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -74,6 +74,9 @@// FAKE_ACP_CANCEL_STOP_REASON the stopReason a cancelled hanging prompt answers (default cancelled; OpenCode answers end_turn)// FAKE_ACP_HANG_ONCE_FILE with FAKE_ACP_HANG_ON, only the first matching prompt hangs; it writes this file// FAKE_ACP_HOLD_FILE while this file exists, a session/prompt waits before it is answered+// FAKE_ACP_AGY_STEPS_FILE JSON [[stepType, text], …] re-read per prompt and appended to the session's log under+// GEMINI_HOME (antigravity-acp/conversations/<session>.db, a folder made at startup), as agy_acp_server 1.4.5+// writes its trajectory// FAKE_ACP_MODE=hermes-steer hermes-agent's ACP `/steer`: sessions advertise `steer`; a prompt says "working. ", waits for// FAKE_ACP_GATE_FILE, then says "done" and every steer it took; `/steer <text>` during it answers "⏩ Steer queued for// the active turn: …" (FAKE_ACP_STEER_FAIL=1: "⚠️ Steer failed: …"; =rpc: a JSON-RPC error), and with no prompt running it runs <text>@@ -605,6 +608,24 @@ function failRpc(msg: { method: string; id: unknown }): boolean {return true;}+const antigravityConversations = process.env.FAKE_ACP_AGY_STEPS_FILE && process.env.GEMINI_HOME+ ? `${process.env.GEMINI_HOME}/antigravity-acp/conversations` : null;+if (antigravityConversations) mkdirSync(antigravityConversations, { recursive: true });++function appendAntigravitySteps(sessionId: unknown): void {+ const file = process.env.FAKE_ACP_AGY_STEPS_FILE, directory = antigravityConversations;+ if (!file || !directory || typeof sessionId !== "string" || !existsSync(file)) return;+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite");+ const database = new DatabaseSync(`${directory}/${sessionId}.db`);+ try {+ database.exec("CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)");+ const insert = database.prepare("INSERT INTO steps (step_type, step_payload) VALUES (?, ?)");+ for (const [type, text] of JSON.parse(readFileSync(file, "utf8")) as Array<[number, string]>) insert.run(type, Buffer.from(text));+ } finally {+ database.close();+ }+}+function driveMcp(entry: McpEntry, calls: Array<{ name: string | (() => string); args: (prev: string) => object }>, strict = false): Promise<string> {return new Promise((resolve, reject) => {const env = { ...process.env };@@ -1056,6 +1077,7 @@ function handle(msg: any) {if (process.env.FAKE_ACP_DUMP && process.env.FAKE_ACP_DUMP_PROMPT === "1") {writeFileSync(`${process.env.FAKE_ACP_DUMP}.prompt.json`, JSON.stringify(msg.params?.prompt ?? null, null, 2));}+ appendAntigravitySteps(msg.params?.sessionId);if (failRpc(msg)) return;if (mode === "hermes-steer") {hermesPrompt(msg);