Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Antigravity: turns start with less waiting, stalls are caught sooner; Google's native CLI as an opt-in runtime (#7148)

Milind Soni343c745d8293
diff --git a/apps/docs/content/docs/providers/antigravity.mdx b/apps/docs/content/docs/providers/antigravity.mdx
index 7b05f86723..6ecfec9578 100644
--- a/apps/docs/content/docs/providers/antigravity.mdx
+++ b/apps/docs/content/docs/providers/antigravity.mdx
@@ -38,3 +38,18 @@ When the MausBot server and browser are on different computers, Google's final r
Antigravity uses the same MausBot approval cards as other ACP engines. Connected apps, custom MCP servers, the browser, computers, and teammate tools are mounted only for the active session; MausBot no longer edits the user's global Gemini MCP configuration.
The normal mode asks before protected actions. Full access maps to Antigravity's native `yolo` mode, but native questions still wait for a person instead of being guessed automatically.
+
+## Trying Google's native Antigravity CLI (opt-in)
+
+MausBot can run Google's newer native Antigravity CLI (1.5 or later, `agy acp`) instead of the packaged 1.4.3 runtime. It is one program of about 220 MB on a Mac and 275 MB on Linux, instead of about 400 MB and 1 GB, and starts much faster. It is **off by default** for two reasons: its Google sign-in has not yet been tried with a real account in MausBot, and it keeps the sign-in in a different file, so **every Antigravity account signs in with Google once more** after the switch.
+
+To try it on one server or computer:
+
+1. Start MausBot with `OMB_ANTIGRAVITY_NATIVE_CLI=1` in its environment, then restart it. (The setting is read when MausBot starts.)
+2. A few minutes later, while no bot is working, the engine updater installs the CLI from Google's update channel, checked against the SHA-512 that channel names. On a computer with no Antigravity runtime yet, **Install official Antigravity** on the account card installs the CLI instead.
+3. The account card shows **Sign in with Google**. Sign in in your browser. Google's Antigravity page then shows a code: paste it into **Code from the Antigravity page** on the card and select **Send code**.
+4. Send a bot on that account a message and check that it answers.
+
+With the CLI on, MausBot updates it itself (a few minutes after it starts, then once a day), keeps its release folder read-only, turns the CLI's own self-update off, and starts it so that each account keeps its sign-in in its own folder. The CLI always runs in its `default` mode and MausBot answers its requests by the bot's approval level. Once an account on that computer has signed in on the CLI, the 1.4.3 runtime is removed from disk.
+
+To go back, remove `OMB_ANTIGRAVITY_NATIVE_CLI` and restart. Accounts use their 1.4.3 sign-in again if it is still there; MausBot keeps it during the switch. If 1.4.3 was already removed, **Install official Antigravity** downloads it again (about 340 MB on Linux).
diff --git a/docs/approval-levels.md b/docs/approval-levels.md
index 7de198f2b0..1a00d4d1eb 100644
--- a/docs/approval-levels.md
+++ b/docs/approval-levels.md
@@ -325,6 +325,20 @@ level under another name, not a separate permission setting, applies at once
like Full access, and covers every model in that Antigravity instance,
including Gemini.
+The native Antigravity CLI (1.5.0 and later) rejects `yolo` and `auto_edit`,
+so it stays in its `default` mode at every level and asks before each action.
+On Auto the app answers those requests itself, never-list commands excepted.
+On Auto-accept edits it answers a request only when it is a plain file edit
+inside the turn's folder: one that names a command, gives no location, or
+reaches outside that folder is asked as usual. A turn fails rather than start
+when the CLI offers no mode or does not confirm `default`.
+
+A computer that already has the pinned runtime keeps it. To move an
+Antigravity account to the native CLI, set its **CLI path** to `antigravity`
+and choose **Install official Antigravity**; to move back, set the CLI path to
+`agy`. New installs get the native CLI when Google's channel can be reached and
+the pinned runtime otherwise.
+
A new Antigravity bot starts on Auto, the default. Old Antigravity
`auto` / `autoApprove` settings still behave as Ask and are displayed as Ask;
they never become unrestricted access on upgrade. Switching back to Ask
@@ -370,6 +384,7 @@ multi-question card renders its structured form on current apps instead.
| Claude | Native `default` | Native `acceptEdits` | Native `auto` | Native `bypassPermissions` |
| Cursor | Native default | not offered | Native `--auto-review` | Native `--force` |
| Antigravity | Native `default` | Native `auto_edit` | Legacy `auto` behaves as Ask; UI Auto selects Full access | Native `yolo` plus automatic approval of remaining tool-permission requests; shown as Auto |
+| Antigravity (native CLI, 1.5.0 and later) | Native `default` | Native `default`; the app answers file edits inside the turn's folder itself | as Antigravity | Native `default`; the app answers every tool-permission request, never-list commands excepted; shown as Auto |
| Grok Build | Native `default` | Native `acceptEdits` | Native `--permission-mode auto`; availability of Grok's reviewer depends on its feature rollout | Native `bypassPermissions` plus automatic approval of remaining tool-permission requests |
| OpenCode | Ask | not offered | Ask | Approve individual ACP permission requests, never task questions |
| Qwen Code | Native `default` | Native `--approval-mode auto-edit` | Native `--approval-mode auto` (Qwen's LLM classifier approves safe actions, blocks risky ones) | `--yolo`, plus automatic approval of remaining ACP permission requests |
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index e0851d8c76..6185f95570 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -9,7 +9,7 @@ import { BOX_ENV_NAMES, BOX_ENV_NEVER, BOX_ENV_OMB_NAMES, BOX_ENV_OMB_PREFIXES,
const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_ACP_LIMIT_QUIET_MS", "OMB_ACP_NO_SIGNS_STOP_MS", "OMB_ACP_PLAN_LINES", "OMB_ACP_QUIET_NOTICE_MS",
"OMB_ACP_QUIET_TICK_MS", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP",
- "OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY",
+ "OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY", "OMB_ANTIGRAVITY_NATIVE_CLI",
"OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT",
"OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
"OMB_BROWSER_CONNECTION", "OMB_BROWSER_HOLD_IDLE_MS", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",
@@ -115,6 +115,13 @@ describe("the box's environment allow-list", () => {
for (const name of ["ANTIGRAVITY_HARNESS_PATH", "AGY_ACP_FORCE_FILE_STORAGE", "BROWSER", "GEMINI_HOME"]) expect(boxEnvironmentAllows(name), name).toBe(true);
});
+ it("keeps what Antigravity's native CLI is started with: no self-update, and the SSH_CONNECTION that keeps its sign-in in the profile", () => {
+ for (const name of ["AGY_CLI_DISABLE_AUTO_UPDATE", "SSH_CONNECTION"]) expect(boxEnvironmentAllows(name), name).toBe(true);
+ expect(boxEnvironment({ SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", AGY_CLI_DISABLE_AUTO_UPDATE: "1" })).toEqual({ SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", AGY_CLI_DISABLE_AUTO_UPDATE: "1" });
+ // A server started over SSH: its own session's addresses never reach a box.
+ expect(boxEnvironment({ SSH_CONNECTION: "203.0.113.7 51234 10.0.0.5 22", PATH: "/usr/bin" })).toEqual({ PATH: "/usr/bin" });
+ });
+
it("keeps the keys one spawn vouches for, under any name, past the allow-list and the deny, never past the never-list or OMB_", () => {
const deny = new Set(["OPENCODE_API_KEY", "OMB_COMPOSIO_BROKER_TOKEN"]);
const allow = new Set(["NANO_GPT_API_KEY", "OPENCODE_API_KEY", "OMB_LICENSE_KEY", "OMB_CLOUD_AI_TOKEN", "OMB_COMPOSIO_BROKER_TOKEN"]);
diff --git a/server/bot-box/env.ts b/server/bot-box/env.ts
index 60141d78af..cacf26ba46 100644
--- a/server/bot-box/env.ts
+++ b/server/bot-box/env.ts
@@ -11,8 +11,14 @@ export const BOX_ENV_NAMES: ReadonlySet<string> = new Set([
"XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR", "DISPLAY", "WAYLAND_DISPLAY",
"AGENT_BROWSER_EXECUTABLE_PATH", "BROWSER", "BASH_MAX_TIMEOUT_MS", "ELECTRON_RUN_AS_NODE", "PYTHONUNBUFFERED", "PYTHONDONTWRITEBYTECODE",
"GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL",
+ // Antigravity's native CLI keeps each profile's Google sign-in in that profile's own file only while this is set
+ // (server/drivers/antigravity-acp.ts sets a fixed value); without it, it waits on an OS keyring the box does not have.
+ "SSH_CONNECTION",
]);
+/** The one SSH_CONNECTION value a box may see (server/drivers/antigravity-acp.ts starts the native CLI with it). */
+export const BOX_SSH_CONNECTION = "127.0.0.1 0 127.0.0.1 0";
+
/** OpenMausBot's own variables a boxed process reads: what the harness sets for a bot's engine, its hooks and the MCP
* proxies it starts. Security: no other `OMB_` name passes, whatever the operator set on the server (an SMTP URL, a
* token); env.test.ts lists every `OMB_` name the server knows, so a new one needs a decision. */
@@ -74,6 +80,8 @@ export function boxEnvironment(
const kept: Record<string, string> = {};
for (const [name, value] of Object.entries(env)) {
if (value === undefined || !boxEnvironmentAllows(name, deny, allow)) continue;
+ // Security: only the fixed value an engine is started with passes, never the server's own SSH session (its addresses).
+ if (name === "SSH_CONNECTION" && value !== BOX_SSH_CONNECTION) continue;
kept[name] = value;
}
return kept;
diff --git a/server/contracts.ts b/server/contracts.ts
index 24573c2315..28e036d15d 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -431,10 +431,12 @@ export interface EngineInstall {
/** The vendor's npm package, for an engine whose `command` is its own installer script: Settings installs it on the
* server when npm is there, while a terminal keeps the vendor's command. */
npmPackage?: string;
- /** The app downloads and verifies a pinned provider runtime itself. */
+ /** The app downloads and verifies a provider runtime itself. `downloadBytes` is a number for every client; with
+ * `sizeUnknown` it is not the size of what will be downloaded, and a client shows no size. */
managed?: {
label: string;
downloadBytes: number;
+ sizeUnknown?: true;
};
/** The engine needs a key saved in the app rather than a terminal step. */
settings?: "connections";
@@ -502,6 +504,8 @@ export interface ProviderAuthenticationStart {
expiresAt: string | null;
/** A short-lived code to enter only at the provider's authorization URL. */
userCode?: string;
+ /** The provider's page shows a code after the sign-in, which the person pastes back (Antigravity's native CLI). */
+ pasteCode?: boolean;
}
export interface ProviderAuthenticationStatus extends Omit<ProviderAuthenticationStart, "phase"> {
diff --git a/server/drivers/acp/applied-config.ts b/server/drivers/acp/applied-config.ts
new file mode 100644
index 0000000000..e8ce867d7b
--- /dev/null
+++ b/server/drivers/acp/applied-config.ts
@@ -0,0 +1,35 @@
+// What a live ACP session last confirmed for each session config option the driver set (a permission mode, a thinking
+// level), so a turn that asks for the same value sends no `session/set_config_option` again.
+//
+// Adapted from pingdotgg/t3code@38067630229, MIT License, Copyright (c) 2026 T3 Tools Inc. (full text in
+// third_party/t3-code/LICENSE); modified: packages/provider-acp/src/server/adapter.ts (configureSession runs only when
+// the model, interaction mode or runtime mode changed) and AcpSessionRuntime.ts (each setter skips the RPC when the value
+// already matches) become one per-session record. A value is skipped only when this session confirmed it AND the
+// session's latest reported options still say so; the record is forgotten when the session is new, loaded or resumed,
+// when the model is switched, when the agent reports a config change between turns, and when a call fails.
+
+export class AppliedConfig {
+ private readonly values = new Map<string, string>();
+
+ /** This session confirmed `value` for `configId`, and the options it reported last still hold it. */
+ holds(configId: string, value: string, reported: unknown): boolean {
+ return this.values.get(configId) === value && reported === value;
+ }
+
+ accepted(configId: string, value: string): void {
+ this.values.set(configId, value);
+ }
+
+ clear(): void {
+ this.values.clear();
+ }
+
+ get size(): number {
+ return this.values.size;
+ }
+}
+
+/** The `currentValue` of one option in a session's `configOptions`, as the agent reported it last. */
+export function reportedConfigValue(configOptions: unknown, configId: string): unknown {
+ return Array.isArray(configOptions) ? configOptions.find((option: any) => option?.id === configId)?.currentValue : undefined;
+}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 329d635f98..e81ab88c47 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -25,10 +25,7 @@ import { applyOneShotEnv, runAcpOneShot } from "./background-text.ts"; import ty
import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";
import { acpNativeLogMessage } from "./tool-log.ts";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
-import {
- classifyQuiet, describeQuiet, formatQuietLimit, quietNoticeText, lastSeenPhrase, LIMIT_WORDS, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, quietVerdict, sampleProcessTree,
- type LogSignal, type ProcessSample, type QuietState,
-} from "./quiet-status.ts";
+import { formatQuietLimit, lastSeenPhrase, LIMIT_WORDS, promptIdleTimeoutMs, type LogSignal } from "./quiet-status.ts"; import { startAcpQuietWatch } from "./quiet-watch.ts"; import { AppliedConfig } from "./applied-config.ts"; import { modelRefused, roomForReadBeside, startupRefresh } from "./startup-refresh.ts"; import { stderrFailureOf, watchStderrFailure, type StderrFailure } from "./harness-failure.ts"; import { timed, turnStartClock, type TurnStartClock } from "../../perf/turn-starts.ts";
import { acpMissingSession } from "./rpc-error.ts";
import { readSessionReport } from "./session-reports.ts";
import { promptTokenUsage } from "./prompt-usage.ts";
@@ -62,7 +59,7 @@ import { supportsApprovalMode } from "../../../shared/approval-mode.ts";
import { MAX_QUESTION_TEXT, parseAskQuestions, parseChoices, questionAnswersByQuestion } from "../../../shared/ask-question.ts";
import { appendNative } from "../native.ts";
-import { acpSessionOperationKey, acpShellRequest, answersAlone, permissionLaunchCwd } from "../permission-command.ts"; import { acpReadPaths } from "../../own-file-reads.ts";
+import { acpAnswersAlone, acpSessionOperationKey, acpShellRequest, permissionLaunchCwd } from "../permission-command.ts"; import { acpReadPaths } from "../../own-file-reads.ts";
import { openQuestionRequest, questionRequestFor, type AcpQuestionRequest } from "./question-requests.ts";
import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";
import { acpToolEndEvents } from "./tool-items.ts";
@@ -72,7 +69,7 @@ import { decodeAcpConfig } from "./config-decode.ts";
import { endTurn, trackAssistantImage, trackAssistantWords, trackThoughtAfterTool, trackRunningTool, trackToolEndShown, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";
import { recoveryPromptFor } from "../../resume-recovery.ts";
import { noticeFailure } from "../../chat-notices.ts";
-import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "../session-idle.ts";
+import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose, type ColdStartCost } from "../session-idle.ts";
import { startupFailureRecoverable } from "./startup-recovery.ts";
import { engineFailure, engineFailureKind } from "../engine-errors.ts";
import { acpRuntimeFailure, acpStopFailure } from "./failure-words.ts";
@@ -179,6 +176,14 @@ export interface AcpSupport extends AcpDriverHooks {
config: AcpConfig,
instanceId: string,
): Promise<ProviderSnapshot>;
+ /** A cold start of this engine takes tens of seconds: where memory allows, its idle process is kept longer (session-idle.ts). */
+ coldStartCost?: ColdStartCost;
+ /** A turn the saved model list serves goes ahead while the startup read runs (startup-refresh.ts). */
+ modelListStandsIn?: boolean;
+ /** Lines on the agent's stderr after which its process cannot run a turn (harness-failure.ts). */
+ stderrFailure?: StderrFailure;
+ /** How long session/new and session/resume (or load) may go unanswered on a live process; initialize keeps its own limit. */
+ sessionSetupTimeoutMs?: number;
/** Google Antigravity resumes through session/resume, not session/load. */
resumeMethod?: "load" | "resume";
/** Some agents acknowledge a live load without applying new MCP credentials. */
@@ -252,7 +257,7 @@ export interface AcpSupport extends AcpDriverHooks {
* and take the model/mode over the wire (droid); a throw fails the turn rather than run another model. */
configureSession?(ctx: {
request: (method: string, params: unknown, timeoutMs?: number) => Promise<any>;
- sessionId: string;
+ sessionId: string; instanceId: string;
env: Record<string, string | undefined>;
config: AcpConfig;
turn: SendTurnInput;
@@ -262,6 +267,7 @@ export interface AcpSupport extends AcpDriverHooks {
/** Last model acknowledged by session/new/load/set_model, preserved for pooled turns. */
currentModelId?: string;
/** The session's effort, and where a live change to it is recorded. */ currentEffort?: EffortLevel; effortApplied?(effort: EffortLevel | undefined): void;
+ /** What this live session last confirmed per config option; absent for a one-shot session. */ applied?: AppliedConfig;
/** session/new's or session/load's `configOptions`, verbatim. */
configOptions: Array<{ id?: unknown; currentValue?: unknown }>;
/** Tell the person the session runs another model than the one picked. */
@@ -353,17 +359,18 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
resolve: support.resolveModels && ((fresh) => { const env = childEnv(); return support.resolveModels!(env, config, instanceId, fresh, instanceEnvNames(input.environment, env)); }),
explain: (error) => acpDiscoveryProblem(error, support.classifyError) });
const refreshModels = (fresh?: boolean) => catalog.refresh(fresh);
- let startupModelRefresh: Promise<void> | null = null;
+ let startupModelRefresh: Promise<void> | null = null, startupSaved = false;
if (support.resolveModels && support.resolveModelsOnCreate !== false) {
startupModelRefresh = (await openStartupModelCatalog({
instanceId,
- use: (saved) => { catalog.models = saved; },
+ use: (saved) => { catalog.models = saved; startupSaved = true; },
current: () => catalog.models,
refresh: refreshModels,
}))?.pending ?? null;
} else if (support.resolveModelsOnCreate !== false) {
await refreshModels();
}
+ const startup = startupRefresh({ enabled: support.modelListStandsIn === true, room: roomForReadBeside, pending: startupModelRefresh, saved: () => startupSaved, catalog: () => catalog.models, normalize: support.normalizeSessionSelection });
const deviceSignIn = support.deviceSignIn ? new DeviceAuthController(support.deviceSignIn, { cli: config.cli, environment: () => childEnv(), onAuthenticated: refreshModels }) : null;
const browserSignIn = support.browserSignIn ? new AcpBrowserAuth(support.browserSignIn, { cli: config.cli, environment: () => childEnv(), onAuthenticated: refreshModels }) : null;
const listeners = new Set<RuntimeEventListener>();
@@ -395,7 +402,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
}
return stopped;
};
- const sessionIdle = sessionIdlePolicy("ACP");
+ const sessionIdle = sessionIdlePolicy("ACP", process.env, undefined, support.coldStartCost);
const backgroundEnds = new Map<string, Promise<void>>(), endBackground = (threadId: string, session: AcpSession) => support.backgroundWork && !backgroundEnds.has(threadId) && session.child.exitCode === null
&& backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).then(async (ended) => { if (ended === false) await endUncancelled(threadId, session); }).finally(() => backgroundEnds.delete(threadId)));
@@ -467,8 +474,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
// Session allows the driver keeps when the agent offered no `allow_always`: exact operations per
// thread, for the native session's life. A generic title with no input is never remembered.
const sessionAllows = new Map<string, Set<string>>();
+ /** Native sessions whose saved history the agent can no longer send (a reported `acpSessionBroken`): never resumed. */
+ const brokenSessions = new Set<string>();
+ /** Each turn's start timings, by turn id, until its turn.completed writes the line (perf/turn-starts.ts). */
+ const clocks = new Map<string, TurnStartClock>();
+ const finishClock = (turnId: string | undefined, outcome: string) => { const clock = turnId ? clocks.get(turnId) : undefined; if (clock) { clocks.delete(turnId!); clock.finish(outcome, Date.now()); } };
const emit = (event: RuntimeEvent) => {
+ if (event.type === "turn.completed") finishClock(event.turnId, event.stopReason ?? (event.ok ? "end_turn" : "failed"));
for (const listener of listeners) listener(event);
};
@@ -481,79 +494,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
createdAt: new Date().toISOString(),
});
- const startQuietWatch = (threadId: string, session: AcpSession, current: AcpTurn) => {
- const noticeAfterMs = quietNoticeMs();
- const tickMs = quietTickMs();
- const { sessionId } = session;
- const logPath = support.statusLog && sessionId ? support.statusLog.path(session.env, sessionId) : null;
- const tail = logPath ? new LogTail(logPath) : null;
- tail?.read();
- let logged: { signal: LogSignal; at: number } | null = null;
- let context: { tokens: number; threshold: number } | null = null;
- let previous: ProcessSample | null = null;
- let previousAt = 0;
- let shownKey: string | null = null;
- let noSignsSince: number | null = null;
- let notices = 0;
- let probing = false;
- let state: QuietState | null = null;
- const promptStartedAt = Date.now();
- let readAt = promptStartedAt;
- const tick = async () => {
- if (probing || current.state.settled || session.current !== current) return;
- const now = Date.now();
- for (const line of tail?.read() ?? []) {
- if (!support.statusLog!.shared) session.acp.touch();
- const signal = support.statusLog!.parse(line, sessionId!);
- if (signal?.kind === "context") context = { tokens: signal.tokens, threshold: signal.threshold };
- // A shared row was written some time after the last read; date it then, so a reply since clears it.
- else if (signal) logged = { signal, at: support.statusLog!.shared ? readAt : now };
- }
- readAt = now;
- const quietMs = now - Math.max(promptStartedAt, session.acp.lastInboundAt);
- if (quietMs < noticeAfterMs || current.asks.size || current.runningTools.size) {
- if (quietMs < noticeAfterMs && (!support.statusLog?.shared || session.acp.lastInboundAt > (logged?.at ?? 0))) logged = null;
- previous = null;
- shownKey = null;
- noSignsSince = null;
- state = null;
- return;
- }
- // Qwen's SDK retries on its own for about a minute before the next logged attempt.
- if (logged?.signal.kind === "retry"
- && now - logged.at > (logged.signal.delayMs ?? 60_000) + 120_000) logged = null;
- probing = true;
- const sample = session.child.pid ? await sampleProcessTree(session.child.pid) : { cpuMs: null, connections: null };
- probing = false;
- if (current.state.settled || session.current !== current) return;
- let next = classifyQuiet({
- logged: logged?.signal ?? null, context, sample, previous, sinceMs: previous ? now - previousAt : 0,
- });
- const first = previous === null;
- previous = sample;
- previousAt = now;
- if (first && next.kind === "unknown") return;
- // An SDK sleeping between retries holds no socket and burns no CPU (Qwen against a 429ing endpoint); waiting out a
- // usage limit, or no sign of life for minutes, ends the turn now rather than after the full silence guard.
- const verdict = quietVerdict({ next, logged, noSignsSince, now, quietMs, name: support.displayName, stuckAfterMs: ACP_STUCK_AFTER_MS });
- next = verdict.next; noSignsSince = verdict.noSignsSince;
- if (verdict.stop) return void session.acp.failAll(verdict.stop);
- state = next;
- const key = quietKey(next);
- if (key === shownKey || notices >= 12) return;
- shownKey = key;
- notices += 1;
- emit({
- ...base(threadId, current.turnId),
- type: "runtime.notice",
- message: describeQuiet(support.displayName, next, quietMs, promptIdleTimeoutMs()), text: quietNoticeText(support.displayName, next, quietMs),
- });
- };
- const timer = setInterval(() => { void tick(); }, tickMs);
- timer.unref?.();
- current.stopQuietWatch = () => clearInterval(timer);
- return { lastState: () => state };
- };
+ const startQuietWatch = (threadId: string, session: AcpSession, current: AcpTurn) => startAcpQuietWatch({ support, session, current, stuckAfterMs: ACP_STUCK_AFTER_MS,
+ notice: (message, text) => emit({ ...base(threadId, current.turnId), type: "runtime.notice", message, text }) });
const settle = (threadId: string, session: AcpSession, ok: boolean, stopReason: string | null) => {
const current = session.current;
@@ -599,7 +541,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (running) return running;
const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), botThreads: hostKey !== null, ro: launch.ro } }, "bot");
const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse, promptCompletion: support.promptCompletion });
- hosts.add(host); signIn.watch(host);
+ hosts.add(host); signIn.watch(host); if (support.stderrFailure) watchStderrFailure(host, support.stderrFailure);
child.once("close", () => hosts.delete(host));
child.once("error", () => hosts.delete(host));
return host;
@@ -649,14 +591,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const toolCall = params.toolCall ?? {};
const isQuestion = String(toolCall.toolCallId ?? "").startsWith("interaction_");
- if (current.turnConfig.fullAuto && current.turn.approvalMode === undefined && !isQuestion && answersAlone(toolCall.rawInput?.command)) {
+ if ((support.allowsAlone?.(instanceId, current.turn, toolCall) || (current.turnConfig.fullAuto && current.turn.approvalMode === undefined)) && !isQuestion && acpAnswersAlone(toolCall.rawInput)) {
const allow = optionFor("allow");
if (!allow) missing("allow");
return send({ jsonrpc: "2.0", id: msg.id, result: allow ? { outcome: { outcome: "selected", optionId: allow } } : cancelled });
}
const kind = String(toolCall.kind ?? "");
const operationKey = isQuestion || current.controlsHost ? null : acpSessionOperationKey(toolCall);
- if (operationKey && answersAlone(toolCall.rawInput?.command) && sessionAllows.get(threadId)?.has(operationKey)) {
+ if (operationKey && acpAnswersAlone(toolCall.rawInput) && sessionAllows.get(threadId)?.has(operationKey)) {
const allow = optionFor("allow");
if (allow) {
return send({ jsonrpc: "2.0", id: msg.id, result: { outcome: { outcome: "selected", optionId: allow } } });
@@ -760,10 +702,11 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const current = session.current;
if (support.modelVariants && p.update?.sessionUpdate === "config_option_update") {
if (current && !current.state.settled && session.sessionId && p.sessionId === session.sessionId) current.receiveModelVariants(p.update);
+ else session.appliedConfig.clear(); // a change between turns is not read: the next turn sends its values again
return;
}
if (current && ["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"].includes(p.update?.sessionUpdate)) {
- current.state.startupActivity = true; if (current.state.promptSent) current.acknowledge();
+ current.state.startupActivity = true; if (current.state.promptSent) { current.acknowledge(); clocks.get(current.turnId)?.firstUpdate(Date.now()); }
}
if (!current || !current.state.promptSent) return void (!current && support.backgroundWork?.wakes(p.update, Date.now() - (session.settledAt ?? 0)) && endBackground(threadId, session));
const u = filterUpdate ? filterUpdate(p.update ?? {}) : p.update ?? {};
@@ -868,7 +811,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
set initResult(result: any) { host.initResult = result; },
get authenticated() { return host.authenticated; },
set authenticated(done: boolean) { host.authenticated = done; },
- idleTimer: null,
+ idleTimer: null, appliedConfig: new AppliedConfig(),
closing: false,
dead: false,
get stderr() { return host.stderrTail.text; },
@@ -910,7 +853,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const sendTurn = async (turn: SendTurnInput, retryOf?: string) => {
requireRunning();
- if (startupModelRefresh) await startupModelRefresh;
+ // A saved list that offers this turn's model stands in while the startup read runs (startup-refresh.ts).
+ const standIn = startup.standsIn(turn), startedAt = Date.now();
+ if (startupModelRefresh && !standIn) await startupModelRefresh;
+ const modelsWaitedMs = Date.now() - startedAt;
await backgroundEnds.get(turn.threadId); requireRunning();
const parsedScope = parseToolScope(turn.toolScope);
if (!parsedScope.ok) throw new Error(parsedScope.error);
@@ -928,6 +874,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
throw new Error("local computer control requires interactive provider approvals");
}
const turnId = retryOf ?? newId();
+ const clock = (retryOf !== undefined ? clocks.get(turnId) : undefined) ?? turnStartClock(DRIVER_KIND, startedAt);
+ if (clocks.has(turnId)) clock.retried(); else clocks.set(turnId, clock);
+ clock.waited("models", modelsWaitedMs);
const cwd = turn.cwd ?? turnConfig.workspace ?? homedir();
const env = childEnv(turnConfig);
if (
@@ -985,7 +934,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
support.spawnFingerprint?.(spawnEnv, turnConfig) ?? null, launch.ro ?? [], boxAudienceKey(cwd)];
const contractKey = JSON.stringify([...processContract, cwd, turn.toolScope ?? null, inheritedScopeFingerprint]);
const launchModel = support.sessionModelEnv && cliTurn.model && /^[\w.:/-]{1,200}$/u.test(cliTurn.model)
- && catalog.accountModels?.has(cliTurn.model) ? cliTurn.model : undefined;
+ && catalog.accountModels?.has(cliTurn.model) && !standIn ? cliTurn.model : undefined;
const launchEnv = support.sessionModelEnv && launchModel
? { ...spawnEnv, [support.sessionModelEnv]: launchModel }
: spawnEnv;
@@ -995,7 +944,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const launchSession = () => {
const opened = openSession(threadId, launch, [...(launch.args ?? []), ...spawnArgs], launchEnv, cwd, contractKey, hostKey);
opened.launchModel = launchModel; opened.effort = cliTurn.effort;
- launchedThisTurn = true;
+ launchedThisTurn = true; if (opened.host.opened === 1) clock.spawned(Date.now());
return opened;
};
const sessionKey = JSON.stringify([mcpServers, turn.toolScope ?? null, inheritedScopeFingerprint]);
@@ -1006,7 +955,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
}
const pooled = sessions.get(threadId);
let session: AcpSession;
- if (pooled && !pooled.dead && !pooled.closing && pooled.contractKey === contractKey
+ if (pooled && !pooled.dead && !pooled.closing && pooled.contractKey === contractKey && !stderrFailureOf(pooled.host)
&& (!support.restartOnMcpChange || pooled.sessionKey === sessionKey)) {
stopIdleClose(`${instanceId}\0${threadId}`, pooled.idleTimer); // busy again: no longer idle
pooled.idleTimer = null;
@@ -1017,7 +966,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
else closeSession(threadId, "contract");
}
const joining = sharedHost(hostKey, threadId, cwd);
+ const admittingAt = Date.now();
await turn.engineAdmission?.(joining ? "session" : "process", joining?.child.pid);
+ clock.waited("room", Date.now() - admittingAt);
requireRunning();
if (active.has(threadId)) throw new Error("a turn is already running on this thread");
session = launchSession();
@@ -1032,7 +983,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
idleMs?: number,
idleMessage?: string | (() => string),
): Promise<any> =>
- signIn.refused(session.host) ?? session.acp.request(method, params, timeoutMs, receive, idleMs, idleMessage);
+ timed(clock, method, signIn.refused(session.host) ?? session.acp.request(method, params, timeoutMs, receive, idleMs, idleMessage));
const state: AcpTurn["state"] = { settled: false, promptSent: false, text: "", textMessageId: null, producedItem: false, repliedText: false, startupActivity: false, stopped: false, toolsSinceShown: false, thoughtSinceTool: false, usagePeak: null, usageLast: null, usageCompacted: false, cancelling: false };
let acknowledge = () => {};
@@ -1053,7 +1004,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
state: () => session.sessionConfigResult, store: (result) => { session.sessionConfigResult = result; },
report: (model, variants) => emit({ ...base(threadId, turnId), type: "session.model-variants", model, variants }),
});
- const receiveModelVariants = (result: any, replace = false) => modelControls.receive(result, replace);
+ const receiveModelVariants = (result: any, replace = false) => { if (replace) session.appliedConfig.clear(); modelControls.receive(result, replace); };
const requestedVariantOption = () => modelControls.variant(variant);
const flushAssistantText = () => {
@@ -1177,14 +1128,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const selectionParams = narrowsNativeTools(turn.toolScope)
? support.toolScopeSessionParams!(turn, init, mcpServers.length > 0, { config: turnConfig, env, cwd }) : {};
let loaded = false;
- if (cursor && (!support.closeBeforeLiveLoad || liveSessionId !== cursor || await request("session/close", { sessionId: cursor }, 30_000).then(() => { session.sessionId = session.sessionKey = null; return true; }, () => false))) {
+ if (cursor && !brokenSessions.has(cursor) && (!support.closeBeforeLiveLoad || liveSessionId !== cursor || await request("session/close", { sessionId: cursor }, 30_000).then(() => { session.sessionId = session.sessionKey = null; return true; }, () => false))) {
try {
await loadUntilReplayQuiet({
link: session.acp, sessionId: cursor, quietMs: support.loadReplayQuietMs?.(turn), replayed: () => session.sessionConfigResult ?? {},
send: (receive) => request(
support.resumeMethod === "resume" ? "session/resume" : "session/load",
{ sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init), ...selectionParams, ...support.sessionSetupParams?.(init) },
- LOAD_SESSION_TIMEOUT, receive),
+ support.sessionSetupTimeoutMs ?? LOAD_SESSION_TIMEOUT, receive),
receive: (result) => {
if (result) {
loaded = true;
@@ -1226,7 +1177,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
promptTurn = { ...turn, text: recovery.text };
rebuiltFromReplay = recovery.replayed;
}
- await request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init), ...selectionParams, ...support.sessionSetupParams?.(init) }, NEW_SESSION_TIMEOUT, (result) => {
+ await request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init), ...selectionParams, ...support.sessionSetupParams?.(init) }, support.sessionSetupTimeoutMs ?? NEW_SESSION_TIMEOUT, (result) => {
session.sessionId = typeof result?.sessionId === "string" ? result.sessionId : null;
session.sessionKey = sessionKey;
receiveModelVariants(result, true);
@@ -1262,28 +1213,28 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (pick.notice) emit({ ...base(threadId, turnId), type: "runtime.notice", message: pick.notice, text: pick.noticeText });
({ turn: cliTurn, variant, reportedModel } = pick);
current.turn = cliTurn;
- selectedModel = await modelControls.select(request, sessionId, INIT_TIMEOUT);
+ selectedModel = await modelControls.select((m, p, t, r) => (session.appliedConfig.clear(), request(m, p, t, r)), sessionId, INIT_TIMEOUT);
}
if (support.configureSession) {
approvalUnconfirmed = support.sessionScopedApproval === true;
await support.configureSession({
request: async (method, params, timeoutMs) => {
- const result = await request(method, params, timeoutMs ?? SESSION_CONFIG_TIMEOUT);
+ const result = await request(method, params, timeoutMs ?? SESSION_CONFIG_TIMEOUT).catch((error) => { session.appliedConfig.clear(); throw error; });
if (method === "session/set_model" && params && typeof params === "object" && "modelId" in params && typeof params.modelId === "string") {
session.sessionConfigResult = { ...session.sessionConfigResult, models: { ...session.sessionConfigResult?.models, currentModelId: params.modelId } };
}
if (method === "session/set_config_option" && Array.isArray(result?.configOptions)) session.sessionConfigResult = { ...session.sessionConfigResult, configOptions: result.configOptions };
return result;
},
- sessionId,
+ sessionId, instanceId,
env: spawnEnv,
config: turnConfig,
turn: cliTurn,
sessionModels: Array.isArray(session.sessionConfigResult?.models?.availableModels)
? session.sessionConfigResult.models.availableModels
: [],
- currentModelId: session.sessionConfigResult?.models?.currentModelId, currentEffort: session.effort, effortApplied: (effort) => { session.effort = effort; },
+ currentModelId: session.sessionConfigResult?.models?.currentModelId, currentEffort: session.effort, effortApplied: (effort) => { session.effort = effort; }, applied: session.appliedConfig,
configOptions: Array.isArray(session.sessionConfigResult?.configOptions)
? session.sessionConfigResult.configOptions
: [],
@@ -1297,17 +1248,12 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
// initialize's currentModelId is the CLI default, not this turn's model.
if (!selectedModel && cliTurn.model) selectedModel = cliTurn.model;
}
- if (variant !== undefined) {
- const option = requestedVariantOption();
- await request(
- "session/set_config_option",
- { sessionId, configId: option.configId, value: variant },
- SESSION_CONFIG_TIMEOUT,
- receiveModelVariants,
- );
- if (requestedVariantOption().currentValue !== variant) {
- throw new Error(`${support.displayName} did not apply variant ${variant}`);
- }
+ const option = variant === undefined ? null : requestedVariantOption();
+ if (option && variant !== undefined && !session.appliedConfig.holds(option.configId, variant, option.currentValue)) {
+ await request("session/set_config_option", { sessionId, configId: option.configId, value: variant }, SESSION_CONFIG_TIMEOUT, receiveModelVariants)
+ .catch((error) => { session.appliedConfig.clear(); throw error; });
+ if (requestedVariantOption().currentValue !== variant) throw (session.appliedConfig.clear(), new Error(`${support.displayName} did not apply variant ${variant}`));
+ session.appliedConfig.accepted(option.configId, variant);
}
} catch (error) {
// session.started is the only place the resume cursor is recorded.
@@ -1355,7 +1301,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
throw new Error(`${support.displayName} changed variant before the prompt`);
} const promptOutcome = await support.promptOutcome?.(instanceId, sessionId);
if (state.settled || state.stopped || session.closing) throw new Error("turn stopped");
- state.promptSent = true;
+ state.promptSent = true; clock.promptSent(Date.now());
if (!support.promptUnreachedModel) acknowledge();
const promptIdleMs = promptIdleTimeoutMs();
const quiet = startQuietWatch(threadId, session, current);
@@ -1371,6 +1317,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
`${last ? ` (last seen: ${lastSeenPhrase(last)})` : ""}. Send the message again to retry.`;
},
);
+ const harnessFailed = stderrFailureOf(session.host); if (harnessFailed) throw harnessFailed;
const steersOut = current.steering?.promptAnswered();
if (steersOut && !state.stopped) { current.flushAssistantText(); await steersOut; }
if (pendingSplitReceipt) {
@@ -1420,6 +1367,20 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
}
if (!state.settled && !state.cancelling) {
const untouched = retryOf === undefined && !state.producedItem && !state.text && !current.runningTools.size && !asks.size && !state.stopped && !session.closing;
+ if (untouched && standIn && !state.promptSent && modelRefused(e)) { // the saved list was stale: read it, then once more
+ acknowledge(); state.settled = true; session.current = null; current.stopQuietWatch?.(); closeSession(threadId, "stale-models");
+ let stopped = false; // a Stop while the list is read ends the turn at once, and it is not tried again
+ const stopWaiting = () => { if (stopped) return; stopped = true; active.delete(threadId); emit({ ...base(threadId, turnId), type: "turn.completed", ok: true, stopReason: "cancelled", cost: null }); };
+ active.set(threadId, { stop: stopWaiting, interrupt: stopWaiting, turnId, asks: new Map() });
+ return void startup.done().then(() => {
+ if (stopped) return;
+ if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
+ return sendTurn({ ...turn, startupRecovery: undefined }, turnId);
+ }).catch((failure) => {
+ emit({ ...base(threadId, turnId), type: "runtime.error", message: failure instanceof Error ? failure.message : String(failure) });
+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "rpc_error", cost: null });
+ });
+ }
if (untouched && retryUnderToolLimit(e, { key: toolLimitKey, model: resolvedModel, engine: DRIVER_KIND, retry: () => {
acknowledge(); state.settled = true; session.current = null; active.delete(threadId); current.stopQuietWatch?.();
return sendTurn({ ...turn, startupRecovery: undefined, sessionReset: undefined, resumeCursor: session.sessionId ?? turn.resumeCursor }, turnId);
@@ -1442,7 +1403,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (current.interruptTimer) clearTimeout(current.interruptTimer);
active.delete(threadId);
if (stopped && !state.stopped) {
- rejectStartup(new TurnNotStartedError(turnId, message));
+ finishClock(turnId, "not-started"); rejectStartup(new TurnNotStartedError(turnId, message));
return;
}
acknowledge();
@@ -1459,6 +1420,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
...((e as any)?.acpUsageLimit === true || (code === "quota_or_region_restriction" && LIMIT_WORDS.test(message)) ? modelControls.usageLimit((model) => support.limitFacts?.(message, model) ?? { limit: "engine" as const }) : {}), // waited out, or the engine gave up: another AI can carry on
});
// Never replay an accepted prompt (it may have run tools); evict before listeners start the next turn.
+ if ((e as any)?.acpSessionBroken === true && session.sessionId) brokenSessions.add(session.sessionId);
if (signIn.is(e)) closeSession(threadId, "sign-in-required"); else if (!needsAuth && !accountError && ((e as any)?.acpPromptStall === true || (e as any)?.acpUsageLimit === true || (e as any)?.acpSessionFailure === true
|| code === "upstream_outage") && session.child.exitCode === null && !session.closing) {
closeSession(threadId, (e as any)?.acpPromptStall === true ? "prompt-stall" : "rpc-failure");
@@ -1532,7 +1494,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
...(support.configureSession ? {
configure: ({ request, sessionId, session }) => support.configureSession!({
request,
- sessionId,
+ sessionId, instanceId,
env: spawnEnv,
config: turnConfig,
turn,
@@ -1601,7 +1563,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
closeSession(threadId, "dispose");
settle(threadId, session, true, "cancelled");
}
- listeners.clear();
+ listeners.clear(); clocks.clear();
// Engines lead sessions of their own, so nothing stops them once this server exits.
await stopEngineTrees([...disposingSessions.map(([, session]) => session.child), ...[...retiring.values()].flatMap((children) => [...children]), ...leaving]);
},
diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.ts
index 05c51733df..bf3cd14157 100644
--- a/server/drivers/acp/driver-hooks.ts
+++ b/server/drivers/acp/driver-hooks.ts
@@ -26,6 +26,9 @@ export interface AcpDriverHooks {
sessionSetupParams?(initializeResult: unknown): Record<string, unknown>;
/** The `clientInfo` of initialize, for an agent that reads it; the app's own name when unset or undefined. */
clientInfo?(instanceId: string): { name: string; version: string } | undefined;
+ /** Whether the driver answers this permission request with "allow" itself, with no card: for an agent that asks
+ * about actions the turn's approval level already covers. Never consulted for a question or a never-list command. */
+ allowsAlone?(instanceId: string, turn: { approvalMode?: string; cwd?: string }, toolCall: { kind?: unknown; rawInput?: unknown; locations?: unknown }): boolean;
/** Called before each session/prompt. The check it returns gets that prompt's result and names the failure the agent
* reported as an ordinary reply, which then fails the turn. Neither may throw. */
promptOutcome?(instanceId: string, sessionId: string): Promise<(result: unknown) => Promise<Error | undefined>>;
diff --git a/server/drivers/acp/harness-failure.ts b/server/drivers/acp/harness-failure.ts
new file mode 100644
index 0000000000..e1b4003b74
--- /dev/null
+++ b/server/drivers/acp/harness-failure.ts
@@ -0,0 +1,42 @@
+// An agent whose own log, on stderr, says it can no longer run a turn: the turn waiting on it fails now, and the process
+// is not used again, rather than the turn waiting out the five- and fifteen-minute silence guards.
+//
+// Adapted from pingdotgg/t3code@94baff19c65, MIT License, Copyright (c) 2026 T3 Tools Inc. (full text in
+// third_party/t3-code/LICENSE); modified: apps/server/src/provider/antigravityAuthSupport.ts's stderr handler becomes a
+// per-process watch the shared ACP runtime runs for any engine that names such lines. T3 also starts Google's packaged
+// runtime with --alsologtostderr so those lines reach stderr; that flag is not passed here (it was not tried against
+// the runtime this app pins), so the watch acts only on lines the runtime writes to stderr by itself.
+import type { AcpHost } from "./host.ts";
+
+export interface StderrFailure {
+ /** A whole stderr line after which the process cannot run a turn. */
+ line: RegExp;
+ /** What the person is told. */
+ message: string;
+}
+
+const MAX_LINE_CHARS = 64 * 1024;
+const failed = new WeakMap<AcpHost, Error>();
+
+export function watchStderrFailure(host: AcpHost, spec: StderrFailure): void {
+ let partial = "";
+ host.child.stderr.on("data", (chunk: string | Buffer) => {
+ const lines = (partial + String(chunk)).split("\n");
+ partial = lines.pop() ?? "";
+ if (partial.length > MAX_LINE_CHARS) partial = "";
+ if (failed.has(host) || !lines.some((line) => line.length <= MAX_LINE_CHARS && spec.line.test(line.replace(/\r$/u, "")))) return;
+ const error = Object.assign(new Error(spec.message), { acpSessionFailure: true });
+ failed.set(host, error);
+ host.draining = true;
+ for (const link of host.links) link.failAll(error);
+ });
+}
+
+/** The failure this process's stderr reported, if any: a prompt it answered after that is not trusted. */
+export function stderrFailureOf(host: AcpHost): Error | null {
+ return failed.get(host) ?? null;
+}
+
+/** glog records from Google's packaged harness after which its ACP process can no longer run a turn (T3 Code's list). */
+export const ANTIGRAVITY_HARNESS_FAILURE_LOG =
+ /^[IWEF]\d{4} \d{2}:\d{2}:\d{2}\.\d+ +\d+ (?:local_connection\.py:\d+\] harness stderr: Agent run failed:|server\.py:\d+\] (?:Failed to rebuild agent for session |Agent connection lost for session ))/;
diff --git a/server/drivers/acp/host.test.ts b/server/drivers/acp/host.test.ts
index 6a8bc48062..247864a722 100644
--- a/server/drivers/acp/host.test.ts
+++ b/server/drivers/acp/host.test.ts
@@ -1,7 +1,7 @@
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AcpHost, type AcpInbound } from "./host.ts";
@@ -89,3 +89,24 @@ describe("one ACP process for several threads", () => {
expect(h.heard.get("only")).toHaveLength(2);
});
});
+
+describe("a prompt's silence timer across a sleep", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("does not count the time the computer slept as the agent's silence", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
+ const h = hostWith(null);
+ const link = h.link("a", "s-a");
+ let failure: Error | null = null;
+ void link.request("session/prompt", { sessionId: "s-a" }, undefined, undefined, 5 * 60_000).catch((error: Error) => { failure = error; });
+ await vi.advanceTimersByTimeAsync(4 * 60_000);
+ // Asleep for half an hour: the wall clock moves on, the timer does not fire until the computer wakes.
+ vi.setSystemTime(Date.now() + 30 * 60_000);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(failure).toBeNull();
+ await vi.advanceTimersByTimeAsync(4 * 60_000);
+ expect(failure).toBeNull();
+ await vi.advanceTimersByTimeAsync(60_000 + 1);
+ expect(failure).toMatchObject({ acpPromptStall: true });
+ });
+});
diff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.ts
index feeb0f8e11..de30a19c33 100644
--- a/server/drivers/acp/host.ts
+++ b/server/drivers/acp/host.ts
@@ -16,6 +16,10 @@ import { acpRpcError } from "./rpc-error.ts";
/** How long a prompt the agent's own notification ended still waits for its session/prompt reply, which carries the
* prompt's token usage and, in recorded traffic, follows the notification at once. */
const REPLY_AFTER_END_MS = 2_000;
+/** A prompt's silence is timed in slices this long, and a slice that ends this much past its time was the computer asleep.
+ * Adapted from pingdotgg/t3code@990f31cac25, MIT License, Copyright (c) 2026 T3 Tools Inc. (full text in
+ * third_party/t3-code/LICENSE); modified: the prompt-inactivity loop's slices become this request's idle timer. */
+export const IDLE_SLICE_MS = 60_000, HOST_SLEEP_TOLERANCE_MS = 10_000;
/** A stderr line longer than this is not the short line a refused thread start writes. */
const STDERR_LINE_CHARS = 4096;
@@ -269,17 +273,27 @@ export class AcpHost {
timer.unref?.();
}
let idleTimer: ReturnType<typeof setTimeout> | null = null;
+ // The silence is counted in slices: a slice that ends well past its time means the computer slept (timers fire late
+ // on wake on macOS and Windows, and pause while the clock jumps on Linux), and sleep is not the agent's silence.
const armIdle = () => {
if (!(idleMs && idleMs > 0)) return;
if (idleTimer) clearTimeout(idleTimer);
- idleTimer = setTimeout(() => {
- if (link?.inbound?.busy()) { armIdle(); return; }
- this.#pending.delete(id);
- const error = new Error((typeof idleMessage === "function" ? idleMessage() : idleMessage) ?? `${method} stopped responding`);
- Object.assign(error, { acpPromptStall: true });
- reject(error);
- }, idleMs);
- idleTimer.unref?.();
+ let left = idleMs;
+ const slice = () => {
+ const step = Math.min(left, IDLE_SLICE_MS), startedAt = Date.now();
+ idleTimer = setTimeout(() => {
+ if (Date.now() - startedAt > step + HOST_SLEEP_TOLERANCE_MS) left = idleMs;
+ else left -= step;
+ if (left > 0) return slice();
+ if (link?.inbound?.busy()) { armIdle(); return; }
+ this.#pending.delete(id);
+ const error = new Error((typeof idleMessage === "function" ? idleMessage() : idleMessage) ?? `${method} stopped responding`);
+ Object.assign(error, { acpPromptStall: true });
+ reject(error);
+ }, step);
+ idleTimer.unref?.();
+ };
+ slice();
};
armIdle();
this.#pending.set(id, {
diff --git a/server/drivers/acp/quiet-watch.ts b/server/drivers/acp/quiet-watch.ts
new file mode 100644
index 0000000000..01b57acb48
--- /dev/null
+++ b/server/drivers/acp/quiet-watch.ts
@@ -0,0 +1,90 @@
+// The watch on a prompt that has gone quiet: reads the agent's own log and samples its process tree, tells the person what
+// it is doing, and stops a turn that waits out a usage limit or shows no sign of life for minutes. Moved out of core.ts.
+import {
+ classifyQuiet, describeQuiet, quietNoticeText, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, quietVerdict, sampleProcessTree,
+ type LogSignal, type ProcessSample, type QuietState,
+} from "./quiet-status.ts";
+import type { ServerText } from "../../../shared/server-text.ts";
+import { HOST_SLEEP_TOLERANCE_MS } from "./host.ts";
+import type { AcpSupport } from "./core.ts";
+import type { AcpSession, AcpTurn } from "./turn-state.ts";
+
+export function startAcpQuietWatch(input: {
+ support: Pick<AcpSupport, "statusLog" | "displayName">;
+ session: AcpSession;
+ current: AcpTurn;
+ stuckAfterMs: number;
+ notice: (message: string, text: ServerText | undefined) => void;
+}): { lastState: () => QuietState | null } {
+ const { support, session, current } = input;
+ const noticeAfterMs = quietNoticeMs();
+ const tickMs = quietTickMs();
+ const { sessionId } = session;
+ const logPath = support.statusLog && sessionId ? support.statusLog.path(session.env, sessionId) : null;
+ const tail = logPath ? new LogTail(logPath) : null;
+ tail?.read();
+ let logged: { signal: LogSignal; at: number } | null = null;
+ let context: { tokens: number; threshold: number } | null = null;
+ let previous: ProcessSample | null = null;
+ let previousAt = 0;
+ let shownKey: string | null = null;
+ let noSignsSince: number | null = null;
+ let notices = 0;
+ let probing = false;
+ let state: QuietState | null = null;
+ const promptStartedAt = Date.now();
+ let readAt = promptStartedAt, tickedAt = promptStartedAt, wokeAt = 0;
+ const tick = async () => {
+ const now = Date.now();
+ // A tick this late means the computer slept: that time is not the agent's silence (pingdotgg/t3code@990f31cac25).
+ if (now - tickedAt > tickMs + HOST_SLEEP_TOLERANCE_MS) { wokeAt = now; previous = null; noSignsSince = null; }
+ tickedAt = now;
+ if (probing || current.state.settled || session.current !== current) return;
+ for (const line of tail?.read() ?? []) {
+ if (!support.statusLog!.shared) session.acp.touch();
+ const signal = support.statusLog!.parse(line, sessionId!);
+ if (signal?.kind === "context") context = { tokens: signal.tokens, threshold: signal.threshold };
+ // A shared row was written some time after the last read; date it then, so a reply since clears it.
+ else if (signal) logged = { signal, at: support.statusLog!.shared ? readAt : now };
+ }
+ readAt = now;
+ const quietMs = now - Math.max(promptStartedAt, session.acp.lastInboundAt, wokeAt);
+ if (quietMs < noticeAfterMs || current.asks.size || current.runningTools.size) {
+ if (quietMs < noticeAfterMs && (!support.statusLog?.shared || session.acp.lastInboundAt > (logged?.at ?? 0))) logged = null;
+ previous = null;
+ shownKey = null;
+ noSignsSince = null;
+ state = null;
+ return;
+ }
+ // Qwen's SDK retries on its own for about a minute before the next logged attempt.
+ if (logged?.signal.kind === "retry"
+ && now - logged.at > (logged.signal.delayMs ?? 60_000) + 120_000) logged = null;
+ probing = true;
+ const sample = session.child.pid ? await sampleProcessTree(session.child.pid) : { cpuMs: null, connections: null };
+ probing = false;
+ if (current.state.settled || session.current !== current) return;
+ let next = classifyQuiet({
+ logged: logged?.signal ?? null, context, sample, previous, sinceMs: previous ? now - previousAt : 0,
+ });
+ const first = previous === null;
+ previous = sample;
+ previousAt = now;
+ if (first && next.kind === "unknown") return;
+ // An SDK sleeping between retries holds no socket and burns no CPU (Qwen against a 429ing endpoint); waiting out a
+ // usage limit, or no sign of life for minutes, ends the turn now rather than after the full silence guard.
+ const verdict = quietVerdict({ next, logged, noSignsSince, now, quietMs, name: support.displayName, stuckAfterMs: input.stuckAfterMs });
+ next = verdict.next; noSignsSince = verdict.noSignsSince;
+ if (verdict.stop) return void session.acp.failAll(verdict.stop);
+ state = next;
+ const key = quietKey(next);
+ if (key === shownKey || notices >= 12) return;
+ shownKey = key;
+ notices += 1;
+ input.notice(describeQuiet(support.displayName, next, quietMs, promptIdleTimeoutMs()), quietNoticeText(support.displayName, next, quietMs));
+ };
+ const timer = setInterval(() => { void tick(); }, tickMs);
+ timer.unref?.();
+ current.stopQuietWatch = () => clearInterval(timer);
+ return { lastState: () => state };
+}
diff --git a/server/drivers/acp/startup-refresh.test.ts b/server/drivers/acp/startup-refresh.test.ts
new file mode 100644
index 0000000000..cce6aee7ec
--- /dev/null
+++ b/server/drivers/acp/startup-refresh.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import type { ModelCatalog, SendTurnInput } from "../../contracts.ts";
+import { modelRefused, startupRefresh } from "./startup-refresh.ts";
+
+const catalog: ModelCatalog = { default: "gemini-3.8-flash", options: [{ id: "gemini-3.8-flash", label: "Flash" }] };
+const turn = (model?: string) => ({ threadId: "t", text: "hello", ...(model ? { model } : {}) }) as SendTurnInput;
+
+describe("whether a saved model list stands in for the startup read", () => {
+ const make = (over: Partial<Parameters<typeof startupRefresh>[0]> = {}) => startupRefresh({
+ enabled: true, room: () => true, pending: new Promise<void>(() => {}), saved: () => true, catalog: () => catalog, ...over,
+ });
+
+ it("only for an engine that opts in, with a saved list, while the read runs, and with room for the read's own process", () => {
+ expect(make().standsIn(turn("gemini-3.8-flash"))).toBe(true);
+ expect(make().standsIn(turn())).toBe(true);
+ expect(make({ enabled: false }).standsIn(turn("gemini-3.8-flash"))).toBe(false);
+ expect(make({ saved: () => false }).standsIn(turn("gemini-3.8-flash"))).toBe(false);
+ expect(make({ pending: null }).standsIn(turn("gemini-3.8-flash"))).toBe(false);
+ // A small Cloud short of room keeps the old order: the read first, then the turn's own process.
+ expect(make({ room: () => false }).standsIn(turn("gemini-3.8-flash"))).toBe(false);
+ });
+
+ it("not for a model the saved list lacks, unless the driver maps it onto one it has", () => {
+ expect(make().standsIn(turn("gemini-4-neon"))).toBe(false);
+ const normalize = (input: SendTurnInput) => (input.model === "gemini-3.8-flash-high" ? { ...input, model: "gemini-3.8-flash", variant: "high" } : input);
+ expect(make({ normalize }).standsIn(turn("gemini-3.8-flash-high"))).toBe(true);
+ });
+
+ it("stops standing in once the read is over, whatever its outcome", async () => {
+ let fail!: (error: Error) => void;
+ const refresh = make({ pending: new Promise<void>((_resolve, reject) => { fail = reject; }) });
+ expect(refresh.pending).toBe(true);
+ fail(new Error("offline"));
+ await refresh.done();
+ expect(refresh.pending).toBe(false);
+ expect(refresh.standsIn(turn("gemini-3.8-flash"))).toBe(false);
+ });
+
+ it("reads a refusal of the model a turn asked for", () => {
+ expect(modelRefused({ code: -32602, message: "Invalid params: model not found: gemini-old" })).toBe(true);
+ expect(modelRefused(new Error("Google Gemini (Antigravity) did not switch to gemini-old (still gemini-3.8-flash)"))).toBe(true);
+ expect(modelRefused({ code: -32602, message: "Invalid params: sessionId" })).toBe(false);
+ expect(modelRefused(new Error("session/new timed out"))).toBe(false);
+ });
+});
diff --git a/server/drivers/acp/startup-refresh.ts b/server/drivers/acp/startup-refresh.ts
new file mode 100644
index 0000000000..da73dd163e
--- /dev/null
+++ b/server/drivers/acp/startup-refresh.ts
@@ -0,0 +1,62 @@
+// Whether a turn waits for the model list an engine reads again at server start (startup-model-catalog.ts). Reading it
+// can start a second engine process and walk every model's thinking levels; a turn that the saved list already serves
+// goes ahead on it, and the list is read in the background.
+//
+// Adapted from pingdotgg/t3code@38067630229, MIT License, Copyright (c) 2026 T3 Tools Inc. (full text in
+// third_party/t3-code/LICENSE); modified: apps/server/src/provider/Drivers/AntigravityDriver.ts keeps its model survey on
+// a throwaway process at sign-in and on an explicit refresh, never awaited by a turn. Here the survey still runs at start
+// when the saved list is old or from another build, but only a turn the saved list cannot serve waits for it; a turn
+// that went ahead on the saved list never seeds the launch's default model from it, and a model the agent refuses then
+// waits for the read and is tried once more.
+import { boxMemory } from "../../box-memory.ts";
+import type { ModelCatalog, SendTurnInput } from "../../contracts.ts";
+import { engineMemory } from "../../engine-memory.ts";
+import { roomBesideIdle } from "../session-idle.ts";
+
+/** No memory gate (the desktop), or the room holds one more of the largest engines beside what runs now. */
+export const roomForReadBeside = (): boolean => !engineMemory.enabled || roomBesideIdle(engineMemory.roomFactor(), boxMemory().bytes);
+
+export interface StartupRefresh {
+ /** The read is still under way and the saved list stands in for it: this turn does not wait. */
+ standsIn(turn: SendTurnInput): boolean;
+ /** Resolves when the read is over, whatever its outcome. */
+ done(): Promise<void>;
+ readonly pending: boolean;
+}
+
+export function startupRefresh(input: {
+ /** The engine opts in (AcpSupport.modelListStandsIn): others keep waiting as before. */
+ enabled: boolean;
+ /** The read starts an engine process of its own that admission does not count: only stand in where that cannot crowd
+ * the turn's own (no memory gate, or room for one more of the largest engines). */
+ room: () => boolean;
+ pending: Promise<void> | null;
+ /** A saved list was put in place when the engine opened. */
+ saved: () => boolean;
+ catalog: () => ModelCatalog;
+ normalize?: (turn: SendTurnInput, offered: readonly string[], catalog: ModelCatalog) => SendTurnInput;
+}): StartupRefresh {
+ let pending = input.pending !== null;
+ const done = input.pending ? input.pending.then(() => { pending = false; }, () => { pending = false; }) : Promise.resolve();
+ return {
+ get pending() { return pending; },
+ done: () => done,
+ standsIn: (turn) => {
+ if (!input.enabled || !pending || !input.saved() || !input.room()) return false;
+ if (!turn.model) return true;
+ const catalog = input.catalog();
+ const ids = catalog.options.map((option) => option.id);
+ const model = (input.normalize?.(turn, ids, catalog) ?? turn).model;
+ return model !== undefined && ids.includes(model);
+ },
+ };
+}
+
+/** An agent's refusal of the model a turn asked for: the setter's invalid-params answer, or the driver's own check that
+ * the session did not switch or does not list it. */
+export function modelRefused(error: unknown): boolean {
+ const value = error as { code?: unknown; message?: unknown } | null;
+ const message = typeof value?.message === "string" ? value.message : "";
+ return /\bdid not switch to\b|\bdoes not advertise model\b|\bmodel not found\b|\bchanged model before the prompt\b/iu.test(message)
+ || (value?.code === -32602 && /\bmodel\b/iu.test(message));
+}
diff --git a/server/drivers/acp/turn-health.test.ts b/server/drivers/acp/turn-health.test.ts
new file mode 100644
index 0000000000..0bbdee9ce8
--- /dev/null
+++ b/server/drivers/acp/turn-health.test.ts
@@ -0,0 +1,88 @@
+// Turn health on the shared ACP runtime, with the fake agent: a session setup that is never answered, a host that sleeps.
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { ProviderInstance } from "../../contracts.ts";
+import { recordEvents } from "../../testing/events.ts";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { ANTIGRAVITY_SESSION_SETUP_TIMEOUT_MS } from "../antigravity.ts";
+import { createAcpDriver, type AcpSupport } from "./core.ts";
+import { ANTIGRAVITY_HARNESS_FAILURE_LOG } from "./harness-failure.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "testing", "fake-acp-cli.ts");
+const SUPPORT: AcpSupport = {
+ driverKind: "turnHealthTest", displayName: "Turn Health Test",
+ models: { default: "m-one", options: [{ id: "m-one", label: "One" }] },
+ defaultCli: FAKE_CLI, nativeSource: "turn-health.acp", loginNote: "never reached",
+ spawnArgs: () => [], pickAuthMethod: () => null, authFailure: "continue", isAuthenticated: () => true,
+};
+const scratch: string[] = [];
+let instance: ProviderInstance | null = null;
+afterEach(async () => {
+ await instance?.dispose();
+ instance = null;
+ while (scratch.length) await removeTempDir(scratch.pop()!);
+});
+
+function folder(): string {
+ const directory = mkdtempSync(join(tmpdir(), "omb-turn-health-"));
+ scratch.push(directory);
+ return directory;
+}
+
+describe("a session setup the agent never answers", () => {
+ it("fails the turn after the engine's own limit instead of the core's five minutes", async () => {
+ const directory = folder();
+ const failure = join(directory, "failure.json");
+ writeFileSync(failure, JSON.stringify({ code: -32603, message: "never sent" }));
+ const driver = createAcpDriver({ ...SUPPORT, sessionSetupTimeoutMs: 500 });
+ instance = await driver.create({
+ instanceId: "turn-health-setup", displayName: "Turn Health", enabled: true, config: driver.defaultConfig(),
+ // session/new is held behind a gate no one opens: the live process never answers it.
+ environment: { FAKE_ACP_RPC_FAILURE_METHOD: "session/new", FAKE_ACP_RPC_FAILURE_FILE: failure, FAKE_ACP_RPC_FAILURE_GATE: join(directory, "never") },
+ });
+ const recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-setup", text: "hello", cwd: directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 5_000)).toMatchObject({ ok: false });
+ expect(recorder.events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("session/new timed out") });
+ recorder.stop();
+ });
+
+ it("is 90 seconds for Antigravity, as T3 Code's ACP startup", () => {
+ expect(ANTIGRAVITY_SESSION_SETUP_TIMEOUT_MS).toBe(90_000);
+ });
+});
+
+// Adapted from pingdotgg/t3code@94baff19c65 (acp-mock-agent.ts's harness failure line, AntigravityAdapterV2.test.ts's cases).
+const HARNESS_FAILURE = "I1022 11:04:37.910207 1865358 local_connection.py:551] harness stderr: Agent run failed: failed to handle call hook response: no pending hook for ID hook_request_2";
+
+describe("an agent whose own log says its local harness failed", () => {
+ it("knows the packaged Antigravity harness's failure lines, and only those", () => {
+ expect(ANTIGRAVITY_HARNESS_FAILURE_LOG.test(HARNESS_FAILURE)).toBe(true);
+ expect(ANTIGRAVITY_HARNESS_FAILURE_LOG.test("E1022 11:04:38.000001 1865358 server.py:310] Failed to rebuild agent for session abc")).toBe(true);
+ expect(ANTIGRAVITY_HARNESS_FAILURE_LOG.test("W1022 11:04:38.000001 1865358 server.py:310] Agent connection lost for session abc")).toBe(true);
+ expect(ANTIGRAVITY_HARNESS_FAILURE_LOG.test("I1022 11:04:37.910207 1865358 local_connection.py:551] harness stderr: tool call finished")).toBe(false);
+ expect(ANTIGRAVITY_HARNESS_FAILURE_LOG.test("Agent run failed: in a model's reply")).toBe(false);
+ });
+
+ it("fails the waiting turn at once and starts the next one in a new process", async () => {
+ const directory = folder();
+ const launches = join(directory, "launches");
+ const driver = createAcpDriver({ ...SUPPORT, stderrFailure: { line: ANTIGRAVITY_HARNESS_FAILURE_LOG, message: "The local agent connection failed." } });
+ instance = await driver.create({
+ instanceId: "turn-health-harness", displayName: "Turn Health", enabled: true, config: driver.defaultConfig(),
+ environment: { FAKE_ACP_PROMPT_STDERR: HARNESS_FAILURE, FAKE_ACP_PROMPT_STDERR_THEN: "hang", FAKE_ACP_LAUNCH_COUNT_FILE: launches },
+ });
+ const recorder = recordEvents(instance.adapter);
+ for (const threadTurn of [1, 2]) {
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-harness", text: `turn ${threadTurn}`, cwd: directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 5_000)).toMatchObject({ ok: false });
+ expect(recorder.events.filter((event) => event.type === "runtime.error" && event.turnId === turnId).at(-1)).toMatchObject({ message: "The local agent connection failed." });
+ }
+ expect(Number(readFileSync(launches, "utf8"))).toBe(2);
+ recorder.stop();
+ });
+});
diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.ts
index 04ccb25a86..59409c505c 100644
--- a/server/drivers/acp/turn-state.ts
+++ b/server/drivers/acp/turn-state.ts
@@ -5,7 +5,7 @@ import type { spawnCli } from "../../procs.ts";
import { noticeFailure } from "../../chat-notices.ts";
import { errorReplyFailure, type ErrorReplyFailure } from "../engine-errors.ts";
import type { AcpConfig } from "./core.ts";
-import type { AcpHost, AcpLink } from "./host.ts";
+import type { AcpHost, AcpLink } from "./host.ts"; import type { AppliedConfig } from "./applied-config.ts";
import type { AcpTurnSteering } from "./steer.ts";
export type AcpAskFinish = (
@@ -61,6 +61,8 @@ export interface AcpSession {
initResult: any;
authenticated: boolean;
idleTimer: ReturnType<typeof setTimeout> | null;
+ /** The config option values this live session confirmed, so an unchanged one is not sent again. */
+ appliedConfig: AppliedConfig;
closing: boolean;
/** Set when a shared process's session closes through `session/close`: true once the agent confirms it. */
closeConfirmed?: Promise<boolean>;
diff --git a/server/drivers/antigravity-account.ts b/server/drivers/antigravity-account.ts
index 96fe23f519..6e80df990a 100644
--- a/server/drivers/antigravity-account.ts
+++ b/server/drivers/antigravity-account.ts
@@ -4,8 +4,9 @@ import { readFile, stat } from "node:fs/promises";
type Identity = { email: string; method: "login" } | undefined;
const identities = new Map<string, { fingerprint: string; expires: number; result: Promise<Identity> }>();
-/** The official ACP file stores refresh credentials, not the account email.
- * Resolve display identity through Google only; never expose or rewrite tokens. */
+/** The pinned runtime's file stores refresh credentials, not the account email; the native CLI's stores an access token
+ * and no OAuth client, so it is read only while that token is fresh (the CLI refreshes it itself). Resolve display
+ * identity through Google only; never expose or rewrite tokens. */
export async function antigravityAccount(tokenPath: string): Promise<Identity> {
try {
const info = await stat(tokenPath);
@@ -15,9 +16,10 @@ export async function antigravityAccount(tokenPath: string): Promise<Identity> {
const cached = identities.get(tokenPath);
if (cached?.fingerprint === fingerprint && cached.expires > Date.now()) return cached.result;
const credentials = JSON.parse(raw);
- if (!credentials || !["client_id", "client_secret", "refresh_token"].every((key) => typeof credentials[key] === "string" && credentials[key].length > 0)) return undefined;
+ const cliAccess = antigravityCliAccessToken(credentials);
+ if (!cliAccess && (!credentials || !["client_id", "client_secret", "refresh_token"].every((key) => typeof credentials[key] === "string" && credentials[key].length > 0))) return undefined;
const entry = { fingerprint, expires: Date.now() + 60_000, result: Promise.resolve<Identity>(undefined) };
- entry.result = lookup(credentials).then((account) => {
+ entry.result = lookup(cliAccess ? { accessToken: cliAccess.accessToken } : credentials).then((account) => {
if (account) entry.expires = Date.now() + 60 * 60_000;
return account;
});
@@ -31,6 +33,15 @@ export async function antigravityAccount(tokenPath: string): Promise<Identity> {
}
export interface AntigravityStoredSignIn { client_id: string; client_secret: string; refresh_token: string }
+
+/** The access token in the native CLI's sign-in file (`{"token":{"access_token","expiry",…}}`) while it has more than a
+ * minute left; null for any other file or a stale token. */
+export function antigravityCliAccessToken(file: unknown, now = Date.now()): { accessToken: string; expiresAt: number } | null {
+ const token = (file as { token?: { access_token?: unknown; expiry?: unknown } } | null)?.token;
+ if (!token || typeof token.access_token !== "string" || !token.access_token || typeof token.expiry !== "string") return null;
+ const expiresAt = Date.parse(token.expiry);
+ return Number.isFinite(expiresAt) && expiresAt > now + 60_000 ? { accessToken: token.access_token, expiresAt } : null;
+}
type AccessFetch = (url: string, init: { method?: "POST"; headers?: Record<string, string>; body?: string | URLSearchParams; redirect: "error" | "manual"; signal: AbortSignal }) => Promise<Pick<Response, "ok" | "json">>;
/** A short-lived access token for the stored sign-in, from Google only. The token stays in memory: it is never logged,
@@ -52,10 +63,10 @@ export async function refreshAntigravityAccess(
return { accessToken: token.access_token, expiresInSeconds: typeof token.expires_in === "number" && token.expires_in > 0 ? token.expires_in : null };
}
-async function lookup(credentials: AntigravityStoredSignIn): Promise<Identity> {
+async function lookup(credentials: AntigravityStoredSignIn | { accessToken: string }): Promise<Identity> {
try {
const signal = AbortSignal.timeout(3_000);
- const access = await refreshAntigravityAccess(credentials, signal);
+ const access = "accessToken" in credentials ? credentials : await refreshAntigravityAccess(credentials, signal);
if (!access) return undefined;
const identity = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
headers: { Authorization: `Bearer ${access.accessToken}` }, redirect: "error", signal,
diff --git a/server/drivers/antigravity-acp.ts b/server/drivers/antigravity-acp.ts
index fa92229a87..1b1740ecb3 100644
--- a/server/drivers/antigravity-acp.ts
+++ b/server/drivers/antigravity-acp.ts
@@ -12,7 +12,15 @@
// - apps/server/src/provider/acp/AntigravityAcpSupport.ts:55-79, 108-121
// (the session setup for releases that write a workflow skill file);
// - apps/server/src/provider/acp/AntigravityAcpSupport.ts:89-90, 123-129
-// at b732621b51 (the client name by runtime version).
+// at b732621b51 (the client name by runtime version);
+// - apps/server/src/provider/antigravityAuthSupport.ts:467-477,
+// apps/server/src/provider/acp/AntigravityAcpSupport.ts:186-193 and
+// apps/server/src/provider/AntigravityInstallation.ts:501-503 at
+// b732621b51 (the native CLI's launch, its session mode and its name);
+// - apps/server/src/provider/antigravityAuthSupport.ts:167-177, 222-244,
+// 575-644 at 38067630229 (the native CLI's environment: no self-update and
+// the SSH_CONNECTION value that keeps each profile's sign-in in its own
+// file; the `--login` link and the code pasted back).
// The temp folder stays one per instance, the redirect can go through a relay into a boxed runtime, and startup waits
// while a Windows unpack is still growing.
import { execFile } from "node:child_process";
@@ -26,10 +34,12 @@ import { delimiter, isAbsolute, join, resolve } from "node:path";
import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
import { writeFileAtomic } from "../atomic.ts";
import { killCliTree, spawnCli } from "../procs.ts";
+import { BOX_SSH_CONNECTION } from "../bot-box/env.ts";
import type { BoxRelay } from "../bot-box/relay.ts";
import type { ModelCatalog } from "../contracts.ts";
import type { ChildProcess } from "node:child_process";
import type { AntigravityRuntime } from "./antigravity-runtime.ts";
+import { ANTIGRAVITY_CLI_TOKEN_FILE } from "./antigravity-cli-install.ts";
import { acpVariantOption, surveyModelVariants } from "./acp/config-options.ts";
import { StderrTail, exitDetail } from "./acp/exit-report.ts";
import {
@@ -180,6 +190,8 @@ export function authorizationUrlFromLine(line: string): string | null {
}
}
+export const ANTIGRAVITY_SSH_CONNECTION = BOX_SSH_CONNECTION;
+
export function antigravityProfileDirectory(instanceId: string, baseDir = DATA_DIR): string {
return join(baseDir, "providers", "antigravity", createHash("sha256").update(instanceId).digest("hex"));
}
@@ -193,13 +205,24 @@ export async function removeAntigravityProfile(instanceId: string, baseDir = DAT
});
}
+/** The pinned runtime's sign-in. */
export function antigravityTokenPath(instanceId: string, baseDir = DATA_DIR): string {
return join(antigravityProfileDirectory(instanceId, baseDir), "antigravity-acp", "acp_token.json");
}
-/** Signing out forgets only this account's stored Google sign-in; its profile stays for the next sign-in. */
+/** The native CLI's sign-in. */
+export function antigravityCliTokenPath(instanceId: string, baseDir = DATA_DIR): string {
+ return join(antigravityProfileDirectory(instanceId, baseDir), "antigravity-acp", ANTIGRAVITY_CLI_TOKEN_FILE);
+}
+
+/** Both runtimes' sign-in files. The pinned runtime's stays when an account moves to the CLI, so a rollback finds it. */
+export function antigravitySignInPaths(instanceId: string, baseDir = DATA_DIR): string[] {
+ return [antigravityCliTokenPath(instanceId, baseDir), antigravityTokenPath(instanceId, baseDir)];
+}
+
+/** Signing out forgets only this account's stored Google sign-ins, both runtimes'; its profile stays for the next one. */
export async function removeAntigravitySignIn(instanceId: string, baseDir = DATA_DIR): Promise<void> {
- await rm(antigravityTokenPath(instanceId, baseDir), { force: true, maxRetries: 4, retryDelay: 250 });
+ for (const path of antigravitySignInPaths(instanceId, baseDir)) await rm(path, { force: true, maxRetries: 4, retryDelay: 250 });
}
/** The runtime asked for a Google sign-in although a token file is stored (a revoked or ineligible account). */
@@ -265,11 +288,21 @@ export async function prepareAntigravityProfile(input: {
}
stripWorkspaceCredentialEnv(environment);
const caBundle = (input.platform ?? process.platform) === "linux" ? linuxCaBundle(input.baseEnv ?? process.env) : undefined;
+ const nativeCli = input.runtime.harnessPath === null;
Object.assign(environment, {
...(caBundle ? { SSL_CERT_FILE: caBundle } : {}),
GEMINI_HOME: directory,
AGY_ACP_FORCE_FILE_STORAGE: "1",
- ANTIGRAVITY_HARNESS_PATH: input.runtime.harnessPath,
+ ...(nativeCli
+ ? {
+ // Updates come only through this app's updater; the release folder is read-only besides.
+ AGY_CLI_DISABLE_AUTO_UPDATE: "1",
+ // The CLI ignores AGY_ACP_FORCE_FILE_STORAGE and keeps every profile's Google sign-in in one OS keyring entry
+ // unless it believes it runs over SSH: then it uses the profile's own file. A fixed value, so no address of
+ // the host reaches the box.
+ SSH_CONNECTION: ANTIGRAVITY_SSH_CONNECTION,
+ }
+ : { ANTIGRAVITY_HARNESS_PATH: input.runtime.harnessPath! }),
BROWSER: browserCommand,
PYTHONUNBUFFERED: "1",
ELECTRON_RUN_AS_NODE: "1",
@@ -284,7 +317,7 @@ export async function prepareAntigravityProfile(input: {
}
return {
directory,
- tokenPath: join(acpDirectory, "acp_token.json"),
+ tokenPath: join(acpDirectory, nativeCli ? ANTIGRAVITY_CLI_TOKEN_FILE : "acp_token.json"),
environment,
...(tempDirectory ? { tempDirectory } : {}),
};
@@ -342,7 +375,7 @@ export class AntigravityAcpClient {
this.runtimeVersion = runtime.version;
this.child = spawnCli(
runtime.executablePath,
- process.platform === "linux" ? ["--uid="] : [],
+ antigravityLaunchArgs(runtime, profile.directory),
{ cwd, env: profile.environment, stdio: ["pipe", "pipe", "pipe"], box: { ro: [join(profile.directory, "omb-skills")], ...(relay ? { relay: relay.socketPath } : {}) } },
"bot",
);
@@ -546,7 +579,12 @@ export class AntigravityAcpClient {
}
}
-export function parseAntigravityAuthorizationUrl(authorizationUrl: string): {
+/** Where `agy acp --login` sends Google; the page shows a code the person pastes back. */
+export const ANTIGRAVITY_CODE_REDIRECT_URI = "https://antigravity.google/oauth-callback";
+
+/** `loopback`: the pinned runtime's link, which redirects to its listener on 127.0.0.1. `code`: the native CLI's
+ * `--login` link, which redirects to Google's Antigravity page that shows a code. */
+export function parseAntigravityAuthorizationUrl(authorizationUrl: string, kind: "loopback" | "code" = "loopback"): {
authorizationUrl: string;
redirectUri: string;
state: string;
@@ -559,15 +597,16 @@ export function parseAntigravityAuthorizationUrl(authorizationUrl: string): {
const redirectUri = url.searchParams.get("redirect_uri");
if (
url.origin !== "https://accounts.google.com" ||
- url.pathname !== "/o/oauth2/v2/auth" ||
+ url.pathname !== (kind === "loopback" ? "/o/oauth2/v2/auth" : "/o/oauth2/auth") ||
url.username || url.password || url.hash ||
url.searchParams.getAll("state").length !== 1 ||
url.searchParams.getAll("redirect_uri").length !== 1 ||
url.searchParams.getAll("response_type").length !== 1 ||
url.searchParams.get("response_type") !== "code" ||
!state || state.length > 512 || /\s/u.test(state) ||
- !redirectUri || !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/u.test(redirectUri)
+ !redirectUri || (kind === "loopback" ? !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/$/u.test(redirectUri) : redirectUri !== ANTIGRAVITY_CODE_REDIRECT_URI)
) throw new Error("Antigravity returned an invalid Google sign-in URL.");
+ if (kind === "code") return { authorizationUrl, redirectUri, state };
const redirect = new URL(redirectUri);
if (Number(redirect.port) < 1024 || Number(redirect.port) > 65535) {
throw new Error("Antigravity returned an invalid Google sign-in URL.");
@@ -575,6 +614,21 @@ export function parseAntigravityAuthorizationUrl(authorizationUrl: string): {
return { authorizationUrl, redirectUri, state };
}
+/** What `agy acp --login` reads after its link: the code the Antigravity page shows, or that page's URL, which must answer
+ * this sign-in. Undefined for anything else, including any line break. */
+export function antigravityLoginResponse(pending: { redirectUri: string; state: string }, response: string): string | undefined {
+ const value = response.trim();
+ if (/^[\w./~-]{1,2048}$/u.test(value)) return value;
+ if (value.length > 16_384 || /\s/u.test(value)) return undefined;
+ const url = URL.parse(value);
+ if (
+ url === null || `${url.origin}${url.pathname}` !== pending.redirectUri || url.username || url.password ||
+ url.searchParams.getAll("state").length !== 1 || url.searchParams.get("state") !== pending.state ||
+ url.searchParams.getAll("code").length !== 1 || !url.searchParams.get("code")
+ ) return undefined;
+ return value;
+}
+
export function validateAntigravityCallbackUrl(
pending: { redirectUri: string; state: string },
callbackUrl: string,
@@ -727,13 +781,27 @@ export function antigravitySessionSetup(initialized: any): { _meta?: { antigravi
return patch >= 2 && patch <= 5 ? { _meta: { antigravity: { disabledTools: ["run_workflow"] } } } : {};
}
+/** The agy CLI has no harness sibling and serves ACP through its `acp` subcommand. It joins `--app-data-dir` beneath
+ * `--gemini-dir`, including when the value is absolute. */
+export function antigravityLaunchArgs(runtime: Pick<AntigravityRuntime, "harnessPath">, profileDirectory: string, platform: NodeJS.Platform = process.platform): string[] {
+ if (runtime.harnessPath === null) return ["acp", "--gemini-dir", profileDirectory, "--app-data-dir", "antigravity-acp"];
+ return platform === "linux" ? ["--uid="] : [];
+}
+
+/** The agy CLI rejects the pinned runtime's `yolo` and `auto_edit`. It stays in `default`, where it asks before acting
+ * and the app answers by the turn's own approval level. */
+export function antigravityCliSessionMode(mode: string): string {
+ return mode === "yolo" || mode === "auto_edit" ? "default" : mode;
+}
+
export function isValidAntigravityInitializeResult(
initialized: any,
expectedVersion: string,
+ nativeCli = false,
): boolean {
if (!initialized || initialized.protocolVersion !== 1) return false;
const name = initialized.agentInfo?.name;
- if (name !== "antigravity-acp" && name !== "Google Antigravity") return false;
+ if (nativeCli ? name !== "Antigravity ACP Server" : name !== "antigravity-acp" && name !== "Google Antigravity") return false;
const actualVersion = initialized.agentInfo?.version;
if (typeof actualVersion !== "string") return false;
const normalizedActual = runtimeVersion(actualVersion);
@@ -771,7 +839,7 @@ export async function validateAntigravityRuntime(runtime: AntigravityRuntime, ex
tempDirectory = profile.tempDirectory;
client = new AntigravityAcpClient(runtime, profile, profileDirectory);
const initialized = await client.initialize();
- if (!isValidAntigravityInitializeResult(initialized, expectedVersion)) {
+ if (!isValidAntigravityInitializeResult(initialized, expectedVersion, runtime.harnessPath === null)) {
throw new Error("The download did not identify as the expected Google Antigravity ACP release.");
}
} catch (error) {
diff --git a/server/drivers/antigravity-auth.ts b/server/drivers/antigravity-auth.ts
index fa5f1965a8..e72909b4e9 100644
--- a/server/drivers/antigravity-auth.ts
+++ b/server/drivers/antigravity-auth.ts
@@ -1,4 +1,5 @@
-// One Google sign-in at a time for an Antigravity account, run by the runtime's own `authenticate`.
+// One Google sign-in at a time for an Antigravity account: the pinned runtime's own `authenticate`, or the native
+// CLI's `--login`.
//
// Adapted from pingdotgg/t3code@b9bc03869e, MIT License, Copyright (c) 2026
// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
@@ -6,15 +7,25 @@
// 321-333, 434-480 (the sign-in's phases, its fixed failure lines, expiry,
// and one accepted redirect per sign-in), on promises instead of fibers;
// the link is returned by `start` and the redirect can go through a
-// relay into a boxed runtime.
+// relay into a boxed runtime;
+// - apps/server/src/provider/Drivers/AntigravityDriver.ts:422-494 and
+// apps/server/src/provider/AntigravityAuth.ts:330-345, 540-568 at
+// 38067630229 (the native CLI's `--login`: a separate process that prints
+// Google's link and reads the code the Antigravity page shows on stdin,
+// with no display so it opens no browser here).
import { randomUUID } from "node:crypto";
+import { stat } from "node:fs/promises";
+import { join } from "node:path";
import { botBox } from "../bot-box/box.ts";
-import type { BoxRelay } from "../bot-box/relay.ts";
import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";
+import { killCliTree, spawnCli } from "../procs.ts";
import {
AntigravityAcpClient,
STARTUP_TIMEOUT_MS,
+ antigravityLaunchArgs,
+ antigravityLoginResponse,
+ authorizationUrlFromLine,
forwardAntigravityCallback,
parseAntigravityAuthorizationUrl,
validateAntigravityCallbackUrl,
@@ -23,6 +34,7 @@ import {
import type { AntigravityRuntime } from "./antigravity-runtime.ts";
const AUTH_TIMEOUT_MS = 5 * 60_000;
+const LOGIN_LINE_MAX_CHARS = 64 * 1024;
const EXPIRED = "Google sign-in expired. Start sign-in again.";
const CANCELLED = "Google sign-in was cancelled.";
@@ -31,6 +43,7 @@ const NOT_APPROVED = "Google sign-in was not approved. Start sign-in again.";
const NOT_ELIGIBLE = "Google requires an eligible Antigravity subscription for this account.";
const NOT_DELIVERED = "Could not deliver the sign-in response. If Google already finished in your browser, wait a moment. Otherwise send it again.";
const ALREADY_SENT = "The sign-in response was already sent. Wait for Google to finish.";
+const NOT_A_CODE = "Paste the code from the Antigravity page, or that page's full address.";
class SignInExpired extends Error {}
@@ -45,15 +58,18 @@ function failureLine(error: unknown): { phase: "failed" | "expired"; message: st
interface AuthFlow {
id: string;
- client: AntigravityAcpClient;
- relay: BoxRelay | null;
/** Rejects with one of the fixed lines. */
completed: Promise<void>;
pending: { redirectUri: string; state: string };
expiresAt: number;
- /** The runtime's listener takes one response: a second would be read as another sign-in's. Cleared when a
- * delivery fails, which the listener having closed after the browser's own redirect also looks like. */
+ /** The runtime takes one response: a second would be read as another sign-in's. Cleared when a delivery fails, which
+ * the listener having closed after the browser's own redirect also looks like. */
callbackSent: boolean;
+ /** What the person pasted, checked against this sign-in; throws a line for the person when it does not answer it. */
+ accept(pasted: string): string;
+ /** Hands an accepted answer to the runtime. */
+ send(accepted: string): Promise<void>;
+ close(): void;
}
export class AntigravityAuthController {
@@ -65,7 +81,12 @@ export class AntigravityAuthController {
this.onSignedIn = onSignedIn;
}
- async start(runtime: AntigravityRuntime, profile: AntigravityProfile): Promise<ProviderAuthenticationStart> {
+ /** The native CLI signs in through `--login`; the pinned runtime through `authenticate` and its loopback listener. */
+ start(runtime: AntigravityRuntime, profile: AntigravityProfile): Promise<ProviderAuthenticationStart> {
+ return runtime.harnessPath === null ? this.startCodeLogin(runtime, profile) : this.startLoopback(runtime, profile);
+ }
+
+ private async startLoopback(runtime: AntigravityRuntime, profile: AntigravityProfile): Promise<ProviderAuthenticationStart> {
this.cancel();
let foundUrl!: (value: ReturnType<typeof parseAntigravityAuthorizationUrl>) => void;
let failUrl!: (error: Error) => void;
@@ -92,55 +113,141 @@ export class AntigravityAuthController {
await client.initialize();
const expiresAt = Date.now() + AUTH_TIMEOUT_MS;
const authenticated = client.request("authenticate", { methodId: "oauth-personal" }, AUTH_TIMEOUT_MS, async () => new SignInExpired());
- let startupTimer: ReturnType<typeof setTimeout> | undefined;
- const startupTimeout = new Promise<never>((_resolve, reject) => {
- startupTimer = setTimeout(() => reject(new Error("Google sign-in did not start in time.")), STARTUP_TIMEOUT_MS);
- startupTimer.unref?.();
- });
- const outcome = await Promise.race([
+ const outcome = await raceStartup([
urlPromise.then((request) => ({ kind: "url" as const, request })),
authenticated.then(() => ({ kind: "done" as const })),
- startupTimeout,
- ]).finally(() => {
- if (startupTimer) clearTimeout(startupTimer);
- });
+ ]);
if (outcome.kind === "done") {
closeAll();
this.onSignedIn();
return { phase: "succeeded", flowId: null, authorizationUrl: null, expiresAt: null };
}
+ const pending = { redirectUri: outcome.request.redirectUri, state: outcome.request.state };
const flow: AuthFlow = {
id: randomUUID(),
- client,
- relay,
- completed: authenticated.then(
- () => {
- if (this.end(flow, "succeeded")) this.onSignedIn();
- },
- (error) => {
- const { phase, message } = failureLine(error);
- this.end(flow, phase, message);
- throw new Error(message);
- },
- ).finally(closeAll),
- pending: { redirectUri: outcome.request.redirectUri, state: outcome.request.state },
+ completed: this.settle(() => flow, authenticated).finally(closeAll),
+ pending,
expiresAt,
callbackSent: false,
+ accept: (pasted) => validateAntigravityCallbackUrl(pending, pasted).href,
+ send: (accepted) => forwardAntigravityCallback(new URL(accepted), relay ?? undefined),
+ close: closeAll,
+ };
+ flow.completed.catch(() => {});
+ this.flow = flow;
+ return { phase: "waiting", flowId: flow.id, authorizationUrl: outcome.request.authorizationUrl, expiresAt: new Date(flow.expiresAt).toISOString() };
+ } catch (error) {
+ closeAll();
+ throw error;
+ }
+ }
+
+ /** `agy acp --login`: Google's link on its output, then the code the Antigravity page shows on its input. It needs no
+ * listener here, so a sign-in from another computer and one inside a bot box work the same way. */
+ private async startCodeLogin(runtime: AntigravityRuntime, profile: AntigravityProfile): Promise<ProviderAuthenticationStart> {
+ this.cancel();
+ // Without a display it prints the link only, instead of opening a browser on this machine.
+ const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = profile.environment;
+ const child = spawnCli(
+ runtime.executablePath,
+ [...antigravityLaunchArgs(runtime, profile.directory), "--login"],
+ { cwd: profile.directory, env, stdio: ["pipe", "pipe", "pipe"], box: { ro: [join(profile.directory, "omb-skills")] } },
+ "bot",
+ );
+ let foundUrl!: (value: ReturnType<typeof parseAntigravityAuthorizationUrl>) => void;
+ const urlPromise = new Promise<ReturnType<typeof parseAntigravityAuthorizationUrl>>((resolveUrl) => { foundUrl = resolveUrl; });
+ const exited = new Promise<number | null>((resolveExit) => {
+ child.once("close", (code) => resolveExit(code));
+ child.once("error", () => resolveExit(null));
+ });
+ // Nothing the CLI prints reaches the person or a log: only a Google link is taken out of it.
+ const watch = (stream: NodeJS.ReadableStream) => {
+ let buffer = "";
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk: string) => {
+ const lines = (buffer + chunk).split("\n");
+ buffer = lines.pop() ?? "";
+ if (buffer.length > LOGIN_LINE_MAX_CHARS) buffer = "";
+ for (const raw of lines) {
+ const line = raw.replace(/\r$/u, "").trim();
+ const candidate = line.startsWith("https://accounts.google.com/") ? line : authorizationUrlFromLine(line);
+ if (!candidate) continue;
+ try { foundUrl(parseAntigravityAuthorizationUrl(candidate, "code")); } catch {}
+ }
+ });
+ };
+ watch(child.stdout!);
+ watch(child.stderr!);
+ const stop = () => {
+ try { child.stdin?.end(); } catch {}
+ void killCliTree(child).catch(() => false);
+ };
+ try {
+ const outcome = await raceStartup([
+ urlPromise.then((request) => ({ kind: "url" as const, request })),
+ exited.then((code) => ({ kind: "exit" as const, code })),
+ ]);
+ if (outcome.kind === "exit") {
+ // Exiting at once with success means it found a sign-in it could use.
+ if (outcome.code === 0 && await signInFile(profile)) {
+ this.onSignedIn();
+ return { phase: "succeeded", flowId: null, authorizationUrl: null, expiresAt: null };
+ }
+ throw new Error("Antigravity could not start Google sign-in. Start sign-in again.");
+ }
+ const expiresAt = Date.now() + AUTH_TIMEOUT_MS;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const finished = new Promise<void>((resolveFinished, reject) => {
+ timer = setTimeout(() => reject(new SignInExpired()), AUTH_TIMEOUT_MS);
+ timer.unref?.();
+ void exited.then(async (code) => {
+ if (code === 0 && await signInFile(profile)) resolveFinished();
+ else reject(new Error("The Antigravity CLI did not finish the sign-in."));
+ });
+ }).finally(() => clearTimeout(timer));
+ const pending = { redirectUri: outcome.request.redirectUri, state: outcome.request.state };
+ const flow: AuthFlow = {
+ id: randomUUID(),
+ completed: this.settle(() => flow, finished).finally(stop),
+ pending,
+ expiresAt,
+ callbackSent: false,
+ accept: (pasted) => {
+ const response = antigravityLoginResponse(pending, pasted);
+ if (response === undefined) throw new Error(NOT_A_CODE);
+ return response;
+ },
+ send: (accepted) => new Promise<void>((resolveWrite, reject) => {
+ child.stdin!.write(`${accepted}\n`, (error) => error ? reject(error) : resolveWrite());
+ }),
+ close: stop,
};
flow.completed.catch(() => {});
this.flow = flow;
return {
- phase: "waiting",
- flowId: flow.id,
- authorizationUrl: outcome.request.authorizationUrl,
- expiresAt: new Date(flow.expiresAt).toISOString(),
+ phase: "waiting", flowId: flow.id, authorizationUrl: outcome.request.authorizationUrl,
+ expiresAt: new Date(flow.expiresAt).toISOString(), pasteCode: true,
};
} catch (error) {
- closeAll();
+ stop();
throw error;
}
}
+ /** The flow's end: signed in, or one of the fixed lines. */
+ private settle(flow: () => AuthFlow, signedIn: Promise<unknown>): Promise<void> {
+ return signedIn.then(
+ () => {
+ if (this.end(flow(), "succeeded")) this.onSignedIn();
+ },
+ (error) => {
+ const { phase, message } = failureLine(error);
+ this.end(flow(), phase, message);
+ throw new Error(message);
+ },
+ );
+ }
+
/** False when another outcome already ended this sign-in. */
private end(flow: AuthFlow, phase: Exclude<ProviderAuthenticationStatus["phase"], "waiting" | "verifying">, message?: string): boolean {
if (this.flow !== flow) return false;
@@ -163,16 +270,16 @@ export class AntigravityAuthController {
return { phase: "expired", flowId, authorizationUrl: null, expiresAt: null, message: EXPIRED };
}
- async complete(flowId: string, callbackUrl: string): Promise<void> {
+ async complete(flowId: string, pasted: string): Promise<void> {
const flow = this.flow;
if (!flow || flow.id !== flowId || Date.now() >= flow.expiresAt) {
throw new Error("This Google sign-in is no longer active. Start again.");
}
if (flow.callbackSent) throw new Error(ALREADY_SENT);
- const callback = validateAntigravityCallbackUrl(flow.pending, callbackUrl);
+ const accepted = flow.accept(pasted);
flow.callbackSent = true;
try {
- await forwardAntigravityCallback(callback, flow.relay ?? undefined);
+ await flow.send(accepted);
} catch {
flow.callbackSent = false;
throw new Error(NOT_DELIVERED);
@@ -183,7 +290,22 @@ export class AntigravityAuthController {
cancel(): void {
const flow = this.flow;
if (!flow || !this.end(flow, "cancelled", CANCELLED)) return;
- flow.client.close();
- flow.relay?.close();
+ flow.close();
}
}
+
+async function signInFile(profile: AntigravityProfile): Promise<boolean> {
+ const info = await stat(profile.tokenPath).catch(() => null);
+ return info !== null && info.isFile() && info.size > 0;
+}
+
+async function raceStartup<A, B>(outcomes: [Promise<A>, Promise<B>]): Promise<A | B> {
+ let startupTimer: ReturnType<typeof setTimeout> | undefined;
+ const startupTimeout = new Promise<never>((_resolve, reject) => {
+ startupTimer = setTimeout(() => reject(new Error("Google sign-in did not start in time.")), STARTUP_TIMEOUT_MS);
+ startupTimer.unref?.();
+ });
+ return Promise.race([...outcomes, startupTimeout]).finally(() => {
+ if (startupTimer) clearTimeout(startupTimer);
+ });
+}
diff --git a/server/drivers/antigravity-cli-install.ts b/server/drivers/antigravity-cli-install.ts
new file mode 100644
index 0000000000..81d4061d99
--- /dev/null
+++ b/server/drivers/antigravity-cli-install.ts
@@ -0,0 +1,280 @@
+// Installing the native Antigravity CLI from Google's update channel beside the pinned runtime, and naming the one
+// that is active.
+//
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/AntigravityInstallation.ts:53-60, 169-175,
+// 275-309, 532-721, 861-920 (the size limits, the CLI's names, the install
+// record with no harness, the active-release pointer, the checksum-verified
+// download, the one-file archive rule, and publishing a release).
+// - apps/server/src/provider/AntigravityInstallation.ts:321-353, 821-839 at
+// 38067630229 (read-only release folders, and pruning releases that are
+// neither active nor in use).
+// Release withdrawal is left out, and the archive is read in process instead of by the system's tar.
+import { createHash, randomUUID } from "node:crypto";
+import { constants } from "node:fs";
+import { access, chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, statfs, writeFile } from "node:fs/promises";
+import { join, resolve } from "node:path";
+
+import { writeFileAtomic } from "../atomic.ts";
+import type { AntigravityCliReleaseAsset } from "./antigravity-cli-release.ts";
+import type { AntigravityRuntime } from "./antigravity-runtime.ts";
+
+/** The one switch: `OMB_ANTIGRAVITY_NATIVE_CLI=1` in the server's environment, read at start. */
+export const ANTIGRAVITY_NATIVE_CLI_ENV = "OMB_ANTIGRAVITY_NATIVE_CLI";
+
+/** Whether the native CLI is the runtime. Off (the default), everything is as before the CLI: the pinned 1.4.3 runtime
+ * is installed and run, Google's CLI channel is never asked, and a CLI this app installed earlier is left where it is
+ * and not started. On, the CLI is installed and run wherever the channel has a build, a computer that has the pinned
+ * runtime moves to it, and the pinned one is removed once an account there signed in on the CLI. Opt-in because the
+ * CLI's `--login` sign-in has not been run against Google, and every signed-in account signs in again after the move. */
+export const ANTIGRAVITY_NATIVE_CLI = process.env[ANTIGRAVITY_NATIVE_CLI_ENV] === "1";
+
+/** Where the CLI keeps a Google sign-in, under `<profile>/antigravity-acp/`, when it does not use the OS keyring (which
+ * it skips while SSH_CONNECTION is set). It never writes the pinned runtime's `acp_token.json`, and stores no OAuth
+ * client, so this app cannot refresh it. */
+export const ANTIGRAVITY_CLI_TOKEN_FILE = "antigravity-oauth-token";
+
+const DOWNLOAD_TIMEOUT_MS = 45 * 60_000;
+const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
+const MAX_EXECUTABLE_BYTES = 512 * 1024 * 1024;
+const FREE_SPACE_MARGIN = 256 * 1024 * 1024;
+const RECORD_MAX_BYTES = 8 * 1024;
+const RELEASE_RECORD = ".install-complete.json";
+const ACTIVE_RELEASE = "active.json";
+const RELEASE_ID = /^[a-f0-9]{64}$/u;
+const DOWNLOAD_ORIGIN = "https://storage.googleapis.com/antigravity-public/antigravity-cli/";
+
+interface CliRecord {
+ releaseId: string;
+ version: string;
+ executable: { name: string; bytes: number };
+ harness: null;
+}
+
+export interface AntigravityCliInstallOptions {
+ /** The folder that holds `versions/` and the active-release pointer for this platform. */
+ root: string;
+ fetchImpl?: typeof fetch;
+ validate?: (runtime: AntigravityRuntime, expectedVersion: string) => Promise<void>;
+ /** Wraps the final rename, which Windows refuses while a just-stopped runtime still holds its files. */
+ retry?: <T>(step: () => Promise<T>) => Promise<T>;
+ platform?: NodeJS.Platform;
+}
+
+/** Antigravity CLI 1.5.0+ serves ACP itself (`agy acp`), so it has no `localharness_external` sibling. A custom path
+ * counts as that CLI only under the name `antigravity`: a saved `agy` path is the retired CLI's, which the pinned
+ * runtime replaces without the program at that path ever being started. */
+export function isAntigravityCliName(...candidates: readonly string[]): boolean {
+ return candidates.some((candidate) => /^antigravity(?:\.exe)?$/iu.test(candidate.split(/[\\/]/u).at(-1) ?? ""));
+}
+
+const cliExecutableName = (platform: NodeJS.Platform) => platform === "win32" ? "agy.exe" : "antigravity";
+
+async function readRecord<T>(path: string): Promise<T | null> {
+ try {
+ const info = await stat(path);
+ if (!info.isFile() || info.size > RECORD_MAX_BYTES) return null;
+ return JSON.parse(await readFile(path, "utf8")) as T;
+ } catch {
+ return null;
+ }
+}
+
+/** A CLI release this app finished installing under `root`, or null when its record or its executable is not whole. */
+export async function installedAntigravityCli(root: string, releaseId: string, platform: NodeJS.Platform = process.platform): Promise<AntigravityRuntime | null> {
+ if (!RELEASE_ID.test(releaseId)) return null;
+ const directory = join(root, "versions", releaseId);
+ const record = await readRecord<Partial<CliRecord>>(join(directory, RELEASE_RECORD));
+ if (
+ !record || record.releaseId !== releaseId || record.harness !== null
+ || record.executable?.name !== cliExecutableName(platform)
+ || !Number.isSafeInteger(record.executable.bytes) || record.executable.bytes <= 0
+ || typeof record.version !== "string" || !record.version.trim()
+ ) return null;
+ const executablePath = join(directory, record.executable.name);
+ try {
+ const info = await lstat(executablePath);
+ if (!info.isFile() || info.size !== record.executable.bytes) return null;
+ if (platform !== "win32") await access(executablePath, constants.X_OK);
+ } catch {
+ return null;
+ }
+ return { executablePath, harnessPath: null, source: "managed", version: record.version };
+}
+
+/** The CLI release the active pointer names, when it is whole. */
+export async function activeAntigravityCli(root: string, platform: NodeJS.Platform = process.platform): Promise<AntigravityRuntime | null> {
+ const active = await readRecord<{ releaseId?: unknown }>(join(root, ACTIVE_RELEASE));
+ return typeof active?.releaseId === "string" ? installedAntigravityCli(root, active.releaseId, platform) : null;
+}
+
+/** A published release is read-only, so neither the CLI nor anything it starts can change it: only this app's updater
+ * replaces it. */
+async function sealRelease(directory: string, executable: string, platform: NodeJS.Platform): Promise<void> {
+ if (platform === "win32") return;
+ await chmod(join(directory, executable), 0o555);
+ await chmod(join(directory, RELEASE_RECORD), 0o444);
+ await chmod(directory, 0o555);
+}
+
+/** Removes a release folder, sealed or not. */
+export async function removeAntigravityRelease(directory: string): Promise<void> {
+ if (process.platform !== "win32") await chmod(directory, 0o700).catch(() => {});
+ await rm(directory, { recursive: true, force: true, maxRetries: 4, retryDelay: 250 });
+}
+
+/** Removes every CLI release under `root` except the active one and those a live process runs from. Best effort: a
+ * release that cannot be removed now is tried again after the next install. */
+export async function pruneAntigravityCliReleases(root: string, inUse: (directory: string) => boolean): Promise<string[]> {
+ const active = await readRecord<{ releaseId?: unknown }>(join(root, ACTIVE_RELEASE));
+ const versions = join(root, "versions");
+ const removed: string[] = [];
+ for (const name of await readdir(versions).catch(() => [] as string[])) {
+ if (name === active?.releaseId || !RELEASE_ID.test(name)) continue;
+ const directory = resolve(versions, name);
+ const record = await readRecord<Partial<CliRecord>>(join(directory, RELEASE_RECORD));
+ // Only CLI releases: a pinned runtime's record names its harness.
+ if (!record || record.harness !== null || inUse(directory)) continue;
+ try {
+ await removeAntigravityRelease(directory);
+ removed.push(name);
+ } catch (error) {
+ console.warn(`antigravity: could not remove an older CLI release (${error instanceof Error ? error.message : String(error)})`);
+ }
+ }
+ return removed;
+}
+
+function activate(root: string, releaseId: string): void {
+ writeFileAtomic(join(root, ACTIVE_RELEASE), `${JSON.stringify({ releaseId })}\n`, { mode: 0o600 });
+}
+
+async function download(asset: AntigravityCliReleaseAsset, archivePath: string, fetchImpl: typeof fetch): Promise<void> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
+ timeout.unref?.();
+ try {
+ const response = await fetchImpl(asset.url, { signal: controller.signal, redirect: "follow" });
+ if (!response.ok || !response.body) throw new Error(`Google download failed (${response.status}).`);
+ if (!(response.url || asset.url).startsWith(DOWNLOAD_ORIGIN)) throw new Error("The Antigravity download redirected away from Google's release folder.");
+ const handle = await open(archivePath, "wx", 0o600);
+ const hash = createHash("sha512");
+ let downloaded = 0;
+ try {
+ for await (const raw of response.body as unknown as AsyncIterable<Uint8Array>) {
+ const chunk = Buffer.from(raw);
+ downloaded += chunk.length;
+ if (downloaded > MAX_DOWNLOAD_BYTES) throw new Error("The Antigravity download exceeded its allowed size.");
+ let offset = 0;
+ while (offset < chunk.length) {
+ const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset, null);
+ if (bytesWritten <= 0) throw new Error("The Antigravity download could not be written completely.");
+ offset += bytesWritten;
+ }
+ hash.update(chunk);
+ }
+ } finally {
+ await handle.close();
+ }
+ if (hash.digest("hex") !== asset.sha512) throw new Error("The Antigravity download failed its size or checksum check. Nothing was installed.");
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+/** The archive must hold one regular file, the executable, and nothing else. */
+async function extractOnlyExecutable(archivePath: string, directory: string, name: string): Promise<void> {
+ const tar = await import("tar");
+ const members: Array<{ path: string; type: string; size: number }> = [];
+ await tar.t({ file: archivePath, strict: true, onReadEntry: (entry) => { members.push({ path: entry.path, type: entry.type, size: entry.size }); } });
+ if (members.length !== 1 || members[0]!.path !== name || members[0]!.type !== "File") {
+ throw new Error("The Antigravity archive must contain one regular executable.");
+ }
+ if (members[0]!.size <= 0 || members[0]!.size > MAX_EXECUTABLE_BYTES) throw new Error("The Antigravity executable exceeded its size limit.");
+ await tar.x({
+ file: archivePath, cwd: directory, strict: true, preservePaths: false, preserveOwner: false,
+ filter: (path, entry) => path === name && "type" in entry && entry.type === "File",
+ });
+}
+
+/** Staging folders an install that was cut short left behind. Another process may be installing here right now, so
+ * only a folder older than any download may run is removed. */
+async function sweepStaleStaging(versions: string, now = Date.now()): Promise<void> {
+ for (const name of await readdir(versions).catch(() => [] as string[])) {
+ if (!name.startsWith(".install-")) continue;
+ const path = join(versions, name);
+ const info = await stat(path).catch(() => null);
+ if (info?.isDirectory() && now - info.mtimeMs > DOWNLOAD_TIMEOUT_MS + 15 * 60_000) await rm(path, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
+/** Download `asset`, check it against the channel's checksum, start it once to confirm what it is, publish it beside
+ * the other releases and make it the active one. A release already installed is checked again and made active. */
+export async function installAntigravityCli(asset: AntigravityCliReleaseAsset, options: AntigravityCliInstallOptions): Promise<AntigravityRuntime> {
+ const platform = options.platform ?? process.platform;
+ // Existing installation records use 64-character IDs, including native SHA-512 prefixes.
+ const releaseId = asset.sha512.slice(0, 64);
+ const versions = join(options.root, "versions");
+ const destination = join(versions, releaseId);
+ await mkdir(versions, { recursive: true, mode: 0o700 });
+ const finish = async (): Promise<AntigravityRuntime> => {
+ const installed = await installedAntigravityCli(options.root, releaseId, platform);
+ if (!installed) throw new Error("The installed Antigravity runtime is incomplete.");
+ if (installed.version !== asset.version) throw new Error("The existing managed release has the wrong version. Remove it before reinstalling.");
+ return installed;
+ };
+ await sweepStaleStaging(versions);
+ if (await installedAntigravityCli(options.root, releaseId, platform)) {
+ const existing = await finish();
+ // A release installed before releases were sealed, or opened up since, is sealed again.
+ await sealRelease(destination, cliExecutableName(platform), platform).catch(() => {});
+ await options.validate?.(existing, asset.version);
+ activate(options.root, releaseId);
+ return existing;
+ }
+ // What is left of a release whose files were damaged or removed: it is installed again.
+ await removeAntigravityRelease(destination);
+ try {
+ const disk = await statfs(versions, { bigint: true });
+ const required = BigInt(MAX_DOWNLOAD_BYTES + MAX_EXECUTABLE_BYTES + FREE_SPACE_MARGIN);
+ if (disk.bavail * disk.bsize < required) {
+ throw new Error(`Antigravity needs at least ${Math.ceil(Number(required) / 1024 / 1024)} MiB of free space to install.`);
+ }
+ } catch (error) {
+ if (error instanceof Error && error.message.includes("Antigravity needs")) throw error;
+ // statfs is unavailable on a few filesystems.
+ }
+ const staging = await mkdtemp(join(versions, `.install-${randomUUID()}-`));
+ try {
+ const archivePath = join(staging, "download");
+ const runtimeDirectory = join(staging, "runtime");
+ await mkdir(runtimeDirectory, { mode: 0o700 });
+ await download(asset, archivePath, options.fetchImpl ?? fetch);
+ const executablePath = join(runtimeDirectory, asset.executable.name);
+ if (asset.format === "executable") await copyFile(archivePath, executablePath);
+ else await extractOnlyExecutable(archivePath, runtimeDirectory, asset.executable.name);
+ await rm(archivePath, { force: true });
+ const info = await lstat(executablePath);
+ if (!info.isFile() || info.size <= 0 || info.size > MAX_EXECUTABLE_BYTES) throw new Error("Could not extract the Antigravity executable.");
+ if (platform !== "win32") await chmod(executablePath, 0o755);
+ await options.validate?.({ executablePath, harnessPath: null, source: "managed", version: asset.version }, asset.version);
+ const record: CliRecord = { releaseId, version: asset.version, executable: { name: asset.executable.name, bytes: info.size }, harness: null };
+ await writeFile(join(runtimeDirectory, RELEASE_RECORD), `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
+ try {
+ await (options.retry ?? ((step) => step()))(() => rename(runtimeDirectory, destination));
+ // After the move: moving a folder to another parent needs write access to the folder itself.
+ await sealRelease(destination, asset.executable.name, platform);
+ } catch (error) {
+ // Another installation may have published the same release first.
+ if (!(await installedAntigravityCli(options.root, releaseId, platform))) throw error;
+ }
+ const installed = await finish();
+ activate(options.root, releaseId);
+ return installed;
+ } finally {
+ await rm(staging, { recursive: true, force: true, maxRetries: 4, retryDelay: 250 }).catch((error) => {
+ console.warn(`antigravity: could not remove the install folder ${staging} (${error instanceof Error ? error.message : String(error)})`);
+ });
+ }
+}
diff --git a/server/drivers/antigravity-cli-login.test.ts b/server/drivers/antigravity-cli-login.test.ts
new file mode 100644
index 0000000000..f9ab715a52
--- /dev/null
+++ b/server/drivers/antigravity-cli-login.test.ts
@@ -0,0 +1,185 @@
+// The native CLI's launch environment, its own sign-in file, and its `--login` Google sign-in, against a fake CLI.
+//
+// Adapted from pingdotgg/t3code@38067630229, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/antigravityAuthSupport.test.ts and
+// apps/server/src/provider/Drivers/AntigravityDriver.test.ts (the
+// environment's SSH_CONNECTION and self-update cases, the code link and
+// the pasted code or page address), on a fake program instead of a stub.
+import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import {
+ ANTIGRAVITY_CODE_REDIRECT_URI,
+ ANTIGRAVITY_SSH_CONNECTION,
+ antigravityLoginResponse,
+ antigravityProfileAuthenticated,
+ parseAntigravityAuthorizationUrl,
+ prepareAntigravityProfile,
+} from "./antigravity-acp.ts";
+import { antigravityCliAccessToken } from "./antigravity-account.ts";
+import { AntigravityAuthController } from "./antigravity-auth.ts";
+import type { AntigravityRuntime } from "./antigravity-runtime.ts";
+import { antigravitySignInError } from "./antigravity.ts";
+
+const WINDOWS = process.platform === "win32";
+const scratch: string[] = [];
+const controllers: AntigravityAuthController[] = [];
+
+function folder(): string {
+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-login-"));
+ scratch.push(directory);
+ return directory;
+}
+
+afterEach(async () => {
+ for (const controller of controllers.splice(0)) controller.cancel();
+ while (scratch.length) await removeTempDir(scratch.pop()!);
+});
+
+const LINK = `https://accounts.google.com/o/oauth2/auth?client_id=fixture&redirect_uri=${encodeURIComponent(ANTIGRAVITY_CODE_REDIRECT_URI)}&response_type=code&scope=openid&state=fixture-state`;
+
+/** A program named `antigravity` that, with `--login`, prints a Google link among other lines, reads one line, and on
+ * `good-code` (or the page's address carrying it) writes the CLI's sign-in file and exits 0. */
+function fakeCli(): { executable: string; dump: string } {
+ const directory = folder();
+ const script = join(directory, "fake-login.mjs"), dump = join(directory, "dump.json");
+ writeFileSync(script, `
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+const argv = process.argv.slice(2);
+writeFileSync(${JSON.stringify(dump)}, JSON.stringify({ argv, env: process.env }));
+const geminiDir = argv[argv.indexOf("--gemini-dir") + 1];
+process.stdout.write("Signing in to Antigravity.\\nOpen this link in a browser:\\n" + ${JSON.stringify(LINK)} + "\\nPaste the code here: ");
+createInterface({ input: process.stdin }).once("line", (line) => {
+ const ok = line === "good-code" || line.includes("code=good-code");
+ if (ok) {
+ mkdirSync(join(geminiDir, "antigravity-acp"), { recursive: true });
+ writeFileSync(join(geminiDir, "antigravity-acp", "antigravity-oauth-token"), JSON.stringify({ token: { access_token: "a", expiry: "2099-01-01T00:00:00Z" } }));
+ }
+ process.exit(ok ? 0 : 1);
+});
+`);
+ const executable = join(directory, "antigravity");
+ writeFileSync(executable, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(script)} "$@"\n`);
+ chmodSync(executable, 0o755);
+ return { executable, dump };
+}
+
+const cliRuntime = (executablePath: string): AntigravityRuntime => ({ executablePath, harnessPath: null, source: "managed", version: "1.5.15" });
+const pinnedRuntime: AntigravityRuntime = { executablePath: "/r/agy_acp_server.par", harnessPath: "/r/localharness_external", source: "managed", version: "1.4.3" };
+
+describe("the native CLI's environment and sign-in file", () => {
+ it("turns its self-update off and sets the SSH_CONNECTION that keeps the sign-in in the profile, a fixed value even over SSH", async () => {
+ const baseDir = folder();
+ const cli = await prepareAntigravityProfile({
+ instanceId: "cli", baseDir, runtime: cliRuntime("/cli/antigravity"),
+ baseEnv: { PATH: "/usr/bin", SSH_CONNECTION: "203.0.113.9 52144 10.0.0.2 22", AGY_CLI_DISABLE_AUTO_UPDATE: "0" },
+ });
+ expect(cli.environment.AGY_CLI_DISABLE_AUTO_UPDATE).toBe("1");
+ expect(cli.environment.SSH_CONNECTION).toBe(ANTIGRAVITY_SSH_CONNECTION);
+ expect(cli.tokenPath).toBe(join(cli.directory, "antigravity-acp", "antigravity-oauth-token"));
+ const pinned = await prepareAntigravityProfile({
+ instanceId: "pinned", baseDir, runtime: pinnedRuntime, baseEnv: { PATH: "/usr/bin", SSH_CONNECTION: "203.0.113.9 52144 10.0.0.2 22" },
+ });
+ // The pinned runtime gets the environment as before: the server's own value passes, nothing is set.
+ expect(pinned.environment.SSH_CONNECTION).toBe("203.0.113.9 52144 10.0.0.2 22");
+ expect(pinned.environment.AGY_CLI_DISABLE_AUTO_UPDATE).toBeUndefined();
+ expect(pinned.tokenPath).toBe(join(pinned.directory, "antigravity-acp", "acp_token.json"));
+ });
+
+ it("counts an account as signed in on the CLI by the CLI's own file, never by the pinned runtime's", async () => {
+ const baseDir = folder();
+ const profile = await prepareAntigravityProfile({ instanceId: "moved", baseDir, runtime: cliRuntime("/cli/antigravity") });
+ writeFileSync(join(profile.directory, "antigravity-acp", "acp_token.json"), "{\"refresh_token\":\"r\"}");
+ expect(await antigravityProfileAuthenticated(profile)).toBe(false);
+ writeFileSync(profile.tokenPath, "{\"token\":{}}");
+ expect(await antigravityProfileAuthenticated(profile)).toBe(true);
+ });
+
+ it("reads the CLI file's access token only while it has more than a minute left", () => {
+ const now = Date.parse("2026-11-23T12:00:00Z");
+ expect(antigravityCliAccessToken({ token: { access_token: "a", expiry: "2026-11-23T12:05:00Z" } }, now)).toEqual({ accessToken: "a", expiresAt: Date.parse("2026-11-23T12:05:00Z") });
+ expect(antigravityCliAccessToken({ token: { access_token: "a", expiry: "2026-11-23T12:00:30Z" } }, now)).toBeNull();
+ expect(antigravityCliAccessToken({ client_id: "c", refresh_token: "r" }, now)).toBeNull();
+ });
+
+ it("takes the CLI's no-browser answer to authenticate as a sign-in request", () => {
+ expect(antigravitySignInError({ code: -32603, message: "No browser is available here. Run agy --login." })).toBe(true);
+ expect(antigravitySignInError({ code: -32603, message: "Internal error" })).toBe(false);
+ });
+});
+
+describe("the code link and what is pasted back", () => {
+ it("takes the `--login` link only with Google's Antigravity page as its redirect", () => {
+ expect(parseAntigravityAuthorizationUrl(LINK, "code")).toMatchObject({ redirectUri: ANTIGRAVITY_CODE_REDIRECT_URI, state: "fixture-state" });
+ expect(() => parseAntigravityAuthorizationUrl(LINK)).toThrow("invalid Google sign-in URL");
+ expect(() => parseAntigravityAuthorizationUrl(LINK.replace(encodeURIComponent(ANTIGRAVITY_CODE_REDIRECT_URI), encodeURIComponent("https://example.com/cb")), "code")).toThrow("invalid Google sign-in URL");
+ });
+
+ it("accepts the code or that page's address for this sign-in, and nothing with a line break", () => {
+ const pending = { redirectUri: ANTIGRAVITY_CODE_REDIRECT_URI, state: "fixture-state" };
+ expect(antigravityLoginResponse(pending, " 4/0Ab-c_d.e~f ")).toBe("4/0Ab-c_d.e~f");
+ expect(antigravityLoginResponse(pending, `${ANTIGRAVITY_CODE_REDIRECT_URI}?state=fixture-state&code=xyz`)).toBe(`${ANTIGRAVITY_CODE_REDIRECT_URI}?state=fixture-state&code=xyz`);
+ expect(antigravityLoginResponse(pending, `${ANTIGRAVITY_CODE_REDIRECT_URI}?state=other&code=xyz`)).toBeUndefined();
+ expect(antigravityLoginResponse(pending, "https://evil.example/oauth-callback?state=fixture-state&code=xyz")).toBeUndefined();
+ expect(antigravityLoginResponse(pending, "code\nmore")).toBeUndefined();
+ });
+});
+
+describe.skipIf(WINDOWS)("signing in with `agy acp --login`", () => {
+ async function started() {
+ const fake = fakeCli();
+ const profile = await prepareAntigravityProfile({
+ instanceId: `login-${scratch.length}`, baseDir: folder(), runtime: cliRuntime(fake.executable),
+ baseEnv: { ...process.env, DISPLAY: ":0", WAYLAND_DISPLAY: "wayland-0" },
+ });
+ let signedIn = 0;
+ const controller = new AntigravityAuthController(() => { signedIn += 1; });
+ controllers.push(controller);
+ const flow = await controller.start(cliRuntime(fake.executable), profile);
+ return { fake, profile, controller, flow, signedIn: () => signedIn };
+ }
+
+ it("hands over the link it prints, with no display, then finishes with the code pasted back", async () => {
+ const { fake, profile, controller, flow, signedIn } = await started();
+ expect(flow).toMatchObject({ phase: "waiting", authorizationUrl: LINK, pasteCode: true });
+ const launch = JSON.parse(readFileSync(fake.dump, "utf8"));
+ expect(launch.argv).toEqual(["acp", "--gemini-dir", profile.directory, "--app-data-dir", "antigravity-acp", "--login"]);
+ expect(launch.env.DISPLAY).toBeUndefined();
+ expect(launch.env.WAYLAND_DISPLAY).toBeUndefined();
+ expect(launch.env.SSH_CONNECTION).toBe(ANTIGRAVITY_SSH_CONNECTION);
+ expect(launch.env.AGY_CLI_DISABLE_AUTO_UPDATE).toBe("1");
+ // What does not answer this sign-in is refused before anything reaches the CLI.
+ await expect(controller.complete(flow.flowId!, "https://evil.example/x?code=good-code")).rejects.toThrow("Paste the code from the Antigravity page");
+ expect((await controller.get(flow.flowId!)).phase).toBe("waiting");
+ await controller.complete(flow.flowId!, "good-code");
+ expect(await controller.get(flow.flowId!)).toMatchObject({ phase: "succeeded" });
+ expect(signedIn()).toBe(1);
+ expect(await antigravityProfileAuthenticated(profile)).toBe(true);
+ }, 30_000);
+
+ it("finishes with the Antigravity page's address pasted instead of the code", async () => {
+ const { controller, flow, profile } = await started();
+ await controller.complete(flow.flowId!, `${ANTIGRAVITY_CODE_REDIRECT_URI}?state=fixture-state&code=good-code`);
+ expect(existsSync(profile.tokenPath)).toBe(true);
+ }, 30_000);
+
+ it("fails with a fixed line when the CLI does not accept the code", async () => {
+ const { controller, flow, signedIn } = await started();
+ await expect(controller.complete(flow.flowId!, "wrong-code")).rejects.toThrow("Google sign-in failed. Start sign-in again.");
+ expect(await controller.get(flow.flowId!)).toMatchObject({ phase: "failed" });
+ expect(signedIn()).toBe(0);
+ }, 30_000);
+
+ it("stops the CLI when the sign-in is cancelled", async () => {
+ const { controller, flow } = await started();
+ controller.cancel();
+ expect(await controller.get(flow.flowId!)).toMatchObject({ phase: "cancelled" });
+ await expect(controller.complete(flow.flowId!, "good-code")).rejects.toThrow("no longer active");
+ }, 30_000);
+});
diff --git a/server/drivers/antigravity-cli-release.test.ts b/server/drivers/antigravity-cli-release.test.ts
new file mode 100644
index 0000000000..675e102123
--- /dev/null
+++ b/server/drivers/antigravity-cli-release.test.ts
@@ -0,0 +1,84 @@
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/antigravityCliRelease.test.ts (the manifest
+// fixture, the table of platforms and the refused manifests).
+import { describe, expect, it } from "vitest";
+
+import { ANTIGRAVITY_CLI_MANIFEST_BASE, antigravityCliTarget, hostUsesMusl, latestAntigravityCliRelease, parseAntigravityCliRelease } from "./antigravity-cli-release.ts";
+
+const manifest = {
+ version: "1.5.7",
+ url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/darwin-arm/cli_mac_arm64.tar.gz",
+ sha512: "a".repeat(128),
+};
+
+describe("Antigravity CLI release manifests", () => {
+ it.each([
+ ["darwin", "arm64", false, "darwin_arm64", "darwin-arm/cli_mac_arm64.tar.gz"],
+ ["darwin", "x64", false, "darwin_amd64", "darwin-x64/cli_mac_x64.tar.gz"],
+ ["linux", "arm64", false, "linux_arm64", "linux-arm/cli_linux_arm64.tar.gz"],
+ ["linux", "x64", false, "linux_amd64", "linux-x64/cli_linux_x64.tar.gz"],
+ ["linux", "arm64", true, "linux_arm64_musl", "linux-arm-musl/cli_linux_arm64_musl.tar.gz"],
+ ["linux", "x64", true, "linux_amd64_musl", "linux-x64-musl/cli_linux_x64_musl.tar.gz"],
+ ["win32", "arm64", false, "windows_arm64", "windows-arm/cli_windows_arm64.exe"],
+ ["win32", "x64", false, "windows_amd64", "windows-x64/cli_windows_x64.exe"],
+ ] as const)("selects Google's %s-%s release (musl %s)", (platform, arch, musl, target, file) => {
+ expect(antigravityCliTarget(platform, arch, musl)).toBe(target);
+ expect(parseAntigravityCliRelease(
+ { ...manifest, url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/${file}` },
+ platform, arch, musl,
+ )).toMatchObject({
+ version: "1.5.7",
+ format: platform === "win32" ? "executable" : "tar.gz",
+ executable: { name: platform === "win32" ? "agy.exe" : "antigravity" },
+ });
+ });
+
+ it.each([
+ { sha512: "invalid" },
+ { version: "1.4.5" },
+ { version: "1.5" },
+ { url: manifest.url.replace("https:", "http:") },
+ { url: manifest.url.replace("storage.googleapis.com", "storage.googleapis.com.evil.test") },
+ { url: manifest.url.replace("antigravity-public", "another-bucket") },
+ { url: manifest.url.replace("darwin-arm", "linux-arm") },
+ { url: `${manifest.url}?redirect=elsewhere` },
+ { url: manifest.url.replace("1.5.7-123", "1.5.6-123") },
+ ])("rejects invalid or mismatched release metadata: %j", (change) => {
+ expect(parseAntigravityCliRelease({ ...manifest, ...change }, "darwin", "arm64")).toBeNull();
+ });
+
+ it("has no release for a platform Google does not build for, or for anything that is no manifest", () => {
+ expect(antigravityCliTarget("freebsd", "x64")).toBeNull();
+ expect(antigravityCliTarget("linux", "ia32")).toBeNull();
+ expect(parseAntigravityCliRelease(manifest, "freebsd", "x64")).toBeNull();
+ for (const value of [null, "text", 7, []]) expect(parseAntigravityCliRelease(value, "darwin", "arm64")).toBeNull();
+ expect(parseAntigravityCliRelease({ ...manifest, sha512: "A".repeat(128) }, "darwin", "arm64")?.sha512).toBe("a".repeat(128));
+ });
+
+ it("reads musl from the host's loader", () => {
+ expect(hostUsesMusl("linux", "x64", (path) => path === "/lib/libc.musl-x86_64.so.1")).toBe(true);
+ expect(hostUsesMusl("linux", "arm64", (path) => path === "/lib/libc.musl-aarch64.so.1")).toBe(true);
+ expect(hostUsesMusl("linux", "arm64", (path) => path === "/lib/libc.musl-x86_64.so.1")).toBe(false);
+ expect(hostUsesMusl("darwin", "arm64", () => true)).toBe(false);
+ });
+
+ it("asks the channel for this platform's manifest, and takes nothing it cannot check", async () => {
+ const asked: string[] = [];
+ const answering = (body: unknown, status = 200) => (async (url: string | URL | Request, init?: RequestInit) => {
+ asked.push(String(url));
+ expect(init?.redirect).toBe("error");
+ return new Response(typeof body === "string" ? body : JSON.stringify(body), { status });
+ }) as typeof fetch;
+ const musl = { ...manifest, url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/linux-x64-musl/cli_linux_x64_musl.tar.gz" };
+ expect(await latestAntigravityCliRelease({ fetchImpl: answering(musl), platform: "linux", arch: "x64", musl: true })).toMatchObject({ version: "1.5.7" });
+ expect(asked).toEqual([`${ANTIGRAVITY_CLI_MANIFEST_BASE}/linux_amd64_musl.json`]);
+ expect(await latestAntigravityCliRelease({ fetchImpl: answering(musl), platform: "linux", arch: "x64", musl: false })).toBeNull();
+ expect(await latestAntigravityCliRelease({ fetchImpl: answering(manifest, 503), platform: "darwin", arch: "arm64" })).toBeNull();
+ expect(await latestAntigravityCliRelease({ fetchImpl: answering("not json"), platform: "darwin", arch: "arm64" })).toBeNull();
+ expect(await latestAntigravityCliRelease({ fetchImpl: (async () => { throw new Error("offline"); }) as typeof fetch, platform: "darwin", arch: "arm64" })).toBeNull();
+ const before = asked.length;
+ expect(await latestAntigravityCliRelease({ fetchImpl: answering(manifest), platform: "freebsd", arch: "x64" })).toBeNull();
+ expect(asked).toHaveLength(before);
+ });
+});
diff --git a/server/drivers/antigravity-cli-release.ts b/server/drivers/antigravity-cli-release.ts
new file mode 100644
index 0000000000..91ffed979e
--- /dev/null
+++ b/server/drivers/antigravity-cli-release.ts
@@ -0,0 +1,96 @@
+// Google's update channel for the native Antigravity CLI, which serves ACP itself from 1.5.0 on.
+//
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/antigravityCliRelease.ts (the manifest address,
+// the per-platform targets, and the manifest's validation);
+// - apps/server/src/provider/AntigravityInstallation.ts:932-946 (the musl
+// check and the manifest request).
+import { existsSync } from "node:fs";
+
+import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";
+
+export const ANTIGRAVITY_CLI_MANIFEST_BASE =
+ "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests";
+const MANIFEST_TIMEOUT_MS = 10_000;
+const MANIFEST_MAX_BYTES = 64 * 1024;
+
+export interface AntigravityCliReleaseAsset {
+ version: string;
+ url: string;
+ sha512: string;
+ executable: { name: string };
+ format: "tar.gz" | "executable";
+}
+
+export function antigravityCliTarget(platform: NodeJS.Platform, arch: string, musl = false): string | null {
+ if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) return null;
+ const os = platform === "win32" ? "windows" : platform;
+ return `${os}_${arch === "x64" ? "amd64" : arch}${platform === "linux" && musl ? "_musl" : ""}`;
+}
+
+export function parseAntigravityCliRelease(
+ value: unknown,
+ platform: NodeJS.Platform,
+ arch: string,
+ musl = false,
+): AntigravityCliReleaseAsset | null {
+ const manifest = value as { version?: unknown; url?: unknown; sha512?: unknown } | null;
+ if (
+ !manifest || typeof manifest !== "object"
+ || typeof manifest.version !== "string" || !/^\d+\.\d+\.\d+$/u.test(manifest.version)
+ || typeof manifest.url !== "string"
+ || typeof manifest.sha512 !== "string" || !/^[a-fA-F0-9]{128}$/u.test(manifest.sha512)
+ || antigravityCliTarget(platform, arch, musl) === null
+ ) return null;
+ if (!versionAtLeast(parseVersionTriple(manifest.version)!, [1, 5, 0])) return null;
+ const os = platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux";
+ const cpu = arch === "x64" ? "x64" : "arm64";
+ const suffix = platform === "linux" && musl ? "_musl" : "";
+ const extension = platform === "win32" ? "exe" : "tar.gz";
+ const folder = `${platform === "win32" ? "windows" : platform}-${arch === "arm64" ? "arm" : "x64"}${suffix ? "-musl" : ""}`;
+ const prefix = `https://storage.googleapis.com/antigravity-public/antigravity-cli/${manifest.version}-`;
+ const rest = manifest.url.startsWith(prefix) ? manifest.url.slice(prefix.length) : "";
+ if (!/^\d+\//u.test(rest) || rest.replace(/^\d+\//u, "") !== `${folder}/cli_${os}_${cpu}${suffix}.${extension}`) return null;
+ return {
+ version: manifest.version,
+ url: manifest.url,
+ sha512: manifest.sha512.toLowerCase(),
+ executable: { name: platform === "win32" ? "agy.exe" : "antigravity" },
+ format: platform === "win32" ? "executable" : "tar.gz",
+ };
+}
+
+export function hostUsesMusl(platform: NodeJS.Platform = process.platform, arch: string = process.arch, exists: (path: string) => boolean = existsSync): boolean {
+ return platform === "linux" && exists(arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1");
+}
+
+/** The release Google's channel offers this computer right now; null when it has none, cannot be reached, or names
+ * anything but its own download for this platform. */
+export async function latestAntigravityCliRelease(options: {
+ fetchImpl?: typeof fetch;
+ platform?: NodeJS.Platform;
+ arch?: string;
+ musl?: boolean;
+} = {}): Promise<AntigravityCliReleaseAsset | null> {
+ const platform = options.platform ?? process.platform, arch = options.arch ?? process.arch;
+ const musl = options.musl ?? hostUsesMusl(platform, arch);
+ const target = antigravityCliTarget(platform, arch, musl);
+ if (target === null) return null;
+ try {
+ const response = await (options.fetchImpl ?? fetch)(`${ANTIGRAVITY_CLI_MANIFEST_BASE}/${target}.json`, {
+ redirect: "error", signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS),
+ });
+ if (!response.ok || !response.body) return null;
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
+ bytes += chunk.length;
+ if (bytes > MANIFEST_MAX_BYTES) return null;
+ chunks.push(Buffer.from(chunk));
+ }
+ return parseAntigravityCliRelease(JSON.parse(Buffer.concat(chunks).toString("utf8")), platform, arch, musl);
+ } catch {
+ return null;
+ }
+}
diff --git a/server/drivers/antigravity-native-cli.test.ts b/server/drivers/antigravity-native-cli.test.ts
new file mode 100644
index 0000000000..f9c4c34d23
--- /dev/null
+++ b/server/drivers/antigravity-native-cli.test.ts
@@ -0,0 +1,474 @@
+import { createHash } from "node:crypto";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import * as tar from "tar";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { distrustHomePrograms } from "../bot-box/program-trust.ts";
+import { ensureDirs } from "../config.ts";
+import type { ProviderInstance } from "../contracts.ts";
+import { antigravityRuntimesRoot } from "../engine-roots.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { recordEvents } from "../testing/events.ts";
+import {
+ antigravityCliSessionMode,
+ antigravityCliTokenPath,
+ antigravityLaunchArgs,
+ antigravityTokenPath,
+ isValidAntigravityInitializeResult,
+ prepareAntigravityProfile,
+ validateAntigravityRuntime,
+} from "./antigravity-acp.ts";
+import { activeAntigravityCli, isAntigravityCliName } from "./antigravity-cli-install.ts";
+import type { AntigravityCliReleaseAsset } from "./antigravity-cli-release.ts";
+import { resolveAntigravityReleaseAsset } from "./antigravity-release.ts";
+import { antigravityCliUpdate, installAntigravityRuntime, resolveAntigravityRuntime, retirePinnedAntigravityRuntime } from "./antigravity-runtime.ts";
+import { AntigravityDriver } from "./antigravity.ts";
+
+// The opt-in, before any module reads it: this file tests the native CLI switched on.
+vi.hoisted(() => { process.env.OMB_ANTIGRAVITY_NATIVE_CLI = "1"; });
+
+const FAKE_ACP = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-acp-cli.ts");
+const WINDOWS = process.platform === "win32";
+const NAME = WINDOWS ? "agy.exe" : "antigravity";
+const ORIGIN = "https://storage.googleapis.com/antigravity-public/antigravity-cli/";
+const scratch: string[] = [];
+const instances: ProviderInstance[] = [];
+
+function folder(): string {
+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-cli-"));
+ scratch.push(directory);
+ return directory;
+}
+
+/** A release as Google's channel names it, with the bytes its address serves. */
+async function release(version: string, members: Record<string, string | { link: string }> = { [NAME]: `#!/bin/sh\necho ${version}\n` }) {
+ let bytes: Buffer;
+ if (WINDOWS) bytes = Buffer.from(String(Object.values(members)[0]));
+ else {
+ const source = folder();
+ for (const [name, content] of Object.entries(members)) {
+ if (typeof content === "string") writeFileSync(join(source, name), content, { mode: 0o755 });
+ else symlinkSync(content.link, join(source, name));
+ }
+ const archive = join(folder(), "cli.tar.gz");
+ await tar.c({ gzip: true, file: archive, cwd: source, portable: true }, Object.keys(members));
+ bytes = readFileSync(archive);
+ }
+ const asset: AntigravityCliReleaseAsset = {
+ version, url: `${ORIGIN}${version}-1/fixture`, sha512: createHash("sha512").update(bytes).digest("hex"),
+ executable: { name: NAME }, format: WINDOWS ? "executable" : "tar.gz",
+ };
+ return { asset, bytes };
+}
+
+function serving(files: Array<{ asset: AntigravityCliReleaseAsset; bytes: Buffer }>, finalUrl?: string) {
+ const asked: string[] = [];
+ const fetchImpl = (async (url: string | URL | Request) => {
+ asked.push(String(url));
+ const file = files.find(({ asset }) => asset.url === String(url));
+ if (!file) return new Response("missing", { status: 404 });
+ const response = new Response(file.bytes);
+ Object.defineProperty(response, "url", { value: finalUrl ?? String(url) });
+ return response;
+ }) as typeof fetch;
+ return { fetchImpl, asked };
+}
+
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ for (const instance of instances.splice(0)) await instance.dispose();
+ while (scratch.length) await removeTempDir(scratch.pop()!);
+});
+
+describe("installing the native CLI from Google's channel", () => {
+ it("verifies, unpacks, checks and activates a release, then reuses it without another download", async () => {
+ const baseDir = folder();
+ const one = await release("1.5.7");
+ const { fetchImpl, asked } = serving([one]);
+ const validate = vi.fn(async () => {});
+ const installed = await installAntigravityRuntime({ baseDir, fetchImpl, validate, native: true, cliRelease: one.asset });
+ expect(installed).toMatchObject({ harnessPath: null, source: "managed", version: "1.5.7" });
+ expect(installed.executablePath.endsWith(join(one.asset.sha512.slice(0, 64), NAME))).toBe(true);
+ if (!WINDOWS) expect(readFileSync(installed.executablePath, "utf8")).toBe("#!/bin/sh\necho 1.5.7\n");
+ expect(validate).toHaveBeenCalledWith(expect.objectContaining({ harnessPath: null, version: "1.5.7" }), "1.5.7");
+ const root = join(antigravityRuntimesRoot(baseDir), `${process.platform}-${process.arch}`);
+ expect(await activeAntigravityCli(root)).toEqual(installed);
+ expect(readdirSync(join(root, "versions")).filter((name) => name.startsWith(".install-"))).toEqual([]);
+
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toEqual(installed);
+ await expect(resolveAntigravityRuntime("agy", { PATH: "" }, baseDir)).resolves.toEqual(installed);
+ await expect(resolveAntigravityRuntime(undefined, { PATH: "" }, baseDir)).resolves.toEqual(installed);
+
+ await installAntigravityRuntime({ baseDir, fetchImpl, validate, native: true, cliRelease: one.asset });
+ expect(asked).toEqual([one.asset.url]);
+ expect(validate).toHaveBeenCalledTimes(2);
+ });
+
+ it("moves to a newer release, removes the one it replaced, and never moves back to an older one", async () => {
+ const baseDir = folder();
+ const [older, newer] = [await release("1.5.6"), await release("1.5.8")];
+ const { fetchImpl, asked } = serving([older, newer]);
+ const first = await installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: older.asset, native: true });
+ const second = await installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: newer.asset });
+ expect(second.version).toBe("1.5.8");
+ // Pruned once the newer one is active and nothing runs the older one (T3 Code 68ea2220c12).
+ expect(existsSync(dirname(first.executablePath))).toBe(false);
+ if (!WINDOWS) {
+ // Published releases are read-only.
+ expect(statSync(dirname(second.executablePath)).mode & 0o777).toBe(0o555);
+ expect(statSync(second.executablePath).mode & 0o777).toBe(0o555);
+ }
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.8" });
+ expect((await installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: older.asset })).version).toBe("1.5.8");
+ expect(asked).toEqual([older.asset.url, newer.asset.url]);
+ });
+
+ it("installs nothing when the bytes do not match the channel's checksum, or come from somewhere else", async () => {
+ const baseDir = folder();
+ const one = await release("1.5.7");
+ const wrong = { asset: one.asset, bytes: Buffer.concat([one.bytes, Buffer.from("x")]) };
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl: serving([wrong]).fetchImpl, native: true, cliRelease: one.asset }))
+ .rejects.toThrow("failed its size or checksum check. Nothing was installed.");
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl: serving([one], "https://storage.googleapis.com/another-bucket/cli").fetchImpl, native: true, cliRelease: one.asset }))
+ .rejects.toThrow("redirected away from Google's release folder");
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl: serving([]).fetchImpl, native: true, cliRelease: one.asset })).rejects.toThrow("Google download failed (404).");
+ await expect(installAntigravityRuntime({ baseDir, native: true, cliRelease: null })).rejects.toThrow("Could not find a native Antigravity CLI release.");
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).rejects.toThrow(/native CLI is not installed.*set the CLI path back to agy/u);
+ const root = join(antigravityRuntimesRoot(baseDir), `${process.platform}-${process.arch}`);
+ expect(existsSync(join(root, "active.json"))).toBe(false);
+ expect(readdirSync(join(root, "versions"))).toEqual([]);
+ });
+
+ it("leaves the release that was running in place when the new one does not start", async () => {
+ const baseDir = folder();
+ const [older, newer] = [await release("1.5.6"), await release("1.5.8")];
+ const { fetchImpl } = serving([older, newer]);
+ await installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: older.asset, native: true });
+ const validate = vi.fn(async () => { throw new Error("The download did not identify as the expected Google Antigravity ACP release."); });
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl, validate, cliRelease: newer.asset, native: true })).rejects.toThrow("did not identify");
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.6" });
+ });
+
+ it.skipIf(WINDOWS).each([
+ ["a second file", { antigravity: "#!/bin/sh\n", extra: "more" }],
+ ["another name", { "agy-other": "#!/bin/sh\n" }],
+ ["a link", { antigravity: { link: "/bin/sh" } }],
+ ] as Array<[string, Record<string, string | { link: string }>]>)("refuses an archive that holds %s", async (_name, members) => {
+ const baseDir = folder();
+ const bad = await release("1.5.7", members);
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl: serving([bad]).fetchImpl, native: true, cliRelease: bad.asset }))
+ .rejects.toThrow("The Antigravity archive must contain one regular executable.");
+ });
+
+ it("moves a computer that has one of the pinned runtime's releases to the native CLI", async () => {
+ const pinned = resolveAntigravityReleaseAsset();
+ if (!pinned) return;
+ const baseDir = folder();
+ const earlier = "f".repeat(64);
+ const directory = join(antigravityRuntimesRoot(baseDir), `${process.platform}-${process.arch}`, "versions", earlier);
+ mkdirSync(directory, { recursive: true });
+ writeFileSync(join(directory, ".install-complete.json"), JSON.stringify({ sha256: earlier, version: "1.1.1" }));
+ const one = await release("1.5.7");
+ const { fetchImpl, asked } = serving([one]);
+ // The updater offers the move while the pinned release is what is installed.
+ expect(await antigravityCliUpdate({ baseDir, now: 1, latest: async () => one.asset })).toBe("1.1.1");
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: one.asset })).resolves.toMatchObject({ harnessPath: null, version: "1.5.7" });
+ expect(asked).toEqual([one.asset.url]);
+ await expect(resolveAntigravityRuntime("agy", { PATH: "" }, baseDir)).resolves.toMatchObject({ harnessPath: null, version: "1.5.7" });
+ expect(await antigravityCliUpdate({ baseDir, now: 2, latest: async () => one.asset })).toBeNull();
+ });
+
+ it("falls back to the pinned runtime when a new install cannot get the native CLI", async () => {
+ const pinned = resolveAntigravityReleaseAsset();
+ if (!pinned) return;
+ const baseDir = folder();
+ const one = await release("1.5.7");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { fetchImpl, asked } = serving([]);
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: one.asset })).rejects.toThrow("Google download failed (404).");
+ expect(asked).toEqual([one.asset.url, pinned.url]);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("using the pinned runtime instead"));
+ warn.mockRestore();
+ });
+
+ it("offers an update while the CLI in use is older than the channel's, asking the channel at most once an hour", async () => {
+ const baseDir = folder();
+ const [current, newer] = [await release("1.5.7"), await release("1.5.8")];
+ await installAntigravityRuntime({ baseDir, fetchImpl: serving([current]).fetchImpl, cliRelease: current.asset, native: true });
+ const latest = vi.fn(async () => newer.asset);
+ const hour = 60 * 60 * 1000, start = Date.now() + 10 * hour;
+ expect(await antigravityCliUpdate({ baseDir, now: start, latest, asset: null })).toBe("1.5.7");
+ // The engine was busy: the next look, minutes later, still finds the update without asking again.
+ expect(await antigravityCliUpdate({ baseDir, now: start + 5 * 60_000, latest, asset: null })).toBe("1.5.7");
+ expect(await antigravityCliUpdate({ baseDir, now: start + hour - 1, latest, asset: null })).toBe("1.5.7");
+ expect(latest).toHaveBeenCalledTimes(1);
+ expect(await antigravityCliUpdate({ baseDir, now: start + hour, latest: async () => current.asset, asset: null })).toBeNull();
+ // A channel that did not answer is asked again on the next look.
+ const silent = vi.fn(async () => null);
+ expect(await antigravityCliUpdate({ baseDir, now: start + 2 * hour, latest: silent, asset: null })).toBeNull();
+ expect(await antigravityCliUpdate({ baseDir, now: start + 2 * hour + 1, latest, asset: null })).toBe("1.5.7");
+ expect(await antigravityCliUpdate({ baseDir: folder(), now: start + 4 * hour, latest, asset: null })).toBeNull();
+ });
+
+ it.skipIf(!resolveAntigravityReleaseAsset() || WINDOWS)("runs and updates the CLI where the pinned runtime is also installed, and removes the pinned one once an account signed in on the CLI", async () => {
+ const pinned = resolveAntigravityReleaseAsset()!;
+ const baseDir = folder();
+ const [current, newer] = [await release("1.5.7"), await release("1.5.8")];
+ await installAntigravityRuntime({ baseDir, fetchImpl: serving([current]).fetchImpl, cliRelease: current.asset, native: true });
+ // The pinned release, whole: sparse files of the pinned sizes.
+ const directory = join(antigravityRuntimesRoot(baseDir), `${process.platform}-${process.arch}`, "versions", pinned.sha256);
+ mkdirSync(directory, { recursive: true });
+ for (const file of [pinned.executable, pinned.harness]) {
+ writeFileSync(join(directory, file.name), "");
+ truncateSync(join(directory, file.name), file.bytes);
+ chmodSync(join(directory, file.name), 0o755);
+ }
+ writeFileSync(join(directory, ".install-complete.json"), JSON.stringify({ sha256: pinned.sha256, version: pinned.version, executable: pinned.executable, harness: pinned.harness }));
+ await expect(resolveAntigravityRuntime("agy", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.7" });
+ await expect(resolveAntigravityRuntime(undefined, { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.7" });
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.7" });
+ const latest = async () => newer.asset, at = Date.now() + 100 * 60 * 60 * 1000;
+ expect(await antigravityCliUpdate({ baseDir, now: at, latest })).toBe("1.5.7");
+ // Kept until an account here has signed in on the CLI, and while a process still runs it.
+ expect(await retirePinnedAntigravityRuntime({ baseDir, inUse: () => false })).toEqual([]);
+ const cliToken = antigravityCliTokenPath("moved", baseDir), pinnedToken = antigravityTokenPath("moved", baseDir);
+ mkdirSync(dirname(cliToken), { recursive: true });
+ writeFileSync(cliToken, "{}");
+ writeFileSync(pinnedToken, "{}");
+ expect(await retirePinnedAntigravityRuntime({ baseDir, inUse: () => true })).toEqual([]);
+ expect(existsSync(directory)).toBe(true);
+ expect(await retirePinnedAntigravityRuntime({ baseDir, inUse: () => false })).toEqual([pinned.sha256]);
+ expect(existsSync(directory)).toBe(false);
+ // The pinned runtime's sign-in stays for a rollback.
+ expect(existsSync(pinnedToken)).toBe(true);
+ await expect(resolveAntigravityRuntime("agy", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.7" });
+ });
+
+ it("installs a release again when its folder is there but its files are damaged, and clears staging folders an old install left", async () => {
+ const baseDir = folder();
+ const one = await release("1.5.7");
+ const { fetchImpl, asked } = serving([one]);
+ const installed = await installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: one.asset, native: true });
+ const versions = dirname(dirname(installed.executablePath));
+ const stale = join(versions, ".install-stale"), recent = join(versions, ".install-recent");
+ for (const path of [stale, recent]) mkdirSync(path);
+ utimesSync(stale, new Date(Date.now() - 2 * 60 * 60_000), new Date(Date.now() - 2 * 60 * 60_000));
+ // Opened up first: a release is published read-only.
+ const open = () => { if (!WINDOWS) { chmodSync(dirname(installed.executablePath), 0o755); if (existsSync(installed.executablePath)) chmodSync(installed.executablePath, 0o755); } };
+ for (const damage of [() => rmSync(installed.executablePath), () => rmSync(join(dirname(installed.executablePath), ".install-complete.json")), () => writeFileSync(installed.executablePath, "cut short")]) {
+ open();
+ damage();
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).rejects.toThrow(/not installed/u);
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl, cliRelease: one.asset, native: true })).resolves.toEqual(installed);
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toEqual(installed);
+ }
+ expect(asked).toHaveLength(4);
+ expect(existsSync(stale)).toBe(false);
+ expect(existsSync(recent)).toBe(true);
+ });
+
+ it("fails, and keeps the release in use, when a newer one cannot be installed over a CLI already here", async () => {
+ const baseDir = folder();
+ const [current, newer] = [await release("1.5.7"), await release("1.5.8")];
+ await installAntigravityRuntime({ baseDir, fetchImpl: serving([current]).fetchImpl, cliRelease: current.asset, native: true });
+ await expect(installAntigravityRuntime({ baseDir, fetchImpl: serving([]).fetchImpl, cliRelease: newer.asset })).rejects.toThrow("Google download failed (404).");
+ await expect(installAntigravityRuntime({ baseDir, cliRelease: null })).rejects.toThrow("Could not find a native Antigravity CLI release.");
+ await expect(resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: "1.5.7" });
+ });
+
+ it("gives a native install asked for during a pinned one its own result", async () => {
+ const pinned = resolveAntigravityReleaseAsset();
+ if (!pinned) return;
+ const baseDir = folder();
+ const one = await release("1.5.7");
+ let release404: () => void = () => {};
+ const held = new Promise<void>((done) => { release404 = done; });
+ const { fetchImpl } = serving([one]);
+ const slow = (async (url: string | URL | Request, init?: RequestInit) => {
+ if (String(url) === pinned.url) { await held; return new Response("missing", { status: 404 }); }
+ return fetchImpl(url, init);
+ }) as typeof fetch;
+ const pinnedInstall = installAntigravityRuntime({ baseDir, fetchImpl: slow, asset: pinned });
+ pinnedInstall.catch(() => {});
+ const nativeInstall = installAntigravityRuntime({ baseDir, fetchImpl: slow, cliRelease: one.asset, native: true });
+ expect(nativeInstall).not.toBe(pinnedInstall);
+ await expect(nativeInstall).resolves.toMatchObject({ harnessPath: null, version: "1.5.7" });
+ release404();
+ await expect(pinnedInstall).rejects.toThrow("Google download failed (404).");
+ });
+});
+
+describe("starting the native CLI", () => {
+ it("launches through its acp subcommand with the profile folder, and without a harness", async () => {
+ const directory = folder();
+ expect(antigravityLaunchArgs({ harnessPath: null }, "/profile")).toEqual(["acp", "--gemini-dir", "/profile", "--app-data-dir", "antigravity-acp"]);
+ expect(antigravityLaunchArgs({ harnessPath: "/runtime/localharness_external" }, "/profile", "linux")).toEqual(["--uid="]);
+ expect(antigravityLaunchArgs({ harnessPath: "/runtime/localharness_external" }, "/profile", "darwin")).toEqual([]);
+ const cli = await prepareAntigravityProfile({ instanceId: "cli", baseDir: directory, runtime: { executablePath: "/cli/antigravity", harnessPath: null, source: "managed", version: "1.5.7" } });
+ expect("ANTIGRAVITY_HARNESS_PATH" in cli.environment).toBe(false);
+ expect(cli.environment.GEMINI_HOME).toBe(cli.directory);
+ const pair = await prepareAntigravityProfile({ instanceId: "pair", baseDir: directory, runtime: { executablePath: "/r/agy_acp_server.par", harnessPath: "/r/localharness_external", source: "managed", version: "1.4.3" } });
+ expect(pair.environment.ANTIGRAVITY_HARNESS_PATH).toBe("/r/localharness_external");
+ });
+
+ it("knows the CLI by its names and by the name it gives itself", () => {
+ for (const name of ["antigravity", "/usr/local/bin/antigravity", "C:\\Tools\\Antigravity.exe"]) expect(isAntigravityCliName(name)).toBe(true);
+ for (const name of ["agy", "/opt/homebrew/bin/agy", "C:\\Tools\\agy.exe", "agy.cmd", "agy_acp_server.par", "antigravity-acp", "/antigravity/custom"]) expect(isAntigravityCliName(name)).toBe(false);
+ const initialized = (name: string) => ({
+ protocolVersion: 1, agentInfo: { name, version: "1.5.7" }, authMethods: [{ id: "oauth-personal" }],
+ agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} }, auth: { logout: {} } },
+ });
+ expect(isValidAntigravityInitializeResult(initialized("Antigravity ACP Server"), "1.5.7", true)).toBe(true);
+ expect(isValidAntigravityInitializeResult(initialized("antigravity-acp"), "1.5.7", true)).toBe(false);
+ expect(isValidAntigravityInitializeResult(initialized("Antigravity ACP Server"), "1.5.7")).toBe(false);
+ expect(isValidAntigravityInitializeResult(initialized("Antigravity ACP Server"), "1.5.8", true)).toBe(false);
+ });
+
+ it("stays in default where the pinned runtime would be in yolo or auto_edit", () => {
+ expect(["yolo", "auto_edit", "default", "plan"].map(antigravityCliSessionMode)).toEqual(["default", "default", "default", "plan"]);
+ });
+});
+
+describe.skipIf(WINDOWS)("a native CLI set as the engine's own path", () => {
+ /** A program named `antigravity` that answers as the fake runtime does. */
+ function cli(): { directory: string; executable: string; dump: string } {
+ const directory = folder();
+ const executable = join(directory, "antigravity");
+ writeFileSync(executable, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(FAKE_ACP)} "$@"\n`);
+ chmodSync(executable, 0o755);
+ return { directory, executable, dump: join(directory, "dump.json") };
+ }
+
+ async function create(instanceId: string, executable: string, environment: Record<string, string>) {
+ ensureDirs();
+ // The CLI's own sign-in file: the pinned runtime's acp_token.json does not sign in the CLI.
+ const token = antigravityCliTokenPath(instanceId);
+ mkdirSync(dirname(token), { recursive: true });
+ writeFileSync(token, "{}", { mode: 0o600 });
+ const instance = await AntigravityDriver.create({
+ instanceId, displayName: "Antigravity", enabled: true, config: { cli: executable, fullAuto: false },
+ environment: { FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "gemini-3.8-flash", FAKE_ACP_AGENT_NAME: "Antigravity ACP Server", FAKE_ACP_VERSION: "1.5.7", ...environment },
+ });
+ instances.push(instance);
+ return instance;
+ }
+
+ it("is taken as the CLI only from 1.5.0 on, and a saved agy path is never started", async () => {
+ const fake = cli();
+ await expect(resolveAntigravityRuntime(fake.executable, { ...process.env, FAKE_ACP_VERSION: "1.5.7" }))
+ .resolves.toEqual({ executablePath: fake.executable, harnessPath: null, source: "override", version: "1.5.7" });
+ const old = cli();
+ await expect(resolveAntigravityRuntime(old.executable, { ...process.env, FAKE_ACP_VERSION: "antigravity 1.4.9" }, folder()))
+ .rejects.toThrow(/custom Antigravity ACP executable/u);
+ const directory = folder(), started = join(directory, "started"), legacy = join(directory, "agy");
+ writeFileSync(legacy, `#!/bin/sh\ntouch ${JSON.stringify(started)}\necho 1.5.7\n`);
+ chmodSync(legacy, 0o755);
+ await expect(resolveAntigravityRuntime(legacy, { PATH: "" }, folder())).rejects.toThrow();
+ expect(existsSync(started)).toBe(false);
+ });
+
+ it("is not started for its version from a folder the bots can write", async () => {
+ const directory = folder(), started = join(directory, "started"), program = join(directory, "antigravity");
+ writeFileSync(program, `#!/bin/sh\ntouch ${JSON.stringify(started)}\necho 1.5.7\n`);
+ chmodSync(program, 0o755);
+ distrustHomePrograms(directory);
+ try {
+ await expect(resolveAntigravityRuntime(program, { PATH: "" }, folder())).rejects.toThrow("is in a folder the bots can write");
+ expect(existsSync(started)).toBe(false);
+ } finally {
+ distrustHomePrograms(null);
+ }
+ await expect(resolveAntigravityRuntime(program, { PATH: "" }, folder())).resolves.toMatchObject({ harnessPath: null, version: "1.5.7" });
+ });
+
+ it("passes the check a download gets, by the name and version it reports", async () => {
+ const fake = cli();
+ vi.stubEnv("FAKE_ACP_AUTH_METHOD", "oauth-personal");
+ vi.stubEnv("FAKE_ACP_AGENT_NAME", "Antigravity ACP Server");
+ vi.stubEnv("FAKE_ACP_AGENT_VERSION", "1.5.7");
+ const runtime = { executablePath: fake.executable, harnessPath: null, source: "managed" as const, version: "1.5.7" };
+ await expect(validateAntigravityRuntime(runtime, "1.5.7")).resolves.toBeUndefined();
+ await expect(validateAntigravityRuntime(runtime, "1.5.8")).rejects.toThrow("did not identify as the expected Google Antigravity ACP release");
+ }, 60_000);
+
+ it("runs a Full access turn in default mode, started through acp with our own client name", async () => {
+ const fake = cli();
+ const instance = await create("antigravity-cli-full", fake.executable, { FAKE_ACP_MODES: "default,plan", FAKE_ACP_DUMP: fake.dump });
+ const recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "cli-full", text: "hello", approvalMode: "full", cwd: fake.directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: true });
+ const prompts = readFileSync(`${fake.dump}.prompts.jsonl`, "utf8").trim().split("\n").map((line) => JSON.parse(line));
+ expect(prompts.at(-1)).toMatchObject({ mode: "default" });
+ const launch = JSON.parse(readFileSync(fake.dump, "utf8"));
+ expect(launch.argv.slice(0, 2)).toEqual(["acp", "--gemini-dir"]);
+ expect(launch.argv.slice(3)).toEqual(["--app-data-dir", "antigravity-acp"]);
+ expect(launch.env.ANTIGRAVITY_HARNESS_PATH).toBeUndefined();
+ expect(JSON.parse(readFileSync(`${fake.dump}.initialize.json`, "utf8")).clientInfo).toEqual({ name: "openmausbot", version: "0.0.0" });
+ }, 90_000);
+
+ it("fails closed when the CLI does not confirm default mode", async () => {
+ const fake = cli();
+ const instance = await create("antigravity-cli-unconfirmed", fake.executable, { FAKE_ACP_MODES: "default,plan", FAKE_ACP_EMPTY_MODE_ACK: "1" });
+ const recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "cli-unconfirmed", text: "hello", approvalMode: "full", cwd: fake.directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: false });
+ expect(recorder.events.some((event) => event.type === "runtime.error" && /did not apply default permission mode/u.test(event.message))).toBe(true);
+ }, 90_000);
+
+ it("fails closed when the CLI offers no mode at all", async () => {
+ const fake = cli();
+ const instance = await create("antigravity-cli-no-mode", fake.executable, {});
+ const recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "cli-no-mode", text: "hello", approvalMode: "full", cwd: fake.directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: false });
+ expect(recorder.events.some((event) => event.type === "runtime.error" && /did not report its permission mode/u.test(event.message))).toBe(true);
+ }, 90_000);
+
+ /** One turn at `approvalMode` whose runtime asks about `toolCall`; a card that opens is denied. */
+ async function asked(name: string, approvalMode: "edits" | "full", toolCall: (directory: string) => object) {
+ const fake = cli();
+ const answer = join(fake.directory, "answer");
+ const instance = await create(`antigravity-cli-${name}`, fake.executable, {
+ FAKE_ACP_MODES: "default,plan", FAKE_ACP_MODE: "permission", FAKE_ACP_PERMISSION_ANSWER: answer,
+ FAKE_ACP_PERMISSION_TOOL_CALL: JSON.stringify(toolCall(fake.directory)),
+ });
+ const recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: name, text: "hello", approvalMode, cwd: fake.directory });
+ const first = await recorder.until((event) => event.turnId === turnId && (event.type === "request.opened" || event.type === "turn.completed"));
+ if (first.type === "request.opened") await instance.adapter.respondToRequest(name, (first as { requestId: string }).requestId, { behavior: "deny" });
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ const opened = recorder.events.find((event) => event.type === "request.opened") as { commandLine?: string } | undefined;
+ return { card: opened !== undefined, commandLine: opened?.commandLine, answer: readFileSync(answer, "utf8") };
+ }
+
+ it("answers a file edit inside the turn's folder itself on Auto-accept edits", async () => {
+ expect(await asked("edits-inside", "edits", (directory) => ({ kind: "edit", title: "Edit notes.md", locations: [{ path: join(directory, "notes.md") }] })))
+ .toEqual({ card: false, commandLine: undefined, answer: "allow-once" });
+ expect(await asked("edits-new-folder", "edits", (directory) => ({ kind: "edit", title: "Edit", locations: [{ path: join(directory, "new", "deep", "notes.md") }] })))
+ .toMatchObject({ card: false, answer: "allow-once" });
+ }, 90_000);
+
+ it.each([
+ ["a command", () => ({ kind: "execute", rawInput: { command: "echo hi" }, title: "echo hi" })],
+ ["an edit that names a command", (directory: string) => ({ kind: "edit", rawInput: { CommandLine: "rm -rf ~" }, locations: [{ path: join(directory, "notes.md") }] })],
+ ["an edit that names a command the other way", (directory: string) => ({ kind: "edit", rawInput: { command: "echo hi" }, locations: [{ path: join(directory, "notes.md") }] })],
+ ["an edit outside the turn's folder", (directory: string) => ({ kind: "edit", locations: [{ path: join(directory, "..", "elsewhere.md") }] })],
+ ["an edit of the folder next door", (directory: string) => ({ kind: "edit", locations: [{ path: `${directory}-other/notes.md` }] })],
+ ["an edit with one place inside and one outside", (directory: string) => ({ kind: "edit", locations: [{ path: join(directory, "notes.md") }, { path: "/etc/hosts" }] })],
+ ["an edit through a link that leaves the folder", (directory: string) => { symlinkSync(tmpdir(), join(directory, "out")); return { kind: "edit", locations: [{ path: join(directory, "out", "notes.md") }] }; }],
+ ["an edit that gives no place", () => ({ kind: "edit", title: "Edit notes.md" })],
+ ["an edit with a relative place", () => ({ kind: "edit", locations: [{ path: "notes.md" }] })],
+ ] as Array<[string, (directory: string) => object]>)("still asks, on Auto-accept edits, about %s", async (name, toolCall) => {
+ expect(await asked(`edits-${name.replaceAll(" ", "-")}`, "edits", toolCall)).toMatchObject({ card: true, answer: "reject" });
+ }, 90_000);
+
+ it("hands a command a request names as CommandLine to the never-list, whatever kind the request claims", async () => {
+ expect(await asked("full-commandline", "full", () => ({ kind: "edit", rawInput: { CommandLine: "rm -rf ~" }, title: "Edit" })))
+ .toMatchObject({ card: true, commandLine: "rm -rf ~" });
+ expect(await asked("full-other-kind", "full", () => ({ kind: "other", rawInput: { CommandLine: "rm -rf ~" }, title: "Tool" })))
+ .toMatchObject({ card: true, commandLine: "rm -rf ~" });
+ }, 90_000);
+});
diff --git a/server/drivers/antigravity-opt-in.test.ts b/server/drivers/antigravity-opt-in.test.ts
new file mode 100644
index 0000000000..a26e21e2df
--- /dev/null
+++ b/server/drivers/antigravity-opt-in.test.ts
@@ -0,0 +1,170 @@
+// The native CLI is opt-in (OMB_ANTIGRAVITY_NATIVE_CLI=1). Off, the default, Antigravity behaves as before the CLI: the
+// pinned 1.4.3 runtime is kept and run, Google's CLI channel is never asked, a CLI release is never started, the
+// signed-in check reads acp_token.json, and the updater offers nothing new. On, a computer with the pinned runtime moves.
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, statSync, truncateSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { resolveAntigravityReleaseAsset } from "./antigravity-release.ts";
+
+const WINDOWS = process.platform === "win32";
+const pinned = resolveAntigravityReleaseAsset();
+const scratch: string[] = [];
+const CLI_ID = "c".repeat(64);
+const CHANNEL = "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/";
+
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ while (scratch.length) await removeTempDir(scratch.pop()!);
+});
+
+function dataFolder(): string {
+ const baseDir = mkdtempSync(join(tmpdir(), "omb-antigravity-opt-in-"));
+ scratch.push(baseDir);
+ return baseDir;
+}
+
+/** A data folder with the pinned release (sparse files of its sizes), and optionally an active CLI release and a CLI
+ * sign-in beside the pinned one for one account. */
+function computer(options: { pinned?: boolean; cli?: boolean; cliSignIn?: boolean } = {}) {
+ const baseDir = dataFolder();
+ const root = join(baseDir, "tools", "antigravity-acp", `${process.platform}-${process.arch}`);
+ const pinnedDir = join(root, "versions", pinned!.sha256);
+ if (options.pinned !== false) {
+ mkdirSync(pinnedDir, { recursive: true });
+ for (const file of [pinned!.executable, pinned!.harness]) {
+ writeFileSync(join(pinnedDir, file.name), "");
+ truncateSync(join(pinnedDir, file.name), file.bytes);
+ chmodSync(join(pinnedDir, file.name), 0o755);
+ }
+ writeFileSync(join(pinnedDir, ".install-complete.json"), JSON.stringify({ sha256: pinned!.sha256, version: pinned!.version, executable: pinned!.executable, harness: pinned!.harness }));
+ }
+ const started = join(baseDir, "cli-started");
+ if (options.cli) {
+ const cliDir = join(root, "versions", CLI_ID);
+ mkdirSync(cliDir, { recursive: true });
+ writeFileSync(join(cliDir, "antigravity"), `#!/bin/sh\ntouch ${JSON.stringify(started)}\necho 1.5.15\n`, { mode: 0o755 });
+ writeFileSync(join(cliDir, ".install-complete.json"), JSON.stringify({ releaseId: CLI_ID, version: "1.5.15", executable: { name: "antigravity", bytes: statSync(join(cliDir, "antigravity")).size }, harness: null }));
+ writeFileSync(join(root, "active.json"), JSON.stringify({ releaseId: CLI_ID }));
+ }
+ if (options.cliSignIn) {
+ const profile = join(baseDir, "providers", "antigravity", "a".repeat(64), "antigravity-acp");
+ mkdirSync(profile, { recursive: true });
+ writeFileSync(join(profile, "antigravity-oauth-token"), "{}");
+ writeFileSync(join(profile, "acp_token.json"), "{}");
+ }
+ return { baseDir, pinnedDir, started };
+}
+
+const latestRelease = async () => ({ version: "1.5.15", url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-1/x", sha512: "0".repeat(128), executable: { name: "antigravity" }, format: "tar.gz" as const });
+
+/** Every address asked, each answered 404. */
+function recordingFetch() {
+ const asked: string[] = [];
+ const fetchImpl = (async (url: string | URL | Request) => {
+ asked.push(String(url));
+ return new Response("missing", { status: 404 });
+ }) as typeof fetch;
+ return { asked, fetchImpl };
+}
+
+describe.skipIf(!pinned || WINDOWS)("with the native CLI off (the default), Antigravity behaves as before it", () => {
+ it("is off unless OMB_ANTIGRAVITY_NATIVE_CLI is exactly 1", async () => {
+ expect((await import("./antigravity-cli-install.ts")).ANTIGRAVITY_NATIVE_CLI).toBe(false);
+ for (const value of ["0", "true", "yes", ""]) {
+ vi.stubEnv("OMB_ANTIGRAVITY_NATIVE_CLI", value);
+ vi.resetModules();
+ expect((await import("./antigravity-cli-install.ts")).ANTIGRAVITY_NATIVE_CLI, value).toBe(false);
+ }
+ });
+
+ it("keeps a computer on the pinned runtime, even beside a CLI release, never starts the CLI, and the updater offers nothing new", async () => {
+ const runtime = await import("./antigravity-runtime.ts");
+ const { baseDir, pinnedDir, started } = computer({ cli: true, cliSignIn: true });
+ for (const cli of ["agy", undefined]) {
+ await expect(runtime.resolveAntigravityRuntime(cli, { PATH: "" }, baseDir)).resolves.toMatchObject({ version: pinned!.version, source: "managed" });
+ }
+ // `antigravity` is no alias for the CLI when off: a custom name looked up on PATH, as on main.
+ await expect(runtime.resolveAntigravityRuntime("antigravity", { PATH: "" }, baseDir)).rejects.toThrow("sibling is missing.");
+ const latest = vi.fn(latestRelease);
+ expect(await runtime.antigravityCliUpdate({ baseDir, now: Date.now() + 1e9, latest })).toBeNull();
+ expect(latest).not.toHaveBeenCalled();
+ // The updater's own question, as main asks it: is an older pinned release installed? No.
+ expect(await runtime.antigravityOlderRuntime(baseDir)).toBeNull();
+ expect(await runtime.retirePinnedAntigravityRuntime({ baseDir, inUse: () => false })).toEqual([]);
+ expect(existsSync(pinnedDir)).toBe(true);
+ expect(existsSync(started)).toBe(false);
+ });
+
+ it("never asks Google's CLI channel: an install over the pinned runtime reuses it, and a fresh install downloads the pinned runtime", async () => {
+ const runtime = await import("./antigravity-runtime.ts");
+ const existing = computer();
+ const reuse = recordingFetch();
+ await expect(runtime.installAntigravityRuntime({ baseDir: existing.baseDir, fetchImpl: reuse.fetchImpl })).resolves.toMatchObject({ version: pinned!.version });
+ expect(reuse.asked).toEqual([]);
+ const fresh = recordingFetch();
+ await expect(runtime.installAntigravityRuntime({ baseDir: dataFolder(), fetchImpl: fresh.fetchImpl })).rejects.toThrow("Google download failed (404).");
+ expect(fresh.asked).toEqual([pinned!.url]);
+ expect(fresh.asked.some((url) => url.startsWith(CHANNEL))).toBe(false);
+ expect(runtime.isAntigravityNativeAlias("antigravity")).toBe(false);
+ });
+
+ it("does not start a custom program named antigravity, and says what it said before", async () => {
+ const runtime = await import("./antigravity-runtime.ts");
+ const directory = dataFolder(), started = join(directory, "started"), program = join(directory, "antigravity");
+ writeFileSync(program, `#!/bin/sh\ntouch ${JSON.stringify(started)}\necho 1.5.15\n`, { mode: 0o755 });
+ await expect(runtime.resolveAntigravityRuntime(program, { PATH: "" }, dataFolder()))
+ .rejects.toThrow(/^The custom Antigravity ACP executable or its localharness_external sibling is missing\.$/u);
+ expect(existsSync(started)).toBe(false);
+ });
+
+ it("reads the signed-in state from acp_token.json and starts the runtime with the environment it had", async () => {
+ const acp = await import("./antigravity-acp.ts");
+ const profile = await acp.prepareAntigravityProfile({
+ instanceId: "off", baseDir: dataFolder(), runtime: { executablePath: "/r/agy_acp_server.par", harnessPath: "/r/localharness_external", source: "managed", version: pinned!.version },
+ baseEnv: { PATH: "/usr/bin", SSH_CONNECTION: "203.0.113.9 52144 10.0.0.2 22" },
+ });
+ expect(profile.tokenPath).toBe(join(profile.directory, "antigravity-acp", "acp_token.json"));
+ expect(profile.environment.AGY_CLI_DISABLE_AUTO_UPDATE).toBeUndefined();
+ expect(profile.environment.SSH_CONNECTION).toBe("203.0.113.9 52144 10.0.0.2 22");
+ expect(profile.environment.ANTIGRAVITY_HARNESS_PATH).toBe("/r/localharness_external");
+ // A CLI sign-in file beside it does not count; the pinned runtime's own does.
+ writeFileSync(join(profile.directory, "antigravity-acp", "antigravity-oauth-token"), "{\"token\":{}}");
+ expect(await acp.antigravityProfileAuthenticated(profile)).toBe(false);
+ writeFileSync(profile.tokenPath, "{\"refresh_token\":\"r\"}");
+ expect(await acp.antigravityProfileAuthenticated(profile)).toBe(true);
+ });
+
+ it("offers the pinned install card with its download size, as before", async () => {
+ const { AntigravityDriver } = await import("./antigravity.ts");
+ expect(AntigravityDriver.install?.managed).toEqual({ label: "Install official Antigravity", downloadBytes: pinned!.archiveBytes });
+ });
+});
+
+describe.skipIf(!pinned || WINDOWS)("with OMB_ANTIGRAVITY_NATIVE_CLI=1", () => {
+ async function optedIn() {
+ vi.stubEnv("OMB_ANTIGRAVITY_NATIVE_CLI", "1");
+ vi.resetModules();
+ return import("./antigravity-runtime.ts");
+ }
+
+ it("keeps running the pinned runtime until the CLI is installed, and the updater offers the move from its version", async () => {
+ const runtime = await optedIn();
+ const { baseDir } = computer();
+ await expect(runtime.resolveAntigravityRuntime("agy", { PATH: "" }, baseDir)).resolves.toMatchObject({ version: pinned!.version });
+ expect(await runtime.antigravityCliUpdate({ baseDir, now: Date.now() + 1e9, latest: latestRelease })).toBe(pinned!.version);
+ expect(await runtime.retirePinnedAntigravityRuntime({ baseDir, inUse: () => false })).toEqual([]);
+ });
+
+ it("runs the CLI once it is installed, and removes the pinned runtime only after an account signed in on it", async () => {
+ const runtime = await optedIn();
+ const before = computer({ cli: true });
+ await expect(runtime.resolveAntigravityRuntime("agy", { PATH: "" }, before.baseDir)).resolves.toMatchObject({ version: "1.5.15", harnessPath: null });
+ expect(await runtime.retirePinnedAntigravityRuntime({ baseDir: before.baseDir, inUse: () => false })).toEqual([]);
+ const after = computer({ cli: true, cliSignIn: true });
+ expect(await runtime.retirePinnedAntigravityRuntime({ baseDir: after.baseDir, inUse: () => false })).toEqual([pinned!.sha256]);
+ });
+});
diff --git a/server/drivers/antigravity-runtime-unsupported.test.ts b/server/drivers/antigravity-runtime-unsupported.test.ts
index eed95918c0..a0b28a7402 100644
--- a/server/drivers/antigravity-runtime-unsupported.test.ts
+++ b/server/drivers/antigravity-runtime-unsupported.test.ts
@@ -8,6 +8,12 @@ vi.mock("./antigravity-release.ts", async (importOriginal) => ({
resolveAntigravityReleaseAsset: () => null,
}));
+// Nor a native CLI build: no channel target for this platform.
+vi.mock("./antigravity-cli-release.ts", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./antigravity-cli-release.ts")>(),
+ antigravityCliTarget: () => null,
+}));
+
const { resolveAntigravityRuntime } = await import("./antigravity-runtime.ts");
describe("Antigravity on a platform Google publishes no runtime for", () => {
diff --git a/server/drivers/antigravity-runtime.ts b/server/drivers/antigravity-runtime.ts
index 37ecc3efba..ecff5004e8 100644
--- a/server/drivers/antigravity-runtime.ts
+++ b/server/drivers/antigravity-runtime.ts
@@ -1,3 +1,14 @@
+// Finding the Antigravity runtime to start, and installing Google's releases of it.
+//
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/AntigravityInstallation.ts:57, 311-345, 922-966,
+// 985-999 (a CLI needs no harness sibling, the hourly look at the channel,
+// and keeping an installed CLI that is newer than the channel's).
+// By default the pinned runtime, as before. With OMB_ANTIGRAVITY_NATIVE_CLI=1 (ANTIGRAVITY_NATIVE_CLI) the native CLI is
+// the runtime wherever Google's channel has a build: a computer that has the pinned runtime moves to it through the engine
+// updater, and the pinned one is removed once an account here has signed in on the CLI; the pinned runtime stays the
+// fallback where the channel has no build or cannot be reached. A saved `agy` path is never started.
import { createHash, randomUUID } from "node:crypto";
import {
access,
@@ -16,7 +27,10 @@ import {
import { constants } from "node:fs";
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
+import { execFile } from "node:child_process";
+
import { DATA_DIR } from "../config.ts";
+import { liveCliCommands, outsideBoxOptions } from "../procs.ts";
import { antigravityRuntimesRoot } from "../engine-roots.ts";
import { extractZipMember, readZipDirectory } from "../zip-archive.ts";
import { augmentedPath } from "../env-path.ts";
@@ -24,6 +38,16 @@ import {
resolveAntigravityReleaseAsset,
type AntigravityReleaseAsset,
} from "./antigravity-release.ts";
+import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";
+import {
+ ANTIGRAVITY_CLI_TOKEN_FILE,
+ ANTIGRAVITY_NATIVE_CLI,
+ activeAntigravityCli,
+ installAntigravityCli,
+ isAntigravityCliName,
+ pruneAntigravityCliReleases,
+} from "./antigravity-cli-install.ts";
+import { antigravityCliTarget, latestAntigravityCliRelease, type AntigravityCliReleaseAsset } from "./antigravity-cli-release.ts";
const FREE_SPACE_MARGIN = 256 * 1024 * 1024;
const DOWNLOAD_TIMEOUT_MS = 45 * 60_000;
@@ -61,9 +85,13 @@ export async function retryOnWindowsFileLock<T>(step: () => Promise<T>, options:
const INSTALL_RECORD = ".install-complete.json";
+const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
+const CLI_VERSION_PROBE_MS = 5_000;
+
export interface AntigravityRuntime {
executablePath: string;
- harnessPath: string;
+ /** Null for the native CLI, which embeds the harness and runs as `agy acp`. */
+ harnessPath: string | null;
source: "managed" | "override" | "path";
version: string | null;
}
@@ -86,7 +114,12 @@ interface InstallRecord {
export interface AntigravityInstallOptions {
baseDir?: string;
+ /** Naming a pinned release installs exactly that one, with no look at the native CLI's channel. */
asset?: AntigravityReleaseAsset | null;
+ /** The engine's CLI path asks for the native CLI: install it or fail, with no pinned runtime in its place. */
+ native?: boolean;
+ /** The native CLI release to install, instead of asking Google's channel. */
+ cliRelease?: AntigravityCliReleaseAsset | null;
fetchImpl?: typeof fetch;
validate?: (runtime: AntigravityRuntime, expectedVersion: string) => Promise<void>;
}
@@ -147,12 +180,41 @@ function pathCandidates(binary: string, env: NodeJS.ProcessEnv): string[] {
.map((part) => resolve(part, binary));
}
-async function externalRuntime(candidate: string, source: "override" | "path"): Promise<AntigravityRuntime | null> {
+const cliVersions = new Map<string, { stamp: string; version: string | null }>();
+
+/** The version a custom `antigravity` executable reports, when it is 1.5.0 or newer: only those serve ACP themselves. */
+async function nativeCliVersion(executablePath: string, env: NodeJS.ProcessEnv): Promise<string | null> {
+ const info = await stat(executablePath);
+ const stamp = `${info.size}:${info.mtimeMs}`;
+ const known = cliVersions.get(executablePath);
+ if (known?.stamp === stamp) return known.version;
+ // Security: the probe runs outside the bot box, so the program-trust rule decides whether it may run at all.
+ const options = outsideBoxOptions(executablePath, { env, timeout: CLI_VERSION_PROBE_MS, killSignal: "SIGKILL" as const, maxBuffer: 64 * 1024, windowsHide: true, encoding: "utf8" as const });
+ const output = await new Promise<string>((done) => {
+ execFile(executablePath, ["--version"], options, (error, stdout, stderr) => done(error ? "" : `${stdout}\n${stderr}`));
+ });
+ const triple = parseVersionTriple(output);
+ const version = triple && versionAtLeast(triple, [1, 5, 0]) ? triple.join(".") : null;
+ if (cliVersions.size >= 32) cliVersions.delete(cliVersions.keys().next().value!);
+ cliVersions.set(executablePath, { stamp, version });
+ return version;
+}
+
+async function externalRuntime(candidate: string, source: "override" | "path", env?: NodeJS.ProcessEnv): Promise<AntigravityRuntime | null> {
const names = executableNames();
const executablePath = resolve(candidate);
+ if (!(await executableFile(executablePath))) return null;
const harnessPath = join(dirname(executablePath), names.harness);
- if (!(await executableFile(executablePath)) || !(await executableFile(harnessPath))) return null;
- return { executablePath, harnessPath, source, version: null };
+ if (await executableFile(harnessPath)) return { executablePath, harnessPath, source, version: null };
+ if (!ANTIGRAVITY_NATIVE_CLI || env === undefined || !isAntigravityCliName(executablePath)) return null;
+ const version = await nativeCliVersion(executablePath, env);
+ return version === null ? null : { executablePath, harnessPath: null, source, version };
+}
+
+/** Whether the engine's CLI path asks for the native CLI this app installs: the bare name, as the CLI itself is named. */
+export function isAntigravityNativeAlias(cli: string | undefined): boolean {
+ const name = cli?.trim() ?? "";
+ return ANTIGRAVITY_NATIVE_CLI && !/[\\/]/u.test(name) && isAntigravityCliName(name);
}
/** Legacy `agy` commands (saved absolute paths, Windows shims) migrate without editing user config. */
@@ -163,18 +225,25 @@ export async function resolveAntigravityRuntime(
): Promise<AntigravityRuntime> {
const override = binaryPath?.trim();
const legacyCli = override !== undefined && /(?:^|[\\/])agy(?:\.(?:cmd|bat|exe|ps1))?$/iu.test(override);
- if (override && override !== "agy") {
+ const native = isAntigravityNativeAlias(override);
+ if (override && override !== "agy" && !native) {
for (const candidate of pathCandidates(override, env)) {
- const found = await externalRuntime(candidate, "override");
+ const found = await externalRuntime(candidate, "override", env);
if (found) return found;
}
if (!legacyCli) {
throw new AntigravitySetupError(
- "The custom Antigravity ACP executable or its localharness_external sibling is missing.",
+ `The custom Antigravity ACP executable or its localharness_external sibling is missing.${ANTIGRAVITY_NATIVE_CLI ? " The native CLI from 1.5.0 on, under its name antigravity, needs no sibling." : ""}`,
);
}
}
+ const installedCli = ANTIGRAVITY_NATIVE_CLI ? await activeAntigravityCli(runtimeRoot(baseDir)) : null;
+ if (installedCli) return installedCli;
+ if (native) {
+ throw new AntigravitySetupError("Antigravity's native CLI is not installed. Install the official Google runtime to continue, or set the CLI path back to agy.");
+ }
+ // Until the CLI is installed, a computer that has the pinned runtime keeps running it.
const asset = resolveAntigravityReleaseAsset();
if (asset) {
const managed = await completedRelease(join(runtimeRoot(baseDir), "versions", asset.sha256), asset);
@@ -185,7 +254,7 @@ export async function resolveAntigravityRuntime(
const found = await externalRuntime(candidate, "path");
if (found) return found;
}
- if (!asset) {
+ if (!antigravityManagedInstallAvailable()) {
throw new AntigravitySetupError(legacyCli
? `Antigravity no longer runs the agy command, and Google does not publish its official runtime for ${process.platform}-${process.arch}. Set the custom executable path to ${names.executable}, with ${names.harness} in the same folder.`
: `Google does not publish an Antigravity runtime for ${process.platform}-${process.arch}. Set a custom executable path.`);
@@ -220,10 +289,41 @@ async function extractPinnedArchive(
if (seen.size !== 2) throw new Error("The archive is missing an expected file.");
}
+/** Every install takes the native CLI, including on a computer that has the pinned runtime. Null when the pinned
+ * runtime is the one to install or keep: the CLI's own failure is thrown unless the pinned runtime can stand in (no
+ * CLI here yet, and Google publishes the pinned runtime for this platform). */
+async function installNativeCli(options: AntigravityInstallOptions, root: string): Promise<AntigravityRuntime | null> {
+ if (!ANTIGRAVITY_NATIVE_CLI || options.asset !== undefined) return null;
+ const pinned = resolveAntigravityReleaseAsset();
+ const active = await activeAntigravityCli(root);
+ try {
+ const release = options.cliRelease !== undefined ? options.cliRelease : await latestAntigravityCliRelease({ fetchImpl: options.fetchImpl });
+ if (!release) throw new Error("Could not find a native Antigravity CLI release. Check the network connection and try again.");
+ if (active?.version && isNewer(active.version, release.version)) {
+ await options.validate?.(active, active.version);
+ return active;
+ }
+ const installed = await installAntigravityCli(release, { root, fetchImpl: options.fetchImpl, validate: options.validate, retry: retryOnWindowsFileLock });
+ await pruneAntigravityCliReleases(root, runningFrom).catch(() => []);
+ return installed;
+ } catch (error) {
+ if (options.native || !pinned || active) throw error;
+ console.warn(`antigravity: the native CLI could not be installed (${error instanceof Error ? error.message : String(error)}); using the pinned runtime instead`);
+ return null;
+ }
+}
+
+function isNewer(version: string, than: string): boolean {
+ const left = parseVersionTriple(version), right = parseVersionTriple(than);
+ return left !== null && right !== null && versionAtLeast(left, right) && left.join(".") !== right.join(".");
+}
+
async function installOnce(options: AntigravityInstallOptions): Promise<AntigravityRuntime> {
+ const root = runtimeRoot(options.baseDir);
+ const cli = await installNativeCli(options, root);
+ if (cli) return cli;
const asset = options.asset === undefined ? resolveAntigravityReleaseAsset() : options.asset;
if (!asset) throw new Error(`Google does not publish an Antigravity runtime for ${process.platform}-${process.arch}.`);
- const root = runtimeRoot(options.baseDir);
const versions = join(root, "versions");
const destination = join(versions, asset.sha256);
await mkdir(versions, { recursive: true, mode: 0o700 });
@@ -336,7 +436,7 @@ async function installOnce(options: AntigravityInstallOptions): Promise<Antigrav
}
export function installAntigravityRuntime(options: AntigravityInstallOptions = {}): Promise<AntigravityRuntime> {
- const key = runtimeRoot(options.baseDir);
+ const key = `${runtimeRoot(options.baseDir)}\0${options.asset !== undefined ? "pinned" : options.native ? "native" : "default"}`;
const existing = installs.get(key);
if (existing) return existing;
const running = installOnce(options).finally(() => installs.delete(key));
@@ -344,6 +444,81 @@ export function installAntigravityRuntime(options: AntigravityInstallOptions = {
return running;
}
+let channelAnswer: { at: number; version: string } | undefined;
+
+/** The version installed here when the engine updater has something to install: a newer native CLI on Google's
+ * channel, or, on a computer that still runs the pinned runtime, the move to the CLI. The channel's answer is kept for
+ * an hour, so an update found while the engine is busy is still there on the next look; a channel that did not answer
+ * is asked again. */
+export async function antigravityCliUpdate(options: {
+ baseDir?: string; now?: number; latest?: () => Promise<AntigravityCliReleaseAsset | null>; asset?: AntigravityReleaseAsset | null;
+} = {}): Promise<string | null> {
+ if (!ANTIGRAVITY_NATIVE_CLI) return null;
+ const root = runtimeRoot(options.baseDir);
+ const active = await activeAntigravityCli(root);
+ const pinned = options.asset === undefined ? resolveAntigravityReleaseAsset() : options.asset;
+ const current = active?.version
+ ?? (pinned && (await completedRelease(join(root, "versions", pinned.sha256), pinned)) ? pinned.version : null)
+ ?? await antigravityOlderRuntime(options.baseDir, pinned);
+ if (!current) return null;
+ const now = options.now ?? Date.now();
+ if (channelAnswer === undefined || now - channelAnswer.at >= UPDATE_CHECK_INTERVAL_MS || now < channelAnswer.at) {
+ const latest = await (options.latest ?? latestAntigravityCliRelease)();
+ if (!latest) return null;
+ channelAnswer = { at: now, version: latest.version };
+ }
+ if (!active) return current;
+ return active.version && isNewer(channelAnswer.version, active.version) ? active.version : null;
+}
+
+/** Whether a process this server started runs a program from `directory`. */
+function runningFrom(directory: string): boolean {
+ const root = resolve(directory);
+ for (const line of liveCliCommands()) {
+ if (line.some((part) => typeof part === "string" && resolve(part).startsWith(root))) return true;
+ }
+ return false;
+}
+
+/** Whether an account here holds a sign-in the native CLI wrote: proof the CLI signs in on this computer. */
+async function cliSignedInHere(baseDir: string): Promise<boolean> {
+ const profiles = join(baseDir, "providers", "antigravity");
+ for (const name of await readdir(profiles).catch(() => [] as string[])) {
+ const info = await stat(join(profiles, name, "antigravity-acp", ANTIGRAVITY_CLI_TOKEN_FILE)).catch(() => null);
+ if (info?.isFile() && info.size > 0) return true;
+ }
+ return false;
+}
+
+/** Removes the pinned runtime (about 1 GB on Linux) once the switch to the native CLI has worked here: the switch is on,
+ * the CLI is installed and whole, an account signed in on it, and no process runs the pinned runtime. Nothing is removed
+ * with the switch off; turning it off later downloads the pinned runtime again. The folders it removed. */
+export async function retirePinnedAntigravityRuntime(options: { baseDir?: string; inUse?: (directory: string) => boolean } = {}): Promise<string[]> {
+ if (!ANTIGRAVITY_NATIVE_CLI) return [];
+ const baseDir = options.baseDir ?? DATA_DIR;
+ const root = runtimeRoot(baseDir);
+ if (!(await activeAntigravityCli(root)) || !(await cliSignedInHere(baseDir))) return [];
+ const versions = join(root, "versions");
+ const removed: string[] = [];
+ for (const name of await readdir(versions).catch(() => [] as string[])) {
+ const directory = join(versions, name);
+ let record: Partial<InstallRecord> | null = null;
+ try {
+ record = JSON.parse(await readFile(join(directory, INSTALL_RECORD), "utf8")) as Partial<InstallRecord>;
+ } catch {}
+ // Only a pinned runtime: its record names its harness and its folder is its SHA-256.
+ if (!record || record.sha256 !== name || !record.harness || (options.inUse ?? runningFrom)(directory)) continue;
+ try {
+ await retryOnWindowsFileLock(() => rm(directory, { recursive: true, force: true }));
+ removed.push(name);
+ console.warn(`antigravity: removed the pinned ${record.version ?? ""} runtime now that the native CLI runs here`);
+ } catch (error) {
+ console.warn(`antigravity: could not remove the pinned runtime (${error instanceof Error ? error.message : String(error)})`);
+ }
+ }
+ return removed;
+}
+
/** The newest runtime the app installed here, when it is not the pinned one; null when the pinned one is installed or none is. */
export async function antigravityOlderRuntime(baseDir = DATA_DIR, asset = resolveAntigravityReleaseAsset()): Promise<string | null> {
if (!asset) return null;
@@ -360,5 +535,5 @@ export async function antigravityOlderRuntime(baseDir = DATA_DIR, asset = resolv
}
export function antigravityManagedInstallAvailable(): boolean {
- return resolveAntigravityReleaseAsset() !== null;
+ return resolveAntigravityReleaseAsset() !== null || (ANTIGRAVITY_NATIVE_CLI && antigravityCliTarget(process.platform, process.arch) !== null);
}
diff --git a/server/drivers/antigravity-turn-outcome.test.ts b/server/drivers/antigravity-turn-outcome.test.ts
index 33f175c498..2c82bd3025 100644
--- a/server/drivers/antigravity-turn-outcome.test.ts
+++ b/server/drivers/antigravity-turn-outcome.test.ts
@@ -2,7 +2,7 @@
// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
// - apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts (the error
// payload fixtures and the cases of the two reader tests).
-import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
@@ -39,6 +39,16 @@ const UNAVAILABLE_ERROR = errorText("Error 503, Message: The service is currentl
const TIMESTAMP_ERROR = errorText(
"Error 429, Message: Quota exhausted., Status: RESOURCE_EXHAUSTED, Details: [map[metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-20T10:00:00Z] reason:QUOTA_EXHAUSTED]]",
);
+// Adapted from pingdotgg/t3code@f9a3c38c505 and f68d36d8aa9 (AntigravityTurnOutcome.test.ts fixtures).
+const MISSING_SIGNATURE_ERROR = errorText(
+ 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"}}, Status: INVALID_ARGUMENT, Details: []',
+);
+const INVALID_SIGNATURE_ERROR = errorText(
+ 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.3.content.0: Invalid `signature` in `thinking` block"}}, Status: INVALID_ARGUMENT, Details: []',
+);
+const NOT_FOUND_ERROR = errorText("Error 404, Message: Requested entity was not found., Status: NOT_FOUND, Details: []");
+// Antigravity 1.5 with a Google account writes "STATUS (code NNN): message", then the HTTP body.
+const STATUS_NOT_FOUND_ERROR = '\u00127NOT_FOUND (code 404): Requested entity was not found.\u001a\u0080\u0001HTTP 404 Not Found\n\n{"error":{"code":404,"message":"Requested entity was not found.","status":"NOT_FOUND"}}';
// The model's reply quoting the agent's quota notice is an ordinary planner response.
const QUOTED_NOTICE = "Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.";
@@ -127,6 +137,33 @@ describe("watchAntigravityPromptOutcome", () => {
expect(refusal!.facts.limitResetsAt).toBeUndefined();
});
+ it("reads a lost thinking signature as a broken session, a 404 by when it came, and restarts the runtime after any of them", async () => {
+ const { directory, conversations } = profile();
+ const sessionId = "4c2b7d1e-5472-4277-b6ee-27b2e05570a7";
+ const turn = async (steps: ReadonlyArray<readonly [number, string]>) => {
+ const check = await watchAntigravityPromptOutcome(NAME, directory, sessionId, () => 0);
+ append(join(conversations, `${sessionId}.db`), steps);
+ return check({ stopReason: "end_turn" });
+ };
+ expect(await turn([[USER_INPUT, "hello"], [PLANNER_RESPONSE, "fine"]])).toBeUndefined();
+ for (const error of [MISSING_SIGNATURE_ERROR, INVALID_SIGNATURE_ERROR]) {
+ expect(await turn([[USER_INPUT, "again"], [ERROR_MESSAGE, error]])).toMatchObject({
+ acpSessionBroken: true, acpSessionFailure: true, acpUsageLimit: false,
+ message: `${NAME}'s saved conversation can no longer be sent to the model. The next message starts a fresh ${NAME} session with this conversation's context.`,
+ });
+ }
+ // After the model answered in this turn, a 404 in either form is a temporary edge error.
+ for (const error of [NOT_FOUND_ERROR, STATUS_NOT_FOUND_ERROR]) {
+ const failure = await turn([[USER_INPUT, "go"], [PLANNER_RESPONSE, "working"], [TOOL, "ran"], [ERROR_MESSAGE, error]]);
+ expect(failure).toMatchObject({ acpSessionFailure: true, message: expect.stringContaining("temporary server problem (HTTP 404") });
+ expect(failure).not.toHaveProperty("acpSessionBroken");
+ }
+ // Before the model answered, it is an unknown or unentitled model.
+ expect((await turn([[USER_INPUT, "go"], [ERROR_MESSAGE, STATUS_NOT_FOUND_ERROR]]))!.message).toContain("stopped with an error (HTTP 404");
+ expect(await turn([[USER_INPUT, "go"], [ERROR_MESSAGE, INVALID_ARGUMENT_ERROR]])).toMatchObject({ acpSessionFailure: true });
+ expect(await turn([[USER_INPUT, "go"], [ERROR_MESSAGE, QUOTA_ERROR]])).toMatchObject({ acpSessionFailure: true, acpUsageLimit: true });
+ });
+
it.skipIf(process.platform === "win32")("reads only this session's own unlinked log, and keeps a typed refusal", async () => {
const { directory, conversations } = profile();
const own = "e6aba774-5472-4277-b6ee-27b2e05570a7";
@@ -239,6 +276,30 @@ describe("an Antigravity turn whose reply was an upstream failure", () => {
expect(later.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
}, 90_000);
+ it("starts the turn after a lost thinking signature in a fresh session, from this conversation's context, in a new process", async () => {
+ const { created, directory, stepsFile } = await instance("antigravity-outcome-signature", [[USER_INPUT, "hello"], [ERROR_MESSAGE, INVALID_SIGNATURE_ERROR]]);
+ const rpc = join(directory, "rpc.jsonl");
+ process.env.FAKE_ACP_RPC_APPEND_FILE = rpc;
+ try {
+ const recorder = recordEvents(created.adapter);
+ const { turnId } = await created.adapter.sendTurn({ threadId: "signature", text: "hello", model: "gemini-3.8-flash", approvalMode: "full", cwd: directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: false });
+ const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId) as { sessionId: string };
+ writeFileSync(stepsFile, JSON.stringify([[USER_INPUT, "again"], [PLANNER_RESPONSE, "fine"]]));
+ const next = await created.adapter.sendTurn({
+ threadId: "signature", text: "again", approvalMode: "full", cwd: directory,
+ resumeCursor: started.sessionId, recoveryText: "Person: hello\nBot: (failed)",
+ });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === next.turnId)).toMatchObject({ ok: true });
+ const calls = readFileSync(rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { pid: number; method: string });
+ const second = calls.filter((call) => call.pid !== calls[0]!.pid);
+ expect(second.map((call) => call.method)).toContain("session/new");
+ expect(second.map((call) => call.method)).not.toContain("session/resume");
+ } finally {
+ delete process.env.FAKE_ACP_RPC_APPEND_FILE;
+ }
+ }, 90_000);
+
it("leaves a normal reply, and a runtime that keeps no log, alone", async () => {
for (const [instanceId, steps] of [["antigravity-outcome-fine", [[USER_INPUT, "hello"], [PLANNER_RESPONSE, "fine"]]], ["antigravity-outcome-no-log", null]] as const) {
const { created, directory } = await instance(instanceId, steps as Array<[number, string]> | null);
diff --git a/server/drivers/antigravity-turn-outcome.ts b/server/drivers/antigravity-turn-outcome.ts
index b0d1c3770f..22db939e6b 100644
--- a/server/drivers/antigravity-turn-outcome.ts
+++ b/server/drivers/antigravity-turn-outcome.ts
@@ -7,7 +7,16 @@
// the quota and reset patterns, and the before and after reads of the
// session's own unlinked log);
// - apps/server/src/provider/acp/AntigravityProfilePaths.ts (the proof that
-// no component of a path below the profile is a link).
+// no component of a path below the profile is a link);
+// - from pingdotgg/t3code@f9a3c38c505: a lost thinking signature marks the
+// session broken, and the next turn starts a fresh one from this
+// conversation's context instead of resuming it;
+// - from pingdotgg/t3code@f68d36d8aa9: the 1.5 "STATUS (code NNN): message"
+// form, and a 404 after the model already answered in this turn counted
+// as a temporary server error, not a refusal (the one resend T3 sends then
+// rides its 1.5 steering and is not ported);
+// - every failure found this way restarts the runtime before the next turn,
+// as T3 Code does after any hidden failure.
// The failure is a plain error for the shared ACP runtime to throw, worded as every engine's usage limit is. A reset
// time is taken only inside the coming eight days, and a log or step too large to read quickly is not read.
import type { Stats } from "node:fs";
@@ -20,11 +29,18 @@ import { engineFailure } from "./engine-errors.ts";
// CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory.
const ERROR_STEP_TYPE = 17;
+// CORTEX_STEP_TYPE_PLANNER_RESPONSE: the model answered within this turn.
+const PLANNER_RESPONSE_STEP_TYPE = 15;
// The harness error text leads the payload; a Go stack trace follows it.
const MAX_ERROR_PAYLOAD_BYTES = 16_384;
// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.
const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;
+// Antigravity 1.5 with a Google account writes "STATUS (code NNN): message".
+const STATUS_ERROR = /(?<![A-Z_])([A-Z_]+) \(code (\d{3})\): (\P{Cc}+)/u;
const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
+// Claude rejects a saved thinking block without a valid signature. It sits in the native history, so every later prompt
+// to that session fails the same way.
+const INVALID_THINKING_SIGNATURE = /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/;
const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
// google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset.
@@ -51,6 +67,8 @@ const CONVERSATION_SEGMENTS = ["antigravity-acp", "conversations"];
interface LastStep {
type: number;
payload: Uint8Array | null;
+ /** A planner response step came before it in this turn: the model had answered. */
+ reachedModel?: boolean;
}
export type AntigravityPromptCheck = (result: unknown) => Promise<AcpReportedFailure | undefined>;
@@ -97,7 +115,8 @@ const lastStepAfter = (index: number) => (database: DatabaseSync): LastStep | un
if (typeof row?.type !== "number") return undefined;
if (row.type !== ERROR_STEP_TYPE || typeof row.bytes !== "number" || row.bytes > MAX_STEP_BYTES) return { type: row.type, payload: null };
const payload = database.prepare("SELECT substr(step_payload, 1, ?) AS payload FROM steps WHERE idx = ?").get(MAX_ERROR_PAYLOAD_BYTES, row.idx)?.payload;
- return { type: row.type, payload: payload instanceof Uint8Array ? payload : null };
+ const reachedModel = database.prepare("SELECT 1 FROM steps WHERE idx > ? AND step_type = ? LIMIT 1").get(index, PLANNER_RESPONSE_STEP_TYPE) !== undefined;
+ return { type: row.type, payload: payload instanceof Uint8Array ? payload : null, reachedModel };
};
function resetAtFrom(text: string, now: number): number | undefined {
@@ -135,6 +154,17 @@ function usageLimit(provider: string, text: string, now: number, timeZone?: stri
return new AcpReportedFailure({ ...failure, ...(resetsAt === undefined ? {} : { limitResetsAt: resetsAt }) }, true);
}
+/** Reorders STATUS_ERROR's groups to API_ERROR's: HTTP status, message, status name. */
+function statusError(text: string): readonly [string, string, string, string] | null {
+ const match = STATUS_ERROR.exec(text);
+ return match === null ? null : [match[0], match[2]!, match[3]!, match[1]!];
+}
+
+/** Any failure read from the session log restarts the runtime before the next turn; a broken session is not resumed. */
+function restarting(failure: AcpReportedFailure, broken = false): AcpReportedFailure {
+ return Object.assign(failure, { acpSessionFailure: true }, broken ? { acpSessionBroken: true } : {});
+}
+
/** The failure a prompt's result and the last step it added stand for; undefined for a normal reply. */
export function antigravityTurnFailure(
provider: string,
@@ -147,13 +177,18 @@ export function antigravityTurnFailure(
// The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
if (errorText === undefined && stopReason !== "refusal") return undefined;
const text = errorText ?? "";
- const apiError = API_ERROR.exec(text);
- if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) return usageLimit(provider, text, now, timeZone);
- if (apiError === null) return new AcpReportedFailure(engineFailure(provider, "", { kind: "refused", status: null })!, false);
+ const apiError = API_ERROR.exec(text) ?? statusError(text);
+ if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) return restarting(usageLimit(provider, text, now, timeZone));
+ if (INVALID_THINKING_SIGNATURE.test(text)) {
+ return restarting(new AcpReportedFailure({ message: `${provider}'s saved conversation can no longer be sent to the model. The next message starts a fresh ${provider} session with this conversation's context.` }, false), true);
+ }
+ if (apiError === null) return restarting(new AcpReportedFailure(engineFailure(provider, "", { kind: "refused", status: null })!, false));
const [, httpStatus, message, status] = apiError;
- if (httpStatus === "429" || status === "RESOURCE_EXHAUSTED") return usageLimit(provider, text, now, timeZone);
+ if (httpStatus === "429" || status === "RESOURCE_EXHAUSTED") return restarting(usageLimit(provider, text, now, timeZone));
const http = Number(httpStatus);
- return new AcpReportedFailure(engineFailure(provider, message!.trim(), { kind: http >= 500 ? "server" : "refused", status: http })!, false);
+ // A 404 before the model answered is an unknown or unentitled model; after, a transient edge error.
+ const transient = http >= 500 || (http === 404 && step?.reachedModel === true);
+ return restarting(new AcpReportedFailure(engineFailure(provider, message!.trim(), { kind: transient ? "server" : "refused", status: http })!, false));
}
/**
diff --git a/server/drivers/antigravity-usage-limits.test.ts b/server/drivers/antigravity-usage-limits.test.ts
index b55a373072..bd3a533462 100644
--- a/server/drivers/antigravity-usage-limits.test.ts
+++ b/server/drivers/antigravity-usage-limits.test.ts
@@ -103,6 +103,26 @@ afterEach(async () => {
});
describe("Antigravity subscription limits", () => {
+ it("reads the native CLI's sign-in with its own access token while it is fresh, and nothing once it is stale", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-usage-cli-"));
+ scratch.push(directory);
+ const tokenPath = join(directory, "antigravity-oauth-token");
+ const now = at("2026-11-23T12:00:00Z");
+ writeFileSync(tokenPath, JSON.stringify({ token: { access_token: "cli-access", refresh_token: "cli-refresh", expiry: "2026-11-23T12:30:00Z" } }));
+ const asked: Array<{ url: string; authorization?: string; body?: string }> = [];
+ const fetch: PlanFetch = async (url, init) => {
+ asked.push({ url, authorization: init.headers?.Authorization, body: init.body });
+ return { ok: true, status: 200, text: async () => JSON.stringify(summary) };
+ };
+ expect((await readAntigravityUsageWindows(tokenPath, { fetch, now: () => now })).map((window) => window.id)).toContain("gemini-5h");
+ // No refresh: the file names no OAuth client. The CLI refreshes it itself.
+ expect(asked.some((request) => request.url.endsWith("/token"))).toBe(false);
+ expect(asked.every((request) => request.authorization === "Bearer cli-access" && request.body === "{}")).toBe(true);
+ asked.length = 0;
+ expect(await readAntigravityUsageWindows(tokenPath, { fetch, now: () => at("2026-11-23T12:29:30Z") })).toEqual([]);
+ expect(asked).toEqual([]);
+ });
+
it("omits rolling resets for untouched summary buckets and keeps used Gemini resets", async () => {
const { windows } = fixture({
now: at("2026-10-21T10:16:04Z"),
diff --git a/server/drivers/antigravity-usage-limits.ts b/server/drivers/antigravity-usage-limits.ts
index 88a730eb9f..b2a58b00f7 100644
--- a/server/drivers/antigravity-usage-limits.ts
+++ b/server/drivers/antigravity-usage-limits.ts
@@ -5,6 +5,9 @@
// - apps/server/src/provider/antigravityUsageLimits.ts (the endpoints and
// their order, the request's client line, the summary and per-model
// quota readers, the untouched-bucket reset rule, and the access cache).
+// - apps/server/src/provider/antigravityUsageLimits.ts:43-51, 331-392 at
+// 38067630229 (the native CLI's sign-in file, read only while its access
+// token is fresh, since it stores no OAuth client to refresh it with).
// Only the personal Google sign-in is read, the account fingerprint is left out, and every failure is no row at all.
//
// Security: the access token lives in this module's memory and in request headers only. It is never logged, written or
@@ -12,9 +15,11 @@
import { createHash } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
+import { ANTIGRAVITY_NATIVE_CLI } from "./antigravity-cli-install.ts";
+
import type { PlanExtra, PlanFetch, PlanModelUsage, PlanWindow, PlanWindows } from "../plan-usage.ts";
-import { antigravityTokenPath } from "./antigravity-acp.ts";
-import { refreshAntigravityAccess } from "./antigravity-account.ts";
+import { antigravityCliTokenPath, antigravityTokenPath } from "./antigravity-acp.ts";
+import { antigravityCliAccessToken, refreshAntigravityAccess } from "./antigravity-account.ts";
import { antigravityQuotaFamily } from "./antigravity-turn-outcome.ts";
/** Whether Antigravity accounts are asked for their limits at all. Off, they have no row in the usage report. */
@@ -226,10 +231,13 @@ interface StoredSignIn {
project_id?: string;
}
-async function storedSignIn(tokenPath: string): Promise<{ signIn: StoredSignIn; fingerprint: string } | null> {
+async function storedSignIn(tokenPath: string, now: number): Promise<{ signIn: StoredSignIn; fingerprint: string } | { cliAccess: string } | null> {
const info = await stat(tokenPath);
if (!info.isFile() || info.size > TOKEN_FILE_MAX_BYTES) return null;
- const fields = record(JSON.parse(await readFile(tokenPath, "utf8")));
+ const parsed = JSON.parse(await readFile(tokenPath, "utf8"));
+ const cli = antigravityCliAccessToken(parsed, now);
+ if (cli) return { cliAccess: cli.accessToken };
+ const fields = record(parsed);
if (!fields || !["client_id", "client_secret", "refresh_token"].every((key) => typeof fields[key] === "string" && fields[key])) return null;
const signIn: StoredSignIn = {
client_id: fields.client_id as string, client_secret: fields.client_secret as string, refresh_token: fields.refresh_token as string,
@@ -277,15 +285,17 @@ const refreshHolds = new Map<string, { fingerprint: string; until: number }>();
/** The windows Google reports for the sign-in stored at `tokenPath`; empty when it reports none. Throws on any failure.
* Every request shares `signal`, the one deadline of the whole read. */
export async function readAntigravityUsageWindows(tokenPath: string, deps: AntigravityUsageDeps, signal: AbortSignal = AbortSignal.timeout(deps.timeoutMs ?? READ_DEADLINE_MS)): Promise<AntigravityUsageWindow[]> {
- const stored = await storedSignIn(tokenPath).catch(() => null);
+ const now = deps.now ?? Date.now;
+ const stored = await storedSignIn(tokenPath, now()).catch(() => null);
if (!stored) {
cachedAccess.delete(tokenPath);
return [];
}
- const now = deps.now ?? Date.now;
- const { signIn, fingerprint } = stored;
- let cached = cachedAccess.get(tokenPath);
- if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now() + 60_000) {
+ // The native CLI's token is used as it is: the CLI refreshes it while it runs.
+ const signIn: StoredSignIn | null = "cliAccess" in stored ? null : stored.signIn;
+ let cached = "cliAccess" in stored ? { fingerprint: "", accessToken: stored.cliAccess, expiresAt: Infinity } : cachedAccess.get(tokenPath);
+ if (signIn && "fingerprint" in stored && (cached?.fingerprint !== stored.fingerprint || cached.expiresAt <= now() + 60_000)) {
+ const { fingerprint } = stored;
cachedAccess.delete(tokenPath);
const held = refreshHolds.get(tokenPath);
if (held?.fingerprint === fingerprint && now() < held.until) throw new Error("held");
@@ -306,9 +316,9 @@ export async function readAntigravityUsageWindows(tokenPath: string, deps: Antig
if (cachedAccess.size >= 128) cachedAccess.delete(cachedAccess.keys().next().value!);
cachedAccess.set(tokenPath, cached);
}
- const { accessToken } = cached;
+ const { accessToken } = cached!;
const headers = { Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(process.platform, process.arch), "content-type": "application/json" };
- const body = JSON.stringify(signIn.project_id ? { project: signIn.project_id } : {});
+ const body = JSON.stringify(signIn?.project_id ? { project: signIn.project_id } : {});
// Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
const fetchWindows = async (operation: string, parse: (response: unknown, requestedAt: number) => AntigravityUsageWindow[]) => {
const responses = await Promise.all(PERSONAL_ENDPOINTS.map(async (endpoint) => {
@@ -333,10 +343,14 @@ export async function readAntigravityUsageWindows(tokenPath: string, deps: Antig
export async function antigravityPlanUsage(
instanceId: string,
deps: AntigravityUsageDeps,
- tokenPath = antigravityTokenPath(instanceId),
+ tokenPath?: string,
enabled = ANTIGRAVITY_USAGE_LIMITS,
): Promise<PlanWindows | null> {
if (!enabled) return null;
+ // The sign-in of the runtime in use: the native CLI's while it runs, else the pinned runtime's.
+ tokenPath ??= ANTIGRAVITY_NATIVE_CLI && await stat(antigravityCliTokenPath(instanceId)).then((info) => info.size > 0, () => false)
+ ? antigravityCliTokenPath(instanceId)
+ : antigravityTokenPath(instanceId);
try {
// One deadline for the refresh, the summary and the fallback together.
const windows = await readAntigravityUsageWindows(tokenPath, deps, AbortSignal.timeout(deps.timeoutMs ?? READ_DEADLINE_MS));
diff --git a/server/drivers/antigravity.test.ts b/server/drivers/antigravity.test.ts
index e436d84d01..97b66c7f72 100644
--- a/server/drivers/antigravity.test.ts
+++ b/server/drivers/antigravity.test.ts
@@ -5,6 +5,8 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, ensureDirs } from "../config.ts";
+import { startupModelCachePath } from "../startup-model-catalog.ts";
+import { recentTurnStarts } from "../perf/turn-starts.ts";
import { TurnNotStartedError, type ProviderInstance } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { removeTempDir } from "../testing/cleanup.ts";
@@ -719,7 +721,7 @@ describe("official Antigravity runtime", () => {
expect(installAntigravityRuntime(options)).toBe(first);
const installed = await first;
expect(readFileSync(installed.executablePath, "utf8")).toBe("#!/bin/sh\nexit 0\n");
- expect(readFileSync(installed.harnessPath, "utf8")).toBe("#!/bin/sh\nexit 0\n");
+ expect(readFileSync(installed.harnessPath!, "utf8")).toBe("#!/bin/sh\nexit 0\n");
await installAntigravityRuntime(options);
expect(fetches).toBe(1);
expect(validations).toBe(2);
@@ -881,7 +883,8 @@ describe("Antigravity driver over shared ACP", () => {
it("uses managed setup and defaults to approval cards", () => {
expect(AntigravityDriver.defaultConfig()).toEqual({ cli: "agy", fullAuto: false, workspace: undefined });
expect(AntigravityDriver.install?.docsUrl).toContain("antigravity-acp");
- if (resolveAntigravityReleaseAsset()) expect(AntigravityDriver.install?.managed?.downloadBytes).toBeGreaterThan(0);
+ // The native CLI is opt-in: by default the card offers the pinned runtime with its download size, as before it.
+ expect(AntigravityDriver.install?.managed).toEqual({ label: "Install official Antigravity", downloadBytes: resolveAntigravityReleaseAsset()?.archiveBytes ?? 0 });
expect(antigravityPermissionMode(false)).toBe("default");
expect(antigravityPermissionMode(false, "ask")).toBe("default");
expect(antigravityPermissionMode(false, "auto")).toBe("default");
@@ -1163,6 +1166,186 @@ describe("Antigravity driver over shared ACP", () => {
]);
});
+ it("sends an unchanged permission mode and thinking level once per live session, and a change at once", async () => {
+ ensureDirs();
+ const fake = fakeRuntime();
+ const dump = join(fake.directory, "dump.json");
+ const instanceId = "antigravity-config-once";
+ const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
+ mkdirSync(tokenDirectory, { recursive: true });
+ writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
+ const levels = [{ value: "low", name: "Low" }, { value: "high", name: "High" }];
+ instance = await AntigravityDriver.create({
+ instanceId,
+ displayName: "Antigravity",
+ environment: {
+ FAKE_ACP_AUTH_METHOD: "oauth-personal",
+ FAKE_ACP_MODELS: "gemini-3.8-flash",
+ FAKE_ACP_VARIANTS: JSON.stringify({ "gemini-3.8-flash": { id: "thought_level", currentValue: "low", options: levels } }),
+ FAKE_ACP_MODES: "default,yolo,auto_edit",
+ FAKE_ACP_DUMP: dump,
+ },
+ enabled: true,
+ config: { cli: fake.executable, fullAuto: false },
+ });
+ await instance.startupModelRefresh;
+ recorder = recordEvents(instance.adapter);
+ const configCalls = () => (JSON.parse(readFileSync(`${dump}.config.json`, "utf8")) as Array<{ params: { configId: string; value: string } }>)
+ .map((call) => [call.params.configId, call.params.value]);
+ const run = async (approvalMode: "ask" | "full", variant: string, extra: { sessionReset?: true } = {}) => {
+ const { turnId } = await instance!.adapter.sendTurn({
+ threadId: "thread-config-once", text: "hello", approvalMode, model: "gemini-3.8-flash", variant, cwd: fake.directory,
+ resumeCursor: "fake-acp-session", ...extra,
+ });
+ expect(await recorder!.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: true });
+ };
+ await run("ask", "high");
+ await run("ask", "high");
+ await run("ask", "high");
+ expect(configCalls()).toEqual([["mode", "default"], ["thought_level", "high"]]);
+ await run("full", "high");
+ await run("full", "low");
+ await run("full", "low");
+ expect(configCalls()).toEqual([["mode", "default"], ["thought_level", "high"], ["mode", "yolo"], ["thought_level", "low"]]);
+ // A reset session (here in a new process, whose record starts empty) confirms nothing yet: both are sent again.
+ await run("full", "low", { sessionReset: true });
+ expect(configCalls()).toEqual([["mode", "yolo"], ["thought_level", "low"]]);
+ await run("full", "low");
+ expect(configCalls()).toEqual([["mode", "yolo"], ["thought_level", "low"]]);
+ });
+
+ describe("after a restart with a saved model list from another build", () => {
+ const levels = [{ value: "low", name: "Low" }, { value: "high", name: "High" }];
+ const seed = (instanceId: string, models: string[]) => {
+ ensureDirs();
+ writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify([{ id: "bot-restart" }]));
+ const path = startupModelCachePath(instanceId)!;
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, JSON.stringify({ default: models[0], options: models.map((id) => ({ id, label: id })), checkedAt: Date.now() - 60_000, build: "0.0.0-older" }));
+ const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
+ mkdirSync(tokenDirectory, { recursive: true });
+ writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
+ };
+ afterEach(() => rmSync(join(DATA_DIR, "bots.json"), { force: true }));
+
+ it("runs the first turn on the saved list while the list is read again in the background", async () => {
+ const fake = fakeRuntime();
+ seed("antigravity-restart-standin", ["gemini-3.8-flash", "gemini-4-argon"]);
+ instance = await AntigravityDriver.create({
+ instanceId: "antigravity-restart-standin",
+ displayName: "Antigravity",
+ environment: {
+ FAKE_ACP_AUTH_METHOD: "oauth-personal",
+ FAKE_ACP_MODELS: "gemini-3.8-flash,gemini-4-argon",
+ FAKE_ACP_VARIANTS: JSON.stringify({ "gemini-3.8-flash": { id: "thought_level", currentValue: "low", options: levels } }),
+ FAKE_ACP_MODES: "default,yolo",
+ // The background read's thinking-level survey hangs on this model until its budget runs out.
+ FAKE_ACP_HANG_ON_MODEL: "gemini-4-argon",
+ },
+ enabled: true,
+ config: { cli: fake.executable, fullAuto: false },
+ });
+ expect(instance.startupModelRefresh).toBeDefined();
+ let refreshed = false;
+ const refresh = instance.startupModelRefresh!.then(() => { refreshed = true; });
+ recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-restart", text: "hello", approvalMode: "ask", model: "gemini-3.8-flash", variant: "high", cwd: fake.directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 8_000)).toMatchObject({ ok: true });
+ expect(refreshed).toBe(false);
+ await refresh;
+ }, 40_000);
+
+ it("reads the list and tries once more when the agent refuses a model the stale list still named", async () => {
+ const fake = fakeRuntime();
+ const rpc = join(fake.directory, "rpc.jsonl");
+ seed("antigravity-restart-stale", ["gemini-retired", "gemini-3.8-flash"]);
+ instance = await AntigravityDriver.create({
+ instanceId: "antigravity-restart-stale",
+ displayName: "Antigravity",
+ environment: {
+ FAKE_ACP_AUTH_METHOD: "oauth-personal",
+ FAKE_ACP_MODELS: "gemini-3.8-flash",
+ FAKE_ACP_MODES: "default,yolo",
+ FAKE_ACP_RPC_APPEND_FILE: rpc,
+ FAKE_ACP_DUMP: join(fake.directory, "dump.json"),
+ },
+ enabled: true,
+ config: { cli: fake.executable, fullAuto: false },
+ });
+ recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-stale", text: "hello", approvalMode: "ask", model: "gemini-retired", cwd: fake.directory });
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 15_000)).toMatchObject({ ok: false });
+ await instance.startupModelRefresh;
+ // The stale id never reached the runtime as its unchecked launch default.
+ expect(JSON.parse(readFileSync(join(fake.directory, "dump.json"), "utf8")).env.AGY_ACP_DEFAULT_MODEL).toBeUndefined();
+ const turnSelects = readFileSync(rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { method: string; cwd: string })
+ .filter((line) => line.method === "session/set_config_option" && realpathSync(line.cwd) === realpathSync(fake.directory));
+ expect(turnSelects).toHaveLength(2);
+ expect(instance.models.options.map((option) => option.id)).not.toContain("gemini-retired");
+ expect(recorder.events.filter((event) => event.type === "turn.started")).toHaveLength(1);
+ }, 40_000);
+ });
+
+ it("writes one start-timing line per turn: a cold one, a warm one, and one refused for sign-in", async () => {
+ ensureDirs();
+ const fake = fakeRuntime();
+ const instanceId = "antigravity-turn-starts";
+ const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
+ mkdirSync(tokenDirectory, { recursive: true });
+ writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
+ instance = await AntigravityDriver.create({
+ instanceId, displayName: "Antigravity", enabled: true, config: { cli: fake.executable, fullAuto: false },
+ environment: { FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "gemini-3.8-flash", FAKE_ACP_MODES: "default,yolo" },
+ });
+ await instance.startupModelRefresh;
+ recorder = recordEvents(instance.adapter);
+ const run = async () => {
+ const { turnId } = await instance!.adapter.sendTurn({ threadId: "thread-starts", text: "hello", approvalMode: "ask", model: "gemini-3.8-flash", cwd: fake.directory, resumeCursor: "fake-acp-session" });
+ await recorder!.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ return recentTurnStarts().at(-1)!;
+ };
+ expect(await run()).toMatch(/^\[perf\] engine turn antigravityAgent: new process, models waited \d+ ms, spawn to initialize \d+ ms, authenticate \d+ ms, session (?:new|resume) \d+ ms, config 1 call \d+ ms, prompt to first update \d+ ms, total \d+ ms, ended end_turn$/u);
+ expect(await run()).toMatch(/^\[perf\] engine turn antigravityAgent: kept process, models waited \d+ ms, session live, config 0 calls 0 ms, prompt to first update \d+ ms, total \d+ ms, ended end_turn$/u);
+ rmSync(join(tokenDirectory, "acp_token.json"));
+ expect(await run()).toMatch(/: no process, .*no prompt, total \d+ ms, ended auth_required$/u);
+ });
+
+ it("ends a stale-model turn at once when the person stops it while the model list is read", async () => {
+ ensureDirs();
+ writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify([{ id: "bot-restart" }]));
+ try {
+ const fake = fakeRuntime();
+ const instanceId = "antigravity-restart-stale-stop";
+ const path = startupModelCachePath(instanceId)!;
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, JSON.stringify({ default: "gemini-retired", options: [{ id: "gemini-retired", label: "Retired" }, { id: "gemini-3.8-flash", label: "Flash" }], checkedAt: Date.now() - 60_000, build: "0.0.0-older" }));
+ const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
+ mkdirSync(tokenDirectory, { recursive: true });
+ writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
+ const levels = [{ value: "low", name: "Low" }, { value: "high", name: "High" }];
+ instance = await AntigravityDriver.create({
+ instanceId, displayName: "Antigravity", enabled: true, config: { cli: fake.executable, fullAuto: false },
+ environment: {
+ FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "gemini-3.8-flash,gemini-4-argon", FAKE_ACP_MODES: "default,yolo",
+ FAKE_ACP_VARIANTS: JSON.stringify({ "gemini-4-argon": { id: "thought_level", currentValue: "low", options: levels } }),
+ // The read's survey hangs here until its budget runs out, so the turn is still waiting when it is stopped.
+ FAKE_ACP_HANG_ON_MODEL: "gemini-4-argon",
+ },
+ });
+ recorder = recordEvents(instance.adapter);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-stale-stop", text: "hello", approvalMode: "ask", model: "gemini-retired", cwd: fake.directory });
+ await vi.waitFor(() => expect(instance!.adapter.hasSession("thread-stale-stop")).toBe(true));
+ // Refused once, now waiting for the read.
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ await instance.adapter.interruptTurn("thread-stale-stop");
+ expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 2_000)).toMatchObject({ ok: true, stopReason: "cancelled" });
+ await instance.startupModelRefresh;
+ expect(recorder.events.filter((event) => event.type === "turn.completed" && event.turnId === turnId)).toHaveLength(1);
+ } finally {
+ rmSync(join(DATA_DIR, "bots.json"), { force: true });
+ }
+ }, 40_000);
+
it("never starts a session on a model this account has not offered", async () => {
ensureDirs();
const fake = fakeRuntime();
diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.ts
index feb284f064..7fb8960b0b 100644
--- a/server/drivers/antigravity.ts
+++ b/server/drivers/antigravity.ts
@@ -13,14 +13,18 @@ import type {
SendTurnInput,
} from "../contracts.ts";
import { createAcpDriver, type AcpConfig, type AcpSupport } from "./acp/core.ts";
+import { reportedConfigValue } from "./acp/applied-config.ts";
+import { ANTIGRAVITY_HARNESS_FAILURE_LOG } from "./acp/harness-failure.ts";
import { acpVendorMessage } from "./acp/rpc-error.ts";
import { classifyError } from "./retry.ts";
import {
+ antigravityCliSessionMode,
antigravityClientInfo,
+ antigravityLaunchArgs,
antigravityProfileAuthenticated,
antigravityProfileDirectory,
antigravitySessionSetup,
- antigravityTokenPath,
+ antigravitySignInPaths,
authorizationUrlFromLine,
noteAntigravitySignedIn,
noteAntigravitySignInRequired,
@@ -35,9 +39,13 @@ import { splitAntigravityThinking } from "./antigravity-models.ts";
import { AntigravityAuthController } from "./antigravity-auth.ts";
import {
antigravityManagedInstallAvailable,
+ isAntigravityNativeAlias,
installAntigravityRuntime,
resolveAntigravityRuntime,
+ retirePinnedAntigravityRuntime,
} from "./antigravity-runtime.ts";
+import { ANTIGRAVITY_NATIVE_CLI } from "./antigravity-cli-install.ts";
+import { acpFileEditWithin } from "./permission-command.ts";
import { resolveAntigravityReleaseAsset } from "./antigravity-release.ts";
import { AntigravityProcesses } from "./antigravity-processes.ts";
import { VERIFICATION_TEMP_KEY, scheduleAntigravityTempSweep } from "./antigravity-temp.ts";
@@ -46,6 +54,9 @@ import { bundledEngineCatalog } from "../model-manifest/bundled.ts";
import { currentEngineCatalog } from "../model-manifest/manifest.ts";
export const STATIC_ANTIGRAVITY_MODELS: ModelCatalog = bundledEngineCatalog("antigravity");
+/** A live runtime that never answers session/new or session/resume gives up after this, as T3 Code's ACP startup does
+ * (pingdotgg/t3code@2f19cec0793); initialize keeps the core's longer limit, which the Windows runtime's unpack needs. */
+export const ANTIGRAVITY_SESSION_SETUP_TIMEOUT_MS = 90_000;
/** Bots saved before the thinking-level option hold ids like `gemini-3.8-flash-medium` or `gemini-4-neon-high`;
* the official runtime offers only the base model with that option, so run the base at the saved level. A runtime
@@ -91,9 +102,11 @@ const SIGN_IN_ASKED = /\bauthentication required\b|\bunauthenticated\b|\bnot (?:
const UNREACHABLE = /\bnetwork\b|\bunreachable\b|\boffline\b|\bgetaddrinfo\b|\benotfound\b|\beai_again\b/iu;
/** -32000 is ACP's `auth_required`, but an agent may reuse it for other failures, a sign-in service it cannot reach
- * among them. Words that ask for a sign-in decide; words that only mention one do unless the failure is one that passes. */
+ * among them. Words that ask for a sign-in decide; words that only mention one do unless the failure is one that passes.
+ * The native CLI answers `authenticate` with -32603 "No browser is available here" when it has no sign-in and no display. */
export function antigravitySignInError(error: unknown): boolean {
const value = error as { code?: unknown; message?: unknown; data?: any } | null;
+ if (value?.code === -32603 && typeof value.message === "string" && value.message.startsWith("No browser is available here")) return true;
if (value?.code !== -32000) return false;
const data = value.data;
const bounded = (fields: unknown[]) => fields.filter((field): field is string => typeof field === "string").map((field) => field.slice(0, 2_000)).join(" ");
@@ -107,8 +120,8 @@ const managedAsset = resolveAntigravityReleaseAsset();
const runtimeProcesses = new AntigravityProcesses();
/** Every model id an account here has been offered, beside the bundled catalog's. */
const offeredModels = new Set<string>();
-/** The version of the runtime each instance's turns were last started on, known before it answers initialize. */
-const launchedVersions = new Map<string, string | null>();
+/** The runtime each instance's turns were last started on, known before it answers initialize. */
+const launched = new Map<string, { version: string | null; nativeCli: boolean }>();
const support: AcpSupport = {
driverKind: "antigravityAgent",
@@ -120,8 +133,9 @@ const support: AcpSupport = {
loginNote: "Antigravity needs a Google account — choose Sign in with Google in engine setup",
install: {
docsUrl: "https://github.com/agentclientprotocol/registry/tree/main/antigravity-acp",
- ...(managedAsset
- ? { managed: { label: "Install official Antigravity", downloadBytes: managedAsset.archiveBytes } }
+ ...(antigravityManagedInstallAvailable()
+ // A client from before the native CLI shows this size whatever else is sent: the pinned archive's, or none.
+ ? { managed: { label: "Install official Antigravity", downloadBytes: managedAsset?.archiveBytes ?? 0, ...(ANTIGRAVITY_NATIVE_CLI ? { sizeUnknown: true as const } : {}) } }
: {}),
},
images: true,
@@ -135,6 +149,15 @@ const support: AcpSupport = {
sessionModelEnv: "AGY_ACP_DEFAULT_MODEL",
sessionScopedApproval: true,
resumeMethod: "resume",
+ // The packaged runtime unpacks and loads a ~1 GB Python bundle before it answers initialize (STARTUP_TIMEOUT_MS).
+ coldStartCost: "expensive",
+ // The startup model read is a second runtime process and a thinking-level survey: a saved list stands in for it.
+ modelListStandsIn: true,
+ sessionSetupTimeoutMs: ANTIGRAVITY_SESSION_SETUP_TIMEOUT_MS,
+ stderrFailure: {
+ line: ANTIGRAVITY_HARNESS_FAILURE_LOG,
+ message: "Antigravity's local agent connection failed. Send the message again to continue in a fresh Antigravity process.",
+ },
clientFileSystem: true,
clientReadRoots: (turn) => (turn.skillFiles ?? []).map(dirname),
sanitizeToolPayload: true,
@@ -142,12 +165,12 @@ const support: AcpSupport = {
resolveCommand: async (env, config, instanceId) => {
const runtime = await resolveAntigravityRuntime(config.cli, env);
- launchedVersions.set(instanceId, runtime.version);
+ launched.set(instanceId, { version: runtime.version, nativeCli: runtime.harnessPath === null });
const profile = await prepareAntigravityProfile({ instanceId, runtime, baseEnv: env });
if (profile.tempDirectory) scheduleAntigravityTempSweep(instanceId);
return {
command: runtime.executablePath,
- args: process.platform === "linux" ? ["--uid="] : [],
+ args: antigravityLaunchArgs(runtime, profile.directory),
env: profile.environment,
ro: [join(profile.directory, "omb-skills")],
};
@@ -175,13 +198,16 @@ const support: AcpSupport = {
signInRequest: {
stderrLine: (line) => authorizationUrlFromLine(line) !== null,
rpcError: antigravitySignInError,
- required: (instanceId) => noteAntigravitySignInRequired(antigravityTokenPath(instanceId)),
+ required: (instanceId) => antigravitySignInPaths(instanceId).forEach(noteAntigravitySignInRequired),
},
processStarted: (child, instanceId) => runtimeProcesses.track(instanceId, child),
sessionSetupParams: antigravitySessionSetup,
// One model family's quota is not the account's: Gemini and the models that share another allowance keep running.
limitFacts: (_text, model) => antigravityLimitFacts(model, [...support.models.options.map((option) => option.id), ...offeredModels]),
- clientInfo: (instanceId) => antigravityClientInfo(launchedVersions.get(instanceId)),
+ clientInfo: (instanceId) => antigravityClientInfo(launched.get(instanceId)?.version),
+ // In `default` the native CLI asks before every edit; Auto-accept edits answers those, as `auto_edit` did.
+ // Security: only a file edit inside the turn's folder is answered; one that names a command or another place is asked.
+ allowsAlone: (instanceId, turn, toolCall) => launched.get(instanceId)?.nativeCli === true && turn.approvalMode === "edits" && acpFileEditWithin(toolCall, turn.cwd),
promptOutcome: (instanceId, sessionId) => watchAntigravityPromptOutcome(support.displayName, antigravityProfileDirectory(instanceId), sessionId),
requireAuthenticationBeforeSpawn: true,
isAuthenticated: async (env, config, instanceId) => {
@@ -208,11 +234,17 @@ const support: AcpSupport = {
}
},
- configureSession: async ({ request, sessionId, config, turn, configOptions }) => {
+ configureSession: async ({ request, sessionId, instanceId, config, turn, configOptions, applied }) => {
+ const nativeCli = launched.get(instanceId)?.nativeCli === true;
if (!Array.isArray(configOptions) || !configOptions.some(option => option?.id === "mode")) {
+ // The native CLI answers by the turn's level only in `default`; with no mode to confirm, nothing says it is there.
+ if (nativeCli) throw new Error("Antigravity did not report its permission mode.");
return;
}
- const wanted = antigravityPermissionMode(config.fullAuto, turn.approvalMode);
+ const level = antigravityPermissionMode(config.fullAuto, turn.approvalMode);
+ const wanted = nativeCli ? antigravityCliSessionMode(level) : level;
+ // A mode this live session confirmed, and still reports, is not sent again.
+ if (applied?.holds("mode", wanted, reportedConfigValue(configOptions, "mode"))) return;
const result = await request("session/set_config_option", {
sessionId,
configId: "mode",
@@ -221,7 +253,8 @@ const support: AcpSupport = {
const mode = Array.isArray(result?.configOptions)
? result.configOptions.find((option: any) => option?.id === "mode")?.currentValue
: undefined;
- if (mode !== wanted) throw new Error(`Antigravity did not apply ${wanted} permission mode.`);
+ if (mode !== wanted) throw (applied?.clear(), new Error(`Antigravity did not apply ${wanted} permission mode.`));
+ applied?.accepted("mode", wanted);
},
};
@@ -233,9 +266,13 @@ export const AntigravityDriver: ProviderDriver<AcpConfig> = {
const base = await AcpAntigravityDriver.create(input);
scheduleAntigravityTempSweep(input.instanceId);
scheduleAntigravityTempSweep(VERIFICATION_TEMP_KEY);
+ // Once an account here signed in on the native CLI, the pinned runtime it replaced is removed.
+ const retirePinned = () => void retirePinnedAntigravityRuntime().catch(() => []);
+ retirePinned();
const auth = new AntigravityAuthController(() => {
- noteAntigravitySignedIn(antigravityTokenPath(input.instanceId));
+ antigravitySignInPaths(input.instanceId).forEach(noteAntigravitySignedIn);
void base.refreshModels?.();
+ retirePinned();
});
let signingOut: Promise<void> = Promise.resolve();
let installFailure: string | undefined;
@@ -277,7 +314,7 @@ export const AntigravityDriver: ProviderDriver<AcpConfig> = {
installRuntime: async () => {
installFailure = undefined;
try {
- await installAntigravityRuntime({ validate: validateAntigravityRuntime });
+ await installAntigravityRuntime({ validate: validateAntigravityRuntime, native: isAntigravityNativeAlias(input.config.cli) });
} catch (error) {
installFailure = error instanceof Error ? error.message : String(error);
throw error;
@@ -289,7 +326,8 @@ export const AntigravityDriver: ProviderDriver<AcpConfig> = {
startAuthentication: async () => {
await signingOut;
const { runtime, profile } = await runtimeAndProfile();
- await verifyAntigravityBrowserHelper(profile);
+ // The native CLI's `--login` hands its link over itself; only the pinned runtime needs the browser helper.
+ if (runtime.harnessPath !== null) await verifyAntigravityBrowserHelper(profile);
return auth.start(runtime, profile);
},
getAuthentication: async (flowId) => auth.get(flowId),
diff --git a/server/drivers/permission-command.test.ts b/server/drivers/permission-command.test.ts
index 390abea695..a806d00ced 100644
--- a/server/drivers/permission-command.test.ts
+++ b/server/drivers/permission-command.test.ts
@@ -1,6 +1,8 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { acpPermissionCommand, permissionCommand } from "./permission-command.ts";
+import { bindSafetyFloor } from "../safety-floor-gate.ts";
+
+import { acpAnswersAlone, acpCarriesCommand, acpFileEditWithin, acpPermissionCommand, acpShellRequest, answersAlone, permissionCommand } from "./permission-command.ts";
const CWD = "/home/user/work";
@@ -56,3 +58,45 @@ describe("permissionCommand", () => {
expect(permissionCommand(undefined, CWD)).toBeUndefined();
});
});
+
+describe("the never-list on an ACP request", () => {
+ beforeEach(() => bindSafetyFloor(() => ({ safetyFloor: { enabled: true } }) as never, undefined, "linux"));
+ afterEach(() => bindSafetyFloor(() => ({})));
+
+ it("reads a command under either spelling, whatever the request's kind", () => {
+ expect(answersAlone("rm -rf ~")).toBe(false);
+ expect(acpAnswersAlone({ command: "rm -rf ~" })).toBe(false);
+ expect(acpAnswersAlone({ CommandLine: "rm -rf ~" })).toBe(false);
+ expect(acpAnswersAlone({ command: "ls", CommandLine: "rm -rf ~" })).toBe(false);
+ expect(acpAnswersAlone({ CommandLine: 42 })).toBe(false);
+ expect(acpAnswersAlone({ CommandLine: "ls" })).toBe(true);
+ expect(acpAnswersAlone({ command: "ls", CommandLine: "ls" })).toBe(true);
+ for (const none of [undefined, null, {}, { path: "/tmp/a" }, ["rm -rf ~"]]) expect(acpAnswersAlone(none)).toBe(true);
+ expect(acpCarriesCommand({ CommandLine: "ls" })).toBe(true);
+ expect(acpCarriesCommand({ command: "" })).toBe(true);
+ expect(acpCarriesCommand({ path: "/tmp/a" })).toBe(false);
+ });
+
+ it("carries the command line of a request that is not a shell call, and both lines when two spellings differ", () => {
+ expect(acpShellRequest(false, { CommandLine: "rm -rf ~" }, CWD)).toEqual({ command: undefined, commandLine: "rm -rf ~" });
+ expect(acpShellRequest(false, { command: "ls" }, CWD)).toEqual({ command: undefined, commandLine: "ls" });
+ expect(acpShellRequest(true, { CommandLine: "ls" }, CWD)).toEqual({ command: { command: "ls", cwd: CWD }, commandLine: "ls" });
+ expect(acpShellRequest(true, { command: "ls", CommandLine: "rm -rf ~" }, CWD)).toEqual({ command: undefined, commandLine: "ls\nrm -rf ~" });
+ expect(acpShellRequest(false, { path: "/tmp/a" }, CWD)).toEqual({ command: undefined, commandLine: undefined });
+ expect(acpShellRequest(false, undefined, CWD)).toEqual({ command: undefined, commandLine: undefined });
+ });
+
+ it("takes a request for a file edit only when it is one, inside the folder", () => {
+ const root = process.cwd();
+ const inside = { kind: "edit", locations: [{ path: `${root}/notes.md` }] };
+ expect(acpFileEditWithin(inside, root)).toBe(true);
+ expect(acpFileEditWithin(inside, undefined)).toBe(false);
+ expect(acpFileEditWithin({ ...inside, kind: "execute" }, root)).toBe(false);
+ expect(acpFileEditWithin({ ...inside, rawInput: { CommandLine: "ls" } }, root)).toBe(false);
+ expect(acpFileEditWithin({ kind: "edit", locations: [{ path: root }] }, root)).toBe(false);
+ expect(acpFileEditWithin({ kind: "edit", locations: [] }, root)).toBe(false);
+ expect(acpFileEditWithin({ kind: "edit", locations: [{ path: `${root}/../x` }] }, root)).toBe(false);
+ expect(acpFileEditWithin({ kind: "edit", locations: [{ path: `${root}/a\0b` }] }, root)).toBe(false);
+ expect(acpFileEditWithin({ kind: "edit", locations: [{}] }, root)).toBe(false);
+ });
+});
diff --git a/server/drivers/permission-command.ts b/server/drivers/permission-command.ts
index 52a16d22ac..dbad798e82 100644
--- a/server/drivers/permission-command.ts
+++ b/server/drivers/permission-command.ts
@@ -1,5 +1,5 @@
import { realpathSync } from "node:fs";
-import { isAbsolute } from "node:path";
+import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { safetyFloorClears } from "../safety-floor-gate.ts";
@@ -54,11 +54,62 @@ export function acpPermissionCommand(rawInput: unknown, launchCwd: string | unde
return permissionCommand(commands[0], directories[0] ?? launchCwd);
}
+/** Every command an ACP rawInput names, under either spelling. */
+function acpCommands(rawInput: unknown): unknown[] {
+ if (!rawInput || typeof rawInput !== "object" || Array.isArray(rawInput)) return [];
+ return COMMAND_KEYS.map((key) => (rawInput as Record<string, unknown>)[key]).filter((value) => value !== undefined);
+}
+
+export function acpCarriesCommand(rawInput: unknown): boolean {
+ return acpCommands(rawInput).length > 0;
+}
+
+/** answersAlone for an ACP request: every command it names, under either spelling, must clear the never-list, and a
+ * command that cannot be read as a line never does. */
+export function acpAnswersAlone(rawInput: unknown): boolean {
+ return acpCommands(rawInput).every((command) => {
+ const line = floorCommandLine(command);
+ return line === undefined ? typeof command === "string" : safetyFloorClears(line);
+ });
+}
+
/** shellRequest for an ACP tool call: only a shell-typed call gets the descriptor, but any call naming a command
- * line carries it for the safety floor. */
+ * line, under either spelling, carries it for the safety floor. Two different spellings are both read. */
export function acpShellRequest(isShellCommand: boolean, rawInput: unknown, launchCwd: string | undefined): ReturnType<typeof shellRequest> {
- const command = rawInput && typeof rawInput === "object" && !Array.isArray(rawInput) ? (rawInput as Record<string, unknown>).command : undefined;
- return { command: isShellCommand ? acpPermissionCommand(rawInput, launchCwd) : undefined, commandLine: shellRequest(command, undefined).commandLine };
+ const lines = [...new Set(acpCommands(rawInput).map(floorCommandLine).filter((line) => line !== undefined))];
+ return { command: isShellCommand ? acpPermissionCommand(rawInput, launchCwd) : undefined, commandLine: lines.length ? lines.join("\n") : undefined };
+}
+
+/** Where `path` really is: links resolved as far as the path exists, the rest appended as written. */
+function realTarget(path: string): string | undefined {
+ let existing = resolve(path);
+ const rest: string[] = [];
+ for (;;) {
+ try {
+ return join(realpathSync(existing), ...rest);
+ } catch {
+ const parent = dirname(existing);
+ if (parent === existing) return undefined;
+ rest.unshift(basename(existing));
+ existing = parent;
+ }
+ }
+}
+
+/** Whether an ACP permission request is only a file edit inside `root`: its kind is `edit`, it names no command, and
+ * every location it gives is an absolute path that stays inside `root` once links are resolved. A request that gives
+ * no location cannot be placed, so it is not one. */
+export function acpFileEditWithin(toolCall: { kind?: unknown; rawInput?: unknown; locations?: unknown }, root: string | undefined): boolean {
+ if (toolCall.kind !== "edit" || !root || acpCarriesCommand(toolCall.rawInput)) return false;
+ const realRoot = permissionLaunchCwd(root);
+ if (!realRoot || !Array.isArray(toolCall.locations) || !toolCall.locations.length) return false;
+ return toolCall.locations.every((location) => {
+ const path = (location as { path?: unknown } | null)?.path;
+ if (typeof path !== "string" || !isAbsolute(path) || path.includes("\0")) return false;
+ const target = realTarget(path);
+ const inside = target === undefined ? "" : relative(realRoot, target);
+ return inside !== "" && !inside.startsWith("..") && !isAbsolute(inside);
+ });
}
/** An ACP permission request's exact operation, for the driver's own session allow; null for a generic title with no input. */
diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.ts
index 7a9db462d8..f7df5d29a7 100644
--- a/server/drivers/session-idle.test.ts
+++ b/server/drivers/session-idle.test.ts
@@ -4,7 +4,7 @@ import { forgetPresence, personAsks, sawThread, seenWithin } from "../thread-pre
import {
armedIdleCount, armIdleClose, engineIdleMs, idleEngineCap, idleEnginesAllowed, keepWarm, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES,
SMALL_BOX_IDLE_ENGINES, SMALL_BOX_IDLE_MS, stopIdleClose, sweepIdleEngines,
- UNWATCHED_IDLE_MS, warmEngineKeys, type WarmEngine,
+ UNWATCHED_IDLE_MS, warmEngineKeys, type WarmEngine, EXPENSIVE_IDLE_MS, EXPENSIVE_UNWATCHED_IDLE_MS, roomBesideIdle,
} from "./session-idle.ts";
const GB = 1024 ** 3;
@@ -345,3 +345,57 @@ describe("engines started before a first message", () => {
}
});
});
+
+describe("an engine whose cold start is expensive", () => {
+ const now = 1_800_000_000_000;
+ const cloud = (factor: number) => ({ enabled: true, headroom: () => factor, roomFactor: () => factor });
+ const small = 4 * GB, large = 16 * GB;
+ afterEach(forgetPresence);
+
+ it("is kept longer only by drivers that say so, never when an idle time is configured or on a box of 1.5 GB or less", () => {
+ expect(sessionIdlePolicy("ACP", {}, small, "expensive")).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000, expensiveIdleMs: EXPENSIVE_IDLE_MS });
+ expect(sessionIdlePolicy("ACP", {}, small)).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000 });
+ expect(sessionIdlePolicy("ACP", { OMB_ACP_SESSION_IDLE_MS: "120000" }, small, "expensive").expensiveIdleMs).toBeUndefined();
+ expect(sessionIdlePolicy("ACP", { OMB_SESSION_IDLE_MS: "120000" }, small, "expensive").expensiveIdleMs).toBeUndefined();
+ expect(sessionIdlePolicy("ACP", {}, 1.5 * GB, "expensive").expensiveIdleMs).toBeUndefined();
+ });
+
+ it("needs room for one more of the largest engines above the floor beside it", () => {
+ // headroom = (free - floor) / (total / 2): 1.5 GB above the floor is 0.75 on a 4 GB Cloud, 0.1875 on a 16 GB one.
+ expect(roomBesideIdle(0.75, small)).toBe(true);
+ expect(roomBesideIdle(0.7, small)).toBe(false);
+ expect(roomBesideIdle(0.19, large)).toBe(true);
+ expect(roomBesideIdle(0.18, large)).toBe(false);
+ // A 2 GB box never has that much headroom; a 3 GB one only with nearly all of it (1,500 MiB of 1,536).
+ expect(roomBesideIdle(1, 2 * GB)).toBe(false);
+ expect(roomBesideIdle(0.97, 3 * GB)).toBe(false);
+ expect(roomBesideIdle(1, 1.5 * GB)).toBe(false);
+ });
+
+ it("keeps a watched conversation's idle process 30 minutes and an unwatched one 3 while the room allows, else the usual rule", () => {
+ const policy = sessionIdlePolicy("ACP", {}, small, "expensive");
+ sawThread("open", now - 60_000);
+ expect(engineIdleMs("open", policy, cloud(1), now, small)).toBe(EXPENSIVE_IDLE_MS);
+ expect(engineIdleMs("open", policy, cloud(0.8), now, small)).toBe(EXPENSIVE_IDLE_MS);
+ expect(engineIdleMs("open", policy, cloud(0.5), now, small)).toBe(5 * 60_000);
+ expect(engineIdleMs("open", policy, cloud(0.1), now, small)).toBe(60_000);
+ expect(engineIdleMs("routine", policy, cloud(1), now, small)).toBe(EXPENSIVE_UNWATCHED_IDLE_MS);
+ expect(engineIdleMs("routine", policy, cloud(0.5), now, small)).toBe(UNWATCHED_IDLE_MS);
+ expect(engineIdleMs("routine", policy, cloud(1), now, 2 * GB)).toBe(UNWATCHED_IDLE_MS);
+ // The desktop, with no memory to read, keeps the configured time: nothing could shorten a longer one later.
+ expect(engineIdleMs("open", policy, { enabled: false, headroom: () => 1 }, now, large)).toBe(10 * 60_000);
+ });
+
+ it("is closed by the sweep once the room shrinks below that", () => {
+ const policy = sessionIdlePolicy("ACP", {}, small, "expensive");
+ sawThread("open-sweep", now);
+ let closed = 0;
+ const engine: WarmEngine = { idle: () => true, close: () => { closed += 1; }, threadId: "open-sweep", policy };
+ armIdleClose("expensive-sweep", EXPENSIVE_IDLE_MS, engine, now);
+ const room = (factor: number) => ({ enabled: true, headroom: () => factor, roomFactor: () => factor, shortOfRoom: () => false });
+ expect(sweepIdleEngines(room(0.8), now + 20 * 60_000, small)).toBe(0);
+ expect(closed).toBe(0);
+ expect(sweepIdleEngines(room(0.5), now + 20 * 60_000, small)).toBe(1);
+ expect(closed).toBe(1);
+ });
+});
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index 2bc80b4f49..3aba8b8f90 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -16,7 +16,7 @@
// closes as another goes idle, and its conversation's next turn resumes its session by id.
import { availableMemory, boxMemory, type BoxMemory } from "../box-memory.ts";
import { stoppedForBotMemory } from "../bot-memory-cap.ts";
-import { engineMemory, type EngineMemory } from "../engine-memory.ts";
+import { ENGINE_MAX_BYTES, engineMemory, type EngineMemory } from "../engine-memory.ts";
import { onThreadSeen, seenWithin } from "../thread-presence.ts";
export type IdleScope = "per-chat" | "per-bot" | "shared";
@@ -28,6 +28,24 @@ export const idleAfter = (baseMs: number, minimumMs: number, factor: number): nu
export interface SessionIdlePolicy {
idleMs: number;
minimumMs: number;
+ /** An engine whose cold start costs tens of seconds, with no idle time configured: where turns wait for room, how long
+ * its idle process stays up for a watched conversation while the room holds one more of the largest engines. */
+ expensiveIdleMs?: number;
+}
+
+/** What a driver says a cold start of its engine costs: "expensive" for one that takes tens of seconds (Google's packaged
+ * Antigravity server, a ~1 GB runtime that unpacks and loads its own Python before it answers). */
+export type ColdStartCost = "expensive";
+/** Where turns wait for room, an expensive engine's idle process for a watched conversation stays up this long while the
+ * room allows (the time a reference ACP client keeps an idle Antigravity process), and this long for an unwatched one. */
+export const EXPENSIVE_IDLE_MS = 30 * 60_000;
+export const EXPENSIVE_UNWATCHED_IDLE_MS = 3 * 60_000;
+
+/** Room for one more of the largest engines admission plans for (ENGINE_MAX_BYTES) above the memory floor, besides this
+ * idle one: headroom is (free - floor) / (total / 2), so that is a factor of at least ENGINE_MAX_BYTES / (total / 2). Never
+ * on a box under 3 GB, whose whole headroom is less than that engine; on a 3 GB box only with all of it free. */
+export function roomBesideIdle(factor: number, boxBytes: number): boolean {
+ return boxBytes > SMALL_BOX_BYTES && Math.min(1, factor) * (boxBytes / 2) >= ENGINE_MAX_BYTES;
}
const DEFAULT_IDLE_MS = 10 * 60_000;
@@ -51,6 +69,7 @@ export function sessionIdlePolicy(
driverPrefix: string,
env: Record<string, string | undefined> = process.env,
boxBytes: number = boxMemory().bytes,
+ coldStart?: ColdStartCost,
): SessionIdlePolicy {
const minimumMs = Math.max(
MINIMUM_IDLE_MS,
@@ -62,7 +81,9 @@ export function sessionIdlePolicy(
usableMilliseconds(
env[`OMB_${driverPrefix}_SESSION_IDLE_MS`] ?? env.OMB_SESSION_IDLE_MS,
) ?? (boxBytes <= SMALL_BOX_BYTES ? SMALL_BOX_IDLE_MS : DEFAULT_IDLE_MS);
- return { idleMs: Math.max(minimumMs, configured), minimumMs };
+ const idleMs = Math.max(minimumMs, configured);
+ const chosen = usableMilliseconds(env[`OMB_${driverPrefix}_SESSION_IDLE_MS`] ?? env.OMB_SESSION_IDLE_MS) !== null;
+ return { idleMs, minimumMs, ...(coldStart === "expensive" && !chosen && boxBytes > SMALL_BOX_BYTES ? { expensiveIdleMs: Math.max(idleMs, EXPENSIVE_IDLE_MS) } : {}) };
}
/** On a small box with less than half of it free, a second idle engine would leave no room for a turn's own engine. On a
@@ -178,7 +199,7 @@ export function stopIdleClose(key: string, timer: ReturnType<typeof setTimeout>
/** Closes each idle per-chat engine kept past what the room allows now; short of room, a keep-warm hold too. Runs on
* engine-memory's tick. Returns how many it closed. */
-export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroom" | "roomFactor" | "shortOfRoom"> = engineMemory, now: number = Date.now()): number {
+export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroom" | "roomFactor" | "shortOfRoom"> = engineMemory, now: number = Date.now(), boxBytes: number = boxMemory().bytes): number {
if (!memory.enabled || !armed.size) return 0;
const factor = memory.roomFactor(), short = memory.shortOfRoom();
if (factor >= 1 && !short) return 0;
@@ -187,7 +208,7 @@ export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroo
// No longer idle (a turn took it again, or it ended): its driver arms it again when it next goes idle.
if (!engine.idle()) { armed.delete(key); continue; }
if (!engine.threadId || !engine.policy || (engine.held?.() && !short)) continue;
- if (!engine.spare?.() && now - since < engineIdleMs(engine.threadId, engine.policy, { enabled: true, headroom: () => factor, roomFactor: () => factor }, now)) continue;
+ if (!engine.spare?.() && now - since < engineIdleMs(engine.threadId, engine.policy, { enabled: true, headroom: () => factor, roomFactor: () => factor }, now, boxBytes)) continue;
armed.delete(key);
warmEngines.delete(key);
engine.close();
@@ -224,14 +245,22 @@ export function prestartAllowed(box: Pick<BoxMemory, "bytes"> = boxMemory(), mem
/**
* How long one conversation's idle engine (per-chat) stays up after a turn. Where turns wait for room (a Cloud home, a
* self-hosted Linux server): briefly for a thread no person has had in front of them lately, and for the one they have,
- * the configured time scaled by the room left (memory and, under a pids limit, processes; down to a tenth). Elsewhere the
- * configured time.
+ * the configured time scaled by the room left (memory and, under a pids limit, processes; down to a tenth). An engine whose
+ * cold start is expensive keeps EXPENSIVE_IDLE_MS (watched) or EXPENSIVE_UNWATCHED_IDLE_MS (unwatched) instead while the
+ * room holds one more of the largest engines beside it (roomBesideIdle); the sweep shortens it again as soon as it does
+ * not, and admission stops it first when another engine needs the room. Elsewhere the configured time: with no memory to
+ * read there, nothing could shorten a longer one later.
*/
export function engineIdleMs(threadId: string, policy: SessionIdlePolicy,
- memory: Pick<EngineMemory, "enabled" | "headroom"> & Partial<Pick<EngineMemory, "roomFactor">> = engineMemory, now: number = Date.now()): number {
+ memory: Pick<EngineMemory, "enabled" | "headroom"> & Partial<Pick<EngineMemory, "roomFactor">> = engineMemory, now: number = Date.now(),
+ boxBytes: number = boxMemory().bytes): number {
if (!memory.enabled) return policy.idleMs;
- if (!seenWithin(threadId, WATCHED_MS, now)) return Math.max(policy.minimumMs, Math.min(policy.idleMs, UNWATCHED_IDLE_MS));
- return idleAfter(policy.idleMs, policy.minimumMs, memory.roomFactor?.() ?? memory.headroom());
+ const factor = memory.roomFactor?.() ?? memory.headroom();
+ const roomy = policy.expensiveIdleMs !== undefined && roomBesideIdle(factor, boxBytes);
+ if (!seenWithin(threadId, WATCHED_MS, now)) {
+ return Math.max(policy.minimumMs, roomy ? EXPENSIVE_UNWATCHED_IDLE_MS : Math.min(policy.idleMs, UNWATCHED_IDLE_MS));
+ }
+ return roomy ? policy.expensiveIdleMs! : idleAfter(policy.idleMs, policy.minimumMs, factor);
}
/** Whether this thread's engine (`pid`, the process that exited) was just stopped to make room, or for want of it, or for
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index e8c46127ce..ba9c3bd1d3 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -19,7 +19,9 @@ const PAGE_BYTES = 4096;
/** What one engine and its MCP servers take until one has been measured here: `opencode acp` 1.19.3 measured 361 MB on a
* Cloud home before its first prompt and 623 MB with six stdio MCP servers, and about 466 MB while working. */
export const ENGINE_DEFAULT_BYTES = 700 * MB;
-const ENGINE_MIN_BYTES = 300 * MB, ENGINE_MAX_BYTES = 1500 * MB;
+const ENGINE_MIN_BYTES = 300 * MB;
+/** The most admission plans for one engine, however large the ones measured here. */
+export const ENGINE_MAX_BYTES = 1500 * MB;
/** One more session in a running shared process: OpenCode 1.19.3 grew about 110 MB a session with three stdio MCP
* servers after a prompt; more MCP servers cost more. */
export const SESSION_BYTES = 200 * MB;
diff --git a/server/engine-updates-host.ts b/server/engine-updates-host.ts
index aa1f891ec5..dfe2f9c178 100644
--- a/server/engine-updates-host.ts
+++ b/server/engine-updates-host.ts
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { DATA_DIR } from "./config.ts";
import type { AnyProviderDriver } from "./contracts.ts";
import { validateAntigravityRuntime } from "./drivers/antigravity-acp.ts";
-import { antigravityManagedInstallAvailable, antigravityOlderRuntime, installAntigravityRuntime } from "./drivers/antigravity-runtime.ts";
+import { antigravityCliUpdate, antigravityManagedInstallAvailable, antigravityOlderRuntime, installAntigravityRuntime, retirePinnedAntigravityRuntime } from "./drivers/antigravity-runtime.ts";
import { antigravityRuntimesRoot } from "./engine-roots.ts";
import { createEngineUpdater, enginePlans, type EngineUpdater, type ManagedRuntime } from "./engine-updates.ts";
@@ -11,8 +11,12 @@ function managedRuntimes(): Record<string, ManagedRuntime> {
if (!antigravityManagedInstallAvailable()) return {};
return {
antigravityAgent: {
- older: () => antigravityOlderRuntime(),
- install: () => installAntigravityRuntime({ validate: validateAntigravityRuntime }).then(() => {}),
+ older: async () => (await antigravityCliUpdate()) ?? antigravityOlderRuntime(),
+ install: async () => {
+ const installed = await installAntigravityRuntime({ validate: validateAntigravityRuntime });
+ await retirePinnedAntigravityRuntime().catch(() => []);
+ return installed.version ?? undefined;
+ },
folder: antigravityRuntimesRoot(DATA_DIR),
},
};
diff --git a/server/engine-updates.test.ts b/server/engine-updates.test.ts
index 40e3b22e6c..38b6958224 100644
--- a/server/engine-updates.test.ts
+++ b/server/engine-updates.test.ts
@@ -348,6 +348,28 @@ describe("a runtime the app manages itself", () => {
await removeTempDir(scratch);
}
});
+
+ it("names the version a runtime really moved to, and counts an install that changed nothing as failed", async () => {
+ const scratch = mkdtempSync(join(tmpdir(), "omb-engine-updates-"));
+ try {
+ const lines: string[] = [];
+ let installs: string | void = "1.5.8";
+ const managed = { older: async () => "1.5.7", install: async () => installs, folder: join(scratch, "runtimes") };
+ const engines = createEngineUpdater({
+ plans: [{ driverKind: "managedEngine", name: "Managed", pin: { target: "1.4.3", minimum: "1.4.3" }, managed }],
+ baseDir: scratch, statePath: join(scratch, "state.json"), turnRunning: () => false, log: (line) => lines.push(line),
+ liveCommands: () => [], steps: noSteps(),
+ });
+ await engines.check();
+ expect(lines).toEqual(["Engine update: Managed 1.5.7 → 1.5.8"]);
+ expect(engines.shown("managedEngine").autoUpdated?.version).toBe("1.5.8");
+ installs = "1.5.7";
+ await engines.check();
+ expect(lines[1]).toBe("Engine update: Managed stays on 1.5.7; 1.5.7 could not be installed (the install left the same version in place). Trying again later.");
+ } finally {
+ await removeTempDir(scratch);
+ }
+ });
});
describe.skipIf(process.platform === "win32")("the ACP handshake", () => {
diff --git a/server/engine-updates.ts b/server/engine-updates.ts
index a93abb826a..d70e1183b6 100644
--- a/server/engine-updates.ts
+++ b/server/engine-updates.ts
@@ -31,9 +31,10 @@ const SWITCH_POLL_MS = 15_000;
/** A runtime the app manages itself (Antigravity): it installs each version beside the others and checks it. */
export interface ManagedRuntime {
- /** The older version installed when the pinned one is not, else null. */
+ /** The version installed when a newer one is to be installed, else null. */
older(): Promise<string | null>;
- install(): Promise<void>;
+ /** Resolves with the version it installed when that is not the pinned one. */
+ install(): Promise<string | void>;
folder: string;
}
@@ -278,12 +279,14 @@ export function createEngineUpdater(options: EngineUpdaterOptions): EngineUpdate
const older = await managed.older();
if (older === null) return { kind: "absent" };
if (engineBusy(plan)) return { kind: "busy" };
+ let installed: string | void;
try {
- await managed.install();
+ installed = await managed.install();
} catch (error) {
return { kind: "failed", from: older, to: plan.pin.target, reason: error instanceof Error ? error.message : String(error) };
}
- return { kind: "updated", from: older, to: plan.pin.target };
+ const to = installed ?? plan.pin.target;
+ return to === older ? { kind: "failed", from: older, to, reason: "the install left the same version in place" } : { kind: "updated", from: older, to };
}
const updateOne = (plan: EnginePlan): Promise<Outcome> => {
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index 9f4a1abaf6..f9abb3ac52 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -17,6 +17,7 @@ import type { FailoverWhy } from "./turn-record.ts";
import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";
import { createLaunchTimings, LAUNCH_FILE, type LaunchTimings } from "./launch-timings.ts";
import { startStallWatch, stallReportLines, type StallWatch } from "./stall-watch.ts";
+import { turnStartsSection } from "./turn-starts.ts";
export const PERF_FILE = "perf-timings.json";
/** The last storage pass and the one under way: under `cache`, which backups leave behind, since they describe this volume only. */
@@ -170,7 +171,8 @@ export function createPerfHost(deps: PerfHostDeps) {
},
/** For the desktop's diagnostics export: every bot's latest turns. */
text(): string {
- return stallsFirst(guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE)).join("\n");
+ return [...stallsFirst(guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE)),
+ ...guarded("turn-starts", () => turnStartsSection(), [])].join("\n");
},
/** The graceful shutdown: no more samples, and the turns since the last save written now. */
stop() { sampler.stop(); stalls.stop(); watch?.stop(); void disk?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },
diff --git a/server/perf/turn-starts.test.ts b/server/perf/turn-starts.test.ts
new file mode 100644
index 0000000000..8119876573
--- /dev/null
+++ b/server/perf/turn-starts.test.ts
@@ -0,0 +1,51 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { createPerfHost } from "./perf-host.ts";
+import { recentTurnStarts, TURN_STARTS_KEPT, turnStartClock } from "./turn-starts.ts";
+
+describe("one line per ACP engine turn on how its start went", () => {
+ it("names a new process's steps, its config calls and its first update, in numbers and fixed words only", () => {
+ const logged: string[] = [];
+ const clock = turnStartClock("antigravityAgent", 1_000, (line) => logged.push(line));
+ clock.waited("models", 12);
+ clock.spawned(Date.now());
+ for (const [method, ms] of [["initialize", 8_200], ["authenticate", 310], ["session/resume", 1_500], ["session/set_config_option", 200], ["session/set_config_option", 150]] as const) clock.call(method, ms);
+ clock.promptSent(50_000);
+ clock.firstUpdate(52_300);
+ clock.firstUpdate(53_000);
+ clock.call("session/set_config_option", 99);
+ const line = clock.finish("end_turn", 61_000)!;
+ expect(line).toMatch(/^\[perf\] engine turn antigravityAgent: new process, models waited 12 ms, spawn to initialize \d+ ms, authenticate 310 ms, session resume 1500 ms, config 2 calls 350 ms, prompt to first update 2300 ms, total 60\.0 s, ended end_turn$/u);
+ expect(logged).toEqual([line]);
+ expect(clock.finish("again", 62_000)).toBeNull();
+ expect(recentTurnStarts().at(-1)).toBe(line);
+ });
+
+ it("says when the process was kept and no session call was needed, and never repeats a word it was not given", () => {
+ const clock = turnStartClock("[email protected]", 0, () => {});
+ clock.promptSent(10);
+ const line = clock.finish("/Users/ada/secret", 20)!;
+ expect(line).toBe("[perf] engine turn acp: kept process, models waited 0 ms, session live, config 0 calls 0 ms, prompt to first update none, total 20 ms, ended other");
+ expect(turnStartClock("x", 0, () => {}).finish("auth_required", 5)).toBe("[perf] engine turn x: no process, models waited 0 ms, config 0 calls 0 ms, no prompt, total 5 ms, ended auth_required");
+ });
+
+ it("keeps only the latest lines, and they are in the diagnostics export", () => {
+ for (let index = 0; index < TURN_STARTS_KEPT + 5; index++) turnStartClock("codex", 0, () => {}).finish("end_turn", index);
+ expect(recentTurnStarts()).toHaveLength(TURN_STARTS_KEPT);
+ const dir = mkdtempSync(join(tmpdir(), "turn-starts-"));
+ try {
+ const perf = createPerfHost({
+ dataDir: dir, timer: false, wholeMachine: false, log: () => {},
+ bus: { subscribe: () => () => {} }, store: { onChange: () => () => {}, botByThread: () => null },
+ });
+ const text = perf.text();
+ expect(text).toContain("## Engine turn starts (latest, oldest first)");
+ expect(text).toContain(recentTurnStarts().at(-1)!);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/perf/turn-starts.ts b/server/perf/turn-starts.ts
new file mode 100644
index 0000000000..e3c976d7df
--- /dev/null
+++ b/server/perf/turn-starts.ts
@@ -0,0 +1,89 @@
+// One compact line per ACP engine turn on how its start went: a new process or a kept one, how long the agent took to
+// answer each protocol step before the prompt, and how long from the prompt to its first update. Always on, written to
+// the server log and kept (the latest few) for the desktop's diagnostics export. Only the engine's kind, fixed words and
+// numbers: no ids, prompts, paths, tokens or accounts.
+
+/** The diagnostics export keeps this many of the latest lines. */
+export const TURN_STARTS_KEPT = 20;
+
+const recent: string[] = [];
+
+/** The protocol steps a line names, in the order they run; anything else sent before the prompt counts as config. */
+const STEPS = ["initialize", "authenticate", "session/resume", "session/load", "session/new"] as const;
+const CONFIG = new Set(["session/set_config_option", "session/set_model", "session/set_mode"]);
+
+export interface TurnStartClock {
+ /** A request the turn sent before its prompt was answered or failed after `ms`. */
+ call(method: string, ms: number): void;
+ /** The turn waited `ms` for something before its engine: the startup model read, or room in memory. */
+ waited(what: "models" | "room", ms: number): void;
+ /** The turn started a process of its own (`spawnedAt`), rather than one kept from an earlier turn. */
+ spawned(at: number): void;
+ promptSent(at: number): void;
+ firstUpdate(at: number): void;
+ retried(): void;
+ /** Writes the line once; later calls do nothing. */
+ finish(outcome: string, at: number): string | null;
+}
+
+const ms = (value: number) => (value >= 10_000 ? `${(value / 1000).toFixed(1)} s` : `${Math.round(value)} ms`);
+
+export function turnStartClock(engine: string, startedAt: number, log: (line: string) => void = (line) => console.info(line)): TurnStartClock {
+ const steps = new Map<string, number>();
+ const waits = { models: 0, room: 0 };
+ let config = 0, configMs = 0, spawnedAt: number | null = null, initializedAfter: number | null = null;
+ let promptAt: number | null = null, firstAt: number | null = null, retries = 0, done = false;
+ return {
+ call(method, took) {
+ if (promptAt !== null) return;
+ if (CONFIG.has(method)) { config += 1; configMs += took; return; }
+ if (method === "initialize" && spawnedAt !== null) initializedAfter = Date.now() - spawnedAt;
+ steps.set(method, (steps.get(method) ?? 0) + took);
+ },
+ waited(what, took) { waits[what] += took; },
+ spawned(at) { spawnedAt ??= at; },
+ promptSent(at) { promptAt ??= at; },
+ firstUpdate(at) { if (promptAt !== null) firstAt ??= at; },
+ retried() { retries += 1; },
+ finish(outcome, at) {
+ if (done) return null;
+ done = true;
+ const parts = [
+ spawnedAt !== null ? "new process" : promptAt !== null || steps.size || config ? "kept process" : "no process",
+ `models waited ${ms(waits.models)}`,
+ ...(waits.room ? [`room waited ${ms(waits.room)}`] : []),
+ ...(initializedAfter !== null ? [`spawn to initialize ${ms(initializedAfter)}`] : []),
+ ...STEPS.filter((step) => step !== "initialize" && steps.has(step)).map((step) => `${step.replace("session/", "session ")} ${ms(steps.get(step)!)}`),
+ ...(STEPS.some((step) => step.startsWith("session/") && steps.has(step)) || promptAt === null ? [] : ["session live"]),
+ `config ${config} call${config === 1 ? "" : "s"} ${ms(configMs)}`,
+ promptAt === null ? "no prompt" : firstAt === null ? "prompt to first update none" : `prompt to first update ${ms(firstAt - promptAt)}`,
+ `total ${ms(at - startedAt)}`,
+ ...(retries ? [`retried ${retries}`] : []),
+ `ended ${/^[\w-]{1,40}$/u.test(outcome) ? outcome : "other"}`,
+ ];
+ const line = `[perf] engine turn ${/^[\w-]{1,40}$/u.test(engine) ? engine : "acp"}: ${parts.join(", ")}`;
+ recent.push(line);
+ if (recent.length > TURN_STARTS_KEPT) recent.splice(0, recent.length - TURN_STARTS_KEPT);
+ try { log(line); } catch {}
+ return line;
+ },
+ };
+}
+
+/** Hands back `request` unchanged, noting how long it took once it settles; a prompt is timed by its first update. */
+export function timed<T>(clock: TurnStartClock, method: string, request: Promise<T>): Promise<T> {
+ if (method === "session/prompt") return request;
+ const sentAt = Date.now();
+ const note = () => clock.call(method, Date.now() - sentAt);
+ request.then(note, note);
+ return request;
+}
+
+/** The latest lines, oldest first, for the diagnostics export. */
+export function recentTurnStarts(): readonly string[] {
+ return [...recent];
+}
+
+export function turnStartsSection(): string[] {
+ return recent.length ? ["## Engine turn starts (latest, oldest first)", ...recent] : [];
+}
diff --git a/server/startup-model-catalog.test.ts b/server/startup-model-catalog.test.ts
index f2c02abc18..b926c81b57 100644
--- a/server/startup-model-catalog.test.ts
+++ b/server/startup-model-catalog.test.ts
@@ -331,4 +331,27 @@ describe("startup model catalogs", () => {
expect(spawn).toHaveBeenCalled();
await instance.dispose();
});
+
+ it("an ACP engine that opts in runs a turn the saved catalog serves without waiting for the refresh", async () => {
+ seedBots();
+ writeStartupModelCache("cursor", CACHED, STALE);
+ const gate = deferredCatalog();
+ const spawn = vi.spyOn(procs, "spawnCli").mockImplementation(() => {
+ throw new Error("spawned");
+ });
+ const driver = createAcpDriver({ ...acpSupport(() => gate.promise), modelListStandsIn: true });
+ const instance = await driver.create({ instanceId: "cursor", displayName: "Cursor", environment: {}, enabled: true, config: driver.defaultConfig() });
+ for (const model of ["cached-model", undefined]) {
+ await expect(instance.adapter.sendTurn({ threadId: `thread-${model ?? "default"}`, text: "hello", model, cwd: DATA_DIR })).rejects.toThrow("spawned");
+ }
+ expect(spawn).toHaveBeenCalledTimes(2);
+ expect(instance.models).toEqual(CACHED);
+ // A model the saved catalog lacks still waits for the read.
+ const unknown = instance.adapter.sendTurn({ threadId: "thread-unknown", text: "hello", model: "fresh-model", cwd: DATA_DIR });
+ expect(await settledSoon(unknown)).toBe(false);
+ gate.release(FRESH);
+ await expect(unknown).rejects.toThrow("spawned");
+ expect(instance.models).toEqual(FRESH);
+ await instance.dispose();
+ });
});
diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.ts
index 237c06f2ab..c5ad3b373c 100644
--- a/server/system-prompt.test.ts
+++ b/server/system-prompt.test.ts
@@ -495,6 +495,8 @@ it("tells Cloud bots that a sign-in ending on an unreachable 127.0.0.1 page is f
for (const text of [cloudHomePrompt(true), cloudHomePrompt(false), cloudHomePrompt(true, [], [{ name: "ASH-PC", platform: "win32" }], true)]) {
expect(text).toContain("ends on a 127.0.0.1 or localhost page that can't be reached, that is the expected last step, not a failed sign-in");
expect(text).toContain("paste it in the \"Paste its address here\" field on the AI's card");
+ // Antigravity's native CLI signs in with a code its Google page shows instead.
+ expect(text).toContain("paste the code in the \"Code from the Antigravity page\" field on the AI's card, then press Send code");
}
});
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index 26830ab90d..abe75ab3ff 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -194,7 +194,8 @@ export { syncedFolders } from "./cloud-sync-store.ts";
export const CLOUD_ENGINES_HERE = " The AIs bots run on (Claude, Codex, Cursor and the rest) run here, on My Cloud, not on their computer or their cloud computer."
+ " If one needs installing or signing in, tell them to choose it in the model picker: its card does that here, with a sign-in link they open on any device."
+ " Never tell them to run an AI's install or sign-in command on their own computer, and never run one on their cloud computer yourself: neither signs in the AIs here."
- + " When an AI's Google sign-in ends on a 127.0.0.1 or localhost page that can't be reached, that is the expected last step, not a failed sign-in: tell them to copy that page's full address and paste it in the \"Paste its address here\" field on the AI's card, then press Send redirect.";
+ + " When an AI's Google sign-in ends on a 127.0.0.1 or localhost page that can't be reached, that is the expected last step, not a failed sign-in: tell them to copy that page's full address and paste it in the \"Paste its address here\" field on the AI's card, then press Send redirect."
+ + " When Google's Antigravity page shows a code after the sign-in, that is the last step too: tell them to paste the code in the \"Code from the Antigravity page\" field on the AI's card, then press Send code.";
/** `asks`: the person's own Cloud, whose bots ask them to turn on what their computer doesn't give now (ask_for_computer). */
export function cloudHomePrompt(sharedComputerTools: boolean, synced: ReadonlyArray<{ computerName: string; pcPath: string; cloudPath: string }> = [],
diff --git a/server/testing/cleanup.ts b/server/testing/cleanup.ts
index b44e03ce56..bb2007c035 100644
--- a/server/testing/cleanup.ts
+++ b/server/testing/cleanup.ts
@@ -1,6 +1,7 @@
// Teardown primitives for suites that spawn a real process against a throwaway home.
import type { ChildProcess } from "node:child_process";
-import { rmSync } from "node:fs";
+import { chmodSync, readdirSync, rmSync } from "node:fs";
+import { join } from "node:path";
export interface WaitForExitOptions {
/** Sent immediately. Omit for a child the caller has already signalled. */
@@ -53,6 +54,8 @@ export async function removeTempDir(dir: string): Promise<void> {
return;
} catch (error) {
lastError = error;
+ // A read-only folder inside (a published engine release) blocks removal of what it holds.
+ if ((error as NodeJS.ErrnoException).code === "EACCES" && process.platform !== "win32") openFolders(dir);
await new Promise((r) => setTimeout(r, 100));
}
}
@@ -60,3 +63,10 @@ export async function removeTempDir(dir: string): Promise<void> {
`test cleanup could not remove ${dir}: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
);
}
+
+function openFolders(dir: string): void {
+ try {
+ chmodSync(dir, 0o700);
+ for (const entry of readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) openFolders(join(dir, entry.name));
+ } catch {}
+}
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index a78459cc1c..485f7e2cd4 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -44,6 +44,7 @@
// and <dump>.initialize.json for the initialize params
// FAKE_ACP_LAUNCH_COUNT_FILE process counter incremented at startup
// FAKE_ACP_VERSION what `--version` prints (default "fake-acp 1.0.0"); a CLI the driver checks the shape of needs its own
+// FAKE_ACP_PROMPT_STDERR a line written to stderr when a prompt arrives; FAKE_ACP_PROMPT_STDERR_THEN=hang leaves it open
// FAKE_ACP_RPC_DUMP this process's method list, rewritten after every request
// FAKE_ACP_RPC_APPEND_FILE one {"pid","method","cwd"} line appended per request
// FAKE_ACP_RPC_FAILURE_FILE JSON-RPC error for session/prompt; once read the process stays poisoned
@@ -1324,6 +1325,10 @@ function handle(msg: any) {
writeFileSync(`${process.env.FAKE_ACP_DUMP}.prompt.json`, JSON.stringify(msg.params?.prompt ?? null, null, 2));
}
appendAntigravitySteps(msg.params?.sessionId);
+ if (process.env.FAKE_ACP_PROMPT_STDERR) {
+ process.stderr.write(`${process.env.FAKE_ACP_PROMPT_STDERR}\n`);
+ if (process.env.FAKE_ACP_PROMPT_STDERR_THEN === "hang") return;
+ }
if (failRpc(msg)) return;
if (mode === "hermes-steer") {
hermesPrompt(msg);
diff --git a/src/components/EngineSetup.antigravity.test.ts b/src/components/EngineSetup.antigravity.test.ts
index 69529f05ca..66b8695017 100644
--- a/src/components/EngineSetup.antigravity.test.ts
+++ b/src/components/EngineSetup.antigravity.test.ts
@@ -61,6 +61,10 @@ it("shows the paste-the-redirect field the whole time the card waits, on the per
expect(host.querySelector("details")).toBeNull();
await new Promise((resolve) => setTimeout(resolve, 2_300));
expect(host.querySelector("[data-redirect-paste] input")).not.toBeNull();
+ // The pinned runtime's sign-in (the default; the native CLI is opt-in) shows no code field, as before it.
+ expect(host.querySelector("[data-code-paste]")).toBeNull();
+ expect(host.textContent).not.toContain("Code from the Antigravity page");
+ expect(host.textContent).toContain("I finished signing in");
}, 15_000);
it("opens the same Google link again instead of starting another sign-in", async () => {
@@ -113,3 +117,30 @@ it("names Google on the sign-in card, never another provider", () => {
expect(host.textContent).toContain("Sign in with Google");
expect(host.textContent).not.toContain("Mistral");
});
+
+// Antigravity's native CLI signs in with `--login`: Google's Antigravity page shows a code to paste back, and there is no
+// redirect to paste and nothing to finish by itself.
+it("asks for the code the Antigravity page shows when the sign-in is the native CLI's, and sends it", async () => {
+ vi.stubGlobal("ogb", { platform: "linux", openExternal: vi.fn(async () => {}), remoteClient: { active: false } });
+ const fetched = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => String(input).includes("/auth/status")
+ ? auth({ phase: "waiting", flowId: "flow-1", authorizationUrl: null })
+ : auth({ phase: "waiting", flowId: "flow-1", authorizationUrl: "https://accounts.google.com/o/oauth2/auth?state=s", pasteCode: true }));
+ vi.stubGlobal("fetch", fetched);
+ const store = { state: { config: { cloudHome: true } }, dispatch: vi.fn(), refreshInstances: vi.fn(async () => {}), refreshModels: vi.fn(async () => {}) } as unknown as ReturnType<typeof useStore>;
+ flushSync(() => root.render(createElement(BotEditorStore, { value: store, children: createElement(EngineSetup, { instance: antigravity }) })));
+ [...host.querySelectorAll("button")].find((b) => /Sign in with Google/.test(b.textContent ?? ""))!.click();
+ await vi.waitFor(() => expect(host.querySelector("[data-code-paste]")).not.toBeNull());
+ expect(host.querySelector("[data-redirect-paste]")).toBeNull();
+ expect(host.textContent).not.toContain("I finished signing in");
+ expect(host.textContent).not.toContain("Google opens a page that won’t load");
+ expect(host.querySelector("[data-code-paste] p")?.textContent).toBe("After you sign in, Google shows a code on the Antigravity page. Copy it and paste it here.");
+ const field = host.querySelector<HTMLInputElement>("[data-code-paste] input")!;
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ flushSync(() => { setValue.call(field, "4/0Ab-code"); field.dispatchEvent(new Event("input", { bubbles: true })); });
+ const send = [...host.querySelectorAll("button")].find((b) => b.textContent === "Send code")!;
+ await vi.waitFor(() => expect(send.disabled).toBe(false));
+ send.click();
+ await vi.waitFor(() => expect(fetched.mock.calls.some(([url]) => String(url).includes("/auth/complete"))).toBe(true));
+ const [, init] = fetched.mock.calls.find(([url]) => String(url).includes("/auth/complete"))!;
+ expect(JSON.parse(String(init?.body))).toEqual({ flowId: "flow-1", callbackUrl: "4/0Ab-code" });
+});
diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsx
index 95b957fd58..800ebc274e 100644
--- a/src/components/EngineSetup.tsx
+++ b/src/components/EngineSetup.tsx
@@ -277,7 +277,8 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
const signInStarted = useSignInStarted(instance.instanceId);
const [busy, setBusy] = useState<"install" | "signin" | "complete" | "check" | null>(null);
const [error, setError] = useState<string | null>(null);
- const [flow, setFlow] = useState<{ flowId: string; authorizationUrl: string } | null>(null);
+ // `pasteCode`: Antigravity's native CLI, whose Google page shows a code to paste back instead of a redirect.
+ const [flow, setFlow] = useState<{ flowId: string; authorizationUrl: string; pasteCode?: boolean } | null>(null);
const [callbackUrl, setCallbackUrl] = useState("");
const managed = instance.install!.managed!;
@@ -341,7 +342,7 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
return;
}
if (!auth.flowId || !auth.authorizationUrl) throw new Error(t("engineSetup.googleNoLink"));
- setFlow({ flowId: auth.flowId, authorizationUrl: auth.authorizationUrl });
+ setFlow({ flowId: auth.flowId, authorizationUrl: auth.authorizationUrl, pasteCode: auth.pasteCode === true });
await openLink(auth.authorizationUrl);
});
@@ -373,9 +374,9 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
{busy === "install" ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
{busy === "install" ? t("engineSetup.installing") : managed.label}
</button>
- <p className="mt-1.5 text-center text-[11px] text-ink-tertiary">
+ {!managed.sizeUnknown && <p className="mt-1.5 text-center text-[11px] text-ink-tertiary">
{t("engineSetup.downloadNote", { mb: Math.ceil(managed.downloadBytes / 1024 / 1024) })}
- </p>
+ </p>}
{error && <p className="mt-2 text-[12px] text-danger">{error}</p>}
</div>
);
@@ -384,7 +385,7 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
const cloudHome = state.config?.cloudHome === true;
return (
<div className="mt-3 space-y-2">
- {cloudHome && <p className="text-[12px] leading-relaxed text-ink-secondary">{t("engineSetup.cloudPasteHint")}</p>}
+ {cloudHome && !flow?.pasteCode && <p className="text-[12px] leading-relaxed text-ink-secondary">{t("engineSetup.cloudPasteHint")}</p>}
<button
type="button"
disabled={busy !== null}
@@ -399,7 +400,27 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
: t("engineSetup.signInGoogle")}
</button>
{busy === "signin" && <p role="status" className="text-[12px] text-ink-secondary">{t("engineSetup.antigravitySlow")}</p>}
- {flow && (
+ {flow?.pasteCode && (
+ <div data-code-paste className="rounded-lg border border-hairline/50 bg-app px-2.5 py-2 text-[12px] text-ink-secondary">
+ <p className="leading-relaxed">{t("engineSetup.pasteCodeHint")}</p>
+ <input
+ value={callbackUrl}
+ onChange={(event) => setCallbackUrl(event.target.value)}
+ aria-label={t("engineSetup.pasteCodeLabel")}
+ autoComplete="off"
+ className="mt-2 w-full rounded-md border border-hairline bg-inset px-2 py-1.5 text-[11px] text-ink outline-none focus:border-accent"
+ />
+ <button
+ type="button"
+ disabled={!callbackUrl.trim() || busy !== null}
+ onClick={() => void complete()}
+ className="mt-2 w-full rounded-md bg-control px-2 py-1.5 font-medium text-ink disabled:opacity-50"
+ >
+ {busy === "complete" ? t("engineSetup.sending") : t("engineSetup.sendCode")}
+ </button>
+ </div>
+ )}
+ {flow && !flow.pasteCode && (
<>
<button type="button" onClick={() => void check()} className="w-full rounded-lg bg-control px-3 py-2 text-[12px] font-semibold text-ink hover:bg-raised-hover">
{busy === "check" ? t("common.checking") : t("engineSetup.finishedSignIn")}
diff --git a/src/locales/en.json b/src/locales/en.json
index 11afc7fd0a..cc2914f265 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3723,6 +3723,9 @@
"engineSetup.otherComputerUrl": "Page address from the other computer",
"engineSetup.sending": "Sending…",
"engineSetup.sendRedirect": "Send redirect",
+ "engineSetup.pasteCodeHint": "After you sign in, Google shows a code on the Antigravity page. Copy it and paste it here.",
+ "engineSetup.pasteCodeLabel": "Code from the Antigravity page",
+ "engineSetup.sendCode": "Send code",
"engineSetup.googleNoLink": "Google sign-in did not return a link.",
"engineSetup.googleExpired": "Google sign-in expired. Start again.",
"engineSetup.googleFailed": "Google sign-in did not finish. Start again.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3640b9601e..027110aba1 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -3532,6 +3532,9 @@
"engineSetup.otherComputerUrl": "Endereço da página no outro computador",
"engineSetup.sending": "Enviando…",
"engineSetup.sendRedirect": "Enviar link",
+ "engineSetup.pasteCodeHint": "Depois que você entrar, o Google mostra um código na página do Antigravity. Copie e cole aqui.",
+ "engineSetup.pasteCodeLabel": "Código da página do Antigravity",
+ "engineSetup.sendCode": "Enviar código",
"engineSetup.googleNoLink": "O login do Google não devolveu um link.",
"engineSetup.googleExpired": "O login com o Google expirou. Comece de novo.",
"engineSetup.googleFailed": "O login com o Google não foi concluído. Comece de novo.",
diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.ts
index 30e45aadb4..e87a47f4b1 100644
--- a/src/locales/server-lines.test.ts
+++ b/src/locales/server-lines.test.ts
@@ -502,6 +502,23 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni
["server/team-setup-requests.ts", "Team setup not applied"],
],
"restarts, stops and context": [
+ ["server/drivers/acp/quiet-status.ts", "hit a rate limit (HTTP 429)"],
+ ["server/drivers/acp/quiet-status.ts", "got a server error from its model provider (HTTP"],
+ ["server/drivers/acp/quiet-status.ts", "got an error from its model provider (HTTP"],
+ ["server/drivers/acp/quiet-status.ts", "had a failed model request"],
+ ["server/drivers/acp/quiet-status.ts", " Next try in … s."],
+ ["server/drivers/acp/quiet-status.ts", "and is retrying … . … It is still working."],
+ ["server/drivers/acp/quiet-status.ts", "'s model request failed:"],
+ ["server/drivers/acp/quiet-status.ts", "is compressing its conversation history to make room."],
+ ["server/drivers/acp/quiet-status.ts", "Its history is nearly full, so it may be compressing it."],
+ ["server/drivers/acp/quiet-status.ts", "; with no tool or question active, the turn may stop after"],
+ ["server/drivers/acp/quiet-status.ts", "Its model provider may be slow or busy"],
+ ["server/drivers/acp/quiet-status.ts", "is busy on this computer but has sent nothing for"],
+ ["server/drivers/acp/quiet-status.ts", "and has no request open to its model right now."],
+ ["server/drivers/acp/quiet-status.ts", "It may be waiting before a retry. Still waiting; press Stop to end the"],
+ ["server/drivers/acp/quiet-status.ts", "has no open request to its model, and is not using the CPU. It may be"],
+ ["server/drivers/acp/quiet-status.ts", "Press Stop to end the turn; otherwise it is stopped after"],
+ ["server/drivers/acp/quiet-status.ts", "… has sent nothing for … . Still waiting; press Stop to end the turn."],
["server/index.ts", "context compaction started ( … )"],
["server/host/warm-summary-host.ts", "context compaction started (auto)"],
["server/index.ts", "context compacted — re-sent the last … digest …"],
diff --git a/src/state/engine-install.ts b/src/state/engine-install.ts
index 9bc957dbcc..053005fdea 100644
--- a/src/state/engine-install.ts
+++ b/src/state/engine-install.ts
@@ -7,7 +7,7 @@ export interface EngineInstall {
docsUrl?: string;
signInCommand?: string;
needsNode?: boolean;
- managed?: { label: string; downloadBytes: number };
+ managed?: { label: string; downloadBytes: number; sizeUnknown?: true };
server?: { package?: string; standalone?: { version: string; downloadBytes: number } };
settings?: "connections";
/** The CLI runs the copy OpenMausBot installed, which the person's terminal does not reach: set up in the app, not there. */