Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(agent-driver): add persistent Antigravity ACP backend (#869)
Gustavo Ye902082bfe58a
diff --git a/src/daemon/agent-driver/README.md b/src/daemon/agent-driver/README.mdindex 7ea178d9c..6a0aa12a3 100644--- a/src/daemon/agent-driver/README.md+++ b/src/daemon/agent-driver/README.md@@ -1,7 +1,7 @@# @alook/agent-driver-Repository-private logical-session drivers for Claude, Codex, Cursor, OpenCode,-and Pi.+Repository-private logical-session drivers for Claude, Codex, Cursor, Grok,+OpenCode, Pi, and Antigravity.The package's exported contract owns backend lifecycle, message admission,buffering, queueing, interrupts, stop deadlines, and normalized events. The@@ -206,3 +206,84 @@ affected backend or leave it incompatible/unhealthy if ACP or v2 is unavailable;it must not ship, retain, or automatically select the restored one-shot path.Do not fall back to `cursor-agent --print` or `opencode run`. Verify theunaffected backends and the capability probe before resuming rollout.+++## Antigravity (native ACP)++The `antigravity` backend uses Google's native `agy_acp_server.par` (`agy_acp_server.exe`+on Windows), not the one-shot `agy --print` command. It keeps one process and one+provider session across turns. Busy input queues until the current prompt returns;+concurrent steering is not advertised. Restart uses `session/load` with the stored+provider session ID. An unavailable session requires an explicit reset.++Install the native distribution listed in the+[ACP registry](https://github.com/agentclientprotocol/registry/blob/main/antigravity-acp/agent.json).+Version 1.3.0 was used for protocol validation. Keep `localharness_external` beside+the server executable. Put an executable wrapper named `agy_acp_server.par` on PATH,+which execs the absolute server path, or set the runtime's `command` override to+that path. Linux adds the registry's `--uid=` argument; Windows uses the `.exe` name.+Do not substitute a third-party ACP wrapper around print mode.++For example, after extracting the macOS arm64 archive into+`$HOME/.local/share/alook/runtimes/antigravity-acp/1.3.0`, a PATH wrapper contains:++```sh+#!/bin/sh+exec "$HOME/.local/share/alook/runtimes/antigravity-acp/1.3.0/agy_acp_server.par" "$@"+```++Authentication is local to Google's ACP server. Complete Google sign-in using an+ACP client's `authenticate` request with `methodId: "oauth-personal"` before+launching an agent. The provider's settings live under+`~/.gemini/antigravity-acp/`; leave credentials there and never put them in agent+instructions. Runtime detection initializes the protocol and requests a session catalog without+authenticating or sending a prompt. Healthy means the native binary is compatible,+not that an account is signed in; unauthenticated discovery has no model catalog.+The catalog probe can create an empty provider session. The adapter does not+send an `authenticate` request during discovery or launch. It reports explicit+provider authentication errors when returned. In native 1.3.0 testing, unreadable+Keychain credentials with no valid file fallback left `session/load` waiting for+login and discovery ended with `antigravity_acp_timeout` at the existing 10-second+deadline. A separate 30-second diagnostic on the same credential condition was+correlated with an opened Google sign-in page by its OAuth callback port. The+native server can therefore start its own browser login flow during discovery,+even though the adapter does not send `authenticate`. Complete native sign-in+before running the daemon; a timeout does not establish that credentials are valid.++Standing instructions accompany the first prompt of every physical session,+including resumed sessions. Later prompts reuse its context. Tools use ACP+permission requests scoped to the active session and prompt, choosing only a+provider-offered `allow_once` option. Models must be present in the native session's+advertised model catalog before they can be selected. Discovery publishes the+native model catalog through the existing machine model/effort controls. Gemini+high/medium/low variants are offered as effort choices only when the same model+family's exact variant IDs are returned by the server. Effort changes select that+native variant on the same idle session; unsupported values fail explicitly.++Native 1.3.0 exposes model/mode config options but no independent effort option.+The adapter reads generation usage from the exact session's native SQLite WAL view;+input already excludes cache and output includes thinking. Missing fields stay null.+Native session/home plus generation index deduplicates accounting across reloads.+Dates use the native invocation start timestamp. The daemon commits counts and+processed generation ranges in one atomic daily store, retries transient write+failures on subsequent telemetry reads, and recovers native records after restart.+Reading requires Node's built-in SQLite (Node 22.13+) or the system sqlite3 CLI;+if neither is available, conversations continue and metrics remain unknown.+Child trajectories are not yet aggregated: their presence makes session metrics+unknown rather than presenting partial root usage as complete.++Personal OAuth quota uses the official loadCodeAssist and retrieveUserQuotaSummary+endpoints with the native credential storage. Reading never starts onboarding or+interactive authentication. API-key/business modes and absent credentials report+unavailable/unauthorized. Native bucket identity, remainingFraction and resetTime+are preserved; provider-defined windows are not guessed. ACP usage_update is+context occupancy and is never counted. Recent-history import remains unavailable.+On October 6, 2026, real authenticated execution with official ACP 1.3.0 passed+on macOS, including native model/effort selection, persistent turns, daemon+recovery and native/local/D1/API usage correlation. Real quota reading passed+with the official isolated file credential store and with Keychain-first file+fallback, using the reader's existing five-second request deadlines. The default+Keychain store remained unreadable on the tested machine and had no file fallback;+that condition reports retryable unavailable before HTTP, not an authentication+refusal. These results supersede the earlier Google location-eligibility block+and do not establish default Keychain access or acceptance on other platforms.diff --git a/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.tsnew file mode 100644index 000000000..ed077d61d--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts@@ -0,0 +1,813 @@+import { NativeUsageReader } from "./usage.js";+import type { RuntimeSettingsUpdate, RuntimeSettingsUpdateResult } from "../../contract.js";+import { parseAntigravityCatalog, antigravityModelForEffort, type AntigravityCatalog } from "./catalog.js";+import { EventEmitter } from "node:events";+import type {+ AdapterEvent,+ AdapterLaunchContext,+ LaneAdmission,+ LaneInterruptInput,+ LaneSendInput,+ LaneStartInput,+ LaneStopInput,+ RuntimeLane,+ RuntimeLaneEventMap,+ SpawnedProcess,+ SpawnedProcessHandle,+} from "../../internal/adapter.js";+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";+import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";+++const ACP_PROTOCOL_VERSION = 1;+const HANDSHAKE_TIMEOUT_MS = 15_000;++const PROMPT_STOP_REASONS = new Set([+ "end_turn",+ "max_tokens",+ "max_turn_requests",+ "refusal",+ "cancelled",+]);++type JsonRpcId = number | string;+type JsonRecord = Record<string, unknown>;++interface PendingCall {+ readonly kind: "call";+ readonly method: string;+ readonly resolve: (result: unknown) => void;+ readonly reject: (error: Error) => void;+ readonly timer?: ReturnType<typeof setTimeout>;+}++interface PendingPrompt {+ readonly kind: "prompt";+ readonly method: "session/prompt";+ readonly prompt: PromptRequest;+}++type PendingRequest = PendingCall | PendingPrompt;++interface RpcRequest {+ readonly id: number;+ readonly promise: Promise<unknown>;+}++interface PromptRequest {+ readonly requestId: number;+ readonly receipt: string;+}++interface AntigravityAcpProcessFactory {+ spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess & { usageHome?: string }>;+}++interface AntigravityAcpLaneOptions {+ readonly onRawStdoutLine?: (line: string) => void;+ readonly handshakeTimeoutMs?: number;+ readonly usageReader?: Pick<NativeUsageReader, "read">;+}++class AntigravityAcpResetRequiredError extends Error {}+class AntigravityAcpIncompatibleError extends Error {}+class AntigravityAcpAuthenticationError extends Error {}++class AntigravityAcpRpcError extends Error {+ constructor(+ readonly method: string,+ readonly code: number | undefined,+ message: string,+ ) {+ super(message);+ }+}++function record(value: unknown): JsonRecord | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? value as JsonRecord+ : null;+}++function safeLabel(value: unknown): string {+ return typeof value === "string" && /^[a-z0-9_-]{1,64}$/i.test(value) ? value : "unknown";+}++function rpcErrorMessage(error: unknown): string {+ const payload = record(error);+ const message = typeof payload?.message === "string" && payload.message.trim()+ ? payload.message+ : "Antigravity ACP request failed";+ const data = record(payload?.data);+ const detail = typeof data?.message === "string" && data.message.trim() ? data.message : undefined;+ return detail ? `${message}: ${detail}` : message;+}++function isMissingSessionError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ return /\bsession\b.*\b(not found|missing|unknown|invalid)\b/i.test(message)+ || /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);+}++export class AntigravityAcpLane implements RuntimeLane {+ private readonly events = new EventEmitter();+ private readonly pending = new Map<number, PendingRequest>();+ private readonly openToolCalls = new Set<string>();+ private readonly seenToolCalls = new Set<string>();+ private catalog?: AntigravityCatalog;+ private baselineModelId?: string;+ private cancelling = false;+ private usageHome?: string;+ private usageReader?: Pick<NativeUsageReader, "read">;+ private process: SpawnedProcessHandle | null = null;+ private stdoutBuffer = "";+ private requestSequence = 0;+ private started = false;+ private ready = false;+ private sessionId: string | null = null;+ private currentPromptRequestId: number | null = null;+ private terminalOwner: string | null = null;+ private requestedStopReason?: string;+ private spawnPromise?: Promise<SpawnedProcess & { usageHome?: string }>;+ private stopPromise?: Promise<void>;+ private suppressExit = false;+ private processTerminal = false;+ private processActivated = false;+ private processStartError: Error | null = null;++ constructor(+ private readonly factory: AntigravityAcpProcessFactory,+ private readonly ctx: AdapterLaunchContext,+ private readonly options: AntigravityAcpLaneOptions = {},+ ) {}++ get currentSessionId(): string | null {+ return this.sessionId;+ }++ on<K extends keyof RuntimeLaneEventMap>(+ event: K,+ listener: (value: RuntimeLaneEventMap[K]) => void,+ ): void {+ this.events.on(event, listener);+ }++ async start(input: LaneStartInput): Promise<LaneAdmission> {+ if (this.started) {+ return { ok: false, reason: "runtime_error", error: "Antigravity ACP session already started" };+ }+ this.started = true;+ const launchCtx: AdapterLaunchContext = {+ ...this.ctx,+ prompt: input.text,+ config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },+ };+ try {+ this.spawnPromise = this.factory.spawn(launchCtx).then((spawned) => {+ this.usageHome = spawned.usageHome;+ this.process = spawned.process;+ this.attachProcess(spawned.process);+ return spawned;+ });+ await this.spawnPromise;+ if (this.requestedStopReason) {+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });+ throw new Error("Antigravity ACP start was cancelled");+ }+ await this.handshake(launchCtx);+ if (this.requestedStopReason) {+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });+ throw new Error("Antigravity ACP start was cancelled");+ }+ if (this.processStartError) throw this.processStartError;+ if (this.processTerminal || this.isClosed()) {+ throw new Error("Antigravity ACP process exited during startup");+ }+ const sessionId = this.sessionId;+ if (!sessionId) throw new Error("Antigravity ACP handshake completed without a session id");+ this.usageReader = this.options.usageReader ?? (this.usageHome ? new NativeUsageReader(this.usageHome, sessionId) : undefined);+ this.processActivated = true;+ this.ready = true;+ this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);+ return this.admitPrompt([this.ctx.standingPrompt, input.text].filter(Boolean).join("\n\n"));+ } catch (error) {+ this.suppressExit = true;+ await this.stop({ reason: "failed_start", forceAfterMs: 0 }).catch(() => {});+ if (error instanceof AntigravityAcpResetRequiredError) {+ return { ok: false, reason: "reset_required", error: error.message };+ }+ if (error instanceof AntigravityAcpIncompatibleError) {+ return { ok: false, reason: "incompatible_configuration", error: error.message };+ }+ if (error instanceof AntigravityAcpAuthenticationError) {+ return { ok: false, reason: "authentication", error: error.message };+ }+ throw error;+ }+ }++ async send(input: LaneSendInput): Promise<LaneAdmission> {+ if (!this.ready || !this.process || this.isClosed()) return { ok: false, reason: "closed" };+ if (input.mode === "busy" || this.currentPromptRequestId !== null) {+ return { ok: false, reason: "runtime_busy", error: "Antigravity queues messages until the current prompt ends" };+ }+ return this.admitPrompt(input.text);+ }++ async interrupt(_input: LaneInterruptInput): Promise<boolean> {+ if (!this.ready || !this.sessionId || this.currentPromptRequestId === null || this.isClosed()) return false;+ const previous = this.cancelling;+ this.cancelling = true;+ try {+ this.write({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });+ } catch (error) {+ this.cancelling = previous;+ throw error;+ }+ return true;+ }++ stop(input: LaneStopInput = {}): Promise<void> {+ this.requestedStopReason ??= input.reason ?? "requested_stop";+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.openToolCalls.clear();+ this.rejectAllPending(new Error("Antigravity ACP lane stopped"));+ this.stopPromise ??= this.stopPhysicalOnce(input);+ return this.stopPromise;+ }++ private async stopPhysicalOnce(input: LaneStopInput): Promise<void> {+ await this.spawnPromise?.catch(() => undefined);+ const proc = this.process;+ if (!proc) return;+ if (proc.pid) {+ await killProcessTree(proc.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });+ } else if (!this.isClosed()) {+ proc.kill(input.signal ?? "SIGTERM");+ }+ }++ private async handshake(ctx: AdapterLaunchContext): Promise<void> {+ const initialize = record(await this.call("initialize", {+ protocolVersion: ACP_PROTOCOL_VERSION,+ clientCapabilities: {+ fs: { readTextFile: false, writeTextFile: false },+ terminal: false,+ },+ clientInfo: { name: "alook-agent-driver", version: "1" },+ }));+ if (initialize?.protocolVersion !== ACP_PROTOCOL_VERSION) {+ throw new AntigravityAcpIncompatibleError("Installed Antigravity ACP does not support protocol version 1");+ }+ if (record(initialize.agentInfo)?.name !== "antigravity-acp") {+ throw new AntigravityAcpIncompatibleError("Expected Google's native Antigravity ACP server");+ }+ const capabilities = record(initialize.agentCapabilities);+ if (capabilities?.loadSession !== true) {+ throw new AntigravityAcpIncompatibleError("Installed Antigravity ACP does not support persistent session loading");+ }+ let session: JsonRecord | null;+ if (ctx.config.sessionId) {+ try {+ session = record(await this.call("session/load", {+ sessionId: ctx.config.sessionId,+ cwd: ctx.workingDirectory,+ mcpServers: [],+ }));+ } catch (error) {+ if (isMissingSessionError(error)) {+ throw new AntigravityAcpResetRequiredError(+ "Antigravity session cannot be loaded through ACP; reset this agent to start a new ACP session",+ );+ }+ throw error;+ }+ } else {+ session = record(await this.call("session/new", { cwd: ctx.workingDirectory, mcpServers: [] }));+ }+ if (!session) throw new Error("Antigravity ACP did not return a valid session response");+ const returnedSessionId = session.sessionId;+ if (returnedSessionId !== undefined+ && (typeof returnedSessionId !== "string" || !returnedSessionId.trim())) {+ throw new Error("Antigravity ACP did not return a valid session id");+ }+ if (ctx.config.sessionId) {+ if (returnedSessionId !== undefined && returnedSessionId !== ctx.config.sessionId) {+ throw new AntigravityAcpResetRequiredError(+ "Antigravity ACP loaded a different session; reset this agent before continuing",+ );+ }+ this.sessionId = ctx.config.sessionId;+ } else {+ if (typeof returnedSessionId !== "string") {+ throw new Error("Antigravity ACP did not return a valid session id");+ }+ this.sessionId = returnedSessionId;+ }+ await this.configureModel(session, ctx);+ }++ private async configureModel(session: JsonRecord, ctx: AdapterLaunchContext): Promise<void> {+ this.catalog = parseAntigravityCatalog(session);+ const configured = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);+ this.baselineModelId = configured.model ?? this.catalog?.currentModelId;+ if (!configured.model && !configured.reasoningEffort) return;+ const modelId = this.catalog && this.baselineModelId+ ? antigravityModelForEffort(this.catalog, this.baselineModelId, configured.reasoningEffort)+ : undefined;+ if (!modelId) throw new AntigravityAcpIncompatibleError("Configured Antigravity model or reasoning effort is unavailable");+ await this.setModel(modelId);+ }++ private async setModel(modelId: string): Promise<void> {+ if (this.catalog?.configId) {+ const response = await this.call("session/set_config_option", {+ sessionId: this.sessionId, configId: this.catalog.configId, value: modelId,+ });+ const catalog = parseAntigravityCatalog(response);+ if (!catalog || catalog.currentModelId !== modelId) throw new Error("Antigravity did not confirm the selected model");+ this.catalog = catalog;+ } else {+ await this.call("session/set_model", { sessionId: this.sessionId, modelId });+ if (this.catalog) this.catalog = { ...this.catalog, currentModelId: modelId };+ }+ }++ async updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {+ const failed = (code: string, message: string, retryable = false): RuntimeSettingsUpdateResult => ({+ status: "failed", error: { category: "configuration", code, message, retryable },+ });+ if (!this.ready || this.isClosed()) return failed("settings_session_unavailable", "Antigravity session is unavailable", true);+ if (this.currentPromptRequestId !== null) return failed("settings_runtime_busy", "Antigravity settings require an idle session", true);+ const modelId = this.catalog && this.baselineModelId+ ? antigravityModelForEffort(this.catalog, this.baselineModelId, input.reasoningEffort ?? undefined)+ : undefined;+ if (!modelId) return failed("unsupported_reasoning_effort", "Antigravity did not offer the requested model/effort variant");+ try {+ await this.setModel(modelId);+ return { status: "applied" };+ } catch {+ return failed("settings_update_failed", "Antigravity rejected the settings update", true);+ }+ }++ private admitPrompt(text: string): LaneAdmission {+ if (!this.sessionId) return { ok: false, reason: "not_ready", error: "Antigravity ACP session is not ready" };+ const requestId = ++this.requestSequence;+ const prompt: PromptRequest = {+ requestId,+ receipt: `antigravity:acp:${requestId}`,+ };+ const previousPromptRequestId = this.currentPromptRequestId;+ const previousTerminalOwner = this.terminalOwner;+ const previousOpenToolCalls = new Set(this.openToolCalls);+ const previousSeenToolCalls = new Set(this.seenToolCalls);+ const previousCancelling = this.cancelling;+ this.terminalOwner = prompt.receipt;+ this.currentPromptRequestId = requestId;+ this.cancelling = false;+ this.seenToolCalls.clear();+ this.openToolCalls.clear();+ this.pending.set(requestId, { kind: "prompt", method: "session/prompt", prompt });+ try {+ this.write({+ jsonrpc: "2.0",+ id: requestId,+ method: "session/prompt",+ params: {+ sessionId: this.sessionId,+ prompt: [{ type: "text", text }],+ },+ });+ } catch (error) {+ this.pending.delete(requestId);+ if (this.currentPromptRequestId === requestId) {+ this.currentPromptRequestId = previousPromptRequestId;+ this.terminalOwner = previousTerminalOwner;+ this.cancelling = previousCancelling;+ this.seenToolCalls.clear();+ for (const toolCallId of previousSeenToolCalls) this.seenToolCalls.add(toolCallId);+ this.openToolCalls.clear();+ for (const toolCallId of previousOpenToolCalls) this.openToolCalls.add(toolCallId);+ }+ throw error;+ }+ return { ok: true, acceptedAs: "prompt", receipt: prompt.receipt };+ }++ private completePrompt(prompt: PromptRequest, value: unknown): void {+ if (this.currentPromptRequestId !== prompt.requestId) return;+ const result = record(value);+ if (!result || typeof result.stopReason !== "string" || !PROMPT_STOP_REASONS.has(result.stopReason)) {+ this.failPrompt(+ prompt,+ new Error("Antigravity ACP prompt response did not contain a supported stopReason"),+ "antigravity.invalid_stop_reason",+ );+ return;+ }+ if (result.stopReason === "cancelled") {+ this.failPrompt(prompt, new Error("Antigravity ACP prompt was cancelled"), "antigravity.cancelled");+ return;+ }+ const terminalOwner = this.terminalOwner ?? prompt.receipt;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.openToolCalls.clear();+ this.events.emit("runtime_event", {+ kind: "turn_end",+ sessionId: this.sessionId ?? undefined,+ turnOwner: terminalOwner,+ } satisfies AdapterEvent);+ }++ private failPrompt(prompt: PromptRequest, error: unknown, code = "antigravity.prompt_failed"): void {+ if (this.currentPromptRequestId !== prompt.requestId) return;+ const terminalOwner = this.terminalOwner ?? prompt.receipt;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.openToolCalls.clear();+ this.events.emit("runtime_event", {+ kind: "error",+ code,+ message: error instanceof Error ? error.message : String(error),+ } satisfies AdapterEvent);+ this.events.emit("runtime_event", {+ kind: "turn_end",+ pendingContent: "discard",+ sessionId: this.sessionId ?? undefined,+ turnOwner: terminalOwner,+ } satisfies AdapterEvent);+ }++ private call(method: string, params: JsonRecord): Promise<unknown> {+ return this.request(method, params, this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS).promise;+ }++ private request(method: string, params: JsonRecord, timeoutMs?: number): RpcRequest {+ const id = ++this.requestSequence;+ let resolve!: (result: unknown) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<unknown>((accept, decline) => {+ resolve = accept;+ reject = decline;+ });+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {+ const pending = this.pending.get(id);+ if (!pending || pending.kind !== "call") return;+ this.pending.delete(id);+ pending.reject(new Error(`Antigravity ACP ${method} timed out`));+ }, timeoutMs);+ timer?.unref?.();+ this.pending.set(id, { kind: "call", method, resolve, reject, ...(timer ? { timer } : {}) });+ try {+ this.write({ jsonrpc: "2.0", id, method, params });+ } catch (error) {+ const pending = this.pending.get(id);+ this.pending.delete(id);+ if (pending?.kind === "call" && pending.timer) clearTimeout(pending.timer);+ throw error instanceof Error ? error : new Error(String(error));+ }+ return { id, promise };+ }++ private write(message: JsonRecord): void {+ const stdin = this.process?.stdin;+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {+ throw new Error("Antigravity ACP stdin is not writable");+ }+ stdin.write(`${JSON.stringify(message)}\n`);+ }++ private attachProcess(proc: SpawnedProcessHandle): void {+ proc.stdout?.on("data", (chunk) => {+ this.stdoutBuffer += chunk.toString();+ if (Buffer.byteLength(this.stdoutBuffer) > 8 * 1024 * 1024) {+ this.stdoutBuffer = "";+ this.protocolFailure("Antigravity ACP exceeded the protocol buffer limit");+ return;+ }+ const lines = this.stdoutBuffer.split("\n");+ this.stdoutBuffer = lines.pop() ?? "";+ for (const line of lines) {+ if (!line.trim()) continue;+ try {+ this.options.onRawStdoutLine?.(line);+ } catch {+ }+ let message: unknown;+ try {+ message = JSON.parse(line);+ } catch {+ this.protocolFailure("Antigravity ACP emitted malformed JSON");+ continue;+ }+ try {+ this.handleMessage(message);+ } catch {+ this.protocolFailure("Antigravity ACP could not answer a client-side protocol request");+ }+ }+ });+ proc.stderr?.on("data", (chunk) => {+ const text = chunk.toString().trim();+ if (text) this.events.emit("stderr", text);+ });+ proc.on("error", (error) => {+ if (this.process !== proc || this.processTerminal) return;+ const normalized = error instanceof Error ? error : new Error(String(error));+ this.rejectAllPending(normalized);+ if (!this.processActivated || this.requestedStopReason) {+ if (!this.processActivated) this.processStartError ??= normalized;+ this.events.emit("error", normalized);+ return;+ }+ this.processTerminal = true;+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.openToolCalls.clear();+ this.stopPromise ??= this.stopPhysicalOnce({ reason: "runtime_error", forceAfterMs: 0 });+ void this.stopPromise.catch(() => {});+ this.events.emit("error", normalized);+ if (this.suppressExit) return;+ this.events.emit("exit", {+ code: null,+ signal: null,+ reason: "runtime_exit",+ });+ });+ proc.on("exit", (code, signal) => {+ if (this.processTerminal || this.process !== proc) return;+ this.processTerminal = true;+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.openToolCalls.clear();+ this.rejectAllPending(new Error("Antigravity ACP process exited"));+ if (this.suppressExit || !this.processActivated) return;+ this.events.emit("exit", {+ code,+ signal,+ reason: this.requestedStopReason ? "requested" : "runtime_exit",+ });+ });+ }++ private handleMessage(value: unknown): void {+ const message = record(value);+ if (!message || message.jsonrpc !== "2.0") {+ this.protocolFailure("Antigravity ACP emitted an invalid JSON-RPC message");+ return;+ }+ if ((typeof message.id === "number" || typeof message.id === "string") && typeof message.method !== "string") {+ this.handleResponse(message.id, message);+ return;+ }+ if (typeof message.method === "string") {+ if (message.id !== undefined) {+ this.handleRequest(message.id as JsonRpcId, message.method, message.params);+ } else {+ this.handleNotification(message.method, message.params);+ }+ return;+ }+ this.protocolFailure("Antigravity ACP emitted an unrecognized JSON-RPC message");+ }++ private handleResponse(id: JsonRpcId, message: JsonRecord): void {+ const pending = typeof id === "number" ? this.pending.get(id) : undefined;+ if (typeof id !== "number" || !pending) {+ this.diagnostic("warning", "Antigravity ACP emitted a duplicate or unknown response id");+ return;+ }+ if (pending.kind === "prompt") {+ this.pending.delete(id);+ const finish = () => {+ if (message.error !== undefined) {+ const payload = record(message.error);+ const rpcCode = typeof payload?.code === "number" && Number.isSafeInteger(payload.code)+ ? payload.code+ : undefined;+ this.failPrompt(+ pending.prompt,+ new AntigravityAcpRpcError(pending.method, rpcCode, rpcErrorMessage(message.error)),+ rpcCode === undefined ? "antigravity.rpc_error" : `antigravity.rpc.${rpcCode}`,+ );+ } else if (!("result" in message)) {+ this.failPrompt(+ pending.prompt,+ new Error("Antigravity ACP response omitted result"),+ "antigravity.invalid_response",+ );+ } else {+ this.completePrompt(pending.prompt, message.result);+ }+ };+ if (this.usageReader) {+ void (async () => {+ const deadline = Date.now() + 5_000;+ for (let batch = 0; batch < 16; batch++) {+ const result = await this.usageReader!.read();+ if (this.currentPromptRequestId !== pending.prompt.requestId || this.isClosed() || this.requestedStopReason) return;+ for (const sample of result.samples) this.events.emit("runtime_event", { kind: "telemetry", name: "token_usage", source: "antigravity.native", ...sample } satisfies AdapterEvent);+ if (result.incompleteScope) throw new Error("Child trajectory accounting unavailable");+ if (result.complete) {+ this.events.emit("runtime_event", { kind: "telemetry", name: "token_usage_status", source: "antigravity.native", status: "available" } satisfies AdapterEvent);+ return;+ }+ if (Date.now() >= deadline) break;+ }+ throw new Error("Native accounting backlog remains");+ })().catch(() => {+ if (this.currentPromptRequestId !== pending.prompt.requestId || this.isClosed() || this.requestedStopReason) return;+ this.diagnostic("warning", "Antigravity native token usage unavailable: SQLite reader, record or timestamp missing");+ this.events.emit("runtime_event", { kind: "telemetry", name: "token_usage_status", source: "antigravity.native", status: "unavailable" } satisfies AdapterEvent);+ }).finally(finish);+ } else finish();+ return;+ }+ if (message.error !== undefined) {+ const payload = record(message.error);+ if (/authentication required|not authenticated|login required/i.test(rpcErrorMessage(message.error))) {+ this.settleRequest(id, false, new AntigravityAcpAuthenticationError(+ "Antigravity ACP requires local authentication; complete its Google sign-in before starting this agent",+ ));+ return;+ }+ this.settleRequest(id, false, new AntigravityAcpRpcError(+ pending.method,+ typeof payload?.code === "number" ? payload.code : undefined,+ rpcErrorMessage(message.error),+ ));+ return;+ }+ if (!("result" in message)) {+ this.settleRequest(id, false, new Error("Antigravity ACP response omitted result"));+ return;+ }+ this.settleRequest(id, true, message.result);+ }++ private settleRequest(id: number, ok: boolean, value: unknown): void {+ const pending = this.pending.get(id);+ if (!pending || pending.kind !== "call") return;+ this.pending.delete(id);+ if (pending.timer) clearTimeout(pending.timer);+ if (ok) pending.resolve(value);+ else pending.reject(value instanceof Error ? value : new Error(String(value)));+ }++ private handleRequest(id: JsonRpcId, method: string, params: unknown): void {+ if (method !== "session/request_permission") {+ this.write({+ jsonrpc: "2.0",+ id,+ error: { code: -32601, message: "Unsupported Antigravity ACP client request" },+ });+ this.diagnostic("warning", `Unsupported Antigravity ACP client request: ${safeLabel(method)}`);+ return;+ }+ const payload = record(params);+ const sameSession = payload?.sessionId === this.sessionId;+ const options = Array.isArray(payload?.options) ? payload.options.map(record).filter(Boolean) as JsonRecord[] : [];+ const allowOnce = options.find((option) => (+ option.kind === "allow_once"+ && typeof option.optionId === "string"+ && option.optionId.trim().length > 0+ ));+ if (!this.ready || this.cancelling || this.currentPromptRequestId === null || !sameSession || !allowOnce) {+ this.write({ jsonrpc: "2.0", id, result: { outcome: { outcome: "cancelled" } } });+ this.diagnostic("error", "Antigravity ACP permission request was not allowed for the active prompt");+ return;+ }+ this.write({+ jsonrpc: "2.0",+ id,+ result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } },+ });+ }++ private handleNotification(method: string, params: unknown): void {+ if (method === "session/update") {+ this.handleSessionUpdate(params);+ return;+ }+ this.diagnostic("warning", `Unsupported Antigravity ACP notification: ${safeLabel(method)}`);+ }++ private handleSessionUpdate(params: unknown): void {+ const payload = record(params);+ if (!payload || payload.sessionId !== this.sessionId) {+ this.diagnostic("warning", "Antigravity ACP emitted an update for a different session");+ return;+ }+ const configuration = record(payload.update);+ if (configuration?.sessionUpdate === "config_option_update") {+ this.catalog = parseAntigravityCatalog(configuration) ?? this.catalog;+ return;+ }+ if (!this.ready || this.currentPromptRequestId === null) {+ this.diagnostic("warning", "Antigravity ACP emitted a session update without an active prompt");+ return;+ }+ const update = record(payload.update) ?? {};+ const updateType = update?.sessionUpdate;+ switch (updateType) {+ case "agent_message_chunk": {+ const content = record(update.content);+ if (content?.type === "text" && typeof content.text === "string") {+ this.events.emit("runtime_event", { kind: "assistant_message_delta", text: content.text } satisfies AdapterEvent);+ }+ return;+ }+ case "agent_thought_chunk": {+ const content = record(update.content);+ if (content?.type === "text" && typeof content.text === "string") {+ this.events.emit("runtime_event", { kind: "assistant_reasoning_delta", text: content.text } satisfies AdapterEvent);+ }+ return;+ }+ case "user_message_chunk":+ case "usage_update":+ return;+ case "tool_call": {+ if (typeof update.toolCallId !== "string" || typeof update.title !== "string") {+ this.diagnostic("warning", "Antigravity ACP emitted a malformed tool_call update");+ return;+ }+ if (this.seenToolCalls.has(update.toolCallId)) return;+ this.seenToolCalls.add(update.toolCallId);+ this.openToolCalls.add(update.toolCallId);+ this.events.emit("runtime_event", {+ kind: "tool_call",+ callId: update.toolCallId,+ name: update.title,+ input: update.rawInput,+ } satisfies AdapterEvent);+ if (update.status === "completed" || update.status === "failed") {+ this.openToolCalls.delete(update.toolCallId);+ this.events.emit("runtime_event", {+ kind: "tool_output", callId: update.toolCallId, name: update.title,+ } satisfies AdapterEvent);+ }+ return;+ }+ case "tool_call_update": {+ if (+ typeof update.toolCallId === "string"+ && (update.status === "completed" || update.status === "failed")+ && this.openToolCalls.delete(update.toolCallId)+ ) {+ this.events.emit("runtime_event", {+ kind: "tool_output",+ callId: update.toolCallId,+ name: typeof update.title === "string" ? update.title : "Antigravity tool",+ } satisfies AdapterEvent);+ }+ return;+ }+ case "plan":+ this.events.emit("runtime_event", {+ kind: "internal_progress",+ source: "antigravity.acp",+ itemType: "plan",+ } satisfies AdapterEvent);+ return;+ default:+ this.diagnostic("warning", `Unsupported Antigravity ACP session update: ${safeLabel(updateType)}`);+ }+ }++ private diagnostic(severity: "error" | "warning", message: string): void {+ this.events.emit("runtime_event", {+ kind: "runtime_diagnostic",+ severity,+ source: "antigravity.acp",+ message,+ } satisfies AdapterEvent);+ }++ private protocolFailure(message: string): void {+ const error = new Error(message);+ this.rejectAllPending(error);+ this.events.emit("error", error);+ void this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});+ }++ private rejectAllPending(error: Error): void {+ for (const [id, pending] of [...this.pending]) {+ this.pending.delete(id);+ if (pending.kind === "call") {+ if (pending.timer) clearTimeout(pending.timer);+ pending.reject(error);+ }+ }+ }++ private isClosed(): boolean {+ return this.process ? this.process.exitCode !== null || this.process.signalCode !== null : false;+ }+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/catalog.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/catalog.test.tsnew file mode 100644index 000000000..8884ebd43--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/catalog.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";+import { antigravityModelForEffort, antigravityReasoningCatalog, parseAntigravityCatalog } from "./catalog.js";++describe("Antigravity native model variants", () => {+ it("preserves returned choices and maps effort only to offered siblings", () => {+ const models = ["gemini-3.8-flash-high", "gemini-3.8-flash-low", "gemini-3.1-pro-low", "other-high"];+ const catalog = parseAntigravityCatalog({ models: { currentModelId: models[0], availableModels: models.map((modelId) => ({ modelId, name: modelId })) } })!;+ const publicCatalog = antigravityReasoningCatalog(catalog);+ expect(publicCatalog.defaultModelId).toBe(models[0]);+ expect(publicCatalog.models[0]?.supportedReasoningEfforts).toEqual([{ value: "high" }, { value: "low" }]);+ expect(publicCatalog.models[3]?.supportedReasoningEfforts).toEqual([]);+ expect(antigravityModelForEffort(catalog, models[0]!, "low")).toBe(models[1]);+ expect(antigravityModelForEffort(catalog, models[2]!, "high")).toBeUndefined();+ expect(antigravityModelForEffort(catalog, "other-high", "high")).toBeUndefined();+ expect(antigravityModelForEffort(catalog, models[0]!)).toBe(models[0]);+ });++ it("prefers config options, flattens groups, deduplicates and bounds metadata", () => {+ expect(parseAntigravityCatalog({ models: { availableModels: [{ modelId: "stale" }] }, configOptions: [{+ id: "native-model", category: "model", type: "select", currentValue: "actual",+ options: [{ group: "g", options: [{ value: "actual", name: "Actual" }, { value: "actual" }, { value: "invalid model" }] }],+ }] })).toEqual({ configId: "native-model", currentModelId: "actual", models: [{ id: "actual", displayName: "Actual" }] });+ expect(parseAntigravityCatalog({ models: { availableModels: Array.from({ length: 513 }, (_, i) => ({ modelId: `model-${i}` })) } })).toBeUndefined();+ expect(parseAntigravityCatalog(null)).toBeUndefined();+ });+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/catalog.ts b/src/daemon/agent-driver/src/adapters/antigravity/catalog.tsnew file mode 100644index 000000000..f79e3c247--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/catalog.ts@@ -0,0 +1,75 @@+import type { RuntimeReasoningCatalog } from "../../contract.js";+import { normalizeRuntimeModelId, RUNTIME_MODEL_CATALOG_MAX } from "../../internal/modelCatalog.js";+import { asRecord } from "../../internal/utils.js";++export type AntigravityModel = { id: string; displayName?: string };+export type AntigravityCatalog = { models: AntigravityModel[]; currentModelId?: string; configId?: string };++function choices(value: unknown): AntigravityModel[] {+ if (!Array.isArray(value) || value.length > RUNTIME_MODEL_CATALOG_MAX) return [];+ const rows: AntigravityModel[] = [];+ for (const item of value) {+ const row = asRecord(item);+ if (!row) continue;+ const nested = Array.isArray(row.options) ? row.options : [row];+ if (nested.length + rows.length > RUNTIME_MODEL_CATALOG_MAX) return [];+ for (const child of nested) {+ const option = asRecord(child);+ const id = normalizeRuntimeModelId(option?.value ?? option?.modelId);+ if (!id) continue;+ const name = option?.name;+ rows.push({ id, ...(typeof name === "string" && name.length <= 256 ? { displayName: name } : {}) });+ }+ }+ return rows.filter((row, index) => rows.findIndex((other) => other.id === row.id) === index);+}++export function parseAntigravityCatalog(value: unknown): AntigravityCatalog | undefined {+ const session = asRecord(value);+ const config = Array.isArray(session?.configOptions) ? session.configOptions.map(asRecord).find(+ (option) => option?.type === "select" && (option.category === "model" || option.id === "model"),+ ) : undefined;+ const legacy = asRecord(session?.models);+ const models = choices(config ? config.options : legacy?.availableModels);+ if (!models.length) return undefined;+ const current = normalizeRuntimeModelId(config ? config.currentValue : legacy?.currentModelId);+ const configId = normalizeRuntimeModelId(config?.id);+ return {+ models,+ ...(current && models.some((model) => model.id === current) ? { currentModelId: current } : {}),+ ...(configId ? { configId } : {}),+ };+}++function variant(id: string): { family: string; effort: string } | undefined {+ const match = /^(gemini-[a-z0-9.-]+)-(high|medium|low)$/.exec(id);+ return match ? { family: match[1]!, effort: match[2]! } : undefined;+}++export function antigravityReasoningCatalog(catalog: AntigravityCatalog): RuntimeReasoningCatalog {+ return {+ updateMode: "live_next_turn",+ ...(catalog.currentModelId ? { defaultModelId: catalog.currentModelId } : {}),+ models: catalog.models.map((model) => {+ const selected = variant(model.id);+ const efforts = selected ? catalog.models.flatMap((candidate) => {+ const other = variant(candidate.id);+ return other?.family === selected.family ? [{ value: other.effort }] : [];+ }) : [];+ return { ...model, supportedReasoningEfforts: efforts,+ ...(selected ? { defaultReasoningEffort: selected.effort } : {}),+ };+ }),+ };+}++export function antigravityModelForEffort(catalog: AntigravityCatalog, modelId: string, effort?: string): string | undefined {+ if (!catalog.models.some((model) => model.id === modelId)) return undefined;+ if (!effort) return modelId;+ const selected = variant(modelId);+ if (!selected) return undefined;+ return catalog.models.find((candidate) => {+ const other = variant(candidate.id);+ return other?.family === selected.family && other.effort === effort;+ })?.id;+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/index.test.tsnew file mode 100644index 000000000..09e4e0c24--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts@@ -0,0 +1,385 @@+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AdapterEvent, SpawnedProcessHandle } from "../../internal/adapter.js";+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+import * as probeModule from "./probe.js";+import { AntigravityDriver } from "./index.js";+import { AntigravityAcpLane } from "./acp-lane.js";+import { antigravitySpawnSpec, probeAntigravity } from "./probe.js";++type Message = { id: number; method?: string; params?: Record<string, unknown>; result?: unknown; error?: unknown };+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function setup(options: { authError?: boolean; loadId?: string; loadError?: boolean; incompatible?: boolean; catalog?: unknown; rejectConfig?: boolean; usageReader?: { read: () => Promise<{ samples: { usage: { input: number | null; output: number | null; cache: number | null }; identity: { source: string; index: number; occurredAt: string } }[]; complete: boolean }> } } = {}) {+ const directory = mkdtempSync(join(tmpdir(), "alook-antigravity-test-"));+ dirs.push(directory);+ const proc = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(), stderr: new PassThrough(), stdin: new PassThrough(),+ exitCode: null as number | null, signalCode: null as NodeJS.Signals | null,+ kill: vi.fn((signal: NodeJS.Signals = "SIGTERM") => { proc.signalCode = signal; proc.emit("exit", null, signal); return true; }),+ });+ const messages: Message[] = [];+ const emit = (value: unknown) => proc.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...value as object })}\n`);+ proc.stdin.on("data", (chunk) => {+ for (const line of chunk.toString().trim().split("\n")) {+ const message = JSON.parse(line) as Message;+ messages.push(message);+ if (message.method === "initialize") emit({ id: message.id, result: {+ protocolVersion: 1, agentInfo: { name: "antigravity-acp", version: "1.3.0" },+ agentCapabilities: { loadSession: !options.incompatible },+ } });+ if (message.method === "session/new" || message.method === "session/load") {+ if (options.authError) emit({ id: message.id, error: { code: -32000, message: "Authentication required" } });+ else if (options.loadError) emit({ id: message.id, error: { code: -32000, message: "Session not found" } });+ else emit({ id: message.id, result: {+ sessionId: options.loadId ?? "native-session", models: { availableModels: [{ modelId: "test-model" }] }, ...options.catalog as object,+ } });+ }+ if (message.method === "session/set_config_option") {+ const configOptions = (options.catalog as { configOptions: Record<string, unknown>[] }).configOptions.map((option) => ({ ...option, currentValue: message.params?.value }));+ emit(options.rejectConfig ? { id: message.id, error: { code: -32602, message: "rejected" } } : { id: message.id, result: { configOptions } });+ }+ if (message.method === "session/set_model") emit({ id: message.id, result: {} });+ }+ });+ const ctx = fakeLaunchContext("antigravity", directory, {+ standingPrompt: "standing-instruction-only-marker", config: { runtimeConfig: { model: { kind: "default" } } },+ });+ const spawn = vi.fn(async () => ({ process: proc as SpawnedProcessHandle }));+ const lane = new AntigravityAcpLane({ spawn }, ctx, { handshakeTimeoutMs: 100, usageReader: options.usageReader });+ const events: AdapterEvent[] = [];+ lane.on("runtime_event", (event) => events.push(event));+ lane.on("error", () => {});+ const prompts = () => messages.filter((message) => message.method === "session/prompt");+ const update = (update: unknown, sessionId = "native-session") => emit({ method: "session/update", params: { sessionId, update } });+ return { directory, ctx, proc, messages, spawn, lane, events, emit, prompts, update };+}++describe("Antigravity native ACP", () => {+ it("reuses one process and exact session across prompts, delivering current instructions once", async () => {+ const h = setup();+ await expect(h.lane.start({ text: "first" })).resolves.toMatchObject({ ok: true, acceptedAs: "prompt" });+ expect(h.prompts()[0]?.params).toMatchObject({ sessionId: "native-session", prompt: [{ type: "text", text: "standing-instruction-only-marker\n\nfirst" }] });+ await expect(h.lane.send({ text: "busy", mode: "busy" })).resolves.toMatchObject({ ok: false, reason: "runtime_busy" });+ expect(h.prompts()).toHaveLength(1);+ h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "end_turn" } });+ await expect(h.lane.send({ text: "second", mode: "idle" })).resolves.toMatchObject({ ok: true });+ expect(h.spawn).toHaveBeenCalledTimes(1);+ expect(h.messages.filter((message) => message.method === "session/new")).toHaveLength(1);+ expect(h.prompts()[1]?.params).toEqual({ sessionId: "native-session", prompt: [{ type: "text", text: "second" }] });+ await h.lane.stop();+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ await h.lane.stop();+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it("loads only the requested session and refuses a substituted or missing session", async () => {+ for (const options of [{ loadId: "saved" }, { loadId: "other" }, { loadError: true }]) {+ const h = setup(options);+ const result = await h.lane.start({ text: "resume", sessionId: "saved" });+ expect(result).toMatchObject(options.loadId === "saved" ? { ok: true } : { ok: false, reason: "reset_required" });+ expect(h.messages.find((message) => message.method === "session/load")?.params).toMatchObject({ sessionId: "saved" });+ expect(h.messages.some((message) => message.method === "session/new")).toBe(false);+ await h.lane.stop();+ }+ });++ it.each([+ [{ authError: true }, "authentication"], [{ incompatible: true }, "incompatible_configuration"],+ ] as const)("rejects startup and cleans up for %j", async (options, reason) => {+ const h = setup(options);+ await expect(h.lane.start({ text: "first" })).resolves.toMatchObject({ ok: false, reason });+ expect(h.prompts()).toHaveLength(0);+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it("only the matching root RPC response ends a turn; updates and old terminals cannot", async () => {+ const h = setup();+ await h.lane.start({ text: "first" });+ const first = h.prompts()[0]!.id;+ h.emit({ id: 999, result: { stopReason: "end_turn" } });+ h.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "wrong" } }, "child-session");+ expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(0);+ h.emit({ id: first, result: { stopReason: "end_turn" } });+ await h.lane.send({ text: "second", mode: "idle" });+ h.emit({ id: first, result: { stopReason: "end_turn" } });+ expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(1);+ h.emit({ id: h.prompts()[1]!.id, result: { stopReason: "end_turn" } });+ expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(2);+ expect(h.events.some((event) => event.kind === "assistant_message_delta" && event.text === "wrong")).toBe(false);+ await h.lane.stop();+ });++ it("tracks tool ownership and permits only the active session's allow-once requests", async () => {+ const h = setup();+ await h.lane.start({ text: "run pwd" });+ h.update({ sessionUpdate: "tool_call", toolCallId: "tool-1", title: "shell", rawInput: { command: "pwd" } });+ h.update({ sessionUpdate: "tool_call_update", toolCallId: "tool-1", status: "completed" });+ h.update({ sessionUpdate: "tool_call_update", toolCallId: "tool-1", status: "completed" });+ expect(h.events.filter((event) => event.kind === "tool_call")).toMatchObject([{ callId: "tool-1" }]);+ expect(h.events.filter((event) => event.kind === "tool_output")).toMatchObject([{ callId: "tool-1" }]);+ for (const sessionId of ["native-session", "other"]) {+ h.emit({ id: 999, method: "session/request_permission", params: {+ sessionId, options: [{ kind: "allow_once", optionId: "once" }],+ } });+ expect(h.messages.at(-1)?.result).toEqual({ outcome: sessionId === "native-session"+ ? { outcome: "selected", optionId: "once" } : { outcome: "cancelled" } });+ }+ await h.lane.interrupt({});+ expect(h.messages.at(-1)).toMatchObject({ method: "session/cancel", params: { sessionId: "native-session" } });+ await h.lane.stop();+ });++ it("denies permissions after cancel but waits for the matching terminal and permits the next turn", async () => {+ const h = setup();+ await h.lane.start({ text: "first" });+ await h.lane.interrupt({});+ const request = { id: 900, method: "session/request_permission", params: {+ sessionId: "native-session", options: [{ kind: "allow_once", optionId: "once" }],+ } };+ h.emit(request);+ expect(h.messages.at(-1)?.result).toEqual({ outcome: { outcome: "cancelled" } });+ expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(0);+ await expect(h.lane.send({ text: "early", mode: "idle" })).resolves.toMatchObject({ ok: false, reason: "runtime_busy" });+ h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "cancelled" } });+ expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(1);+ await h.lane.send({ text: "second", mode: "idle" });+ h.emit(request);+ expect(h.messages.at(-1)?.result).toEqual({ outcome: { outcome: "selected", optionId: "once" } });+ await h.lane.stop();+ });++ it.each(["completed", "failed"])("settles an initially %s tool once, including repeated updates", async (status) => {+ const h = setup();+ await h.lane.start({ text: "first" });+ const call = { sessionUpdate: "tool_call", toolCallId: "already-done", title: "read", status };+ h.update(call);+ h.update(call);+ h.update({ sessionUpdate: "tool_call_update", toolCallId: "already-done", status });+ expect(h.events.filter((event) => event.kind === "tool_call")).toMatchObject([{ callId: "already-done" }]);+ expect(h.events.filter((event) => event.kind === "tool_output")).toMatchObject([{ callId: "already-done" }]);+ await h.lane.stop();+ });++ it("sets an advertised model and rejects an unknown model before prompting", async () => {+ for (const name of ["test-model", "missing"]) {+ const h = setup();+ h.ctx.config.runtimeConfig = { model: { kind: "named", name } };+ const result = await h.lane.start({ text: "hello" });+ expect(result).toMatchObject(name === "test-model" ? { ok: true } : { ok: false, reason: "incompatible_configuration" });+ expect(h.messages.some((message) => message.method === "session/set_model")).toBe(name === "test-model");+ await h.lane.stop();+ }+ });++ it("stops on malformed protocol and refuses later input", async () => {+ const h = setup();+ await h.lane.start({ text: "first" });+ h.proc.stdout.write("not json\n");+ await vi.waitFor(() => expect(h.proc.kill).toHaveBeenCalled());+ await expect(h.lane.send({ text: "later", mode: "idle" })).resolves.toMatchObject({ ok: false, reason: "closed" });+ });++ it("probes the native catalog without prompting or launching interactive auth", async () => {+ const h = setup();+ const cleanup = vi.fn(async () => { h.proc.kill(); });+ expect(await probeAntigravity("/custom/agy_acp_server.par", { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup })).toMatchObject({ status: "healthy", version: "1.3.0", reasoning: { models: [{ id: "test-model" }] } });+ expect(h.messages.map((message) => message.method)).toEqual(["initialize", "session/new"]);+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it.each([+ ["silent", "antigravity_acp_timeout"],+ ["invalid", "antigravity_acp_invalid_json"],+ ["oversized", "antigravity_acp_output_limit"],+ ["foreign", "antigravity_acp_incompatible"],+ ["exit", "antigravity_acp_process_exited"],+ ])("bounds and cleans failed %s probes", async (scenario, lastError) => {+ const h = setup();+ h.proc.stdin.removeAllListeners("data");+ h.proc.stdin.on("data", () => {+ if (scenario === "invalid") h.proc.stdout.write("invalid\n");+ if (scenario === "oversized") h.proc.stdout.write("x".repeat(1024 * 1024 + 1));+ if (scenario === "foreign") h.emit({ id: 1, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, agentInfo: { name: "wrapper" } } });+ if (scenario === "exit") h.proc.emit("exit", 1, null);+ });+ const cleanup = vi.fn(async () => { h.proc.kill(); });+ await expect(probeAntigravity(undefined, { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup, timeoutMs: 10 }))+ .resolves.toEqual({ status: "unhealthy", lastError });+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it("reports a missing executable and cleanup failures without claiming health", async () => {+ await expect(probeAntigravity(undefined, { cacheDirectory: setup().directory, spawn: (() => { throw new Error("ENOENT"); }) as never }))+ .resolves.toMatchObject({ status: "unhealthy", lastError: "antigravity_acp_spawn_failed" });+ const h = setup();+ await expect(probeAntigravity(undefined, { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup: async () => { throw new Error("cleanup"); } }))+ .resolves.toMatchObject({ status: "unhealthy", lastError: "antigravity_acp_cleanup_failed" });+ });++ it("keeps unauthenticated discovery noninteractive without inventing a catalog", async () => {+ const h = setup({ authError: true });+ expect(await probeAntigravity(undefined, { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup: async () => { h.proc.kill(); } }))+ .toEqual({ status: "healthy", version: "1.3.0" });+ expect(h.messages.map((message) => message.method)).toEqual(["initialize", "session/new"]);+ });++ it("selects offered effort variants before prompt and updates them on the same idle session", async () => {+ const configOptions = [{ id: "model", category: "model", type: "select", currentValue: "gemini-3.8-flash-high",+ options: ["high", "low"].map((effort) => ({ value: `gemini-3.8-flash-${effort}`, name: effort })),+ }];+ const h = setup({ catalog: { configOptions } });+ h.ctx.config.runtimeConfig = { model: { kind: "default" }, reasoningEffort: "low" };+ expect(await h.lane.start({ text: "first" })).toMatchObject({ ok: true });+ const setters = () => h.messages.filter((message) => message.method === "session/set_config_option");+ expect(setters()[0]?.params?.value).toBe("gemini-3.8-flash-low");+ expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toMatchObject({ status: "failed" });+ h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "end_turn" } });+ expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toEqual({ status: "applied" });+ expect(setters().at(-1)?.params?.value).toBe("gemini-3.8-flash-high");+ expect(await h.lane.updateSettings({ reasoningEffort: "ultra" })).toMatchObject({ status: "failed" });+ expect(await h.lane.updateSettings({ reasoningEffort: null })).toEqual({ status: "applied" });+ expect(h.spawn).toHaveBeenCalledTimes(1);+ expect(h.messages.filter((message) => message.method === "session/new")).toHaveLength(1);+ await h.lane.stop();+ });++ it("does not report successful settings after native rejection", async () => {+ const h = setup({ rejectConfig: true, catalog: { configOptions: [{ id: "model", category: "model", type: "select", currentValue: "gemini-3.8-flash-high", options: [{ value: "gemini-3.8-flash-high" }] }] } });+ expect(await h.lane.start({ text: "first" })).toMatchObject({ ok: true });+ h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "end_turn" } });+ expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toMatchObject({ status: "failed" });+ await h.lane.stop();+ });++ it("rejects a configured launch when the native session offers no catalog", async () => {+ const h = setup({ catalog: { models: undefined } });+ h.ctx.config.runtimeConfig = { model: { kind: "default" }, reasoningEffort: "low" };+ expect(await h.lane.start({ text: "first" })).toMatchObject({ ok: false, reason: "incompatible_configuration" });+ expect(h.prompts()).toEqual([]);+ expect(h.messages.some((message) => message.method?.startsWith("session/set_"))).toBe(false);+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it("keeps native defaults usable but rejects idle effort updates without a catalog", async () => {+ const h = setup({ catalog: { models: undefined } });+ expect(await h.lane.start({ text: "first" })).toMatchObject({ ok: true });+ h.emit({ id: h.prompts()[0]!.id, result: { stopReason: "end_turn" } });+ expect(await h.lane.updateSettings({ reasoningEffort: "low" })).toMatchObject({+ status: "failed", error: { category: "configuration", code: "unsupported_reasoning_effort" },+ });+ expect(h.messages.some((message) => message.method?.startsWith("session/set_"))).toBe(false);+ expect(await h.lane.send({ text: "next", mode: "idle" })).toMatchObject({ ok: true });+ expect(h.spawn).toHaveBeenCalledTimes(1);+ expect(h.prompts()).toHaveLength(2);+ await h.lane.stop();+ });++ it("uses the native server and Linux uid flag, never print mode", () => {+ expect(antigravitySpawnSpec("/custom/native", "linux")).toMatchObject({ command: "/custom/native", args: ["--uid="] });+ expect(antigravitySpawnSpec("/custom/native", "darwin")).toMatchObject({ command: "/custom/native", args: [] });+ });+});++describe("native usage delivery boundary", () => {+ const sample = { usage: { input: 90, output: 24, cache: 23 }, identity: { source: "native:fixture", index: 0, occurredAt: "2026-10-04T08:00:00Z" } };+ it("publishes recoverable identity before the root terminal and contains reader failure", async () => {+ const read = vi.fn().mockResolvedValueOnce({ samples: [sample], complete: true }).mockRejectedValueOnce(new Error("SQLite unavailable"));+ const h = setup({ usageReader: { read } });+ await h.lane.start({ text: "first" });+ h.emit({ id: h.prompts()[0].id, result: { stopReason: "end_turn" } });+ await vi.waitFor(() => expect(h.events.some((event) => event.kind === "turn_end")).toBe(true));+ const usage = h.events.findIndex((event) => event.kind === "telemetry" && event.name === "token_usage");+ expect(h.events[usage]).toMatchObject({ kind: "telemetry", name: "token_usage", ...sample });+ expect(usage).toBeLessThan(h.events.findIndex((event) => event.kind === "turn_end"));+ await h.lane.send({ text: "second", mode: "idle" });+ h.emit({ id: h.prompts()[1].id, error: { code: -32000, message: "provider failure" } });+ await vi.waitFor(() => expect(h.events.filter((event) => event.kind === "turn_end")).toHaveLength(2));+ expect(h.events).toContainEqual(expect.objectContaining({ kind: "telemetry", name: "token_usage_status", source: "antigravity.native", status: "unavailable" }));+ await h.lane.stop();+ });+ it("fences delayed accounting after stop", async () => {+ let deliver!: (value: { samples: [typeof sample]; complete: boolean }) => void;+ const h = setup({ usageReader: { read: () => new Promise((resolve) => { deliver = resolve; }) } });+ await h.lane.start({ text: "first" });+ h.emit({ id: h.prompts()[0].id, result: { stopReason: "end_turn" } });+ await h.lane.stop();+ deliver({ samples: [sample], complete: true });+ await Promise.resolve(); await Promise.resolve();+ expect(h.events.filter((event) => event.kind === "telemetry")).toEqual([]);+ });+});++describe("catalog probe persistence", () => {+ it("loads its isolated cached session on repeat discovery without creating another native session", async () => {+ const first = setup();+ await probeAntigravity(undefined, { cacheDirectory: first.directory, spawn: (() => first.proc) as never, cleanup: async () => { first.proc.kill(); } });+ expect(readFileSync(join(first.directory, "session"), "utf8")).toBe("native-session");+ const second = setup();+ await probeAntigravity(undefined, { cacheDirectory: first.directory, spawn: (() => second.proc) as never, cleanup: async () => { second.proc.kill(); } });+ expect(second.messages.map((message) => message.method)).toEqual(["initialize", "session/load"]);+ expect(second.messages[1].params?.cwd).toBe(first.directory);+ });+ it("recreates only missing cached sessions and does not retry auth rejection as session creation", async () => {+ const h = setup(); writeFileSync(join(h.directory, "session"), "missing-session");+ h.proc.stdin.prependListener("data", (chunk) => {+ const input = JSON.parse(chunk.toString());+ if (input.method === "session/load") h.emit({ id: input.id, error: { code: -32002, message: "session missing" } });+ });+ await probeAntigravity(undefined, { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup: async () => { h.proc.kill(); } });+ expect(h.messages.filter((message) => message.method === "session/new")).toHaveLength(1);+ const auth = setup({ authError: true }); writeFileSync(join(auth.directory, "session"), "native-session");+ await probeAntigravity(undefined, { cacheDirectory: auth.directory, spawn: (() => auth.proc) as never, cleanup: async () => { auth.proc.kill(); } });+ expect(auth.messages.filter((message) => message.method === "session/new")).toHaveLength(0);+ });+});++describe("probe failure ownership", () => {+ it.each(["closed", "write", "permission", "bad-session", "persist", "storage"])("cleans %s probing without prompts or tool execution", async (fault) => {+ const h = setup(fault === "bad-session" ? { loadId: "../escape" } : {});+ if (fault === "closed") h.proc.stdin.destroy();+ if (fault === "write") vi.spyOn(h.proc.stdin, "write").mockImplementation(() => { throw new Error("write"); });+ if (fault === "storage") mkdirSync(join(h.directory, "session"));+ if (fault === "persist") h.proc.stdin.prependListener("data", (chunk) => { if (JSON.parse(chunk.toString()).method === "session/new") mkdirSync(join(h.directory, "session")); });+ if (fault === "permission") h.proc.stdin.prependListener("data", (chunk) => { if (JSON.parse(chunk.toString()).method === "initialize") h.emit({ method: "session/request_permission", id: "permission", params: {} }); });+ const result = await probeAntigravity(undefined, { cacheDirectory: h.directory, spawn: (() => h.proc) as never });+ expect(result.status).toBe(fault === "permission" ? "healthy" : "unhealthy");+ if (fault === "permission") expect(h.messages).toContainEqual(expect.objectContaining({ id: "permission", result: { outcome: { outcome: "cancelled" } } }));+ expect(h.prompts()).toEqual([]);+ });+});++it("keeps incomplete accounting unavailable until its bounded backlog drains", async () => {+ const h = setup({ usageReader: { read: vi.fn().mockResolvedValueOnce({ samples: [], complete: false }).mockResolvedValueOnce({ samples: [], complete: true }) } });+ await h.lane.start({ text: "first" }); h.emit({ id: h.prompts()[0].id, result: { stopReason: "end_turn" } });+ await vi.waitFor(() => expect(h.events.some((event) => event.kind === "turn_end")).toBe(true));+ expect(h.events.filter((event) => event.kind === "telemetry")).toEqual([{ kind: "telemetry", name: "token_usage_status", source: "antigravity.native", status: "available" }]);+ await h.lane.stop();+});++it("opens its native persistent lane without eager spawn", async () => {+ const lane = await new AntigravityDriver().openLane(setup().ctx);+ expect(lane.currentSessionId).toBeNull();+ await lane.stop();+});++it("does not claim complete accounting after exhausting its scan budget", async () => {+ const read = vi.fn().mockResolvedValue({ samples: [], complete: false });+ const h = setup({ usageReader: { read } });+ await h.lane.start({ text: "first" }); h.emit({ id: h.prompts()[0].id, result: { stopReason: "end_turn" } });+ await vi.waitFor(() => expect(h.events.some((event) => event.kind === "turn_end")).toBe(true));+ expect(read).toHaveBeenCalledTimes(16);+ expect(h.events).toContainEqual({ kind: "telemetry", name: "token_usage_status", source: "antigravity.native", status: "unavailable" });+ await h.lane.stop();+});++it("delegates driver discovery to the noninteractive native probe", async () => {+ const probe = vi.spyOn(probeModule, "probeAntigravity").mockResolvedValue({ status: "healthy", version: "fixture" });+ try { expect(await new AntigravityDriver().probe("fixture-native")).toEqual({ status: "healthy", version: "fixture" }); expect(probe).toHaveBeenCalledWith("fixture-native"); }+ finally { probe.mockRestore(); }+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/index.ts b/src/daemon/agent-driver/src/adapters/antigravity/index.tsnew file mode 100644index 000000000..d28f28a4b--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/index.ts@@ -0,0 +1,34 @@+import type { AdapterLaunchContext, BackendAdapter, RuntimeLaneOpenOptions, SpawnedProcess } from "../../internal/adapter.js";+import { prepareCliTransport } from "../../internal/cliTransport.js";+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";+import { spawnAgentProcess } from "../../internal/killTree.js";+import { nativeUsageHome } from "./usage.js";+import { AntigravityAcpLane } from "./acp-lane.js";+import { antigravitySpawnSpec, probeAntigravity } from "./probe.js";++export class AntigravityDriver implements BackendAdapter {+ readonly id = "antigravity";+ readonly instructionDelivery = { kind: "native" } as const;+ readonly execution = {+ lifetime: "session",+ transport: { kind: "stdio_rpc", protocol: "antigravity.acp.v1" },+ wakeStart: "immediate",+ terminalOwnership: "transport_request",+ } as const;++ probe(command?: string) {+ return probeAntigravity(command);+ }++ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions) {+ return new AntigravityAcpLane(this, ctx, { onRawStdoutLine: options?.onRawStdoutLine });+ }++ async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess & { usageHome: string }> {+ const { spawnEnv } = await prepareCliTransport(ctx);+ const spec = antigravitySpawnSpec(resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command);+ return { usageHome: nativeUsageHome(spawnEnv, ctx.workingDirectory), process: spawnAgentProcess(spec.command, spec.args, {+ cwd: ctx.workingDirectory, env: spawnEnv, shell: spec.shell,+ }) };+ }+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/lane-errors.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/lane-errors.test.tsnew file mode 100644index 000000000..d54aea350--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/lane-errors.test.ts@@ -0,0 +1,171 @@+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import { describe, expect, it, vi } from "vitest";+import type { AdapterEvent, SpawnedProcessHandle } from "../../internal/adapter.js";+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+import { AntigravityAcpLane } from "./acp-lane.js";++type Rpc = Record<string, unknown>;+function harness(handler?: (request: Rpc, send: (value: Rpc) => void) => boolean) {+ const proc = Object.assign(new EventEmitter(), {+ stdin: new PassThrough(), stdout: new PassThrough(), stderr: new PassThrough(),+ exitCode: null as number | null, signalCode: null as NodeJS.Signals | null,+ kill: vi.fn(() => { proc.signalCode = "SIGTERM"; proc.emit("exit", null, "SIGTERM"); return true; }),+ });+ const requests: Rpc[] = [];+ const send = (value: Rpc) => { proc.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...value })}\n`); };+ proc.stdin.on("data", (chunk) => {+ for (const line of chunk.toString().trim().split("\n")) {+ const request = JSON.parse(line) as Rpc;+ requests.push(request);+ if (handler?.(request, send)) continue;+ if (request.method === "initialize") send({ id: request.id, result: { protocolVersion: 1, agentInfo: { name: "antigravity-acp" }, agentCapabilities: { loadSession: true } } });+ if (request.method === "session/new" || request.method === "session/load") send({ id: request.id, result: { sessionId: "native" } });+ }+ });+ const ctx = fakeLaunchContext("antigravity", "/tmp", { config: { runtimeConfig: { model: { kind: "default" } } } });+ const factory = { spawn: vi.fn(async () => ({ process: proc as SpawnedProcessHandle })) };+ const lane = new AntigravityAcpLane(factory, ctx, { handshakeTimeoutMs: 15, onRawStdoutLine: () => { throw new Error("observer"); } });+ const events: AdapterEvent[] = [];+ lane.on("runtime_event", (event) => events.push(event));+ lane.on("error", () => {});+ const update = (value: Rpc) => send({ method: "session/update", params: { sessionId: "native", update: value } });+ const prompt = () => requests.filter((request) => request.method === "session/prompt").at(-1)!;+ return { proc, requests, send, ctx, factory, lane, events, update, prompt };+}++describe("Antigravity transport and lifecycle faults", () => {+ it.each([null, {}, { sessionId: "" }, { sessionId: 5 }])("rejects invalid session response %j", async (result) => {+ const h = harness((r, send) => { if (r.method !== "session/new") return false; send({ id: r.id, result }); return true; });+ await expect(h.lane.start({ text: "first" })).rejects.toThrow();+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it.each([{ protocolVersion: 2 }, { protocolVersion: 1, agentInfo: { name: "foreign" } }])("rejects incompatible handshake %j", async (result) => {+ const h = harness((r, send) => { if (r.method !== "initialize") return false; send({ id: r.id, result }); return true; });+ expect(await h.lane.start({ text: "first" })).toMatchObject({ ok: false, reason: "incompatible_configuration" });+ });++ it.each(["timeout", "missing-result", "rpc-error", "write-error", "closed-stdin"])("releases failed %s startup", async (fault) => {+ const h = harness((r, send) => {+ if (r.method !== "initialize") return false;+ if (fault === "timeout") return true;+ if (fault === "missing-result") { send({ id: r.id }); return true; }+ if (fault === "rpc-error") { send({ id: r.id, error: { data: { message: "detail" } } }); return true; }+ return false;+ });+ if (fault === "write-error") vi.spyOn(h.proc.stdin, "write").mockImplementation(() => { throw new Error("write"); });+ if (fault === "closed-stdin") h.proc.stdin.destroy();+ await expect(h.lane.start({ text: "first" })).rejects.toThrow();+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it.each(["stop", "error", "exit"])("fences %s racing the final handshake", async (fault) => {+ const h = harness((r, send) => {+ if (r.method !== "session/new") return false;+ send({ id: r.id, result: { sessionId: "native" } });+ if (fault === "stop") void h.lane.stop();+ if (fault === "error") h.proc.emit("error", new Error("startup"));+ if (fault === "exit") { h.proc.exitCode = 1; h.proc.emit("exit", 1, null); }+ return true;+ });+ await expect(h.lane.start({ text: "first" })).rejects.toThrow();+ expect(h.requests.some((r) => r.method === "session/prompt")).toBe(false);+ });++ it("preserves a stop issued before spawn resolves", async () => {+ const h = harness();+ let release!: () => void;+ h.factory.spawn.mockImplementation(async () => { await new Promise<void>((resolve) => { release = resolve; }); return { process: h.proc as SpawnedProcessHandle }; });+ const start = h.lane.start({ text: "first" });+ const stopped = h.lane.stop();+ release();+ await expect(start).rejects.toThrow("cancelled");+ await stopped;+ expect(h.requests).toHaveLength(0);+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+ });++ it("preserves resume identity without an echoed id and rejects unrelated load failures", async () => {+ for (const failure of [false, true]) {+ const h = harness((r, send) => { if (r.method !== "session/load") return false; send(failure ? { id: r.id, error: { code: -32603, message: "network" } } : { id: r.id, result: {} }); return true; });+ if (failure) await expect(h.lane.start({ text: "resume", sessionId: "saved" })).rejects.toThrow("network");+ else { expect(await h.lane.start({ text: "resume", sessionId: "saved" })).toMatchObject({ ok: true }); expect(h.lane.currentSessionId).toBe("saved"); }+ await h.lane.stop();+ }+ });++ it("rolls back failed prompt/cancel writes and still admits the next valid turn", async () => {+ const h = harness();+ expect(await h.lane.interrupt({})).toBe(false);+ expect(await h.lane.send({ text: "early", mode: "idle" })).toMatchObject({ ok: false });+ expect(await h.lane.updateSettings({ reasoningEffort: "high" })).toMatchObject({ status: "failed" });+ await h.lane.start({ text: "first" });+ expect(await h.lane.start({ text: "duplicate" })).toMatchObject({ ok: false });+ const write = vi.spyOn(h.proc.stdin, "write").mockImplementationOnce(() => { throw new Error("cancel write"); });+ await expect(h.lane.interrupt({})).rejects.toThrow("cancel write");+ write.mockRestore();+ h.send({ id: h.prompt().id, result: { stopReason: "end_turn" } });+ const broken = vi.spyOn(h.proc.stdin, "write").mockImplementationOnce(() => { throw new Error("prompt write"); });+ await expect(h.lane.send({ text: "second", mode: "idle" })).rejects.toThrow("prompt write");+ broken.mockRestore();+ expect(await h.lane.send({ text: "retry", mode: "idle" })).toMatchObject({ ok: true });+ await h.lane.stop();+ });++ it.each(["oversized", "wrong-version", "no-method", "unwritable-reply"])("closes malformed %s transport", async (fault) => {+ const h = harness();+ await h.lane.start({ text: "first" });+ if (fault === "oversized") h.proc.stdout.write("x".repeat(8 * 1024 * 1024 + 1));+ if (fault === "wrong-version") h.send({ jsonrpc: "1.0" });+ if (fault === "no-method") h.send({});+ if (fault === "unwritable-reply") { h.proc.stdin.destroy(); h.send({ id: 91, method: "unsupported" }); }+ await vi.waitFor(() => expect(h.proc.kill).toHaveBeenCalled());+ });++ it("reports one crash exit and fences later duplicate error/exit", async () => {+ const h = harness();+ const exits = vi.fn();+ const stderr = vi.fn();+ h.lane.on("exit", exits); h.lane.on("stderr", stderr);+ await h.lane.start({ text: "first" });+ h.proc.stderr.write("diagnostic\n");+ h.proc.emit("error", "broken");+ h.proc.emit("error", new Error("duplicate"));+ h.proc.emit("exit", 1, null);+ expect(exits).toHaveBeenCalledTimes(1);+ expect(stderr).toHaveBeenCalledWith("diagnostic");+ await h.lane.stop();+ });++ it("keeps control messages and terminal tools separate from root completion", async () => {+ const h = harness();+ await h.lane.start({ text: "first" });+ h.proc.stdout.write("\n");+ h.send({ id: "unknown", result: {} });+ h.send({ id: 91, method: "unsupported" });+ expect(h.requests.at(-1)).toMatchObject({ id: 91, error: { code: -32601 } });+ h.send({ method: "vendor/unknown" });+ h.update({ sessionUpdate: "unknown" });+ h.update({ sessionUpdate: "tool_call" });+ h.update({ sessionUpdate: "tool_call", toolCallId: "t", title: "shell" });+ h.update({ sessionUpdate: "tool_call_update", toolCallId: "t", status: "completed" });+ h.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "reason" } });+ h.update({ sessionUpdate: "user_message_chunk" });+ h.update({ sessionUpdate: "usage_update", used: 400, size: 1000 });+ h.update({ sessionUpdate: "plan" });+ h.update({ sessionUpdate: "config_option_update", configOptions: [] });+ expect(h.events.filter((e) => e.kind === "telemetry")).toEqual([]);+ h.send({ id: h.prompt().id });+ h.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "late" } });+ expect(h.events.filter((e) => e.kind === "turn_end")).toHaveLength(1);+ expect(h.events.some((e) => e.kind === "assistant_message_delta")).toBe(false);+ await h.lane.stop();+ });+});++it("rejects an in-flight handshake when the owned process fails", async () => {+ const h = harness((request) => { if (request.method === "initialize") { queueMicrotask(() => h.proc.emit("error", new Error("handshake process failure"))); return true; } return false; });+ await expect(h.lane.start({ text: "first" })).rejects.toThrow("handshake process failure");+ expect(h.proc.kill).toHaveBeenCalledTimes(1);+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/local-data.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/local-data.test.tsnew file mode 100644index 000000000..5855eea27--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/local-data.test.ts@@ -0,0 +1,12 @@+import { expect, it } from "vitest";+import { readLocalCommand } from "./local-data.js";++it("bounds local reader output and cleans its exact process after failures", async () => {+ await expect(readLocalCommand(process.execPath, ["-e", "process.stdout.write('x'.repeat(1024));setInterval(()=>{},1000)"], 32)).rejects.toThrow("failed");+ await expect(readLocalCommand(process.execPath, ["-e", "process.exit(1)"])).rejects.toThrow("failed");+ await expect(readLocalCommand("alook-nonexistent-data-reader", [])).rejects.toThrow("failed");+});+it("contains a hung local reader and returns successful output", async () => {+ await expect(readLocalCommand(process.execPath, ["-e", "setInterval(()=>{},1000)"])).rejects.toThrow("timed out");+ await expect(readLocalCommand(process.execPath, ["-e", "process.stdout.write('[]')"])).resolves.toBe("[]");+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/local-data.ts b/src/daemon/agent-driver/src/adapters/antigravity/local-data.tsnew file mode 100644index 000000000..dfd0f6491--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/local-data.ts@@ -0,0 +1,21 @@+import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";++export async function readLocalCommand(command: string, args: string[], limit = 256 * 1024): Promise<string> {+ const child = spawnAgentProcess(command, args, { cwd: process.cwd(), env: process.env, shell: false, stdin: "ignore" });+ try {+ return await new Promise<string>((resolve, reject) => {+ let output = "";+ const timer = setTimeout(() => reject(new Error("Local data read timed out")), 3_000);+ const fail = () => { clearTimeout(timer); reject(new Error("Local data read failed")); };+ child.on("error", fail);+ child.stdout?.on("data", (chunk) => {+ output += chunk.toString();+ if (Buffer.byteLength(output) > limit) fail();+ });+ child.stderr?.on("data", () => {});+ child.on("close", (code) => { clearTimeout(timer); if (code === 0) resolve(output); else fail(); });+ });+ } finally {+ if (child.pid) await killProcessTree(child.pid, { graceMs: 100 });+ }+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/probe.ts b/src/daemon/agent-driver/src/adapters/antigravity/probe.tsnew file mode 100644index 000000000..4c0f57b3a--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/probe.ts@@ -0,0 +1,147 @@+import { createHash, randomUUID } from "node:crypto";+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { parseAntigravityCatalog, antigravityReasoningCatalog } from "./catalog.js";+import type { ProbeResult, SpawnedProcessHandle } from "../../internal/adapter.js";+import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";+import { asRecord } from "../../internal/utils.js";+import { resolveSpawnSpec } from "../../internal/probe.js";++export function antigravitySpawnSpec(command?: string, platform = process.platform): { command: string; args: string[]; shell: boolean } {+ return resolveSpawnSpec(platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par", platform === "linux" ? ["--uid="] : [], command);+}++type ProbeOptions = {+ timeoutMs?: number;+ cacheDirectory?: string;+ spawn?: typeof spawnAgentProcess;+ cleanup?: (proc: SpawnedProcessHandle) => Promise<void>;+};++export async function probeAntigravity(command?: string, options: ProbeOptions = {}): Promise<ProbeResult> {+ const spec = antigravitySpawnSpec(command);+ const identity = createHash("sha256").update(JSON.stringify([spec.command, process.env.GEMINI_HOME ?? ""])).digest("hex").slice(0, 16);+ const directory = options.cacheDirectory ?? join(homedir(), ".cache", "alook", "antigravity-probe", identity);+ const cacheFile = join(directory, "session");+ let cachedSessionId: string | undefined;+ try {+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ try {+ const value = readFileSync(cacheFile, "utf8");+ if (/^[A-Za-z0-9_-]{1,100}$/.test(value)) cachedSessionId = value;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ }+ } catch {+ return { status: "unhealthy", lastError: "antigravity_acp_probe_storage_failed" };+ }+ let proc: SpawnedProcessHandle;+ try {+ proc = (options.spawn ?? spawnAgentProcess)(spec.command, spec.args, {+ cwd: directory, env: { ...process.env, CI: "1" }, shell: spec.shell,+ });+ } catch {+ return { status: "unhealthy", lastError: "antigravity_acp_spawn_failed" };+ }+ return new Promise((resolve) => {+ let settled = false;+ let buffer = "";+ let bytes = 0;+ let version: string | undefined;+ let sessionRequestId = 0;+ let loading = false;+ const finish = (result: ProbeResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ const cleanup = options.cleanup ?? (async (child: SpawnedProcessHandle) => {+ if (child.pid) await killProcessTree(child.pid, { graceMs: 250 });+ else child.kill("SIGTERM");+ });+ void cleanup(proc).then(() => resolve(result), () => resolve({ status: "unhealthy", lastError: "antigravity_acp_cleanup_failed" }));+ };+ const fail = (lastError: string) => finish({ status: "unhealthy", lastError });+ const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? 10_000);+ const write = (value: unknown) => {+ try {+ if (!proc.stdin || proc.stdin.destroyed || proc.stdin.writableEnded || proc.stdin.writable === false) {+ fail("antigravity_acp_stdin_closed");+ return;+ }+ proc.stdin.write(`${JSON.stringify(value)}\n`);+ } catch { fail("antigravity_acp_write_failed"); }+ };+ const requestSession = (sessionId?: string) => {+ loading = sessionId !== undefined;+ sessionRequestId = sessionRequestId ? sessionRequestId + 1 : 2;+ write({ jsonrpc: "2.0", id: sessionRequestId, method: loading ? "session/load" : "session/new", params: {+ cwd: directory, mcpServers: [], ...(sessionId ? { sessionId } : {}),+ } });+ };+ proc.on("error", () => fail("antigravity_acp_spawn_failed"));+ proc.on("exit", () => fail("antigravity_acp_process_exited"));+ proc.stderr?.on("data", () => {});+ proc.stdout?.on("data", (chunk) => {+ if (settled) return;+ const text = chunk.toString();+ bytes += Buffer.byteLength(text);+ if (bytes > 1024 * 1024) return fail("antigravity_acp_output_limit");+ buffer += text;+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (settled) return;+ if (!line.trim()) continue;+ let message: Record<string, unknown> | null;+ try { message = asRecord(JSON.parse(line)); } catch { return fail("antigravity_acp_invalid_json"); }+ if (message?.method) {+ if (message.method === "session/request_permission" && (typeof message.id === "number" || typeof message.id === "string")) {+ write({ jsonrpc: "2.0", id: message.id, result: { outcome: { outcome: "cancelled" } } });+ }+ continue;+ }+ if (sessionRequestId && message?.id === sessionRequestId) {+ if (message.jsonrpc !== "2.0" || (!("result" in message) && !("error" in message))) return fail("antigravity_acp_invalid_json");+ const error = asRecord(message.error);+ if (loading && error && (error.code === -32002 || /session.*(?:not found|missing|unknown)/i.test(String(error.message)))) {+ requestSession();+ continue;+ }+ if (error) {+ finish({ status: "healthy", ...(version ? { version } : {}) });+ continue;+ }+ const result = asRecord(message.result);+ const sessionId = loading ? cachedSessionId : result?.sessionId;+ if (typeof sessionId !== "string" || !/^[A-Za-z0-9_-]{1,100}$/.test(sessionId)+ || (loading && result?.sessionId !== undefined && result.sessionId !== sessionId)) return fail("antigravity_acp_invalid_session");+ if (!loading) {+ try {+ const temporary = `${cacheFile}.${randomUUID()}.tmp`;+ writeFileSync(temporary, sessionId, { mode: 0o600 });+ renameSync(temporary, cacheFile);+ } catch { return fail("antigravity_acp_probe_storage_failed"); }+ }+ const catalog = parseAntigravityCatalog(result);+ finish({ status: "healthy", ...(version ? { version } : {}),+ ...(catalog ? { reasoning: antigravityReasoningCatalog(catalog) } : {}),+ });+ continue;+ }+ if (message?.id !== 1 || sessionRequestId) continue;+ const result = asRecord(message.result);+ if (message.jsonrpc !== "2.0" || message.error || result?.protocolVersion !== 1+ || asRecord(result.agentCapabilities)?.loadSession !== true+ || asRecord(result.agentInfo)?.name !== "antigravity-acp") return fail("antigravity_acp_incompatible");+ const reportedVersion = asRecord(result.agentInfo)?.version;+ version = typeof reportedVersion === "string" ? reportedVersion : undefined;+ requestSession(cachedSessionId);+ }+ });+ write({ jsonrpc: "2.0", id: 1, method: "initialize", params: {+ protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: { name: "alook-agent-driver", version: "1" },+ } });+ });+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/quota.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/quota.test.tsnew file mode 100644index 000000000..f834f076f--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/quota.test.ts@@ -0,0 +1,191 @@+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import * as localData from "./local-data.js";+import { parseAntigravityQuota, readAntigravityQuota } from "./quota.js";++const bucket = (bucketId = "gemini-weekly", remainingFraction: unknown = 0.25) => ({ bucketId, displayName: "Gemini models", window: "weekly", remainingFraction, resetTime: "2026-10-05T00:00:00Z" });+let serial = 0;+function fixture(overrides: { auth?: string; credentials?: unknown; platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; fetch?: typeof fetch } = {}) {+ const credentials = { client_id: "test-client", client_secret: "test-client-secret", refresh_token: `test-refresh-${++serial}`, project_id: "test-project" };+ const calls: { url: string; init?: RequestInit }[] = [];+ const fetchUsage = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input); calls.push({ url, init });+ if (url.endsWith("/token")) return Response.json({ access_token: "test-access", expires_in: 3600 });+ if (url.endsWith(":loadCodeAssist")) return Response.json({ currentTier: { name: "Free" }, cloudaicompanionProject: "test-project" });+ return Response.json({ groups: [{ displayName: "Gemini", buckets: [bucket()] }] });+ });+ return { credentials, calls, fetchUsage, options: {+ platform: overrides.platform ?? "linux", env: overrides.env ?? {}, home: "/test-home",+ readCredentialsFile: vi.fn(async (path: string) => JSON.stringify(path.endsWith("settings.json") ? { auth: { type: overrides.auth ?? "oauth-personal" } } : overrides.credentials ?? credentials)),+ fetchUsage: overrides.fetch ?? fetchUsage as typeof fetch,+ } };+}+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });++describe("Antigravity official account quota", () => {+ it("maps shared groups without inventing model IDs or window duration and ignores disabled/informational groups", () => {+ expect(parseAntigravityQuota({ groups: [{ displayName: "Information" }, { buckets: [bucket(), { ...bucket("disabled"), disabled: true }, { ...bucket("unspecified", 1), window: "" }] }], buckets: [bucket("deprecated")] }))+ .toEqual([+ { bucket: { limitId: "gemini-weekly", product: { kind: "reported", id: "antigravity", displayName: "Antigravity" }, model: { kind: "unknown" }, window: { kind: "provider_defined", id: "weekly", displayName: "Gemini models" } }, usedPercent: 75, resetsAt: "2026-10-05T00:00:00.000Z" },+ { bucket: { limitId: "unspecified", product: { kind: "reported", id: "antigravity", displayName: "Antigravity" }, model: { kind: "unknown" }, window: { kind: "provider_defined", id: "unspecified", displayName: "Gemini models" } }, usedPercent: 0, resetsAt: "2026-10-05T00:00:00.000Z" },+ ]);+ expect(parseAntigravityQuota({ buckets: [bucket(), bucket()] })).toHaveLength(1);+ expect(parseAntigravityQuota({ buckets: [bucket(), bucket("gemini-weekly", 0.1)] })).toBeUndefined();+ expect(parseAntigravityQuota({ groups: [], buckets: [bucket()] })).toEqual([]);+ });++ it.each([undefined, null, -0.01, 1.01, NaN, Infinity, "0.5"])("rejects unavailable or invalid fractions (%s)", (fraction) => {+ expect(parseAntigravityQuota({ buckets: [{ ...bucket(), remainingFraction: fraction }] })).toBeUndefined();+ });++ it.each([null, {}, { groups: {} }, { groups: [null] }, { groups: [{ buckets: {} }] }, { buckets: [null] }, { buckets: [bucket(), { ...bucket(), resetTime: "invalid" }] }, { buckets: [{ ...bucket(), bucketId: "🙂".repeat(17) }] }, { buckets: Array.from({ length: 9 }, (_, i) => bucket(`bucket-${i}`)) }])("rejects malformed or oversized responses %j", (value) => {+ expect(parseAntigravityQuota(value)).toBeUndefined();+ });++ it("silently refreshes native credentials and queries the native consumer endpoint", async () => {+ const h = fixture(); const observation = await readAntigravityQuota(h.options);+ expect(observation).toMatchObject({ status: "available", planName: "Free", limits: [{ usedPercent: 75 }] });+ expect(h.calls.map((call) => call.url)).toEqual(["https://oauth2.googleapis.com/token", "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary"]);+ expect(h.calls[0]!.init?.body).toBeInstanceOf(URLSearchParams);+ expect(new Headers(h.calls[1]!.init?.headers).get("authorization")).toBe("Bearer test-access");+ expect(h.calls[2]!.init?.body).toBe(JSON.stringify({ project: "test-project" }));+ expect(JSON.stringify(observation)).not.toMatch(/test-access|test-refresh|test-client-secret/);+ const second = await readAntigravityQuota(h.options);+ expect(second?.sourceEpoch).toBe(observation.sourceEpoch);+ expect(h.calls.filter((call) => call.url.endsWith("/token"))).toHaveLength(1);+ });++ it("uses native macOS keychain identity and GEMINI_HOME, or forced-file storage", async () => {+ const h = fixture({ platform: "darwin", env: { GEMINI_HOME: "~/isolated" } });+ const readKeychain = vi.fn(async () => JSON.stringify(h.credentials));+ expect(await readAntigravityQuota({ ...h.options, readKeychain })).toMatchObject({ status: "available" });+ expect(readKeychain).toHaveBeenCalledOnce();+ expect(h.options.readCredentialsFile.mock.calls.map(([path]) => path)).toEqual([join("/test-home", "isolated", "antigravity-acp", "settings.json")]);+ const f = fixture({ platform: "darwin", env: { AGY_ACP_FORCE_FILE_STORAGE: "1" } });+ expect(await readAntigravityQuota({ ...f.options, readKeychain })).toMatchObject({ status: "available" });+ expect(readKeychain).toHaveBeenCalledOnce();+ expect(await readAntigravityQuota({ ...fixture({ platform: "darwin" }).options, readKeychain: async () => { throw new Error("locked"); } })).toMatchObject({ status: "available" });+ });++ it("does not call account APIs for another auth mode or missing credentials", async () => {+ const h = fixture({ auth: "gemini-api-key" });+ expect(await readAntigravityQuota(h.options)).toMatchObject({ status: "error", code: "unavailable" });+ expect(h.fetchUsage).not.toHaveBeenCalled();+ const f = fixture({ credentials: {} });+ expect(await readAntigravityQuota(f.options)).toMatchObject({ status: "error", code: "unauthorized" });+ expect(f.fetchUsage).not.toHaveBeenCalled();+ });++ it.each(["timeout", "denied"])("keeps Keychain %s plus an absent file locally unavailable and retryable", async (reason) => {+ const h = fixture({ platform: "darwin" });+ h.options.readCredentialsFile.mockImplementation(async (path) => {+ if (path.endsWith("settings.json")) return JSON.stringify({ auth: { type: "oauth-personal" } });+ throw Object.assign(new Error("missing"), { code: "ENOENT" });+ });+ const result = await readAntigravityQuota({ ...h.options, readKeychain: async () => { throw new Error(reason); } });+ expect(result).toMatchObject({ status: "error", code: "unavailable", retryable: true });+ expect(h.fetchUsage).not.toHaveBeenCalled();+ });++ it("keeps unreadable credential storage distinct from readable incomplete or malformed credentials", async () => {+ const h = fixture({ platform: "darwin" });+ h.options.readCredentialsFile.mockImplementation(async (path) => {+ if (path.endsWith("settings.json")) return JSON.stringify({ auth: { type: "oauth-personal" } });+ throw Object.assign(new Error("denied"), { code: "EACCES" });+ });+ expect(await readAntigravityQuota({ ...h.options, readKeychain: async () => { throw new Error("timeout"); } }))+ .toMatchObject({ status: "error", code: "unavailable", retryable: true });+ expect(await readAntigravityQuota({ ...h.options, readKeychain: async () => JSON.stringify({ refresh_token: "incomplete" }) }))+ .toMatchObject({ status: "error", code: "unauthorized", retryable: false });+ h.options.readCredentialsFile.mockImplementation(async (path) => path.endsWith("settings.json") ? JSON.stringify({ auth: { type: "oauth-personal" } }) : "not-json");+ expect(await readAntigravityQuota({ ...h.options, readKeychain: async () => "not-json" }))+ .toMatchObject({ status: "error", code: "unauthorized", retryable: false });+ expect(h.fetchUsage).not.toHaveBeenCalled();+ });++ it("uses a valid native file fallback after a Keychain timeout", async () => {+ const h = fixture({ platform: "darwin" });+ expect(await readAntigravityQuota({ ...h.options, readKeychain: async () => { throw new Error("timeout"); } }))+ .toMatchObject({ status: "available" });+ expect(h.calls.map((call) => call.url)).toEqual(["https://oauth2.googleapis.com/token", "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary"]);+ });++ it("keeps a settings read failure retryable without attempting credentials or HTTP", async () => {+ const h = fixture({ platform: "darwin" });+ h.options.readCredentialsFile.mockRejectedValue(Object.assign(new Error("denied"), { code: "EACCES" }));+ const readKeychain = vi.fn();+ expect(await readAntigravityQuota({ ...h.options, readKeychain })).toMatchObject({ status: "error", code: "unavailable", retryable: true });+ expect(readKeychain).not.toHaveBeenCalled();+ expect(h.fetchUsage).not.toHaveBeenCalled();+ });++ it.each(["missing", "unreadable", "malformed"])("distinguishes a %s native file when file storage is selected", async (reason) => {+ const h = fixture({ platform: "darwin", env: { AGY_ACP_FORCE_FILE_STORAGE: "1" } });+ h.options.readCredentialsFile.mockImplementation(async (path) => {+ if (path.endsWith("settings.json")) return JSON.stringify({ auth: { type: "oauth-personal" } });+ if (reason === "malformed") return "not-json";+ throw Object.assign(new Error(reason), { code: reason === "missing" ? "ENOENT" : "EACCES" });+ });+ const readKeychain = vi.fn();+ expect(await readAntigravityQuota({ ...h.options, readKeychain })).toMatchObject({+ status: "error", code: reason === "unreadable" ? "unavailable" : "unauthorized", retryable: reason === "unreadable",+ });+ expect(readKeychain).not.toHaveBeenCalled();+ expect(h.fetchUsage).not.toHaveBeenCalled();+ });++ it.each(["missing", "malformed"])("does not claim transient storage failure for %s settings", async (reason) => {+ const h = fixture();+ h.options.readCredentialsFile.mockImplementation(async () => {+ if (reason === "malformed") return "not-json";+ throw Object.assign(new Error("missing"), { code: "ENOENT" });+ });+ expect(await readAntigravityQuota(h.options)).toMatchObject({ status: "error", code: "unavailable", retryable: false });+ expect(h.fetchUsage).not.toHaveBeenCalled();+ });++ it.each([400, 401, 403, 429, 500])("reports token refresh HTTP %s without returning error body", async (status) => {+ const h = fixture({ fetch: (async () => new Response("sensitive error detail", { status })) as typeof fetch });+ expect(await readAntigravityQuota(h.options)).toMatchObject({ status: "error", code: status < 429 ? "unauthorized" : "provider_error", retryable: status >= 429 });+ });++ it.each(["network", "invalid-token-json", "invalid-token", "missing-project", "denied", "invalid-summary", "empty-summary"])("keeps %s unavailable rather than reporting zero", async (fault) => {+ const h = fixture();+ h.fetchUsage.mockImplementation(async (url) => {+ if (fault === "network") throw new Error("network");+ if (String(url).endsWith("/token")) return fault === "invalid-token-json" ? new Response("bad-json") : Response.json(fault === "invalid-token" ? {} : { access_token: "test-access", expires_in: 3600 });+ if (String(url).endsWith(":loadCodeAssist")) return fault === "missing-project" ? Response.json({}) : fault === "denied" ? new Response("private", { status: 403 }) : Response.json({ currentTier: {}, cloudaicompanionProject: "test-project", paidTier: { usesGcpTos: true } });+ return Response.json(fault === "empty-summary" ? { groups: [] } : {});+ });+ expect(await readAntigravityQuota(h.options)).toMatchObject({ status: "error", code: fault === "network" ? "network" : fault === "missing-project" || fault === "denied" ? "unauthorized" : fault === "empty-summary" ? "unavailable" : "invalid_response" });+ });++ it("fences account changes while the old source is in flight", async () => {+ const old = fixture(); const fresh = fixture();+ let release!: () => void;+ const original = old.fetchUsage.getMockImplementation()!;+ old.fetchUsage.mockImplementation(async (url, init) => {+ if (String(url).endsWith(":retrieveUserQuotaSummary")) await new Promise<void>((resolve) => { release = resolve; });+ return original(url, init);+ });+ const pending = readAntigravityQuota(old.options);+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ const current = await readAntigravityQuota(fresh.options);+ release();+ expect(await pending).toMatchObject({ status: "error", sourceEpoch: current.sourceEpoch, code: "unavailable" });+ });+});++it("reads native macOS keychain through the owned bounded command helper", async () => {+ const h = fixture({ platform: "darwin" });+ const read = vi.spyOn(localData, "readLocalCommand").mockResolvedValue(JSON.stringify(h.credentials));+ expect(await readAntigravityQuota(h.options)).toMatchObject({ status: "available" });+ expect(read).toHaveBeenCalledWith("security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp", "-w"]);+});++it.each(["1", "true", "yes", "YES"])("honors native force-file value %s without reading an old keychain account", async (value) => {+ const h = fixture({ platform: "darwin", env: { AGY_ACP_FORCE_FILE_STORAGE: value } });+ const readKeychain = vi.fn(async () => { throw new Error("must not read keychain"); });+ expect(await readAntigravityQuota({ ...h.options, readKeychain })).toMatchObject({ status: "available" });+ expect(readKeychain).not.toHaveBeenCalled();+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/quota.ts b/src/daemon/agent-driver/src/adapters/antigravity/quota.tsnew file mode 100644index 000000000..b82ef87ee--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/quota.ts@@ -0,0 +1,167 @@+import { createHash, randomBytes } from "node:crypto";+import { readFile } from "node:fs/promises";+import { homedir } from "node:os";+import { isAbsolute, join } from "node:path";+import type { ProviderQuotaObservation, QuotaLimit } from "../../contract.js";+import { asRecord } from "../../internal/utils.js";++import { readLocalCommand } from "./local-data.js";+const PROD = "https://cloudcode-pa.googleapis.com";+const DAILY = "https://daily-cloudcode-pa.googleapis.com";+type Source = { identity: string; epoch: string; accessToken?: { value: string; expiresAt: number } };+let activeSource: Source = { identity: "", epoch: randomBytes(16).toString("base64url") };++type AntigravityQuotaReaderOptions = {+ platform?: NodeJS.Platform;+ env?: NodeJS.ProcessEnv;+ home?: string;+ readCredentialsFile?: (path: string) => Promise<string>;+ readKeychain?: () => Promise<string>;+ fetchUsage?: typeof fetch;+};++function text(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function label(value: unknown): string | undefined {+ const result = text(value);+ return result && Buffer.byteLength(result) <= 64 ? result : undefined;+}++export function parseAntigravityQuota(value: unknown): QuotaLimit[] | undefined {+ const body = asRecord(value);+ if (!body) return undefined;+ const groups = body.groups;+ const buckets: { value: unknown; group?: string }[] = [];+ if (groups !== undefined) {+ if (!Array.isArray(groups) || groups.length > 64) return undefined;+ for (const item of groups) {+ const group = asRecord(item);+ if (!group || (group.buckets !== undefined && !Array.isArray(group.buckets))) return undefined;+ for (const value of (group.buckets as unknown[] | undefined) ?? []) buckets.push({ value, group: label(group.displayName) });+ }+ } else {+ if (!Array.isArray(body.buckets)) return undefined;+ for (const value of body.buckets) buckets.push({ value });+ }+ if (buckets.length > 128) return undefined;+ const limits = new Map<string, QuotaLimit>();+ for (const item of buckets) {+ const row = asRecord(item.value);+ if (!row) return undefined;+ if (row.disabled === true) continue;+ const id = label(row.bucketId);+ const fraction = row.remainingFraction;+ const windowId = row.window === undefined || row.window === "" ? "unspecified" : label(row.window);+ if (!id || !windowId || typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1) return undefined;+ const windowName = label(row.displayName) ?? item.group ?? id;+ const resetsAt = text(row.resetTime);+ if (resetsAt && !Number.isFinite(Date.parse(resetsAt))) return undefined;+ const limit: QuotaLimit = {+ bucket: {+ limitId: id,+ product: { kind: "reported", id: "antigravity", displayName: "Antigravity" },+ model: { kind: "unknown" },+ window: { kind: "provider_defined", id: windowId, displayName: windowName },+ },+ usedPercent: (1 - fraction) * 100,+ ...(resetsAt ? { resetsAt: new Date(resetsAt).toISOString() } : {}),+ };+ const key = `${id}\0${windowId}`;+ const previous = limits.get(key);+ if (previous && (previous.usedPercent !== limit.usedPercent || previous.resetsAt !== limit.resetsAt)) return undefined;+ limits.set(key, previous ?? limit);+ }+ return limits.size <= 8 ? [...limits.values()] : undefined;+}++export async function readAntigravityQuota(options: AntigravityQuotaReaderOptions = {}): Promise<ProviderQuotaObservation> {+ const env = options.env ?? process.env;+ const home = options.home ?? homedir();+ const configuredHome = env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, home);+ const root = configuredHome ? (isAbsolute(configuredHome) ? configuredHome : join(process.cwd(), configuredHome)) : join(home, ".gemini");+ const read = options.readCredentialsFile ?? ((path: string) => readFile(path, "utf8"));+ let credentials: Record<string, unknown> | null = null;+ let authType: unknown;+ let storageUnavailable = false;+ const loadCredentials = async (load: () => Promise<string>) => {+ let value: string;+ try { value = await load(); }+ catch (failure) {+ if (asRecord(failure)?.code !== "ENOENT") storageUnavailable = true;+ return null;+ }+ try { return asRecord(JSON.parse(value)); }+ catch { return null; }+ };+ try {+ authType = asRecord(asRecord(JSON.parse(await read(join(root, "antigravity-acp", "settings.json"))))?.auth)?.type;+ if (authType === "oauth-personal") {+ if ((options.platform ?? process.platform) === "darwin" && !/^(1|true|yes)$/i.test(env.AGY_ACP_FORCE_FILE_STORAGE ?? "")) {+ credentials = await loadCredentials(() => options.readKeychain ? options.readKeychain() : readLocalCommand("security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp", "-w"]));+ }+ if (!credentials) {+ credentials = await loadCredentials(() => read(join(root, "antigravity-acp", "acp_token.json")));+ }+ }+ } catch (failure) {+ if (!(failure instanceof SyntaxError) && asRecord(failure)?.code !== "ENOENT") storageUnavailable = true;+ }+ const identity = createHash("sha256").update(JSON.stringify([root, authType, credentials?.client_id, credentials?.refresh_token, credentials?.project_id])).digest("hex");+ if (activeSource.identity !== identity) activeSource = { identity, epoch: randomBytes(16).toString("base64url") };+ const source = activeSource;+ const error = (code: Extract<ProviderQuotaObservation, { status: "error" }>["code"], retryable = false): ProviderQuotaObservation => ({ status: "error", sourceEpoch: activeSource.epoch, code: source === activeSource ? code : "unavailable", retryable: source === activeSource ? retryable : true });+ const clientId = text(credentials?.client_id);+ const clientSecret = text(credentials?.client_secret);+ const refreshToken = text(credentials?.refresh_token);+ if (authType !== "oauth-personal") return error("unavailable", storageUnavailable);+ if (!credentials && storageUnavailable) return error("unavailable", true);+ if (!clientId || !clientSecret || !refreshToken) return error("unauthorized");+ const fetchUsage = options.fetchUsage ?? fetch;+ const post = async (url: string, body: unknown, token: string) => {+ const response = await fetchUsage(url, {+ method: "POST", redirect: "error", signal: AbortSignal.timeout(5_000),+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": "alook-agent-driver/1 antigravity" },+ body: JSON.stringify(body),+ });+ if (!response.ok) throw { quotaCode: response.status === 401 || response.status === 403 ? "unauthorized" : "provider_error", retryable: response.status === 429 || response.status >= 500 };+ try { return asRecord(await response.json()); } catch { throw { quotaCode: "invalid_response", retryable: true }; }+ };+ try {+ if (!source.accessToken || source.accessToken.expiresAt <= Date.now()) {+ const response = await fetchUsage("https://oauth2.googleapis.com/token", {+ method: "POST", redirect: "error", signal: AbortSignal.timeout(5_000),+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" }),+ });+ if (!response.ok) return error(response.status === 400 || response.status === 401 || response.status === 403 ? "unauthorized" : "provider_error", response.status === 429 || response.status >= 500);+ let body: Record<string, unknown> | null;+ try { body = asRecord(await response.json()); } catch { return error("invalid_response", true); }+ const token = text(body?.access_token);+ const expires = body?.expires_in;+ if (!token || typeof expires !== "number" || !Number.isFinite(expires) || expires <= 0) return error("invalid_response", true);+ source.accessToken = { value: token, expiresAt: Date.now() + Math.min(expires, 3600) * 1000 - 30_000 };+ }+ const bootstrap = env.AGY_ACP_CCPA_BASE_URL || PROD;+ if (bootstrap !== PROD && bootstrap !== DAILY) return error("unavailable");+ const loaded = await post(`${bootstrap}/v1internal:loadCodeAssist`, { metadata: { ideType: "ANTIGRAVITY" } }, source.accessToken.value);+ const project = text(loaded?.cloudaicompanionProject);+ if (!project || !asRecord(loaded?.currentTier)) return error("unauthorized");+ const endpoint = env.AGY_ACP_CCPA_BASE_URL || (asRecord(loaded?.paidTier)?.usesGcpTos === true ? PROD : DAILY);+ const summary = await post(`${endpoint}/v1internal:retrieveUserQuotaSummary`, { project }, source.accessToken.value);+ const limits = parseAntigravityQuota(summary);+ if (!limits) return error("invalid_response", true);+ if (!limits.length) return error("unavailable");+ const planName = label(asRecord(loaded?.paidTier)?.name ?? asRecord(loaded?.currentTier)?.name);+ if (source !== activeSource) return { status: "error", sourceEpoch: activeSource.epoch, code: "unavailable", retryable: true };+ return { status: "available", sourceEpoch: source.epoch, freshForSeconds: 300, ...(planName ? { planName } : {}), limits };+ } catch (failure) {+ const known = asRecord(failure);+ if (known?.quotaCode === "unauthorized" || known?.quotaCode === "provider_error" || known?.quotaCode === "invalid_response") {+ if (known.quotaCode === "unauthorized") source.accessToken = undefined;+ return error(known.quotaCode, known.retryable === true);+ }+ return error("network", true);+ }+}diff --git a/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/session.test.tsnew file mode 100644index 000000000..a12b35bd1--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts@@ -0,0 +1,86 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it, vi } from "vitest";+import { createBuiltinAgentDriverSdk, type AgentEvent, type BuiltinBackendSpecs } from "../../host.js";+import { createFakeAgentDriverHost } from "../../testing/fake-host.js";++describe.skipIf(process.platform === "win32")("Antigravity SDK prompt completion", () => {+ it.each(["error", "error-without-code", "error-string-code", "invalid", "cancelled", "interrupt", "end_turn", "max_tokens", "refusal", "max_turn_requests"])(+ "settles %s once, preserves queued work, and publishes only completed content",+ async (terminal) => {+ const directory = mkdtempSync(join(tmpdir(), "alook-antigravity-sdk-"));+ const executable = join(directory, "acp-fixture");+ const release = join(directory, "release");+ writeFileSync(executable, `#!${process.execPath}+const { createInterface } = require("node:readline");+const { existsSync } = require("node:fs");+const send = (value) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...value }) + "\\n");+const update = (sessionUpdate, text) => send({ method: "session/update", params: { sessionId: "sdk-native", update: { sessionUpdate, content: { type: "text", text } } } });+let count = 0;+let root;+createInterface({ input: process.stdin }).on("line", (line) => {+ const request = JSON.parse(line);+ if (request.method === "initialize") send({ id: request.id, result: { protocolVersion: 1, agentInfo: { name: "antigravity-acp" }, agentCapabilities: { loadSession: true } } });+ if (request.method === "session/new") send({ id: request.id, result: { sessionId: "sdk-native" } });+ if (request.method === "session/cancel") send({ id: root, result: { stopReason: "cancelled" } });+ if (request.method !== "session/prompt") return;+ root = request.id;+ count++;+ update("agent_message_chunk", count === 1 ? "first message" : "next message");+ update("agent_thought_chunk", count === 1 ? "first reasoning" : "next reasoning");+ if (count > 1) { send({ id: request.id, result: { stopReason: "end_turn" } }); return; }+ if (${JSON.stringify(terminal)} === "interrupt") return;+ const timer = setInterval(() => {+ if (!existsSync(${JSON.stringify(release)})) return;+ clearInterval(timer);+ const terminal = ${JSON.stringify(terminal)};+ const reply = terminal === "error" ? { error: { code: -32603, message: "injected failure" } }+ : terminal === "error-without-code" ? { error: { message: "injected failure" } }+ : terminal === "error-string-code" ? { error: { code: "invalid", message: "injected failure" } }+ : { result: { stopReason: terminal } };+ send({ id: request.id, ...reply });+ send({ id: request.id, ...reply });+ }, 5);+});+`, { mode: 0o755 });+ const host = createFakeAgentDriverHost();+ const opened = await createBuiltinAgentDriverSdk({ host }).open({+ backend: "antigravity",+ config: { model: { kind: "default" }, command: executable },+ launch: { workingDirectory: directory, instructions: { format: "markdown", content: "" }, launchId: "sdk-fault" },+ });+ if (!opened.ok) throw new Error(opened.error.message);+ const session = opened.session;+ const events: AgentEvent<BuiltinBackendSpecs, "antigravity">[] = [];+ const collecting = (async () => { for await (const event of session.events) events.push(event); })();+ try {+ expect(await session.start({ id: "first", kind: "user", text: "first" })).toMatchObject({ status: "accepted" });+ await vi.waitFor(() => expect(events.some((event) => event.type === "work_heartbeat")).toBe(true));+ expect(await session.send({ id: "second", kind: "user", text: "second" })).toMatchObject({ status: "queued" });+ if (terminal === "interrupt") {+ expect(await session.interrupt({ requestId: "cancel", reason: "test" })).toMatchObject({ status: "accepted" });+ } else {+ writeFileSync(release, "go");+ }+ await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2));+ const successful = ["end_turn", "max_tokens", "refusal", "max_turn_requests"].includes(terminal);+ expect(events.filter((event) => event.type === "assistant_message_completed").map((event) => event.text))+ .toEqual(successful ? ["first message", "next message"] : ["next message"]);+ expect(events.filter((event) => event.type === "assistant_reasoning_completed").map((event) => event.text))+ .toEqual(successful ? ["first reasoning", "next reasoning"] : ["next reasoning"]);+ expect(events.filter((event) => event.type === "turn_completed")).toMatchObject([+ { commandIds: ["first"], result: { outcome: terminal === "interrupt" ? "interrupted" : successful ? "success" : "failed" } },+ { commandIds: ["second"], result: { outcome: "success" } },+ ]);+ expect(events.filter((event) => event.type === "command_accepted").map((event) => event.commandId)).toEqual(["first", "second"]);+ } finally {+ await session.stop({ reason: "shutdown", forceAfterMs: 50 });+ await session.closed;+ await collecting;+ rmSync(directory, { recursive: true, force: true });+ }+ expect(host.releases).toHaveLength(1);+ },+ );+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/usage.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/usage.test.tsnew file mode 100644index 000000000..c5d982b18--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/usage.test.ts@@ -0,0 +1,119 @@+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { join, resolve } from "node:path";+import { tmpdir, homedir } from "node:os";+import { afterEach, describe, expect, it, vi } from "vitest";+import * as localData from "./local-data.js";+import { NativeUsageReader, nativeUsageHome, parseNativeGeneration, queryNativeRowsWithCli, queryNativeRows } from "./usage.js";++const hasSqliteCli = spawnSync("sqlite3", ["-version"], { timeout: 3_000 }).status === 0;+const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { force: true, recursive: true }); });+function varint(value: bigint | number): number[] {+ let n = BigInt(value); const bytes: number[] = [];+ do { bytes.push(Number(n & 127n) | (n > 127n ? 128 : 0)); n >>= 7n; } while (n);+ return bytes;+}+const scalar = (field: number, value: bigint | number) => [...varint(field * 8), ...varint(value)];+const message = (field: number, value: number[]) => [...varint(field * 8 + 2), ...varint(value.length), ...value];+const generation = (usage: number[] = [...scalar(2, 90), ...scalar(3, 24), ...scalar(5, 23)]) => Buffer.from(message(1, [...message(4, usage), ...message(9, message(4, scalar(1, 1_791_091_200)))]));++describe("Antigravity native accounting", () => {+ it("uses native input/output once, without subtracting cache or adding thoughts again", () => {+ expect(parseNativeGeneration(generation([...scalar(2, 90), ...scalar(3, 24), ...scalar(5, 23), ...scalar(9, 7), ...scalar(10, 17)]))).toEqual({ usage: { input: 90, output: 24, cache: 23 }, occurredAt: "2026-10-04T05:20:00.000Z" });+ });+ it("preserves missing and empty usage as unknown, including absent cache", () => {+ expect(parseNativeGeneration(generation([])).usage).toEqual({ input: null, output: null, cache: null });+ expect(parseNativeGeneration(generation(scalar(2, 113))).usage).toEqual({ input: 113, output: null, cache: null });+ expect(parseNativeGeneration(generation(scalar(5, 0))).usage.cache).toBe(0);+ expect(parseNativeGeneration(Buffer.from(message(1, message(4, scalar(2, 2))))).occurredAt).toBeNull();+ });+ it.each([[0], [10, 99], [10, 2, 8], [15], [9, 0], [13, 0], [128], [...Array(11).fill(128)], [10, 255, 255, 255, 255, 255, 255, 255, 255, 127]])("rejects malformed record %j", (bytes) => {+ expect(() => parseNativeGeneration(Buffer.from(bytes))).toThrow();+ });+ it("rejects overflowing counts and bounds native payloads", () => {+ expect(() => parseNativeGeneration(generation(scalar(2, BigInt(Number.MAX_SAFE_INTEGER) + 1n)))).toThrow();+ expect(() => parseNativeGeneration(new Uint8Array(4 * 1024 * 1024 + 1))).toThrow();+ });+ it("deduplicates by session and generation, replays after restart, and leaves child totals unknown", async () => {+ const rows = [{ idx: 0, data: generation().toString("hex"), has_children: 0 }, { idx: 1, data: generation().toString("hex"), has_children: 1 }];+ const query = async (_: string, cursor: number) => rows.filter((row) => row.idx > cursor);+ const reader = new NativeUsageReader("/fixture", "native-session", query);+ const batch = await reader.read();+ expect(batch.complete).toBe(true);+ const first = batch.samples;+ expect(first[0]).toMatchObject({ usage: { input: 90, output: 24, cache: 23 }, identity: { source: expect.stringMatching(/^antigravity:[a-f0-9]{16}:native-session$/), index: 0 } });+ expect(first[1].usage).toEqual({ input: null, output: null, cache: null });+ expect(await reader.read()).toEqual({ samples: [], complete: true, incompleteScope: true });+ expect((await new NativeUsageReader("/fixture", "native-session", query).read()).samples).toEqual(first);+ expect(() => new NativeUsageReader("/fixture", "../other")).toThrow();+ });+ it("does not advance its cursor on partial failure or missing historical timestamps", async () => {+ const rows = [{ idx: 0, data: generation().toString("hex"), has_children: 0 }, { idx: 1, data: "ff", has_children: 0 }];+ const reader = new NativeUsageReader("/fixture", "native", async (_, cursor) => rows.filter((row) => row.idx > cursor));+ await expect(reader.read()).rejects.toThrow();+ rows.pop();+ expect((await reader.read()).samples).toHaveLength(1);+ await expect(new NativeUsageReader("/fixture", "native", async () => [{ idx: 0, data: "", has_children: 0 }]).read()).rejects.toThrow("timestamp");+ });+ it("resolves the actual transport home, including relative and tilde overrides", () => {+ expect(nativeUsageHome({ GEMINI_HOME: "private" }, "/work")).toBe(resolve("/work", "private"));+ expect(nativeUsageHome({ GEMINI_HOME: "~/private" }, "/work")).toBe(join(homedir(), "private"));+ expect(nativeUsageHome({}, "/work")).toBe(join(homedir(), ".gemini"));+ });+ it("reads the live SQLite WAL view without modifying the provider database", async () => {+ const module = "node:sqlite";+ let sqlite: { DatabaseSync: new(path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void } };+ try { sqlite = await import(module); } catch { return; }+ const home = mkdtempSync(join(tmpdir(), "native-usage-")); roots.push(home);+ const directory = join(home, "antigravity-acp", "conversations"); mkdirSync(directory, { recursive: true });+ const db = new sqlite.DatabaseSync(join(directory, "native.db"));+ try {+ db.exec("PRAGMA journal_mode=WAL; CREATE TABLE gen_metadata(idx INTEGER PRIMARY KEY, data BLOB); CREATE TABLE steps(has_subtrajectory INTEGER)");+ db.prepare("INSERT INTO gen_metadata VALUES(?,?)").run(0, generation());+ expect((await new NativeUsageReader(home, "native").read()).samples).toMatchObject([{ usage: { input: 90, output: 24, cache: 23 } }]);+ } finally { db.close(); }+ });+});++it("skips unrelated fixed-width protobuf fields and rejects invalid field zero", () => {+ const data = Buffer.concat([Buffer.from([17, ...Array(8).fill(0), 29, 0, 0, 0, 0]), generation()]);+ expect(parseNativeGeneration(data).usage.input).toBe(90);+ expect(() => parseNativeGeneration(Buffer.from([0, 0]))).toThrow();+});++it("reports incomplete bounded scans and drains seventeen batches without losing generation identity", async () => {+ const reader = new NativeUsageReader("/fixture", "native", async (_, cursor) => cursor >= 16 ? [] : [{ idx: cursor + 1, data: generation().toString("hex"), has_children: 0 }]);+ const first = await reader.read();+ expect(first.complete).toBe(false); expect(first.samples).toHaveLength(16);+ const second = await reader.read();+ expect(second.complete).toBe(true); expect(second.samples[0].identity.index).toBe(16);+});++it("bounds overlong varints and unsupported wire groups", () => {+ expect(() => parseNativeGeneration(Buffer.from(Array(10).fill(128)))).toThrow("varint");+ expect(() => parseNativeGeneration(Buffer.from([11]))).toThrow("Unsupported");+});++it.skipIf(!hasSqliteCli)("reads the live WAL through the optional CLI and handles empty fallback batches", async () => {+ const module = "node:sqlite";+ let sqlite: { DatabaseSync: new(path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void } };+ try { sqlite = await import(module); } catch { return; }+ const home = mkdtempSync(join(tmpdir(), "native-cli-usage-")); roots.push(home);+ const directory = join(home, "antigravity-acp", "conversations"); mkdirSync(directory, { recursive: true });+ const path = join(directory, "native.db"); const db = new sqlite.DatabaseSync(path);+ try {+ db.exec("PRAGMA journal_mode=WAL; CREATE TABLE gen_metadata(idx INTEGER PRIMARY KEY, data BLOB); CREATE TABLE steps(has_subtrajectory INTEGER)");+ db.prepare("INSERT INTO gen_metadata VALUES(?,?)").run(0, generation());+ expect(await queryNativeRowsWithCli(path, -1)).toMatchObject([{ idx: 0 }]);+ expect(await queryNativeRowsWithCli(path, 0)).toEqual([]);+ const fallback = new NativeUsageReader(home, "native", (file, cursor) => queryNativeRows(file, cursor, async () => { throw new Error("Node 20 has no node:sqlite"); }));+ expect((await fallback.read()).samples).toMatchObject([{ usage: { input: 90, output: 24, cache: 23 } }]);+ expect(await fallback.read()).toEqual({ samples: [], complete: true });+ } finally { db.close(); }+});+it("reports a missing optional CLI reader explicitly when built-in SQLite is absent", async () => {+ const command = vi.spyOn(localData, "readLocalCommand").mockRejectedValue(new Error("Local data read failed"));+ try { await expect(queryNativeRows("native.db", -1, async () => { throw new Error("No built-in SQLite"); })).rejects.toThrow("Local data read failed"); }+ finally { command.mockRestore(); }+});diff --git a/src/daemon/agent-driver/src/adapters/antigravity/usage.ts b/src/daemon/agent-driver/src/adapters/antigravity/usage.tsnew file mode 100644index 000000000..d638be993--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/antigravity/usage.ts@@ -0,0 +1,111 @@+import { createHash } from "node:crypto";+import { homedir } from "node:os";+import { resolve, join } from "node:path";+import type { TokenUsageDelta, TokenUsageIdentity } from "../../contract.js";+import { readLocalCommand } from "./local-data.js";++type Field = { number: number; value: bigint | Uint8Array };+function fields(data: Uint8Array): Field[] {+ if (data.length > 4 * 1024 * 1024) throw new Error("Native usage record too large");+ let offset = 0;+ const varint = () => {+ let value = 0n;+ for (let shift = 0n; shift < 70n; shift += 7n) {+ if (offset >= data.length) throw new Error("Truncated native usage record");+ const byte = data[offset++];+ value |= BigInt(byte & 127) << shift;+ if (!(byte & 128)) return value;+ }+ throw new Error("Invalid native usage varint");+ };+ const result: Field[] = [];+ while (offset < data.length) {+ const tag = varint();+ const number = Number(tag >> 3n);+ const wire = Number(tag & 7n);+ if (!number || number > 536870911) throw new Error("Invalid native usage field");+ if (wire === 0) result.push({ number, value: varint() });+ else if (wire === 2) {+ const length = Number(varint());+ if (!Number.isSafeInteger(length) || length < 0 || offset + length > data.length) throw new Error("Invalid native usage length");+ result.push({ number, value: data.subarray(offset, offset + length) });+ offset += length;+ } else if (wire === 1 || wire === 5) {+ offset += wire === 1 ? 8 : 4;+ if (offset > data.length) throw new Error("Truncated native usage scalar");+ } else throw new Error("Unsupported native usage field");+ }+ return result;+}+function nested(data: Field[], number: number): Field[] {+ const value = data.filter((field) => field.number === number).at(-1)?.value;+ return value instanceof Uint8Array ? fields(value) : [];+}+function count(data: Field[], number: number): number | null {+ const value = data.filter((field) => field.number === number).at(-1)?.value;+ if (value === undefined) return null;+ if (typeof value !== "bigint" || value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("Invalid native token count");+ return Number(value);+}++export function parseNativeGeneration(data: Uint8Array): { usage: TokenUsageDelta; occurredAt: string | null } {+ const chat = nested(fields(data), 1);+ const usage = nested(chat, 4);+ const timestamp = nested(nested(chat, 9), 4);+ const seconds = count(timestamp, 1);+ const nanos = count(timestamp, 2) ?? 0;+ const milliseconds = seconds === null ? NaN : seconds * 1000 + Math.floor(nanos / 1_000_000);+ const occurredAt = nanos < 1_000_000_000 && Number.isFinite(milliseconds) && milliseconds <= 8.64e15 ? new Date(milliseconds).toISOString() : null;+ return { usage: { input: count(usage, 2), output: count(usage, 3), cache: count(usage, 5) }, occurredAt };+}++export function nativeUsageHome(env: NodeJS.ProcessEnv, cwd: string): string {+ return resolve(cwd, env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, homedir()) || join(homedir(), ".gemini"));+}++type Row = { idx: number; data: string; has_children: number };+type Database = { prepare(sql: string): { all(...params: unknown[]): unknown[] }; close(): void };+type Sqlite = { DatabaseSync: new(path: string, options: { readOnly: boolean }) => Database };+const QUERY = "WITH pending AS (SELECT idx,data FROM gen_metadata WHERE idx>? ORDER BY idx LIMIT 128), batch AS (SELECT idx,data,sum(length(data)) OVER (ORDER BY idx) AS bytes FROM pending) SELECT idx,hex(substr(data,1,4194305)) AS data,(SELECT COUNT(*) FROM steps WHERE has_subtrajectory=1) AS has_children FROM batch WHERE bytes<=4194304 OR idx=(SELECT min(idx) FROM batch) ORDER BY idx";++type NativeUsageBatch = { samples: { usage: TokenUsageDelta; identity: TokenUsageIdentity }[]; complete: boolean; incompleteScope?: true };++export class NativeUsageReader {+ private cursor = -1;+ private childTrajectories = false;+ constructor(private readonly home: string, private readonly sessionId: string, private readonly readRows = queryNativeRows) {+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(sessionId)) throw new Error("Invalid native usage session identity");+ }+ async read(): Promise<NativeUsageBatch> {+ const path = join(this.home, "antigravity-acp", "conversations", `${this.sessionId}.db`);+ let cursor = this.cursor;+ let complete = false;+ const result: { usage: TokenUsageDelta; identity: TokenUsageIdentity }[] = [];+ for (let batch = 0; batch < 16; batch++) {+ const rows = await this.readRows(path, cursor);+ for (const row of rows) {+ if (!Number.isSafeInteger(row.idx) || row.idx <= cursor || !/^(?:[a-f0-9]{2})*$/i.test(row.data) || row.data.length > 8 * 1024 * 1024) throw new Error("Invalid native usage row");+ if (row.has_children) this.childTrajectories = true;+ const parsed = parseNativeGeneration(Buffer.from(row.data, "hex"));+ if (!parsed.occurredAt) throw new Error("Native usage timestamp unavailable");+ result.push({ usage: row.has_children ? { input: null, output: null, cache: null } : parsed.usage, identity: { source: `antigravity:${createHash("sha256").update(this.home).digest("hex").slice(0, 16)}:${this.sessionId}`, index: row.idx, occurredAt: parsed.occurredAt } });+ cursor = row.idx;+ }+ if (!rows.length) { complete = true; break; }+ }+ this.cursor = cursor;+ return { samples: result, complete, ...(this.childTrajectories ? { incompleteScope: true as const } : {}) };+ }+}+export async function queryNativeRowsWithCli(path: string, cursor: number): Promise<Row[]> {+ const output = await readLocalCommand("sqlite3", ["-readonly", "-json", path, QUERY.replace("idx>?", `idx>${cursor}`)], 16 * 1024 * 1024);+ return output.trim() ? JSON.parse(output) as Row[] : [];+}++export async function queryNativeRows(path: string, cursor: number, loadSqlite: () => Promise<Sqlite> = async () => { const module = "node:sqlite"; return await import(module) as Sqlite; }): Promise<Row[]> {+ let sqlite: Sqlite;+ try { sqlite = await loadSqlite(); }+ catch { return queryNativeRowsWithCli(path, cursor); }+ const db = new sqlite.DatabaseSync(path, { readOnly: true });+ try { return db.prepare(QUERY).all(cursor) as Row[]; } finally { db.close(); }+}diff --git a/src/daemon/agent-driver/src/builtin-config.test.ts b/src/daemon/agent-driver/src/builtin-config.test.tsindex 86196506f..532c2eec9 100644--- a/src/daemon/agent-driver/src/builtin-config.test.ts+++ b/src/daemon/agent-driver/src/builtin-config.test.ts@@ -54,4 +54,20 @@ describe("builtin config boundary", () => {it("rejects unknown runtime ids", () => {expect(() => toBuiltinBackendSelection(config("unknown"))).toThrow("Unknown runtime: unknown");});++ it.each([{ kind: "default" } as const, { kind: "named", name: "gemini-3.8-flash-high" } as const])(+ "forwards Antigravity native model, effort and launch fields for %j",+ (model) => {+ expect(toBuiltinBackendSelection(config("antigravity", {+ model,+ command: "native-acp",+ envVars: { GEMINI_HOME: "native-home" },+ reasoningEffort: "low",+ provider: { kind: "custom", apiUrl: "https://example.invalid", apiKey: "foreign-provider" },+ }))).toEqual({+ backend: "antigravity",+ config: { model, command: "native-acp", environment: { GEMINI_HOME: "native-home" }, reasoningEffort: "low" },+ });+ },+ );});diff --git a/src/daemon/agent-driver/src/builtin-config.ts b/src/daemon/agent-driver/src/builtin-config.tsindex aa80dcad3..b8b1dfc7a 100644--- a/src/daemon/agent-driver/src/builtin-config.ts+++ b/src/daemon/agent-driver/src/builtin-config.ts@@ -48,6 +48,8 @@ export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): Bubackend: "codex",config: { ...base, reasoningEffort: config.reasoningEffort, mode: config.mode.kind },};+ case "antigravity":+ return { backend: "antigravity", config: { ...base, reasoningEffort: config.reasoningEffort } };case "cursor":return { backend: "cursor", config: base };case "grok":diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.tsindex fbce5a1ee..d10d2af90 100644--- a/src/daemon/agent-driver/src/contract.ts+++ b/src/daemon/agent-driver/src/contract.ts@@ -2,7 +2,7 @@ export type JsonPrimitive = string | number | boolean | null;export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];export type JsonObject = { readonly [key: string]: JsonValue };-export type BuiltinBackendId = "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi";+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi" | "antigravity";export type ReasoningEffort =| "minimal"| "low"@@ -76,6 +76,9 @@ export interface ModelBackendConfig extends BaseBackendConfig {readonly model: ModelSelection;}+export interface AntigravityConfig extends ModelBackendConfig {+ readonly reasoningEffort?: ReasoningEffort;+}export type CursorConfig = ModelBackendConfig;export interface GrokConfig extends ModelBackendConfig {readonly reasoningEffort?: ReasoningEffort;@@ -122,6 +125,7 @@ export type FixedCapabilities<readonly interrupt: true;};+export type AntigravityCapabilities = FixedCapabilities<false, true, false, false, true, "next_turn_queue", "persistent">;export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;@@ -142,6 +146,7 @@ export interface BackendTypeSpec<Config, Capabilities, Extensions, ExtraEvent> {}export interface BuiltinBackendSpecs {+ readonly antigravity: BackendTypeSpec<AntigravityConfig, AntigravityCapabilities, {}, never>;readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;@@ -299,6 +304,8 @@ export type AgentTurnResult =| { readonly outcome: "interrupted"; readonly backendSessionId?: string }| { readonly outcome: "failed"; readonly backendSessionId?: string; readonly error: AgentDriverError };+export type TokenUsageIdentity = { readonly source: string; readonly index: number; readonly occurredAt: string };+export type TokenMetricDelta = number | null;export interface TokenUsageDelta {@@ -436,6 +443,13 @@ export type CoreAgentEventPayload =readonly turnId?: string;readonly source: string;readonly usage: TokenUsageDelta;+ readonly identity?: TokenUsageIdentity;+ }+ | {+ readonly type: "token_usage_status";+ readonly turnId?: string;+ readonly source: string;+ readonly status: "available" | "unavailable";}| {readonly type: "rate_limits";diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.tsindex 8d6ff6fc0..a8bd4abfe 100644--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts@@ -32,6 +32,7 @@ const configs: Record<BuiltinBackendId, unknown> = {claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },codex: { model: { kind: "default" }, mode: "default" },cursor: { model: { kind: "default" } },+ antigravity: { model: { kind: "default" } },grok: { model: { kind: "default" } },opencode: { model: { kind: "default" } },pi: { model: { kind: "default" }, provider: { kind: "default" } },@@ -478,6 +479,47 @@ describe("root-turn text assembly", () => {await session.stop({ reason: "shutdown", forceAfterMs: 10 });});+ it("discards only pending fragments on an owned terminal, preserving prior completions", async () => {+ const lane = new ControlledRuntimeLane();+ const { session } = makeSession("claude", { lane });+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();+ await session.start({ id: "one", kind: "user", text: "start" });+ lane.emit({ kind: "assistant_message_completed", text: "complete message" });+ lane.emit({ kind: "assistant_reasoning_completed", text: "complete reasoning" });+ lane.emit({ kind: "assistant_message_delta", text: "partial message" });+ lane.emit({ kind: "assistant_reasoning_delta", text: "partial reasoning" });+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1", pendingContent: "discard" });+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });+ await collecting;+ expect(observed.filter((event) => event.type === "assistant_message_completed"))+ .toMatchObject([{ text: "complete message" }]);+ expect(observed.filter((event) => event.type === "assistant_reasoning_completed"))+ .toMatchObject([{ text: "complete reasoning" }]);+ expect(observed.filter((event) => event.type === "turn_completed")).toHaveLength(1);+ });++ it.each([undefined, "discard"] as const)("ignores unowned terminals before touching pending content (%s)", async (pendingContent) => {+ const lane = new ControlledRuntimeLane();+ const { session } = makeSession("claude", { lane });+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();+ await session.start({ id: "one", kind: "user", text: "start" });+ lane.emit({ kind: "assistant_message_delta", text: "still " });+ lane.emit({ kind: "assistant_reasoning_delta", text: "thinking " });+ lane.emit({ kind: "turn_end", turnOwner: "stale-owner", pendingContent });+ lane.emit({ kind: "assistant_message_delta", text: "working" });+ lane.emit({ kind: "assistant_reasoning_delta", text: "now" });+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1" });+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });+ await collecting;+ expect(observed.filter((event) => event.type === "assistant_message_completed"))+ .toMatchObject([{ text: "still working" }]);+ expect(observed.filter((event) => event.type === "assistant_reasoning_completed"))+ .toMatchObject([{ text: "thinking now" }]);+ expect(observed.filter((event) => event.type === "turn_completed")).toHaveLength(1);+ });+it("drops an unfinished delta buffer when the runtime crashes before a boundary", async () => {const { session, driver } = makeSession("claude");const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];@@ -1429,7 +1471,7 @@ describe("backend-owned delivery behavior", () => {circular.self = circular;await emit(driver, { kind: "internal_progress", source: "pi", itemType: "working", payloadBytes: 12 });await emit(driver, { kind: "runtime_diagnostic", severity: "notice", source: "pi", message: "heads up" });- await emit(driver, { kind: "telemetry", name: "token_usage", source: "pi", attrs: circular } as never);+ await emit(driver, { kind: "telemetry", name: "token_usage", source: "pi", usage: { input: 90, output: 24, cache: null }, identity: { source: "native:session", index: 0, occurredAt: "2026-10-04T08:00:00Z" }, attrs: circular } as never);await emit(driver, {kind: "telemetry",name: "rate_limits",@@ -1441,7 +1483,8 @@ describe("backend-owned delivery behavior", () => {retryable: false,},});- const events = await take(iterator as never, 7);+ await emit(driver, { kind: "telemetry", name: "token_usage_status", source: "native", status: "unavailable" });+ const events = await take(iterator as never, 8);expect(events.map((event) => event.type)).toEqual(["command_accepted","turn_started",@@ -1450,8 +1493,11 @@ describe("backend-owned delivery behavior", () => {"diagnostic","token_usage","rate_limits",+ "token_usage_status",]);expect(events[4]).toMatchObject({ severity: "info", message: "heads up" });+ expect(events[5]).toMatchObject({ usage: { input: 90, output: 24, cache: null }, identity: { source: "native:session", index: 0 } });+ expect(events[7]).toMatchObject({ type: "token_usage_status", status: "unavailable" });await session.stop({ reason: "shutdown", forceAfterMs: 10 });});diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.tsindex 1846e4452..bc2726b77 100644--- a/src/daemon/agent-driver/src/controller/logical-session.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.ts@@ -882,7 +882,9 @@ implements AgentSession<Specs, Id> {return;case "telemetry": {if (event.name === "token_usage") {- this.emit({ type: "token_usage", turnId, source: event.source, usage: event.usage });+ this.emit({ type: "token_usage", turnId, source: event.source, usage: event.usage, ...(event.identity ? { identity: event.identity } : {}) });+ } else if (event.name === "token_usage_status") {+ this.emit({ type: "token_usage_status", turnId, source: event.source, status: event.status });} else {this.emit({ type: "rate_limits", turnId, source: event.source, quota: event.quota });}@@ -905,6 +907,11 @@ implements AgentSession<Specs, Id> {});return;case "turn_end":+ if (!this.activeTurn?.terminalOwner || event.turnOwner !== this.activeTurn.terminalOwner) return;+ if (event.pendingContent === "discard") {+ this.activeTurn.pendingReasoning = emptySemanticAssembler();+ this.activeTurn.pendingMessage = emptySemanticAssembler();+ }if (turnId && this.activeTurn?.turnId === turnId) {const reasoning = finishSemanticAssembler(this.activeTurn.pendingReasoning);const message = finishSemanticAssembler(this.activeTurn.pendingMessage);diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.tsindex 841afb175..d845a07a1 100644--- a/src/daemon/agent-driver/src/internal/adapter.ts+++ b/src/daemon/agent-driver/src/internal/adapter.ts@@ -14,7 +14,7 @@ import type {RecentContextDiscoveryData,RecentContextDiscoveryRequest,} from "../contract.js";-import type { ProviderQuotaObservation, TokenUsageDelta } from "../contract.js";+import type { ProviderQuotaObservation, TokenUsageDelta, TokenUsageIdentity } from "../contract.js";export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | GrokConfig | OpenCodeConfig | PiConfig;@@ -75,9 +75,10 @@ export type AdapterEvent =| { kind: "runtime_recovery"; stage: "retrying" | "recovered"; source?: string }| { kind: "runtime_metric"; name: "sse_reconnect"; increment: 1 }| { kind: "turn_owner"; receipt: string; nativeTurnId?: string }- | { kind: "turn_end"; sessionId?: string; turnOwner?: string }+ | { kind: "turn_end"; sessionId?: string; turnOwner?: string; pendingContent?: "discard" }| { kind: "error"; code?: string; message: string }- | { kind: "telemetry"; name: "token_usage"; source: string; usage: TokenUsageDelta }+ | { kind: "telemetry"; name: "token_usage"; source: string; usage: TokenUsageDelta; identity?: TokenUsageIdentity }+ | { kind: "telemetry"; name: "token_usage_status"; source: string; status: "available" | "unavailable" }| { kind: "telemetry"; name: "rate_limits"; source: string; quota: ProviderQuotaObservation };export interface LaneStartInput {diff --git a/src/daemon/agent-driver/src/pack.test.ts b/src/daemon/agent-driver/src/pack.test.tsindex 625ac67f3..066126e8a 100644--- a/src/daemon/agent-driver/src/pack.test.ts+++ b/src/daemon/agent-driver/src/pack.test.ts@@ -53,9 +53,17 @@ describe("packed @alook/agent-driver", () => {shell: process.platform === "win32",});writeFileSync(join(root, "usage.ts"), `-import { createAgentDriverSdk } from "@alook/agent-driver";+import { createAgentDriverSdk, type AntigravityConfig, type AntigravityCapabilities } from "@alook/agent-driver";const sdk = createAgentDriverSdk();+const antigravityConfig: AntigravityConfig = { model: { kind: "default" } };+const persistent = (value: AntigravityCapabilities): "persistent" => value.sessionLifetime;+const queued = (value: AntigravityCapabilities): "next_turn_queue" => value.midTurnDelivery;+const openAntigravity = () => sdk.open({+ backend: "antigravity", config: antigravityConfig,+ launch: { workingDirectory: ".", instructions: { format: "markdown", content: "" }, launchId: "antigravity-consumer" },+});+void { persistent, queued, openAntigravity };const opened = await sdk.open({backend: "codex",launch: {diff --git a/src/daemon/agent-driver/src/provider-quota.test.ts b/src/daemon/agent-driver/src/provider-quota.test.tsindex 551be0580..43dae3845 100644--- a/src/daemon/agent-driver/src/provider-quota.test.ts+++ b/src/daemon/agent-driver/src/provider-quota.test.ts@@ -60,3 +60,9 @@ describe("readBuiltinProviderQuota", () => {expect(first?.sourceEpoch).not.toBe(second?.sourceEpoch)})})++it("dispatches Antigravity account quota without interactive onboarding", async () => {+ const fetchUsage = vi.fn();+ expect(await readBuiltinProviderQuota("antigravity", { platform: "linux", env: {}, readCredentialsFile: async () => JSON.stringify({ auth: { type: "api-key" } }), fetchUsage })).toMatchObject({ status: "error", code: "unavailable" });+ expect(fetchUsage).not.toHaveBeenCalled();+});diff --git a/src/daemon/agent-driver/src/provider-quota.ts b/src/daemon/agent-driver/src/provider-quota.tsindex 48110ad8d..c0617c1a5 100644--- a/src/daemon/agent-driver/src/provider-quota.ts+++ b/src/daemon/agent-driver/src/provider-quota.ts@@ -1,3 +1,4 @@+import { readAntigravityQuota } from "./adapters/antigravity/quota.js";import { execFile } from "node:child_process";import { readFile } from "node:fs/promises";import { homedir } from "node:os";@@ -161,5 +162,5 @@ export async function readBuiltinProviderQuota(backend: BuiltinBackendId,options: QuotaReaderOptions = {},): Promise<ProviderQuotaObservation | null> {- return backend === "claude" ? readClaudeQuota(options) : null;+ return backend === "claude" ? readClaudeQuota(options) : backend === "antigravity" ? readAntigravityQuota(options) : null;}diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.tsindex c2ac63e39..67684f648 100644--- a/src/daemon/agent-driver/src/public-contract.ts+++ b/src/daemon/agent-driver/src/public-contract.ts@@ -6,12 +6,12 @@ export const SESSION_FILE_DISCOVERY_CAPABILITIES = sessionFileDiscoveryCapabilitexport type {JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, RuntimeReasoningCatalog,RuntimeSettingsUpdate, RuntimeSettingsUpdateResult, ModelSelection, DefaultProvider,- ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,+ AntigravityConfig, AntigravityCapabilities, ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,GrokConfig, OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,GrokCapabilities, OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,FixedCapabilities, ConfigOf, CapabilitiesOf, ExtensionsOf, ExtraEventOf, AgentInstructions, AgentLaunchContext, AgentMessage,AgentDriverError, OpenSessionResult, DeliveryReceipt, InterruptResult, StopInput, StopReceipt, HostCleanupResult,- AgentSessionResult, AgentTurnResult, TokenMetricDelta, TokenUsageDelta, QuotaErrorCode,+ AgentSessionResult, AgentTurnResult, TokenMetricDelta, TokenUsageDelta, TokenUsageIdentity, QuotaErrorCode,QuotaProductIdentity, QuotaModelIdentity, QuotaWindowIdentity, QuotaLimit,ProviderQuotaObservation, CoreAgentEventPayload, AgentEventEnvelope, AgentEvent,AgentSessionSnapshot, AgentEventStream, ExtensionNames, ExtensionInput, ExtensionOutput, ExtensionResult,diff --git a/src/daemon/agent-driver/src/registry.test.ts b/src/daemon/agent-driver/src/registry.test.tsindex 59bc84410..c6997d9a2 100644--- a/src/daemon/agent-driver/src/registry.test.ts+++ b/src/daemon/agent-driver/src/registry.test.ts@@ -13,6 +13,7 @@ import { ADAPTER_AUTHOR_CONTRACT_VERSION } from "./adapter-author.js";* without updating `capabilities`) trips CI.*/const EXPECTED: Record<BuiltinBackendId, BackendCapabilities> = {+ antigravity: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: true },claude: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true, disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },codex: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },cursor: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },@@ -30,6 +31,7 @@ describe("driver.capabilities", () => {expect(ADAPTER_AUTHOR_CONTRACT_VERSION).toBe(1);const registry = createBuiltinAgentDriverRegistry();const expected = {+ antigravity: { lifetime: "session", transport: { kind: "stdio_rpc", protocol: "antigravity.acp.v1" }, wakeStart: "immediate", terminalOwnership: "transport_request" },claude: {lifetime: "session",transport: { kind: "stdio_stream", protocol: "claude.stream-json.v1" },diff --git a/src/daemon/agent-driver/src/registry.ts b/src/daemon/agent-driver/src/registry.tsindex 8ef3eef73..63e821277 100644--- a/src/daemon/agent-driver/src/registry.ts+++ b/src/daemon/agent-driver/src/registry.ts@@ -6,6 +6,7 @@ import type {CapabilitiesOf,ConfigOf,} from "./contract.js";+import { AntigravityDriver } from "./adapters/antigravity/index.js";import { ClaudeDriver } from "./adapters/claude/index.js";import { CodexDriver } from "./adapters/codex/index.js";import { CursorDriver } from "./adapters/cursor/index.js";@@ -183,9 +184,13 @@ export function assertAdapterCompatibility(}}-export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "grok", "opencode", "pi"] as const;+export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"] as const;const capabilities = {+ antigravity: {+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "next_turn_queue", interrupt: true,+ },claude: {modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true,disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,@@ -220,6 +225,7 @@ export function createBuiltinAgentDriverRegistry(): AgentDriverRegistry<BuiltinB{ id: "grok", contractVersion: 1, capabilities: capabilities.grok, createAdapter: () => new GrokDriver() },{ id: "opencode", contractVersion: 1, capabilities: capabilities.opencode, createAdapter: () => new OpenCodeDriver() },{ id: "pi", contractVersion: 1, capabilities: capabilities.pi, createAdapter: () => new PiDriver() },+ { id: "antigravity", contractVersion: 1, capabilities: capabilities.antigravity, createAdapter: () => new AntigravityDriver() },]);}diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.tsindex 67595415d..d08ade358 100644--- a/src/daemon/agent-driver/src/sdk.test.ts+++ b/src/daemon/agent-driver/src/sdk.test.ts@@ -58,7 +58,7 @@ function sdkTestLane(receipt = "fresh-receipt") {describe("createAgentDriverSdk", () => {it("exposes the built-ins with default options", () => {- expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi"]);+ expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"]);expect(SESSION_FILE_DISCOVERY_CAPABILITIES).toEqual(["supported", "unavailable"]);});@@ -95,7 +95,7 @@ describe("createAgentDriverSdk", () => {);it("public SDK factory delegates to the built-in logical SDK", () => {- expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi"]);+ expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"]);});it.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(@@ -116,6 +116,11 @@ describe("createAgentDriverSdk", () => {},);+ it("reports Antigravity recent-context discovery as unsupported", async () => {+ expect(await createAgentDriverSdk().discoverRecentContext({ backend: "antigravity", recentSessionFilesTopK: 0, recentProjectsTopK: 0 }))+ .toMatchObject({ ok: false, error: { code: "recent_context_discovery_unsupported" } });+ });+it("validates independent Top-K values and dispatches discovery without leaking thrown details", async () => {const sdk = createAgentDriverSdk();const discover = vi.spyOn(ClaudeDriver.prototype, "discoverRecentContext");diff --git a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.tsindex ceb148488..5251c1fbf 100644--- a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts+++ b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts@@ -14,6 +14,7 @@ describe("builtin adapter protocol conformance", () => {claude: ["session", "stdio_stream", "claude.stream-json.v1", "safe_boundary_queue", "vendor_message"],codex: ["session", "stdio_rpc", "codex.app-server.v1", "safe_boundary_queue", "transport_request"],cursor: ["session", "stdio_rpc", "cursor.acp.v1", "steer", "transport_request"],+ antigravity: ["session", "stdio_rpc", "antigravity.acp.v1", "next_turn_queue", "transport_request"],grok: ["session", "stdio_rpc", "grok.acp.v1", "safe_boundary_queue", "transport_request"],opencode: ["session", "http_sse", "opencode.v2.service.1.17.20", "steer", "transport_request"],pi: ["session", "in_process_sdk", "pi_sdk", "steer", "prompt_invocation"],diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.tsindex 034d9f81c..230c0c87d 100644--- a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts@@ -26,6 +26,8 @@ import type {import { ClaudeDriver } from "../adapters/claude/index.js";import { CodexDriver } from "../adapters/codex/index.js";import { CursorDriver } from "../adapters/cursor/index.js";+import { AntigravityAcpLane } from "../adapters/antigravity/acp-lane.js";+import { AntigravityDriver } from "../adapters/antigravity/index.js";import { GrokDriver } from "../adapters/grok/index.js";import { CursorAcpLane } from "../adapters/cursor/acp-lane.js";import { GrokAcpLane } from "../adapters/grok/acp-lane.js";@@ -41,6 +43,7 @@ const configs: { [Id in BuiltinBackendId]: ConfigOf<BuiltinBackendSpecs, Id> } =claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },codex: { model: { kind: "default" }, mode: "default" },cursor: { model: { kind: "default" } },+ antigravity: { model: { kind: "default" } },grok: { model: { kind: "default" } },opencode: { model: { kind: "default" } },pi: { model: { kind: "default" }, provider: { kind: "default" } },@@ -168,7 +171,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {return lane;});} else {- const classes = { claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver };+ const classes = { claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver, antigravity: AntigravityDriver };if (backend === "claude") {const beginTurn = ClaudeDriver.prototype.beginTurn;vi.spyOn(ClaudeDriver.prototype, "beginTurn").mockImplementation(function (this: ClaudeDriver) {@@ -202,7 +205,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {if (!line.trim()) continue;const message = JSON.parse(line) as Record<string, unknown>;stdinMessages.push(message);- if (backend !== "cursor" && backend !== "grok") continue;+ if (backend !== "cursor" && backend !== "grok" && backend !== "antigravity") continue;const respond = (result: unknown) => process.stdout.write(`${JSON.stringify({jsonrpc: "2.0",id: message.id,@@ -211,6 +214,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {if (message.method === "initialize") {respond({protocolVersion: 1,+ agentInfo: { name: "antigravity-acp", version: "1.3.0" },agentCapabilities: { loadSession: true },authMethods: [{ id: backend === "grok" ? "cached_token" : "cursor_login" }],...(backend === "grok" ? {@@ -290,6 +294,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {} });break;case "cursor":+ case "antigravity":case "grok":break;case "opencode":@@ -313,6 +318,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {} });break;case "cursor":+ case "antigravity":case "grok":{const prompts = stdinMessages.filter((message) => message.method === "session/prompt");@@ -344,6 +350,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {} });break;case "cursor":+ case "antigravity":case "grok": {const prompts = stdinMessages.filter((message) => message.method === "session/prompt");const prompt = prompts[turn - 1]!;@@ -484,7 +491,7 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiharness.completeTurn(1);await settle();- if (backend === "cursor" || backend === "grok") {+ if (backend === "cursor" || backend === "grok" || backend === "antigravity") {await vi.waitFor(() => {expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(2);});@@ -500,14 +507,14 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiexpect(await settlePromptAdmission(backend, harness, 2, reuse)).toMatchObject({ status: "accepted" });if (backend === "pi") harness.handles[0]!.isStreaming = true;}- if (backend !== "cursor" && backend !== "grok") {+ if (backend !== "cursor" && backend !== "grok" && backend !== "antigravity") {if (backend !== "codex") harness.sessionReady(2);await settle();harness.completeTurn(2);await settle();}- if (backend === "claude" || backend === "codex" || backend === "grok") {+ if (backend === "claude" || backend === "codex" || backend === "grok" || backend === "antigravity") {expect(harness.processes).toHaveLength(1);expect(harness.processes[0]!.kill).not.toHaveBeenCalled();}@@ -568,7 +575,7 @@ function emitStaleTerminal(backend: BuiltinBackendId, harness: VendorHarness): vharness.duplicateTurn(1);}-describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(+describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"] as const)("%s shared persistent stress conformance",(backend) => {it("runs ten sequential public turns through one physical open", async () => {@@ -655,7 +662,7 @@ describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(},);-describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(+describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"] as const)("%s registered public-session lifecycle conformance",(backend) => {it("runs resume, busy admission, interrupt reuse, environment, release, and requested stop through sdk.open", async () => {@@ -672,7 +679,7 @@ describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(? PiDriver.prototype: backend === "opencode"? OpenCodeDriver.prototype- : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver, opencode: OpenCodeDriver } as const)[backend].prototype;+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver, antigravity: AntigravityDriver, opencode: OpenCodeDriver } as const)[backend].prototype;const existing = (prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!;existing.mockImplementationOnce(async (...args: unknown[]) => {await openGate;@@ -723,7 +730,7 @@ describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(? PiDriver.prototype: backend === "opencode"? OpenCodeDriver.prototype- : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver } as const)[backend].prototype;+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver, antigravity: AntigravityDriver } as const)[backend].prototype;(prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!.mockRejectedValueOnce(new Error("apiKey=supersecret failed at /Users/Alice Smith/private key.json"),);@@ -770,6 +777,8 @@ describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(const harness = installVendorHarness(backend);const laneStop = backend === "pi"? vi.spyOn(SdkLane.prototype, "stop")+ : backend === "antigravity"+ ? vi.spyOn(AntigravityAcpLane.prototype, "stop"): backend === "cursor"? vi.spyOn(CursorAcpLane.prototype, "stop"): backend === "grok"@@ -805,6 +814,8 @@ describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)(const harness = installVendorHarness(backend);const laneStop = backend === "pi"? vi.spyOn(SdkLane.prototype, "stop")+ : backend === "antigravity"+ ? vi.spyOn(AntigravityAcpLane.prototype, "stop"): backend === "cursor"? vi.spyOn(CursorAcpLane.prototype, "stop"): backend === "grok"diff --git a/src/daemon/src/cli/daemonSelfUpdate.real.test.ts b/src/daemon/src/cli/daemonSelfUpdate.real.test.tsindex 2ed668819..df273de53 100644--- a/src/daemon/src/cli/daemonSelfUpdate.real.test.ts+++ b/src/daemon/src/cli/daemonSelfUpdate.real.test.ts@@ -293,6 +293,7 @@ describe("daemon self-update real package/process handoff", () => {wsUrl: control.wsUrl,daemonVersion: "9.9.1",});+ await waitFor(() => updateEvents(baseDir).includes("replacement_ready"));expect(updateEvents(baseDir)).toContain("replacement_ready");expect(fs.readFileSync(path.join(daemonDir(baseDir), "update.log"), "utf8")).not.toContain(credential);} finally {@@ -319,6 +320,7 @@ describe("daemon self-update real package/process handoff", () => {expect(alive(oldOwner.pid)).toBe(false);expect(alive(newOwner.pid)).toBe(true);expect(newOwner.machineId).toBe(oldOwner.machineId);+ await waitFor(() => updateEvents(baseDir).includes("replacement_ready"));expect(updateEvents(baseDir)).toContain("replacement_ready");} finally {await control.close();diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex cb03ca9a2..2f9b8b2df 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -492,7 +492,7 @@ describe("createDaemon", () => {}});- it.each(["codex", "grok"] as const)("re-emits enriched idle when terminal %s telemetry arrives after turn completion", async (backendId) => {+ it.each(["codex", "grok", "antigravity"] as const)("re-emits enriched idle when terminal %s telemetry arrives after turn completion", async (backendId) => {const sockets: FakeSocket[] = [];const sessions: DaemonFakeSession[] = [];const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-provider-telemetry-"));@@ -518,6 +518,7 @@ describe("createDaemon", () => {sessions.push(session);return session;},+ providerQuotaReader: async () => null,capabilities: [],workingDirectoryBase,});@@ -547,12 +548,14 @@ describe("createDaemon", () => {type: "token_usage",turnId: "daemon-test-turn",source: `${backendId}_settled_usage`,+ ...(backendId === "antigravity" ? { identity: { source: "native:test", index: 0, occurredAt: new Date().toISOString() } } : {}),usage: {input: 20,output: 5,cache: null,},});+ if (backendId === "antigravity") await sessions[0]!.fire("agent_event", { type: "token_usage", source: "native:replay", usage: { input: 20, output: 5, cache: null }, identity: { source: "native:test", index: 0, occurredAt: new Date().toISOString() } });await sessions[0]!.fire("agent_event", {type: "rate_limits",source: `${backendId}_rate_limits_updated`,@@ -585,6 +588,19 @@ describe("createDaemon", () => {)).toBe(true));expect(existsSync(join(workingDirectoryBase, ".telemetry", "daily-token-usage.json"))).toBe(true);+ if (backendId === "antigravity") {+ await sessions[0]!.fire("agent_event", { type: "token_usage_status", source: "native", status: "unavailable" });+ await vi.waitFor(() => expect(frames().filter((frame) => frame.type === "agent_activity" && frame.state === "idle").at(-1)?.dailyUsage?.at(-1)?.metrics).toEqual({ input: null, output: null, cache: null }));+ const stored = () => JSON.parse(readFileSync(join(workingDirectoryBase, ".telemetry", "daily-token-usage.json"), "utf8"));+ expect(stored().bots.bot_1[0].metrics.input).toBe(20);+ const switched = vi.spyOn(AgentProcessManager.prototype, "agentBackendId").mockReturnValue("codex");+ await sessions[0]!.fire("agent_event", { type: "token_usage_status", source: "native", status: "unavailable" });+ await vi.waitFor(() => expect(frames().filter((frame) => frame.type === "agent_activity" && frame.state === "idle").at(-1)?.dailyUsage?.at(-1)?.metrics.input).toBe(20));+ switched.mockRestore();+ await sessions[0]!.fire("agent_event", { type: "token_usage_status", source: "native", status: "available" });+ await vi.waitFor(() => expect(frames().filter((frame) => frame.type === "agent_activity" && frame.state === "idle").at(-1)?.dailyUsage?.at(-1)?.metrics.input).toBe(20));+ expect(stored().bots.bot_1[0].metrics.input).toBe(20);+ }const readyBefore = frames().filter((frame) => frame.type === "ready").length;await sessions[0]!.fire("agent_event", {type: "rate_limits",diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 7e90eaa67..6734e3ac9 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -70,7 +70,7 @@ const RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;export const RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";/** How often the daemon rewrites the `daemon status` snapshot file (batch E2). */const STATUS_WRITE_INTERVAL_MS = 5_000;-const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "grok", "opencode", "pi"]);+const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "grok", "opencode", "pi", "antigravity"]);const ONBOARDING_RECENT_SESSION_FILES_TOP_K = 10;const ONBOARDING_RECENT_PROJECTS_TOP_K = 5;@@ -409,10 +409,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst dailyTokenUsage = new DailyTokenUsageStore(workingDirectoryBase);const providerQuotaReader = opts.providerQuotaReader?? (opts.sessionFactory ? async () => null : readBuiltinProviderQuota);- const providerQuotaByBackend = new Map<"claude" | "codex" | "grok", ProviderQuotaSnapshot>();+ const providerQuotaByBackend = new Map<ProviderQuotaSnapshot["agentBackendId"], ProviderQuotaSnapshot>();let requestReadyQuotaResend = (): void => {};const recordProviderQuota = (- backendId: "claude" | "codex" | "grok",+ backendId: ProviderQuotaSnapshot["agentBackendId"],quota: ProviderQuotaObservation,): void => {const previous = providerQuotaByBackend.get(backendId);@@ -456,21 +456,26 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// `auditContext(agentId)` off it inside `onProxyRequest`.const providerQuotaSnapshots = (): ProviderQuotaSnapshot[] =>[...providerQuotaByBackend.values()].map((snapshot) => structuredClone(snapshot));+ const tokenUsageAvailability = new Map<string, { backendId: BuiltinBackendId; status: "available" | "unavailable" }>();const activityPayload = async (info: { agentId: string; state: HostAgentActivity["state"] },): Promise<HostAgentActivity> => {if (info.state !== "idle") return info;const backendId = managerRef?.agentBackendId(info.agentId);- if (backendId === "claude") {- const observed = await providerQuotaReader("claude");- if (observed) recordProviderQuota("claude", observed);+ if (backendId === "claude" || backendId === "antigravity") {+ const observed = await providerQuotaReader(backendId);+ if (observed) recordProviderQuota(backendId, observed);}- const quota = backendId === "claude" || backendId === "codex" || backendId === "grok"+ const quota = backendId === "claude" || backendId === "codex" || backendId === "grok" || backendId === "antigravity"? providerQuotaByBackend.get(backendId): undefined;const usageWindow = backendId && TOKEN_USAGE_BACKENDS.has(backendId)? await dailyTokenUsage.usageWindow(info.agentId): null;+ if (usageWindow && tokenUsageAvailability.get(info.agentId)?.backendId === backendId && tokenUsageAvailability.get(info.agentId)?.status === "unavailable") {+ usageWindow.snapshots = usageWindow.snapshots.filter((snapshot) => snapshot.day !== usageWindow.usageDay);+ usageWindow.snapshots.push({ botId: info.agentId, day: usageWindow.usageDay, metrics: { input: null, output: null, cache: null } });+ }return {...info,...(usageWindow ? {@@ -998,7 +1003,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa? { handshakeTimeoutMs: opts.handshakeTimeoutMs }: {}),tickIntervalMs: opts.tickIntervalMs ?? 2000,- onAgentSession: (info) => void channel.reportAgentSession(info),+ onAgentSession: (info) => { tokenUsageAvailability.delete(info.agentId); void channel.reportAgentSession(info); },onAgentActivity: (info) => {selfSleepScheduler?.observeAgentActivity(info.agentId, info.state === "running");reportAgentActivity(info);@@ -1019,15 +1024,16 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaemitTypingStopsAndClear(info.agentId);}},- onTokenUsage: ({ agentId, usage }) => {- void dailyTokenUsage.record(agentId, usage)+ onTokenUsageStatus: ({ agentId, backendId, status }) => { tokenUsageAvailability.set(agentId, { backendId, status }); reportTelemetryForIdleAgent(agentId); },+ onTokenUsage: ({ agentId, usage, identity }) => {+ void dailyTokenUsage.record(agentId, usage, identity).then(() => reportTelemetryForIdleAgent(agentId)).catch(() => {log.warn("daily token usage persistence failed", { agentId });});},onProviderQuota: ({ agentId, backendId, quota }) => {- if (backendId !== "claude" && backendId !== "codex" && backendId !== "grok") return;+ if (backendId !== "claude" && backendId !== "codex" && backendId !== "grok" && backendId !== "antigravity") return;recordProviderQuota(backendId, quota);reportTelemetryForIdleAgent(agentId);},diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.tsindex ad91f99cc..d4f295e45 100644--- a/src/daemon/src/discovery.test.ts+++ b/src/daemon/src/discovery.test.ts@@ -12,7 +12,7 @@ import {} from "./discovery";import * as drivers from "./drivers/index";-const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "grok", "opencode", "pi"];+const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"];const tmpDirs: string[] = [];function mkTmp(): string {@@ -175,7 +175,7 @@ describe("detectRuntimes", () => {}});- it("advertises exactly the six supported runtimes", () => {+ it("advertises exactly the supported runtimes", () => {const advertised = runtimes.map((r) => r.id).sort();expect(advertised).toEqual([...EXPECTED_RUNTIMES].sort());});@@ -226,12 +226,12 @@ describe("detectRuntimes", () => {});describe("driver registry", () => {- it("contains exactly the six supported runtimes", () => {+ it("contains exactly the supported runtimes", () => {expect(drivers.listRuntimeIds().slice().sort()).toEqual([...EXPECTED_RUNTIMES].sort());});it("rejects removed and unknown runtimes", () => {- for (const removed of ["antigravity", "copilot", "gemini", "kimi", "unknown-runtime"]) {+ for (const removed of ["copilot", "gemini", "kimi", "unknown-runtime"]) {expect(() => drivers.getDriver(removed)).toThrow(/Unknown runtime/);}});diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 14d372543..545a6ef74 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -26,6 +26,7 @@ import type {RuntimeSettingsUpdateResult,ProviderQuotaObservation,TokenUsageDelta,+ TokenUsageIdentity,} from "@alook/agent-driver";import type { HostLaunchContext } from "./hostContext.js";import { runtimeModelName, type RuntimeConfig } from "../runtimeConfig.js";@@ -232,7 +233,8 @@ export interface ManagerRuntimeOpts {now?: () => number;onAgentSession?: (info: { agentId: string; sessionId: string; launchId: string }) => void;onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;- onTokenUsage?: (info: { agentId: string; backendId: BuiltinBackendId; usage: TokenUsageDelta }) => void;+ onTokenUsageStatus?: (info: { agentId: string; backendId: BuiltinBackendId; status: "available" | "unavailable" }) => void;+ onTokenUsage?: (info: { agentId: string; backendId: BuiltinBackendId; usage: TokenUsageDelta; identity?: TokenUsageIdentity }) => void;onProviderQuota?: (info: { agentId: string; backendId: BuiltinBackendId; quota: ProviderQuotaObservation }) => void;onBotAuditEvent?: (agentId: string,@@ -475,6 +477,7 @@ export class AgentProcessManager {| "credentialProxy"| "onAgentSession"| "onAgentActivity"+ | "onTokenUsageStatus"| "onTokenUsage"| "onProviderQuota"| "onBotAuditEvent"@@ -495,6 +498,7 @@ export class AgentProcessManager {| "credentialProxy"| "onAgentSession"| "onAgentActivity"+ | "onTokenUsageStatus"| "onTokenUsage"| "onProviderQuota"| "onBotAuditEvent"@@ -1970,8 +1974,9 @@ export class AgentProcessManager {runtime: runtimeId,});}+ if (event.type === "token_usage_status") this.opts.onTokenUsageStatus?.({ agentId, backendId: runtimeId, status: event.status });if (event.type === "token_usage") {- this.opts.onTokenUsage?.({ agentId, backendId: runtimeId, usage: event.usage });+ this.opts.onTokenUsage?.({ agentId, backendId: runtimeId, usage: event.usage, ...(event.identity ? { identity: event.identity } : {}) });}if (event.type === "rate_limits") {this.opts.onProviderQuota?.({ agentId, backendId: runtimeId, quota: event.quota });diff --git a/src/daemon/src/runtimeConfig.test.ts b/src/daemon/src/runtimeConfig.test.tsindex 0edfdd1df..10364f08b 100644--- a/src/daemon/src/runtimeConfig.test.ts+++ b/src/daemon/src/runtimeConfig.test.ts@@ -3,7 +3,7 @@ import { runtimeModelName, toAgentBackendSelection } from "./runtimeConfig";import { makeRuntimeConfig } from "./runtimeConfig";describe("runtimeModelName", () => {- for (const runtime of ["claude", "codex", "cursor", "grok", "opencode", "pi"]) {+ for (const runtime of ["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"]) {it(`${runtime}: projects a named model without interpreting the backend`, () => {expect(runtimeModelName(makeRuntimeConfig({ runtime, model: { kind: "named", name: "opus" } }))).toBe("opus");diff --git a/src/daemon/src/telemetry/dailyTokenUsage.test.ts b/src/daemon/src/telemetry/dailyTokenUsage.test.tsindex bda2200d7..9e6787f1e 100644--- a/src/daemon/src/telemetry/dailyTokenUsage.test.ts+++ b/src/daemon/src/telemetry/dailyTokenUsage.test.ts@@ -246,3 +246,90 @@ describe("DailyTokenUsageStore", () => {expect(persisted.bots.bot?.at(-1)?.day).toBe("2026-08-30");});});++describe("native generation recovery", () => {+ const sample = (index: number, occurredAt = "2026-10-03T23:59:59Z", source = "provider:session") => ({ source, index, occurredAt });+ function setupRecovery() {+ const root = mkdtempSync(join(tmpdir(), "alook-native-recovery-")); roots.push(root);+ const now = () => new Date("2026-10-04T10:00:00Z");+ return { root, store: new DailyTokenUsageStore(root, now, "UTC"), restart: () => new DailyTokenUsageStore(root, now, "UTC") };+ }+ it("recovers native writes before accounting and suppresses replay after accounting across midnight", async () => {+ const h = setupRecovery();+ await h.store.record("bot", delta(90, 24, 23), sample(0));+ const recovered = h.restart();+ await recovered.record("bot", delta(90, 24, 23), sample(0));+ await recovered.record("bot", delta(90, 24, 23), sample(1, "2026-10-04T00:00:00Z"));+ expect(await recovered.snapshots("bot")).toMatchObject([+ { day: "2026-10-03", metrics: { input: 90, output: 24, cache: 23 } },+ { day: "2026-10-04", metrics: { input: 90, output: 24, cache: 23 } },+ ]);+ await recovered.record("other", delta(90, 24, 23), sample(0));+ expect((await recovered.snapshots("other"))[0].metrics.input).toBe(90);+ });+ it("recovers a failed lower generation after a higher generation commits", async () => {+ const h = setupRecovery();+ await h.store.record("bot", delta(1, 2, 3), sample(0));+ const path = join(h.root, ".telemetry", "daily-token-usage.json");+ rmSync(path); mkdirSync(path);+ await expect(h.store.record("bot", delta(10, 20, 30), sample(1))).rejects.toThrow();+ rmSync(path, { recursive: true });+ await h.store.record("bot", delta(100, 200, 300), sample(2));+ expect((await h.store.snapshots("bot"))[0].metrics).toEqual({ input: 111, output: 222, cache: 333 });+ const recovered = h.restart();+ await recovered.record("bot", delta(10, 20, 30), sample(1));+ await recovered.record("bot", delta(100, 200, 300), sample(2));+ expect((await recovered.snapshots("bot"))[0].metrics).toEqual({ input: 111, output: 222, cache: 333 });+ expect(JSON.parse(readFileSync(path, "utf8")).sources.bot["provider:session"].ranges).toEqual([[0, 2]]);+ });+ it("does not assign old or undated native records to today", async () => {+ const h = setupRecovery();+ await h.store.record("bot", delta(1, 2, 3), sample(0, "2026-01-01T00:00:00Z"));+ expect(await h.store.snapshots("bot")).toEqual([]);+ await expect(h.store.record("bot", delta(1, 2, 3), sample(1, "unknown"))).rejects.toThrow("identity");+ await expect(h.store.record("bot", delta(1, 2, 3), sample(-1))).rejects.toThrow("identity");+ });+ it("keeps sources isolated and missing metrics unknown on replay", async () => {+ const h = setupRecovery();+ await h.store.record("bot", delta(1, 2, 3), sample(0));+ await h.store.record("bot", { input: 90, output: 24, cache: null }, sample(0, undefined, "provider:other"));+ await h.restart().record("bot", delta(90, 24, 23), sample(0, undefined, "provider:other"));+ expect((await h.restart().snapshots("bot"))[0].metrics).toEqual({ input: 91, output: 26, cache: null });+ });+});++it("retries a failed native sample on the next telemetry read without restart or new generation", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-native-retry-")); roots.push(root);+ const store = new DailyTokenUsageStore(root, () => new Date("2026-10-04T10:00:00Z"), "UTC");+ await store.snapshots("bot");+ const directory = join(root, ".telemetry"); mkdirSync(directory);+ const path = join(directory, "daily-token-usage.json"); mkdirSync(path);+ await expect(store.record("bot", delta(90, 24, 23), { source: "native:session", index: 0, occurredAt: "2026-10-04T09:00:00Z" })).rejects.toThrow();+ rmSync(path, { recursive: true });+ expect((await store.snapshots("bot"))[0].metrics).toEqual({ input: 90, output: 24, cache: 23 });+ expect((await new DailyTokenUsageStore(root, () => new Date("2026-10-04T10:00:00Z"), "UTC").snapshots("bot"))[0].metrics.input).toBe(90);+});++it.each([+ { version: 2, bots: {} },+ { version: 1, bots: [] },+ { version: 1, bots: { bot: [{}] } },+ { version: 1, bots: {}, sources: [] },+ { version: 1, bots: {}, sources: { bot: [] } },+ { version: 1, bots: {}, sources: { bot: { source: { ranges: [[2, 1]], day: "2026-10-04" } } } },+])("rejects corrupt accounting rather than silently losing deduplication metadata: %j", async (contents) => {+ const root = mkdtempSync(join(tmpdir(), "alook-usage-corrupt-")); roots.push(root);+ const directory = join(root, ".telemetry"); mkdirSync(directory);+ writeFileSync(join(directory, "daily-token-usage.json"), JSON.stringify(contents));+ await expect(new DailyTokenUsageStore(root).snapshots("bot")).rejects.toThrow();+});++it("expires old source ranges together with retained daily counts", async () => {+ const root = mkdtempSync(join(tmpdir(), "alook-source-retention-")); roots.push(root);+ let now = new Date("2026-10-04T10:00:00Z");+ const store = new DailyTokenUsageStore(root, () => now, "UTC");+ await store.record("bot", delta(90, 24, 23), { source: "native:session", index: 0, occurredAt: now.toISOString() });+ now = new Date("2026-11-20T10:00:00Z");+ expect(await store.snapshots("bot")).toEqual([]);+ expect(JSON.parse(readFileSync(join(root, ".telemetry", "daily-token-usage.json"), "utf8")).sources).toEqual({});+});diff --git a/src/daemon/src/telemetry/dailyTokenUsage.ts b/src/daemon/src/telemetry/dailyTokenUsage.tsindex c5717bfd2..a72c942a6 100644--- a/src/daemon/src/telemetry/dailyTokenUsage.ts+++ b/src/daemon/src/telemetry/dailyTokenUsage.ts@@ -1,7 +1,7 @@import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises";import { dirname, join } from "node:path";import { randomUUID } from "node:crypto";-import type { TokenUsageDelta } from "@alook/agent-driver";+import type { TokenUsageDelta, TokenUsageIdentity } from "@alook/agent-driver";import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared";const TOKEN_USAGE_WINDOW_DAYS = 30;@@ -23,6 +23,7 @@ export interface DailyUsageSnapshot {type UsageFile = {version: 1;bots: Record<string, DailyUsageSnapshot[]>;+ sources?: Record<string, Record<string, { ranges: [number, number][]; day: string }>>;};function oldestRetainedDay(at: Date, timeZone: string): string {@@ -84,6 +85,7 @@ function emptySnapshot(botId: string, day: string): DailyUsageSnapshot {export class DailyTokenUsageStore {private tail: Promise<void> = Promise.resolve();private loaded = false;+ private pending: { botId: string; delta: TokenUsageDelta; identity: TokenUsageIdentity }[] = [];private data: UsageFile = { version: 1, bots: {} };private readonly filePath: string;private readonly resolveTimeZone: () => string;@@ -104,28 +106,68 @@ export class DailyTokenUsageStore {return timeZone;}- record(botId: string, delta: TokenUsageDelta): Promise<void> {+ record(botId: string, delta: TokenUsageDelta, identity?: TokenUsageIdentity): Promise<void> {return this.enqueue(async () => {- await this.load();- const at = this.now();- const timeZone = this.timeZone;- this.prune(at, timeZone);- const day = dayKeyInTimeZone(at, timeZone);- const snapshots = this.data.bots[botId] ?? [];- const existing = snapshots.find((snapshot) => snapshot.day === day);- const next = existing ?? emptySnapshot(botId, day);- next.metrics = {- input: mergeMetric(next.metrics.input, delta.input, existing !== undefined),- output: mergeMetric(next.metrics.output, delta.output, existing !== undefined),- cache: mergeMetric(next.metrics.cache, delta.cache, existing !== undefined),- };- if (!existing) snapshots.push(next);- snapshots.sort((a, b) => a.day.localeCompare(b.day));- this.data.bots[botId] = snapshots;- await this.persist();+ if (identity) {+ if (!identity.source || identity.source.length > 256 || !Number.isSafeInteger(identity.index) || identity.index < 0 || !Number.isFinite(Date.parse(identity.occurredAt))) throw new Error("Invalid token usage identity");+ if (!this.pending.some((sample) => sample.botId === botId && sample.identity.source === identity.source && sample.identity.index === identity.index)) this.pending.push({ botId, delta, identity });+ await this.load();+ await this.flushPending();+ } else {+ await this.load();+ await this.flushPending();+ const previous = this.data;+ this.data = structuredClone(previous);+ try { this.apply(botId, delta); await this.persist(); }+ catch (error) { this.data = previous; throw error; }+ }});}+ private async flushPending(): Promise<void> {+ if (!this.pending.length) return;+ const previous = this.data;+ this.data = structuredClone(previous);+ try {+ for (const sample of this.pending) this.apply(sample.botId, sample.delta, sample.identity);+ await this.persist();+ this.pending = [];+ } catch (error) { this.data = previous; throw error; }+ }++ private apply(botId: string, delta: TokenUsageDelta, identity?: TokenUsageIdentity): void {+ const at = this.now();+ const timeZone = this.timeZone;+ const day = dayKeyInTimeZone(identity ? new Date(identity.occurredAt) : at, timeZone);+ if (identity && day < oldestRetainedDay(at, timeZone)) return;+ if (identity && this.data.sources?.[botId]?.[identity.source]?.ranges.some(([start, end]) => identity.index >= start && identity.index <= end)) return;+ this.prune(at, timeZone);+ const snapshots = this.data.bots[botId] ?? [];+ const existing = snapshots.find((snapshot) => snapshot.day === day);+ const next = existing ?? emptySnapshot(botId, day);+ next.metrics = {+ input: mergeMetric(next.metrics.input, delta.input, existing !== undefined),+ output: mergeMetric(next.metrics.output, delta.output, existing !== undefined),+ cache: mergeMetric(next.metrics.cache, delta.cache, existing !== undefined),+ };+ if (!existing) snapshots.push(next);+ snapshots.sort((a, b) => a.day.localeCompare(b.day));+ this.data.bots[botId] = snapshots;+ if (identity) {+ this.data.sources ??= {};+ this.data.sources[botId] ??= {};+ const saved = this.data.sources[botId][identity.source];+ const ranges: [number, number][] = [...(saved?.ranges ?? []), [identity.index, identity.index] as [number, number]].sort((a, b) => a[0] - b[0]);+ const merged: [number, number][] = [];+ for (const range of ranges) {+ const last = merged.at(-1);+ if (last && range[0] <= last[1] + 1) last[1] = Math.max(last[1], range[1]);+ else merged.push([range[0], range[1]]);+ }+ this.data.sources[botId][identity.source] = { ranges: merged, day: saved && saved.day > day ? saved.day : day };+ }+ }+snapshots(botId: string): Promise<DailyUsageSnapshot[]> {return this.usageWindow(botId).then((window) => window.snapshots);}@@ -140,6 +182,7 @@ export class DailyTokenUsageStore {let usageTimeZone = "";return this.enqueue(async () => {await this.load();+ await this.flushPending();const at = this.now();const timeZone = this.timeZone;usageTimeZone = timeZone;@@ -202,7 +245,17 @@ export class DailyTokenUsageStore {valid[botId] = value;}}- this.data = { version: 1, bots: valid };+ const sources = (parsed as { sources?: UsageFile["sources"] }).sources;+ if (sources !== undefined) {+ if (!sources || typeof sources !== "object" || Array.isArray(sources)) throw new Error("Invalid usage sources");+ for (const entries of Object.values(sources)) {+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new Error("Invalid usage source map");+ for (const [source, cursor] of Object.entries(entries)) {+ if (!source || source.length > 256 || !cursor || !Array.isArray(cursor.ranges) || !cursor.ranges.every((range) => Array.isArray(range) && range.length === 2 && range.every((index) => Number.isSafeInteger(index) && index >= 0) && range[0] <= range[1]) || typeof cursor.day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(cursor.day)) throw new Error("Invalid usage source cursor");+ }+ }+ }+ this.data = { version: 1, bots: valid, ...(sources ? { sources } : {}) };this.loaded = true;}@@ -220,6 +273,10 @@ export class DailyTokenUsageStore {if (retained.length === 0) delete this.data.bots[botId];else this.data.bots[botId] = retained;}+ for (const [botId, entries] of Object.entries(this.data.sources ?? {})) {+ for (const [source, cursor] of Object.entries(entries)) if (cursor.day < oldestDay) { delete entries[source]; changed = true; }+ if (!Object.keys(entries).length) delete this.data.sources![botId];+ }return changed;}diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.tsindex bf5920907..d4bf6da1c 100644--- a/src/shared/src/db/community-machine-schema.ts+++ b/src/shared/src/db/community-machine-schema.ts@@ -282,7 +282,7 @@ export const communityMachineBackendQuota = sqliteTable(machineId: text("machine_id").notNull().references(() => communityMachine.id, { onDelete: "cascade" }),- agentBackendId: text("agent_backend_id").$type<"claude" | "codex" | "grok">().notNull(),+ agentBackendId: text("agent_backend_id").$type<"claude" | "codex" | "grok" | "antigravity">().notNull(),sourceEpoch: text("source_epoch").notNull(),status: text("status").$type<MachineBackendQuotaStatus>().notNull(),planName: text("plan_name"),diff --git a/src/shared/src/provider-telemetry.test.ts b/src/shared/src/provider-telemetry.test.tsindex 1ab254040..43fe35da4 100644--- a/src/shared/src/provider-telemetry.test.ts+++ b/src/shared/src/provider-telemetry.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"import {DailyUsageSnapshotSchema,ProviderQuotaObservationSchema,+ ProviderQuotaSnapshotSchema,} from "./provider-telemetry.js"function quotaLimit() {@@ -18,6 +19,10 @@ function quotaLimit() {}describe("provider telemetry schemas", () => {+ it("accepts Antigravity quota without a schema or DB migration", () => {+ expect(ProviderQuotaSnapshotSchema.safeParse({ agentBackendId: "antigravity", observation: { status: "error", sourceEpoch: "A".repeat(22), code: "unauthorized", retryable: false } }).success).toBe(true)+ })+it("accepts exact zero and unavailable usage without conflating them", () => {expect(DailyUsageSnapshotSchema.parse({botId: "bot_1",diff --git a/src/shared/src/provider-telemetry.ts b/src/shared/src/provider-telemetry.tsindex 3377ff30d..8e67b65bb 100644--- a/src/shared/src/provider-telemetry.ts+++ b/src/shared/src/provider-telemetry.ts@@ -108,7 +108,7 @@ export const ProviderQuotaObservationSchema = z.union([export type ProviderQuotaObservation = z.infer<typeof ProviderQuotaObservationSchema>;export const ProviderQuotaSnapshotSchema = z.object({- agentBackendId: z.enum(["claude", "codex", "grok"]),+ agentBackendId: z.enum(["claude", "codex", "grok", "antigravity"]),observation: ProviderQuotaObservationSchema,}).strict();export type ProviderQuotaSnapshot = z.infer<typeof ProviderQuotaSnapshotSchema>;diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.tsindex 14942663d..3f7046b60 100644--- a/src/shared/src/schemas.test.ts+++ b/src/shared/src/schemas.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from "vitest"import {+ HostReadyMessageSchema,CommunityBotCreateRequestSchema,CommunityBotPatchRequestSchema,CommunityServerOnboardRequestSchema,@@ -359,3 +360,9 @@ describe("BotAuditEventSchema — error", () => {expect(BotAuditEventKindSchema.safeParse("error").success).toBe(true)})})++it("accepts the four supported provider quotas in a ready snapshot and bounds extra entries", () => {+ const providerQuotas = ["claude", "codex", "grok", "antigravity"].map((agentBackendId) => ({ agentBackendId, observation: { status: "error", sourceEpoch: "A".repeat(22), code: "unavailable", retryable: false } }))+ expect(HostReadyMessageSchema.safeParse({ type: "ready", runtimeReport: [], providerQuotas }).success).toBe(true)+ expect(HostReadyMessageSchema.safeParse({ type: "ready", runtimeReport: [], providerQuotas: [...providerQuotas, providerQuotas[0]] }).success).toBe(false)+})diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex fe9610288..33fa4c89d 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -990,7 +990,7 @@ export const HostReadyMessageSchema = z.object({osRelease: z.string().optional(),daemonVersion: z.string().optional(),timeZone: z.string().min(1).max(128).optional(),- providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(3).optional().default([]),+ providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(4).optional().default([]),});export type HostReadyMessage = z.infer<typeof HostReadyMessageSchema>;diff --git a/src/shared/test/migrations/community-machine-backend-quota-antigravity.test.ts b/src/shared/test/migrations/community-machine-backend-quota-antigravity.test.tsnew file mode 100644index 000000000..dc61f3a3d--- /dev/null+++ b/src/shared/test/migrations/community-machine-backend-quota-antigravity.test.ts@@ -0,0 +1,93 @@+import Sqlite from "better-sqlite3";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++const migrationDirectory = resolve(import.meta.dirname, "../../../web/migrations");+const epoch = "a".repeat(22);+const now = "2026-10-06T00:00:00.000Z";++function migrate(db: Sqlite.Database, name: string): void {+ db.transaction(() => db.exec(readFileSync(resolve(migrationDirectory, name), "utf8")))();+}++function insertError(db: Sqlite.Database, backend: string, machine = "machine_1"): void {+ db.prepare(`INSERT INTO community_machine_backend_quota (+ machine_id, agent_backend_id, source_epoch, status, error_code, retryable, observed_at, updated_at+ ) VALUES (?, ?, ?, 'error', 'network', 1, ?, ?)`).run(machine, backend, epoch, now, now);+}++function rows(db: Sqlite.Database): unknown[] {+ return db.prepare("SELECT * FROM community_machine_backend_quota ORDER BY machine_id, agent_backend_id").all();+}++describe("0105 Antigravity backend quota migration", () => {+ let db: Sqlite.Database;++ beforeEach(() => {+ db = new Sqlite(":memory:");+ db.pragma("foreign_keys = ON");+ db.exec(`+ CREATE TABLE user (id TEXT PRIMARY KEY);+ CREATE TABLE community_machine (id TEXT PRIMARY KEY);+ INSERT INTO community_machine VALUES ('machine_1'), ('machine_2');+ `);+ migrate(db, "0092_community_token_usage_quota.sql");+ migrate(db, "0097_community_machine_backend_quota_grok.sql");+ db.prepare(`INSERT INTO community_machine_backend_quota (+ machine_id, agent_backend_id, source_epoch, status, plan_name, fresh_for_seconds,+ limits, observed_at, updated_at+ ) VALUES ('machine_1', 'claude', ?, 'available', 'Existing plan', 300, ?, ?, ?)`).run(+ epoch, JSON.stringify([{ remainingFraction: 0.37 }]), now, "2026-10-06T00:01:00.000Z",+ );+ insertError(db, "codex");+ insertError(db, "grok");+ insertError(db, "grok", "machine_2");+ });++ afterEach(() => db.close());++ it("preserves every old row and admits both Antigravity observation states", () => {+ const before = rows(db);+ expect(() => insertError(db, "antigravity")).toThrow(/CHECK constraint failed/i);+ migrate(db, "0105_community_machine_backend_quota_antigravity.sql");+ expect(rows(db)).toEqual(before);+ expect(db.pragma("foreign_key_check")).toEqual([]);+ insertError(db, "antigravity");+ db.prepare(`INSERT INTO community_machine_backend_quota (+ machine_id, agent_backend_id, source_epoch, status, fresh_for_seconds, limits, observed_at, updated_at+ ) VALUES ('machine_2', 'antigravity', ?, 'available', 300, '[{}]', ?, ?)`).run(epoch, now, now);+ expect(db.prepare("SELECT status FROM community_machine_backend_quota WHERE agent_backend_id = 'antigravity' ORDER BY machine_id").all()).toEqual([+ { status: "error" }, { status: "available" },+ ]);+ });++ it("retains backend, epoch and observation validity constraints", () => {+ migrate(db, "0105_community_machine_backend_quota_antigravity.sql");+ expect(() => insertError(db, "unsupported")).toThrow(/CHECK constraint failed/i);+ insertError(db, "antigravity");+ for (const assignment of [+ "source_epoch = 'invalid'", "status = 'invalid'", "retryable = 2",+ "error_code = 'invalid'", "plan_name = 'invalid'", "limits = '[{}]'",+ ]) {+ expect(() => db.exec(`UPDATE community_machine_backend_quota SET ${assignment} WHERE agent_backend_id = 'antigravity'`)).toThrow(/CHECK constraint failed/i);+ }+ for (const assignment of [+ "fresh_for_seconds = 0", "fresh_for_seconds = 86401", "limits = '[]'",+ "limits = 'not-json'", "error_code = 'network'", "retryable = 1",+ ]) {+ expect(() => db.exec(`UPDATE community_machine_backend_quota SET ${assignment} WHERE agent_backend_id = 'claude'`)).toThrow(/CHECK constraint failed/i);+ }+ });++ it("retains composite uniqueness, machine foreign key and scoped cascade", () => {+ migrate(db, "0105_community_machine_backend_quota_antigravity.sql");+ insertError(db, "antigravity");+ expect(() => insertError(db, "antigravity")).toThrow(/UNIQUE constraint failed/i);+ expect(() => insertError(db, "antigravity", "missing")).toThrow(/FOREIGN KEY constraint failed/i);+ const sibling = db.prepare("SELECT * FROM community_machine_backend_quota WHERE machine_id = 'machine_2'").all();+ db.exec("DELETE FROM community_machine WHERE id = 'machine_1'");+ expect(rows(db)).toEqual(sibling);+ expect(db.pragma("foreign_key_check")).toEqual([]);+ });+});diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.tsindex 48ae6b75d..3832b2369 100644--- a/src/shared/test/schemas/community-runtime.test.ts+++ b/src/shared/test/schemas/community-runtime.test.ts@@ -308,7 +308,7 @@ describe("HostReadyMessageSchema", () => {});it("accepts one quota snapshot for each supported provider backend", () => {- const providerQuotas = (["claude", "codex", "grok"] as const).map((agentBackendId) => ({+ const providerQuotas = (["claude", "codex", "grok", "antigravity"] as const).map((agentBackendId) => ({agentBackendId,observation: {status: "error" as const,diff --git a/src/web/migrations/0105_community_machine_backend_quota_antigravity.sql b/src/web/migrations/0105_community_machine_backend_quota_antigravity.sqlnew file mode 100644index 000000000..9f71e6d5a--- /dev/null+++ b/src/web/migrations/0105_community_machine_backend_quota_antigravity.sql@@ -0,0 +1,51 @@+PRAGMA defer_foreign_keys=ON;++CREATE TABLE community_machine_backend_quota_new (+ machine_id TEXT NOT NULL REFERENCES community_machine(id) ON DELETE CASCADE,+ agent_backend_id TEXT NOT NULL CHECK (agent_backend_id IN ('claude', 'codex', 'grok', 'antigravity')),+ source_epoch TEXT NOT NULL CHECK (length(source_epoch) = 22 AND source_epoch NOT GLOB '*[^A-Za-z0-9_-]*'),+ status TEXT NOT NULL CHECK (status IN ('available', 'error')),+ plan_name TEXT,+ fresh_for_seconds INTEGER,+ limits TEXT,+ error_code TEXT,+ retryable INTEGER,+ observed_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (machine_id, agent_backend_id),+ CHECK (+ (status = 'available' AND fresh_for_seconds BETWEEN 1 AND 86400 AND json_valid(limits) AND json_array_length(limits) BETWEEN 1 AND 8 AND error_code IS NULL AND retryable IS NULL)+ OR+ (status = 'error' AND plan_name IS NULL AND fresh_for_seconds IS NULL AND limits IS NULL AND error_code IN ('unavailable', 'unauthorized', 'network', 'provider_error', 'invalid_response') AND retryable IN (0, 1))+ )+);++INSERT INTO community_machine_backend_quota_new (+ machine_id,+ agent_backend_id,+ source_epoch,+ status,+ plan_name,+ fresh_for_seconds,+ limits,+ error_code,+ retryable,+ observed_at,+ updated_at+)+SELECT+ machine_id,+ agent_backend_id,+ source_epoch,+ status,+ plan_name,+ fresh_for_seconds,+ limits,+ error_code,+ retryable,+ observed_at,+ updated_at+FROM community_machine_backend_quota;++DROP TABLE community_machine_backend_quota;+ALTER TABLE community_machine_backend_quota_new RENAME TO community_machine_backend_quota;diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex 2b22e324e..06bd86575 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -345,6 +345,7 @@ describe("GET /api/community/bots — heatmap activity", () => {{ id: "bot_claude", runtime: "claude" },{ id: "bot_codex", runtime: "codex" },{ id: "bot_cursor", runtime: "cursor" },+ { id: "bot_antigravity", runtime: "antigravity" },{ id: "bot_grok", runtime: "grok" },{ id: "bot_opencode", runtime: "opencode" },{ id: "bot_pi", runtime: "pi" },@@ -387,6 +388,7 @@ describe("GET /api/community/bots — heatmap activity", () => {bot_claude: "supported",bot_codex: "supported",bot_cursor: "unsupported",+ bot_antigravity: "supported",bot_grok: "supported",bot_opencode: "supported",bot_pi: "supported",diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex dc275daf1..504aa2743 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -59,9 +59,9 @@ export const GET = withAuth(async (_req, ctx) => {image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),dailyActivity: activityByBot.get(bot.id) ?? [],usage: {- capability: (["claude", "codex", "grok", "opencode", "pi"] as string[]).includes(bot.runtime)+ capability: (["claude", "codex", "grok", "opencode", "pi", "antigravity"] as string[]).includes(bot.runtime)? "supported" as const- : bot.runtime === "cursor"+ : ["cursor"].includes(bot.runtime)? "unsupported" as const: "unknown" as const,days: usageDays.map((day, index) => {diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.test.tsindex 0af77c80a..237628183 100644--- a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts@@ -1,8 +1,17 @@-import { describe, it, expect, vi, beforeEach } from "vitest";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { NextRequest } from "next/server";+const { mockBindingFetch, mockHttpFetch } = vi.hoisted(() => ({+ mockBindingFetch: vi.fn(),+ mockHttpFetch: vi.fn(),+}));+vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+ getCloudflareContext: vi.fn(async () => ({ env: {+ DB: {},+ WS_DO_WORKER: { fetch: mockBindingFetch },+ DEV_WS_DO_URL: "http://localhost:8789",+ } })),}));vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));@@ -33,6 +42,12 @@ vi.mock("@alook/shared", async () => {});import { POST } from "./route";+import { makeRuntimeConfig, sendWakeToMachine, type HostCommand } from "@alook/shared";++afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});function req(headers: Record<string, string> = {}): NextRequest {return new NextRequest("http://localhost/api/community/daemon/resync-wakes", {@@ -44,6 +59,9 @@ function req(headers: Record<string, string> = {}): NextRequest {describe("POST /api/community/daemon/resync-wakes", () => {beforeEach(() => {vi.clearAllMocks();+ mockDispatchOneUnreadWake.mockReset();+ mockBindingFetch.mockReset();+ mockHttpFetch.mockReset();mockFindCred.mockResolvedValue({credentialId: "cmk_ok",userId: "u_1",@@ -140,3 +158,70 @@ describe("POST /api/community/daemon/resync-wakes", () => {expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled();});});+++describe("resync wake transport", () => {+ const command: HostCommand = {+ type: "agent:wake",+ agentId: "bot_1",+ config: makeRuntimeConfig({ runtime: "antigravity" }),+ launchId: "launch_1",+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },+ };+ const path = "/community-machine/by-id/cm_1/forward-agent-wake";+ const receipt = () => Response.json({ attempted: 1 });++ beforeEach(() => {+ vi.clearAllMocks();+ mockBindingFetch.mockReset();+ mockHttpFetch.mockReset();+ vi.stubEnv("NODE_ENV", "development");+ vi.stubGlobal("fetch", mockHttpFetch);+ mockFindCred.mockResolvedValue({ credentialId: "cmk_ok", userId: "u_1", machineId: "cm_1" });+ mockListBotsForMachine.mockResolvedValue([{ id: "bot_1" }]);+ mockGetLatestUnreadMessageForAgent.mockResolvedValue({ messageId: "msg_1" });+ mockDispatchOneUnreadWake.mockImplementation(async (_db, env) => {+ const { attempted } = await sendWakeToMachine(env, "cm_1", command);+ return { outcome: attempted ? "attempted" : "attempted_nowhere" };+ });+ });++ it.each(["503", "throw"])("development recovers a binding %s through the same worker path and wake body", async (failure) => {+ if (failure === "503") mockBindingFetch.mockResolvedValue(new Response("unavailable", { status: 503 }));+ else mockBindingFetch.mockRejectedValue(new Error("binding disconnected"));+ mockHttpFetch.mockResolvedValue(receipt());++ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));++ expect(await res.json()).toEqual({ attempted: 1 });+ const init = { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) };+ expect(mockBindingFetch).toHaveBeenCalledWith(`http://internal${path}`, init);+ expect(mockHttpFetch).toHaveBeenCalledExactlyOnceWith(`http://localhost:8789${path}`, init);+ });++ it("successful binding stays binding-only", async () => {+ mockBindingFetch.mockResolvedValue(receipt());+ expect(await (await POST(req({ Authorization: "Bearer cmk_ok" }))).json()).toEqual({ attempted: 1 });+ expect(mockHttpFetch).not.toHaveBeenCalled();+ });++ it("development preserves a binding 4xx without HTTP fallback", async () => {+ mockBindingFetch.mockResolvedValue(new Response("bad request", { status: 400 }));+ await expect(POST(req({ Authorization: "Bearer cmk_ok" }))).rejects.toThrow("ws-do route returned 400");+ expect(mockHttpFetch).not.toHaveBeenCalled();+ });++ it.each(["503", "throw"])("production preserves binding %s failure without HTTP fallback", async (failure) => {+ vi.stubEnv("NODE_ENV", "production");+ if (failure === "503") mockBindingFetch.mockResolvedValue(new Response("unavailable", { status: 503 }));+ else mockBindingFetch.mockRejectedValue(new Error("binding disconnected"));+ await expect(POST(req({ Authorization: "Bearer cmk_ok" }))).rejects.toThrow(failure === "503" ? "ws-do route returned 503" : "binding disconnected");+ expect(mockHttpFetch).not.toHaveBeenCalled();+ });++ it("failed development fallback remains a resync failure", async () => {+ mockBindingFetch.mockResolvedValue(new Response("unavailable", { status: 503 }));+ mockHttpFetch.mockResolvedValue(new Response("worker unavailable", { status: 502 }));+ await expect(POST(req({ Authorization: "Bearer cmk_ok" }))).rejects.toThrow("ws-do route returned 502");+ });+});diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.tsindex 6a6451db1..935b7e02b 100644--- a/src/web/src/app/api/community/daemon/resync-wakes/route.ts+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server"import { queries, dispatchOneUnreadWake, withD1Retry } from "@alook/shared"import { getDb } from "@/lib/db"+import { wsDoFetch } from "@/lib/broadcast"import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"/**@@ -24,6 +25,17 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"*/export const POST = withCommunityDaemonAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)+ const wakeEnv = {+ WS_DO_WORKER: {+ fetch(input: string, init: RequestInit = {}) {+ const url = new URL(input)+ return wsDoFetch(ctx.env, url.pathname + url.search, init, {+ label: ctx.machineId,+ type: "agent:wake",+ })+ },+ },+ }const bots = await withD1Retry(() => queries.communityBot.listBotsForMachine(db, ctx.machineId),{ route: "community/daemon/resync-wakes:list-bots" },@@ -36,7 +48,7 @@ export const POST = withCommunityDaemonAuth(async (_req, ctx) => {{ route: "community/daemon/resync-wakes:latest-unread" },)if (!latest) continue- const result = await dispatchOneUnreadWake(db, ctx.env, { messageId: latest.messageId, botUserId: bot.id })+ const result = await dispatchOneUnreadWake(db, wakeEnv, { messageId: latest.messageId, botUserId: bot.id })if (result.outcome === "attempted") attempted++}diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.tsindex 205d8876c..859f3ae78 100644--- a/src/web/src/app/api/community/machines/route.test.ts+++ b/src/web/src/app/api/community/machines/route.test.ts@@ -41,6 +41,41 @@ describe("GET /api/community/machines — provider quota", () => {vi.clearAllMocks()})+ it.each(["available", "error", "pending"] as const)("reports supported Antigravity quota with a %s snapshot", async (status) => {+ const observedAt = new Date().toISOString()+ const limits = [{+ bucket: {+ limitId: "gemini-weekly",+ product: { kind: "reported", id: "antigravity", displayName: "Antigravity" },+ model: { kind: "unknown" },+ window: { kind: "provider_defined", id: "weekly", displayName: "Weekly limit" },+ },+ usedPercent: 12.5,+ }]+ mockListMachinesForUser.mockResolvedValue([{+ id: "cm_1", status: "online", availableRuntimes: [{ id: "antigravity", status: "healthy" }],+ }])+ const observation = status === "available"+ ? { status, sourceEpoch: "A".repeat(22), freshForSeconds: 300, limits }+ : { status: "error", sourceEpoch: "A".repeat(22), code: "unavailable", retryable: true }+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map([[+ "cm_1", status === "pending" ? [] : [{ observedAt, quota: { agentBackendId: "antigravity", observation } }],+ ]]))++ const response = await GET(new NextRequest("http://localhost/api/community/machines"))+ const body = await response.json()+ expect(response.status).toBe(200)+ expect(body.machines[0].quota).toEqual([{+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "antigravity" },+ capability: "supported", runtimeState: "healthy",+ snapshot: status === "available"+ ? { status, observedAt, limits }+ : status === "error" ? { status, code: "unavailable" } : { status },+ }])+ expect(JSON.stringify(body)).not.toContain("sourceEpoch")+ expect(JSON.stringify(body)).not.toContain("retryable")+ })+it("keeps same-runtime catalogs isolated between machine rows", async () => {const runtime = (modelId: string) => ({id: "codex",diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.tsindex fdd9b3e4d..222e37492 100644--- a/src/web/src/app/api/community/machines/route.ts+++ b/src/web/src/app/api/community/machines/route.ts@@ -22,7 +22,7 @@ export const GET = withAuth(async (_req, ctx) => {const withQuota = machines.map((machine) => {const stored = quotaByMachine.get(machine.id) ?? []const quota = machine.availableRuntimes.map((runtime) => {- const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok"+ const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok" || runtime.id === "antigravity"? "supported" as const: runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi"? "unsupported" as constdiff --git a/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts b/src/web/src/components/community/bots/bot-quota-summary.dom.test.tsindex a78a460bc..5a7f9aedb 100644--- a/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts+++ b/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts@@ -219,6 +219,32 @@ describe("MachineQuotaSummary", () => {expect(trigger).toHaveAttribute("aria-label", expect.stringContaining("Codex 62.5% left, stale"))})+ it("exposes unavailable backend details alongside pending peers without inventing limits", () => {+ const pending = { ...quotaEntry([]), snapshot: { status: "pending" as const } }+ const unavailable = {+ ...quotaEntry([], "available", "antigravity"),+ snapshot: { status: "error" as const, code: "unavailable" as const },+ }+ const renderer = render([pending, unavailable])+ const trigger = renderer.getByTestId("community-machine-quota-m1")+ expect(text(trigger)).toBe("Quota pending")+ expect(trigger).toHaveAttribute("aria-expanded", "false")+ fireEvent.click(trigger)+ const detail = renderer.getByTestId("community-machine-quota-detail-m1")+ expect(text(detail.querySelector('[data-quota-backend="antigravity"]')!)).toBe("AntigravityUnavailable")+ expect(text(detail.querySelector('[data-quota-backend="codex"]')!)).toBe("CodexPending")+ expect(text(detail)).not.toMatch(/%|Resets|Updated/)+ })++ it("keeps an available backend with no reported limits visible in details", () => {+ const renderer = render([quotaEntry([], "available", "antigravity")])+ fireEvent.click(renderer.getByTestId("community-machine-quota-m1"))+ const detail = renderer.getByTestId("community-machine-quota-detail-m1")+ expect(text(detail)).toContain("Antigravity")+ expect(text(detail)).toContain("Unavailable")+ expect(text(detail)).not.toContain("%")+ })+it("renders honest fixed-height placeholders for missing capability states", () => {expect(text(render().container)).toContain("Quota unavailable")const unsupported = render([{diff --git a/src/web/src/components/community/bots/bot-quota-summary.tsx b/src/web/src/components/community/bots/bot-quota-summary.tsxindex f3e041fc5..569b49799 100644--- a/src/web/src/components/community/bots/bot-quota-summary.tsx+++ b/src/web/src/components/community/bots/bot-quota-summary.tsx@@ -189,7 +189,7 @@ export function MachineQuotaSummary({}) {const [open, setOpen] = useAtom(useCreateAtom(false))const placeholder = quotaPlaceholder(entries)- if (placeholder || !entries) {+ if (!entries?.length) {return (<divdata-testid={tid.machineQuota(machineId)}@@ -208,7 +208,6 @@ export function MachineQuotaSummary({}const backendSummaries = summarizeQuotaEntries(entries)- if (backendSummaries.length === 0) return nullconst limitCount = entries.reduce((count, entry) => (entry.snapshot.status === "available" || entry.snapshot.status === "stale"? count + entry.snapshot.limits.length@@ -227,12 +226,27 @@ export function MachineQuotaSummary({<buttontype="button"aria-expanded={open}- aria-label={`Quota details: ${summary}. ${limitCount} ${limitCount === 1 ? "limit" : "limits"}`}+ aria-label={placeholder ? `Quota details: ${placeholder}` : `Quota details: ${summary}. ${limitCount} ${limitCount === 1 ? "limit" : "limits"}`}data-testid={tid.machineQuota(machineId)}className="group flex min-h-11 max-w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-md py-2 text-left text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-7 sm:py-1">- <span className="shrink-0 text-foreground/70">Quota</span>- <span aria-hidden className="shrink-0 text-border">·</span>+ {placeholder ? (+ <>+ {entries.map((entry) => (+ <ProviderLogo+ key={entry.scope.agentBackendId}+ provider={entry.scope.agentBackendId}+ className="size-3.5 shrink-0"+ />+ ))}+ <span className="truncate">{placeholder}</span>+ </>+ ) : (+ <>+ <span className="shrink-0 text-foreground/70">Quota</span>+ <span aria-hidden className="shrink-0 text-border">·</span>+ </>+ )}{backendSummaries.map(({ entry, limit }, index) => {const stale = entry.snapshot.status === "stale"const label = `${backendLabel(entry.scope.agentBackendId)}: ${percentLabel(limit)}${stale ? " (stale)" : ""}`diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.dom.test.ts b/src/web/src/components/community/bots/bot-token-usage-chart.dom.test.tsindex cf42e4963..92672ce97 100644--- a/src/web/src/components/community/bots/bot-token-usage-chart.dom.test.ts+++ b/src/web/src/components/community/bots/bot-token-usage-chart.dom.test.ts@@ -171,7 +171,7 @@ describe("BotTokenUsageHeatmap", () => {.toHaveLength(30)})- it("opens mobile details on the newest day with Total and all metric values", () => {+ it("opens mobile details on the newest day with Known total and all metric values", () => {mocks.breakpoint = "mobile"const usage: BotTokenUsage = {capability: "supported",@@ -194,7 +194,7 @@ describe("BotTokenUsageHeatmap", () => {expect(newest).toHaveClass("font-medium")const summary = renderer.getByTestId("community-bot-usage-dialog-summary-bot_1")expect(text(summary)).toContain("Aug 30")- expect(text(summary)).toContain("Total 20")+ expect(text(summary)).toContain("Known total 20")expect(text(summary)).toContain("Input 8")expect(text(summary)).toContain("Output 2")expect(text(summary)).toContain("Cache 10")@@ -217,7 +217,7 @@ describe("BotTokenUsageHeatmap", () => {.toHaveAttribute("aria-pressed", "false")const summary = renderer.getByTestId("community-bot-usage-dialog-summary-bot_1")expect(text(summary)).toContain("Aug 28")- expect(text(summary)).toContain("Total 9,000,000")+ expect(text(summary)).toContain("Known total 9,000,000")expect(text(summary)).toContain("Cache Unavailable")})@@ -226,7 +226,33 @@ describe("BotTokenUsageHeatmap", () => {const renderer = renderUsage({ capability: "supported", days: thirtyDays() })fireEvent.click(renderer.getByTestId("community-bot-usage-dialog-day-bot_1-2026-08-25"))const summary = renderer.getByTestId("community-bot-usage-dialog-summary-bot_1")- expect(text(summary)).toContain("Total Unavailable")+ expect(text(summary)).toContain("Known total Unavailable")expect(text(summary).match(/Unavailable/g)).toHaveLength(4)})++ it.each([+ { metrics: { input: 129, output: unavailable, cache: 1029 }, total: "1,158", missing: "Output" },+ { metrics: { input: 90, output: 24, cache: unavailable }, total: "114", missing: "Cache" },+ { metrics: { input: unavailable, output: 24, cache: 23 }, total: "47", missing: "Input" },+ ])("labels partial usage as Known total with $missing unavailable", ({ metrics, total, missing }) => {+ mocks.breakpoint = "mobile"+ const renderer = renderUsage({ capability: "supported", days: thirtyDays({ 30: metrics }) })+ const summary = renderer.getByTestId("community-bot-usage-dialog-summary-bot_1")+ expect(text(summary)).toContain(`Known total ${total}`)+ expect(text(summary)).toContain(`${missing} Unavailable`)+ expect(renderer.container.querySelector("dialog-description")).toHaveTextContent(+ "Choose a date to view token usage. Known total excludes unavailable values.",+ )+ })++ it("retains a known zero total when every metric is reported as zero", () => {+ mocks.breakpoint = "mobile"+ const renderer = renderUsage({+ capability: "supported",+ days: thirtyDays({ 30: { input: 0, output: 0, cache: 0 } }),+ })+ const summary = renderer.getByTestId("community-bot-usage-dialog-summary-bot_1")+ expect(text(summary)).toContain("Known total 0")+ expect(text(summary)).not.toContain("Unavailable")+ })})diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.tsx b/src/web/src/components/community/bots/bot-token-usage-chart.tsxindex 4838640b1..d17ec42ae 100644--- a/src/web/src/components/community/bots/bot-token-usage-chart.tsx+++ b/src/web/src/components/community/bots/bot-token-usage-chart.tsx@@ -99,7 +99,7 @@ function UsageDayDetail({ day, includeTotal = false }: { day: BotUsageDay; inclu<span className="font-medium">{fullDayLabel(day)}</span>{includeTotal && (<span className="flex items-center justify-between gap-4 font-medium">- <span>Total</span>+ <span>Known total</span><span className="font-mono tabular-nums">{presentation.unavailable ? "Unavailable" : TOKEN_FMT.format(presentation.knownTotal)}</span>@@ -224,7 +224,7 @@ export function BotTokenUsageHeatmap({<DialogContent data-testid={tid.botUsageDialog(botId)} className="gap-4"><DialogHeader><DialogTitle>Token usage</DialogTitle>- <DialogDescription>Choose a date to view exact token totals.</DialogDescription>+ <DialogDescription>Choose a date to view token usage. Known total excludes unavailable values.</DialogDescription></DialogHeader><divdata-testid={tid.botUsageDateRail(botId)}diff --git a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/create-bot-sheet.dom.test.tsindex 7137ea8b2..be83141e7 100644--- a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts+++ b/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts@@ -10,7 +10,7 @@ import {firstHealthyRuntimeId,firstOnlineMachineId,} from "./create-bot-sheet"-import type { CommunityMachineSummary } from "@alook/shared"+import type { CommunityMachineSummary, RuntimeReasoningCatalog } from "@alook/shared"function machine(over: Partial<CommunityMachineSummary>): CommunityMachineSummary {return {@@ -142,21 +142,22 @@ vi.mock("./bot-form-fields", () => ({const modelFieldRenders: Array<{ runtime: { id: string; reasoning?: unknown } | null; value: string | null }> = []const reasoningDaemonVersionRenders: Array<string | undefined> = []vi.mock("./model-field", () => ({- ModelField: ({ runtime, value }: { runtime: { id: string; reasoning?: unknown } | null; value: string | null }) => {+ ModelField: ({ runtime, value, onChange }: { runtime: { id: string; reasoning?: RuntimeReasoningCatalog } | null; value: string | null; onChange: (value: string | null) => void }) => {modelFieldRenders.push({ runtime, value })- return React.createElement("div", { "data-mock": "model-field", "data-value": value ?? "" })+ return React.createElement("button", { "data-mock": "model-field", "data-value": value ?? "", "data-testid": "set-model", onClick: () => onChange(runtime?.reasoning?.defaultModelId ?? null) })},}))vi.mock("./reasoning-effort-field", () => ({- ReasoningEffortField: ({ onChange, daemonVersion }: {+ ReasoningEffortField: ({ onChange, daemonVersion, runtime }: {+ runtime: { reasoning?: RuntimeReasoningCatalog } | nullonChange: (value: string | null) => voiddaemonVersion?: string}) => {reasoningDaemonVersionRenders.push(daemonVersion)return React.createElement("button", {"data-testid": "set-reasoning-effort",- onClick: () => onChange("xhigh"),+ onClick: () => onChange(runtime?.reasoning?.models[0]?.supportedReasoningEfforts[0]?.value ?? "xhigh"),})},}))@@ -355,6 +356,45 @@ describe("CreateBotSheet — auto-select defaults", () => {expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(catalog("a-model"))})+ it("creates Antigravity with exact native model/effort and keeps Default null", async () => {+ const reasoning: RuntimeReasoningCatalog = {+ updateMode: "live_next_turn",+ defaultModelId: "gemini-3.1-pro-high",+ models: [{ id: "gemini-3.1-pro-high", displayName: "Gemini 3.1 Pro (High)",+ supportedReasoningEfforts: [{ value: "high" }, { value: "low" }] }],+ }+ useMachinesMock.mockReturnValue({ machines: [machine({+ id: "mac", daemonVersion: "0.1.43",+ availableRuntimes: [{ id: "antigravity", status: "healthy", reasoning }],+ })] })+ const renderer = render()+ expect(modelFieldRenders.at(-1)?.runtime).toEqual({ id: "antigravity", unhealthy: false, reasoning })+ expect(modelFieldRenders.at(-1)?.value).toBeNull()+ fireEvent.click(renderer.getByTestId("set-model"))+ fireEvent.click(renderer.getByTestId("set-reasoning-effort"))+ await act(async () => {+ fireEvent.click(renderer.getByRole("button", { name: "Create bot" }))+ await Promise.resolve()+ })+ expect(createMutateAsync).toHaveBeenCalledWith(expect.objectContaining({+ machineId: "mac", runtime: "antigravity", model: "gemini-3.1-pro-high", reasoningEffort: "high",+ }))+ })++ it("creates Antigravity Default without inventing a catalog or effort override", async () => {+ useMachinesMock.mockReturnValue({ machines: [machine({+ id: "mac", availableRuntimes: [{ id: "antigravity", status: "healthy" }],+ })] })+ const renderer = render()+ await act(async () => {+ fireEvent.click(renderer.getByRole("button", { name: "Create bot" }))+ await Promise.resolve()+ })+ expect(createMutateAsync).toHaveBeenCalledWith(expect.objectContaining({+ machineId: "mac", runtime: "antigravity", model: null, reasoningEffort: null,+ }))+ })+it("includes the selected runtime-reported reasoning effort in create", async () => {useMachinesMock.mockReturnValue({machines: [diff --git a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.tsindex 2d8bc37e7..a91adae42 100644--- a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts+++ b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import React from "react"import { act, fireEvent } from "@/test/react-dom-harness"import { renderCommunity as render } from "@/test/community-owner-harness"+import type { RuntimeReasoningCatalog } from "@alook/shared"import type { BotSummary } from "@/hooks/community/use-bots"// Online-only UI contract (Ruthann #1274/#1280 / Shelly gate):@@ -136,13 +137,13 @@ vi.mock("./model-field", () => {const React = require("react")return {ModelField: ({ runtime, onChange }: {- runtime: { id: string; reasoning?: unknown } | null+ runtime: { id: string; reasoning?: RuntimeReasoningCatalog } | nullonChange: (v: string | null) => void}) => {modelFieldRenders.push({ runtime })return React.createElement("button", {"data-testid": "set-model",- onClick: () => onChange("claude-sonnet-4-6"),+ onClick: () => onChange(runtime?.reasoning?.defaultModelId ?? "claude-sonnet-4-6"),})},}@@ -150,7 +151,8 @@ vi.mock("./model-field", () => {vi.mock("./reasoning-effort-field", () => {const React = require("react")return {- ReasoningEffortField: ({ onChange, daemonVersion, value }: {+ ReasoningEffortField: ({ onChange, daemonVersion, value, runtime }: {+ runtime: { reasoning?: RuntimeReasoningCatalog } | nullonChange: (value: string | null) => voiddaemonVersion?: stringvalue: string | null@@ -158,7 +160,7 @@ vi.mock("./reasoning-effort-field", () => {reasoningFieldRenders.push({ daemonVersion, value })return React.createElement("button", {"data-testid": "set-reasoning-effort",- onClick: () => onChange("xhigh"),+ onClick: () => onChange(runtime?.reasoning?.models[0]?.supportedReasoningEfforts[0]?.value ?? "xhigh"),})},}@@ -319,6 +321,29 @@ describe("EditBotSheet — reasoning effort", () => {expect(updateMutateAsync.mock.calls[0]?.[0]).not.toHaveProperty("reasoningEffort")})+ it("edits an Antigravity native model/effort through the existing mutation", async () => {+ const bot = { ...BOT, runtime: "antigravity", modelName: "gemini-3.1-pro-low", reasoningEffort: "low" }+ const reasoning: RuntimeReasoningCatalog = {+ updateMode: "live_next_turn", defaultModelId: "gemini-3.1-pro-high",+ models: [{ id: "gemini-3.1-pro-high", supportedReasoningEfforts: [{ value: "high" }, { value: "low" }] }],+ }+ useMachinesMock.mockReturnValue({ machines: [{+ id: "mac1", daemonVersion: "0.1.43",+ availableRuntimes: [{ id: "antigravity", status: "healthy", reasoning }],+ }] })+ updateMutateAsync.mockResolvedValue({ bot, application: "next_turn" })+ const renderer = renderSheet(bot)+ expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(reasoning)+ fireEvent.click(renderer.getByTestId("set-model"))+ fireEvent.click(renderer.getByTestId("set-reasoning-effort"))+ act(() => fireEvent.click(saveButton(renderer)))+ await flush()+ expect(updateMutateAsync).toHaveBeenCalledWith(expect.objectContaining({+ id: "b1", model: "gemini-3.1-pro-high", reasoningEffort: "high",+ }))+ expect(renderer.queryAllByTestId("provider-confirm")).toHaveLength(0)+ })+it("PATCHes the explicit effort without provider confirmation and reports next-turn application", async () => {updateMutateAsync.mockResolvedValue({bot: { ...BOT, reasoningEffort: "xhigh", runtimeConfigRevision: 2 },diff --git a/src/web/src/components/community/bots/model-field-select.dom.test.tsx b/src/web/src/components/community/bots/model-field-select.dom.test.tsxnew file mode 100644index 000000000..38ff8d6d8--- /dev/null+++ b/src/web/src/components/community/bots/model-field-select.dom.test.tsx@@ -0,0 +1,74 @@+import React from "react"+import { describe, expect, it, vi } from "vitest"+import { fireEvent, render, screen } from "@/test/react-dom-harness"+import { ModelField } from "./model-field"++const runtime = {+ id: "antigravity",+ reasoning: {+ updateMode: "live_next_turn" as const,+ defaultModelId: "gemini-3.1-pro-high",+ models: ["gemini-3.1-pro-high", "gemini-3.1-pro-low"].map((id) => ({+ id,+ supportedReasoningEfforts: [{ value: "high" }, { value: "low" }],+ })),+ },+}++describe("ModelField with the real Select", () => {+ it("filters an edited model without changing its selection", () => {+ const onChange = vi.fn()+ render(<ModelField runtime={runtime} value="gemini-3.1-pro-high" onChange={onChange} />)+ expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")+ fireEvent.click(screen.getByTestId("bot-model-select"))+ const filter = screen.getByTestId("bot-model-filter-input")+ fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } })+ expect(filter).toHaveValue("gemini-3.1-pro-low")+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")+ expect(screen.getByTestId("bot-model-probe-results").querySelectorAll('[role="option"]')).toHaveLength(1)+ fireEvent.click(screen.getByRole("option", { name: "gemini-3.1-pro-low" }))+ expect(onChange).toHaveBeenLastCalledWith("gemini-3.1-pro-low")+ })++ it("keeps explicit Default selectable while the current model is filtered out", () => {+ const onChange = vi.fn()+ render(<ModelField runtime={runtime} value="gemini-3.1-pro-high" onChange={onChange} />)+ fireEvent.click(screen.getByTestId("bot-model-select"))+ const filter = screen.getByTestId("bot-model-filter-input")+ fireEvent.change(filter, { target: { value: "no-match" } })+ expect(filter).toHaveValue("no-match")+ expect(screen.getByRole("status")).toHaveTextContent("No matching models")+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")+ const option = screen.getByRole("option", { name: "Default (antigravity's own default)" })+ fireEvent.pointerDown(option, { pointerType: "mouse" })+ fireEvent.click(option)+ expect(onChange).toHaveBeenLastCalledWith(null)+ })++ it("preserves a model chosen after opening a create form with Default", () => {+ const onChange = vi.fn()+ function CreateModel() {+ const [value, setValue] = React.useState<string | null>(null)+ return <ModelField runtime={runtime} value={value} onChange={(next) => {+ setValue(next)+ onChange(next)+ }} />+ }+ render(<CreateModel />)+ fireEvent.click(screen.getByTestId("bot-model-select"))+ const high = screen.getByRole("option", { name: "gemini-3.1-pro-high" })+ fireEvent.pointerDown(high, { pointerType: "mouse" })+ fireEvent.click(high)+ expect(onChange).toHaveBeenLastCalledWith("gemini-3.1-pro-high")+ onChange.mockClear()+ fireEvent.click(screen.getByTestId("bot-model-select"))+ const filter = screen.getByTestId("bot-model-filter-input")+ fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } })+ expect(filter).toHaveValue("gemini-3.1-pro-low")+ expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")+ expect(onChange).not.toHaveBeenCalled()+ })++})diff --git a/src/web/src/components/community/bots/model-field.dom.test.ts b/src/web/src/components/community/bots/model-field.dom.test.tsindex d85b6f591..68982ff60 100644--- a/src/web/src/components/community/bots/model-field.dom.test.ts+++ b/src/web/src/components/community/bots/model-field.dom.test.ts@@ -15,7 +15,12 @@ vi.mock("@/components/ui/select", () => {const React = require("react")return {Select: ({ value, onValueChange, onOpenChange, items, children }: any) => {- selectCalls.push({ value, onValueChange, onOpenChange, items })+ selectCalls.push({+ value,+ onValueChange: (next) => onValueChange(next, { reason: "item-press", cancel: vi.fn() }),+ onOpenChange,+ items,+ })return React.createElement("div", { "data-mock": "select", "data-value": value }, children)},SelectTrigger: ({ children, ...props }: any) =>@@ -290,4 +295,37 @@ describe("ModelField", () => {expect(stopPropagation).toHaveBeenCalledOnce()expect(highlighted.click).toHaveBeenCalledOnce()})++ it("uses exact Antigravity native IDs and labels from the machine catalog", () => {+ const onChange = vi.fn()+ const renderer = render({+ runtime: {+ id: "antigravity",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gemini-3.1-pro-high",+ models: [{+ id: "gemini-3.1-pro-high",+ displayName: "Gemini 3.1 Pro (High)",+ supportedReasoningEfforts: [{ value: "high" }, { value: "low" }],+ }, {+ id: "claude-sonnet-4-6",+ displayName: "Claude Sonnet 4.6",+ supportedReasoningEfforts: [],+ }],+ },+ },+ value: null,+ onChange,+ })+ expect(itemValues(renderer)).toEqual([+ "__default__", "__custom__", "gemini-3.1-pro-high", "claude-sonnet-4-6",+ ])+ expect(itemText(renderer, "gemini-3.1-pro-high")).toContain("Gemini 3.1 Pro (High)")+ expect(onChange).not.toHaveBeenCalled()+ act(() => selectCalls.at(-1)!.onValueChange("gemini-3.1-pro-high"))+ expect(onChange).toHaveBeenLastCalledWith("gemini-3.1-pro-high")+ act(() => selectCalls.at(-1)!.onValueChange("__default__"))+ expect(onChange).toHaveBeenLastCalledWith(null)+ })})diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsxindex 845a69b7b..9f70ba485 100644--- a/src/web/src/components/community/bots/model-field.tsx+++ b/src/web/src/components/community/bots/model-field.tsx@@ -93,7 +93,11 @@ export function ModelField({<Selectitems={items}value={selectValue}- onValueChange={(next: string | null) => {+ onValueChange={(next: string | null, details) => {+ if (details.reason === "none" && normalizedFilter && modelIds.includes(selectValue)) {+ details.cancel()+ return+ }// Base UI can emit `null` on clear — treat it as Default.const nextValue = next ?? MODEL_SELECT_DEFAULTsetSelectValue(nextValue)diff --git a/src/web/src/components/community/bots/reasoning-effort-field.dom.test.ts b/src/web/src/components/community/bots/reasoning-effort-field.dom.test.tsindex 9a170099c..1c65ee2af 100644--- a/src/web/src/components/community/bots/reasoning-effort-field.dom.test.ts+++ b/src/web/src/components/community/bots/reasoning-effort-field.dom.test.ts@@ -1,6 +1,6 @@import React from "react"import { describe, expect, it, vi } from "vitest"-import { render, screen } from "@/test/react-dom-harness"+import { act, render, screen } from "@/test/react-dom-harness"import { ReasoningEffortField } from "./reasoning-effort-field"vi.mock("@/components/ui/label", () => ({@@ -8,6 +8,8 @@ vi.mock("@/components/ui/label", () => ({React.createElement("label", null, children),}))+let selectOnChange: ((value: string | null) => void) | undefined+vi.mock("@/components/ui/select", () => ({Select: ({ children, disabled, items, value, onValueChange }: {children?: React.ReactNode@@ -15,12 +17,15 @@ vi.mock("@/components/ui/select", () => ({items?: unknown[]value?: stringonValueChange?: (value: string | null) => void- }) => React.createElement("select", {- disabled,- value,- "data-items": JSON.stringify(items),- onChange: (event: React.ChangeEvent<HTMLSelectElement>) => onValueChange?.(event.target.value),- }, children),+ }) => {+ selectOnChange = onValueChange+ return React.createElement("select", {+ disabled,+ value,+ "data-items": JSON.stringify(items),+ onChange: (event: React.ChangeEvent<HTMLSelectElement>) => onValueChange?.(event.target.value),+ }, children)+ },SelectContent: ({ children }: { children?: React.ReactNode }) =>React.createElement("div", null, children),SelectItem: ({ children, value }: { children?: React.ReactNode; value: string }) =>@@ -115,4 +120,45 @@ describe("ReasoningEffortField", () => {const { onChange } = renderField({ value: "ultra" })expect(onChange).toHaveBeenCalledWith(null)})++ it("clears an override when the reported model has no effort options", () => {+ const { renderer, onChange } = renderField({+ runtime: { reasoning: { updateMode: "live_next_turn", models: [+ { id: "claude-sonnet-4-6", supportedReasoningEfforts: [] },+ ] } },+ model: "claude-sonnet-4-6",+ value: "high",+ })+ expect(renderer.container.querySelector("select")).toBeDisabled()+ expect(onChange).toHaveBeenCalledWith(null)+ })++ it("preserves an override for a custom model absent from the catalog", () => {+ const { onChange } = renderField({ model: "custom-model", value: "high" })+ expect(onChange).not.toHaveBeenCalled()+ })++ it("exposes only Antigravity's reported variants for its default model", () => {+ const { renderer, onChange } = renderField({+ runtime: { reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gemini-3.1-pro-high",+ models: [{+ id: "gemini-3.1-pro-high",+ supportedReasoningEfforts: [{ value: "high" }, { value: "low" }],+ defaultReasoningEffort: "high",+ }],+ } },+ model: null,+ })+ const select = renderer.container.querySelector("select")!+ expect(select).toBeEnabled()+ expect([...renderer.container.querySelectorAll("option")].map((node) => node.value))+ .toEqual(["__default__", "high", "low"])+ expect(onChange).not.toHaveBeenCalled()+ act(() => selectOnChange?.("low"))+ expect(onChange).toHaveBeenLastCalledWith("low")+ act(() => selectOnChange?.("__default__"))+ expect(onChange).toHaveBeenLastCalledWith(null)+ })})diff --git a/src/web/src/components/community/bots/reasoning-effort-field.tsx b/src/web/src/components/community/bots/reasoning-effort-field.tsxindex b4a79ee00..98ba9ef5c 100644--- a/src/web/src/components/community/bots/reasoning-effort-field.tsx+++ b/src/web/src/components/community/bots/reasoning-effort-field.tsx@@ -43,11 +43,13 @@ export function ReasoningEffortField({[runtime, model, value],)+ const hasModelEvidence = runtime?.reasoning?.models.some((model) => model.id === resolution.modelId) ?? false+useEffect(() => {- if (resolution.options.length > 0 && !resolution.supported && value !== null) {+ if (hasModelEvidence && !resolution.supported && value !== null) {onChange(null)}- }, [onChange, resolution.options.length, resolution.supported, value])+ }, [hasModelEvidence, onChange, resolution.supported, value])const defaultLabel = "Default"const options = value && !resolution.options.some((option) => option.value === value)diff --git a/src/web/src/components/provider-logo.tsx b/src/web/src/components/provider-logo.tsxindex c8230465d..734413d09 100644--- a/src/web/src/components/provider-logo.tsx+++ b/src/web/src/components/provider-logo.tsx@@ -117,12 +117,19 @@ function GeminiLogo({ className }: { className: string }) {}function AntigravityLogo({ className }: { className: string }) {- // Inverted-triangle "falling-up" arrow inside a soft ring — a single-color- // glyph that reads as "anti-gravity" without literal planetary kitsch.return (- <svg viewBox="0 0 16 16" fill="currentColor" className={className}>- <path d="M8 1.25a6.75 6.75 0 1 0 0 13.5 6.75 6.75 0 0 0 0-13.5Zm0 1.5a5.25 5.25 0 1 1 0 10.5 5.25 5.25 0 0 1 0-10.5Z" />- <path d="M8 4.5a.75.75 0 0 1 .75.75v3.69l1.22-1.22a.75.75 0 1 1 1.06 1.06l-2.5 2.5a.75.75 0 0 1-1.06 0l-2.5-2.5a.75.75 0 1 1 1.06-1.06l1.22 1.22V5.25A.75.75 0 0 1 8 4.5Z" transform="rotate(180 8 8)" />+ <svg+ viewBox="0 0 180 180"+ fill="none"+ className={className}+ data-provider-logo="antigravity"+ aria-hidden="true"+ >+ <path+ d="M144.248 149.062C151.748 154.688 162.998 150.938 152.685 140.625C121.748 110.625 128.31 28.125 89.8727 28.125C51.4352 28.125 57.9977 110.625 27.0602 140.625C15.8102 151.875 27.9977 154.688 35.4977 149.062C64.5602 129.375 62.6852 94.6875 89.8727 94.6875C117.06 94.6875 115.185 129.375 144.248 149.062Z"+ fill="#202124"+ className="dark:fill-white"+ /></svg>);}diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex fbd9e24c8..81541b982 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -457,14 +457,15 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({)expect(await dateRail.evaluate((element) => element.scrollLeft)).toBe(0)await expect(newestDay).toHaveAttribute("aria-pressed", "true")- await expect(dialogSummary).toContainText("TotalUnavailable")+ await expect(dialogSummary).toContainText("Known totalUnavailable")+ await expect(usageDialog).toContainText("Known total excludes unavailable values.")expect(await dateRail.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(true)await attachScreenshot(page, testInfo, "my-bots-token-heatmap-mobile-dialog")await selectedDay.click()await expect(selectedDay).toHaveAttribute("aria-pressed", "true")await expect(newestDay).toHaveAttribute("aria-pressed", "false")await expect(dialogSummary).toContainText("Aug 26")- await expect(dialogSummary).toContainText("Total9,000,000")+ await expect(dialogSummary).toContainText("Known total9,000,000")await expect(dialogSummary).toContainText("Input6,000,000")await expect(dialogSummary).toContainText("Output3,000,000")await expect(dialogSummary).toContainText("CacheUnavailable")diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.tsindex f55e88b5a..74319316f 100644--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts+++ b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts@@ -1,6 +1,7 @@import { devices, type Locator, type Page } from "@playwright/test"import { expect, test, userId } from "./_fixtures/community-fixture"import { seedChannel, seedDm, seedJoinServer, seedServer } from "./_fixtures/seed"+import { composerEditable, waitForElementMotion } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"const RAIL_ENDPOINT = "/api/community/users/me/server-rail"@@ -214,6 +215,7 @@ async function touchDrag(}await scrollIntoView(source)await scrollIntoView(target)+ await waitForElementMotion(source)const sourceTestId = await source.getAttribute("data-testid")const sourceBox = await source.boundingBox()const targetBox = await target.boundingBox()@@ -668,9 +670,15 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",expect(expandedTail.targetOwnsCenter).toBe(true)await page.screenshot({ path: testInfo.outputPath("server-rail-touch-combine-390.png") })+ await expect(firstFolder).toBeFocused()await page.setViewportSize({ width: 1280, height: 900 })await page.emulateMedia({ colorScheme: "dark" })await expect(page.locator("html")).toHaveClass(/dark/)+ await expect(page).toHaveURL(new RegExp(`/c/channels/${first}/[^/]+$`))+ const desktopComposer = composerEditable(page)+ await expect(desktopComposer).toBeVisible()+ await waitForElementMotion(desktopComposer)+ await expect(firstFolder).toBeFocused()const darkKeyboardSource = page.getByTestId(tid.serverIcon(first))await darkKeyboardSource.focus()await page.keyboard.press("Space")diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.tsindex 73d907228..93db11df6 100644--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts@@ -474,11 +474,14 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {await bob.page.getByRole("tab", { name: "Marked" }).click()const markedScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))await expect(markedScroll.getByText(`Marked ${stamp} 13`, { exact: true })).toBeAttached()+ await waitForElementMotion(markedScroll)const priorScroll = await markedScroll.evaluate((element) => {element.scrollTop = element.scrollHeightreturn element.scrollTop})expect(priorScroll).toBeGreaterThan(0)+ await waitForElementMotion(markedScroll)+ await expect.poll(() => markedScroll.evaluate((element) => element.scrollTop)).toBe(priorScroll)const getsBeforeResize = inboxGets.lengthawait bob.page.setViewportSize({ width: 640, height: 844 })@@ -487,6 +490,7 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {await expect(bob.page.locator("[data-slot='popover-content']")).toHaveCount(1)await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")const desktopScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))+ await waitForElementMotion(desktopScroll)await expect.poll(() => desktopScroll.evaluate((element) => element.scrollTop)).toBeGreaterThanOrEqual(priorScroll - 1)@@ -494,6 +498,7 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {await expect(bob.page.getByTestId(tid.userBarExtension)).toBeVisible()await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")const mobileScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))+ await waitForElementMotion(mobileScroll)const restoredMobileScroll = await mobileScroll.evaluate((element) => ({scrollTop: element.scrollTop,maxScrollTop: element.scrollHeight - element.clientHeight,diff --git a/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts b/src/web/src/test/e2e-ui/54-blog-multizone.spec.tsindex 5653f8220..0d006d95d 100644--- a/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts+++ b/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts@@ -10,10 +10,11 @@ test("main and Blog navigate across Workers through one public origin", async ({})await page.goto("/")- const banner = page.getByTestId(tid.analyticsConsentBanner)- await expect(banner).toBeVisible()- await banner.getByRole("button", { name: "Only necessary", exact: true }).click()- await expect(banner).toHaveCount(0)+ const consentBanner = page.getByTestId(tid.analyticsConsentBanner)+ await expect(consentBanner).toBeVisible()+ await consentBanner.getByRole("button", { name: "Only necessary", exact: true }).click()+ await expect(consentBanner).toHaveCount(0)+ await expect(consentBanner).toBeHidden()const publicOrigin = new URL(page.url()).originawait page.locator(".hero-section").evaluate((hero) => {window.scrollTo(0, hero.getBoundingClientRect().bottom + window.scrollY + 1)diff --git a/src/web/src/test/e2e/community-machine-backend-quota-schema.test.ts b/src/web/src/test/e2e/community-machine-backend-quota-schema.test.tsindex a6a773173..17118c302 100644--- a/src/web/src/test/e2e/community-machine-backend-quota-schema.test.ts+++ b/src/web/src/test/e2e/community-machine-backend-quota-schema.test.ts@@ -5,7 +5,7 @@ const OWNER_ID = "e2e_backend_quota_owner"const MACHINE_ID = "e2e_backend_quota_machine"const SOURCE_EPOCH = "a".repeat(22)const NOW = "2026-09-08T00:00:00.000Z"-const SUPPORTED_BACKENDS = ["claude", "codex", "grok"] as const+const SUPPORTED_BACKENDS = ["claude", "codex", "grok", "antigravity"] as constfunction insertQuota(agentBackendId: string): void {sqlRun(