Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 189 additions & 2 deletions server/drivers/antigravity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,24 @@
//
// The fake CLI is a shebang script Windows cannot exec directly;
// spawnCli resolves it to `node <script>`, so these run everywhere.
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { ensureDirs } from "../config.ts";
import type { ProviderInstance } from "../contracts.ts";
import { SPAWNED_PROXIES } from "../proxy-paths.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { AntigravityDriver, readAntigravityModelCatalog, STATIC_ANTIGRAVITY_MODELS } from "./antigravity.ts";
import {
ANTIGRAVITY_COMPUTER_MCP_KEY,
AntigravityDriver,
antigravityComputerMcpServer,
ensureAntigravityComputerMcp,
readAntigravityModelCatalog,
STATIC_ANTIGRAVITY_MODELS,
} from "./antigravity.ts";

const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-agy-cli.ts");

Expand Down Expand Up @@ -198,3 +206,182 @@ describe("Antigravity snapshot", () => {
}
});
});

describe("Antigravity computer MCP config", () => {
const configPath = (home: string) => join(home, ".gemini", "config", "mcp_config.json");
const readConfig = (home: string) => JSON.parse(readFileSync(configPath(home), "utf8"));
const boxIntegrations = {
computer: {
kind: "box" as const,
boxId: "bx_1",
token: "box-tok",
control: { url: "http://127.0.0.1:9/control", token: "ctl-tok" },
},
};
const boxEntry = () => antigravityComputerMcpServer(boxIntegrations)!;

it("builds the cloud-box spec on the shared computer proxy (never path-resolved locally)", () => {
expect(antigravityComputerMcpServer(boxIntegrations)).toEqual({
command: process.execPath,
args: [SPAWNED_PROXIES.computer],
env: {
ELECTRON_RUN_AS_NODE: "1",
OGB_BOX_ID: "bx_1",
OGB_BOX_TOKEN: "box-tok",
OMB_CONTROL_URL: "http://127.0.0.1:9/control",
OMB_CONTROL_TOKEN: "ctl-tok",
},
});
});

it("passes a Local VM / VPS stdio connection through unchanged, and yields null without a computer", () => {
expect(
antigravityComputerMcpServer({
localComputer: { command: "/opt/cua", args: ["--mcp"], env: { CUA_SOCKET: "/tmp/cua.sock" } },
}),
).toEqual({ command: "/opt/cua", args: ["--mcp"], env: { CUA_SOCKET: "/tmp/cua.sock" } });
expect(antigravityComputerMcpServer({})).toBeNull();
expect(antigravityComputerMcpServer(undefined)).toBeNull();
});

it("upserts only its own key — the user's servers and unknown top-level keys survive", () => {
const home = mkdtempSync(join(tmpdir(), "omb-agy-mcpcfg-"));
try {
mkdirSync(join(home, ".gemini", "config"), { recursive: true });
writeFileSync(
configPath(home),
JSON.stringify({
mcpServers: { "sqlite-helper": { command: "sqlite-mcp-server", args: ["/db"] } },
futureTopLevelKey: { keep: true },
}),
);
ensureAntigravityComputerMcp(boxEntry(), { HOME: home });
let config = readConfig(home);
expect(config.mcpServers["sqlite-helper"]).toEqual({ command: "sqlite-mcp-server", args: ["/db"] });
expect(config.futureTopLevelKey).toEqual({ keep: true });
expect(config.mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY]).toEqual(boxEntry());

// A later turn on a different computer overwrites the key in place.
ensureAntigravityComputerMcp(
{ command: "/opt/cua", args: ["--mcp"], env: { CUA_SOCKET: "/tmp/cua.sock" } },
{ HOME: home },
);
config = readConfig(home);
expect(config.mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY].command).toBe("/opt/cua");
expect(config.mcpServers["sqlite-helper"]).toEqual({ command: "sqlite-mcp-server", args: ["/db"] });
expect(config.futureTopLevelKey).toEqual({ keep: true });
} finally {
rmSync(home, { recursive: true, force: true });
}
});

it("starts fresh from malformed JSON instead of failing the turn", () => {
const home = mkdtempSync(join(tmpdir(), "omb-agy-mcpbad-"));
try {
mkdirSync(join(home, ".gemini", "config"), { recursive: true });
writeFileSync(configPath(home), "{{{ not json");
ensureAntigravityComputerMcp(boxEntry(), { HOME: home });
expect(readConfig(home).mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY]).toEqual(boxEntry());
} finally {
rmSync(home, { recursive: true, force: true });
}
});

it("a computer-less turn removes only its own key, and never creates the file just to remove", () => {
const home = mkdtempSync(join(tmpdir(), "omb-agy-mcprm-"));
try {
// No file at all: removal is a no-op, not an empty file in the user's home.
ensureAntigravityComputerMcp(null, { HOME: home });
expect(existsSync(configPath(home))).toBe(false);

mkdirSync(join(home, ".gemini", "config"), { recursive: true });
writeFileSync(
configPath(home),
JSON.stringify({
mcpServers: {
"sqlite-helper": { command: "sqlite-mcp-server", args: ["/db"] },
[ANTIGRAVITY_COMPUTER_MCP_KEY]: boxEntry(),
},
}),
);
ensureAntigravityComputerMcp(null, { HOME: home });
const config = readConfig(home);
expect(config.mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY]).toBeUndefined();
expect(config.mcpServers["sqlite-helper"]).toEqual({ command: "sqlite-mcp-server", args: ["/db"] });
} finally {
rmSync(home, { recursive: true, force: true });
}
});

it("advertises computerMcp only on full-auto instances, and never localComputerMcp", async () => {
const fullAuto = await AntigravityDriver.create({
instanceId: "agy-caps-full",
displayName: undefined,
environment: {},
enabled: true,
config: { cli: FAKE_CLI, fullAuto: true },
});
const acceptEdits = await AntigravityDriver.create({
instanceId: "agy-caps-safe",
displayName: undefined,
environment: {},
enabled: true,
config: { cli: FAKE_CLI, fullAuto: false },
});
try {
expect(fullAuto.adapter.capabilities.computerMcp).toBe(true);
// accept-edits print mode auto-denies tools that would prompt, so a
// mount there could never fire — the capability must not be offered.
expect(acceptEdits.adapter.capabilities.computerMcp).toBe(false);
// The host desktop needs per-action human approval; print mode has no
// approval channel in any mode.
expect(fullAuto.adapter.capabilities.localComputerMcp).toBeUndefined();
expect(acceptEdits.adapter.capabilities.localComputerMcp).toBeUndefined();
} finally {
await fullAuto.dispose();
await acceptEdits.dispose();
}
});

it("writes the mount before spawning agy and clears it on the next computer-less turn", async () => {
ensureDirs();
chmodSync(FAKE_CLI, 0o755);
const home = mkdtempSync(join(tmpdir(), "omb-agy-mcpturn-"));
mkdirSync(join(home, ".gemini", "config"), { recursive: true });
writeFileSync(
configPath(home),
JSON.stringify({ mcpServers: { "sqlite-helper": { command: "sqlite-mcp-server", args: ["/db"] } } }),
);
const instance = await AntigravityDriver.create({
instanceId: "agy-mcp-turn",
displayName: undefined,
environment: { HOME: home },
enabled: true,
config: { cli: FAKE_CLI, fullAuto: true },
});
const recorder = recordEvents(instance.adapter);
try {
await instance.adapter.sendTurn({
threadId: "t-mcp-on",
text: "click things",
integrations: boxIntegrations,
});
// sendTurn resolves after the child is spawned; the write happens
// synchronously before that spawn, so this IS the spawn-time content.
const mounted = readConfig(home);
expect(mounted.mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY]).toEqual(boxEntry());
expect(mounted.mcpServers["sqlite-helper"]).toEqual({ command: "sqlite-mcp-server", args: ["/db"] });
await recorder.until((e) => e.type === "turn.completed");

await instance.adapter.sendTurn({ threadId: "t-mcp-off", text: "no computer here" });
const cleared = readConfig(home);
expect(cleared.mcpServers[ANTIGRAVITY_COMPUTER_MCP_KEY]).toBeUndefined();
expect(cleared.mcpServers["sqlite-helper"]).toEqual({ command: "sqlite-mcp-server", args: ["/db"] });
await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-mcp-off");
} finally {
recorder.stop();
await instance.dispose();
rmSync(home, { recursive: true, force: true });
}
});
});
132 changes: 129 additions & 3 deletions server/drivers/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@
// `request-review` auto-denies; `--dangerously-skip-permissions` (fullAuto)
// approves everything. Real per-action approval cards are a future path via
// native ACP (agy issue #31), which would reuse acp/core.ts like grok/gemini.
//
// Computer use: agy has no per-turn MCP flag, so the bot's computer (cloud
// box / Local VM / VPS) is mounted by upserting one key into the global
// `~/.gemini/config/mcp_config.json` before each spawn — see
// ensureAntigravityComputerMcp below. Full-auto instances only; the host
// desktop stays off (no approval channel in print mode, ever).
import { describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";
import { mkdirSync, readFileSync } from "node:fs";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { z } from "zod";

import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
import { computerProxyEnv } from "../container-computer.ts";
import { augmentedPath } from "../env-path.ts";
import { SPAWNED_PROXIES } from "../proxy-paths.ts";
import { injectedApiModel, mergeLocalInject } from "./local-inject.ts";

import type { ChildProcess } from "node:child_process";
Expand Down Expand Up @@ -110,6 +119,89 @@ export function readAntigravityModelCatalog(env: Record<string, string | undefin
return { default: STATIC_ANTIGRAVITY_MODELS.default, options };
}

// ── computer MCP mount ──────────────────────────────────────────────────
// agy has no per-session MCP flag and no project-level MCP config: verified
// against agy 1.1.19, whose embedded docs list exactly two locations — the
// global `~/.gemini/config/mcp_config.json` and per-plugin files — and whose
// `agy mcp list` ignores `.gemini/{settings,mcp_config}.json` in the cwd.
// So the bot's computer is mounted by upserting ONE key into the global file
// right before each spawn: every other byte of the user's config is
// preserved, and a malformed file starts from a fresh object instead of
// failing the turn (the ensureOpenCodeInjectModel discipline).
export const ANTIGRAVITY_COMPUTER_MCP_KEY = "openmausbot-computer";

export interface AntigravityComputerMcpServer {
command: string;
args: string[];
env: Record<string, string>;
}

// Lenient by design: keep every unknown key the user put in the file. A
// present-but-wrong mcpServers (e.g. an array) fails the parse and is
// rebuilt fresh — that file was already unusable to agy itself.
const mcpConfigFileSchema = z.looseObject({
mcpServers: z.looseObject({}).optional(),
});

/** The computer MCP server for this turn, or null when the turn has none.
* Cloud boxes go through OpenMausBot's REST-to-MCP adapter (the same spec
* claude.ts and codex.ts build); Local VM and VPS connections arrive as a
* ready-made Cua Driver stdio command and pass through unchanged. */
export function antigravityComputerMcpServer(
integrations: SendTurnInput["integrations"],
): AntigravityComputerMcpServer | null {
const computer = integrations?.computer;
if (computer) {
const proxyEnv = computerProxyEnv(computer);
return {
command: process.execPath,
args: [SPAWNED_PROXIES.computer],
env: {
ELECTRON_RUN_AS_NODE: "1",
OGB_BOX_ID: proxyEnv.OGB_BOX_ID ?? "",
OGB_BOX_TOKEN: proxyEnv.OGB_BOX_TOKEN ?? "",
// who-is-driving endpoint, so a person taking the wheel in the
// panel pauses this bot's hands mid-turn
OMB_CONTROL_URL: proxyEnv.OMB_CONTROL_URL ?? "",
OMB_CONTROL_TOKEN: proxyEnv.OMB_CONTROL_TOKEN ?? "",
},
};
}
const local = integrations?.localComputer;
if (local) return { command: local.command, args: local.args, env: { ...local.env } };
return null;
}

/** Upsert (server) or remove (null) the openmausbot-computer entry in the
* global mcp_config.json. Only that one key is ever written; a turn without
* a computer removes it so a previous turn's mount cannot leak tools — or
* box/control tokens — into later turns or the user's own agy sessions. */
export function ensureAntigravityComputerMcp(
server: AntigravityComputerMcpServer | null,
env: Record<string, string | undefined> = process.env,
): void {
const home = env.HOME || env.USERPROFILE || homedir();
const path = join(home, ".gemini", "config", "mcp_config.json");
let config: z.infer<typeof mcpConfigFileSchema> = {};
try {
const parsed = mcpConfigFileSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
if (parsed.success) config = parsed.data;
} catch {
// Missing or malformed user config — rebuild only what the mount needs.
}
const servers = { ...config.mcpServers };
// Nothing to remove and nothing to add: leave the user's file untouched
// (don't create or reformat it on every computer-less turn).
if (!server && !(ANTIGRAVITY_COMPUTER_MCP_KEY in servers)) return;
if (server) {
servers[ANTIGRAVITY_COMPUTER_MCP_KEY] = { command: server.command, args: server.args, env: server.env };
} else {
delete servers[ANTIGRAVITY_COMPUTER_MCP_KEY];
}
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, `${JSON.stringify({ ...config, mcpServers: servers }, null, 2)}\n`);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

function decodeConfig(raw: unknown): AntigravityConfig {
const o = (raw ?? {}) as Record<string, unknown>;
if (o.cli !== undefined && typeof o.cli !== "string") {
Expand Down Expand Up @@ -248,6 +340,27 @@ export const AntigravityDriver: ProviderDriver<AntigravityConfig> = {
return { turnId };
}

// Mount (or unmount) the bot's computer for this turn, in the global
// mcp_config.json, as close to the spawn as possible — the file is
// machine-global, so the window in which a concurrent Antigravity turn
// with a DIFFERENT computer could re-write it before this child reads
// its config should stay as small as it can. A failed write with a
// computer to mount must fail the turn: the bot was promised tools it
// would otherwise burn the whole turn hunting for.
try {
ensureAntigravityComputerMcp(antigravityComputerMcpServer(turn.integrations), catalogEnv);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch (error) {
emit({
...base(threadId, turnId),
type: "runtime.error",
message: `could not update Antigravity's MCP config (${join(".gemini", "config", "mcp_config.json")}): ${
error instanceof Error ? error.message : String(error)
}`,
});
settle(false, "mcp_config_error");
return { turnId };
}

const args = [
"--print", prompt, // print mode reads the prompt from this argv value
"--output-format", "stream-json",
Expand Down Expand Up @@ -428,7 +541,20 @@ export const AntigravityDriver: ProviderDriver<AntigravityConfig> = {
snapshot,
adapter: {
provider: DRIVER_KIND,
capabilities: { sessionModelSwitch: "in-session", images: true },
capabilities: {
sessionModelSwitch: "in-session",
images: true,
// Cloud box, Local VM, and VPS computers all mount through the
// global mcp_config.json above. Only full-auto instances advertise
// it: print mode has no interactive approval channel, and outside
// --dangerously-skip-permissions agy auto-denies tools that would
// prompt (the accept-edits shell behavior in the header comment),
// so a non-fullAuto mount could never fire. localComputerMcp stays
// unset on purpose — the host desktop requires per-action human
// approval (see contracts.ts), which print mode cannot deliver in
// any mode; that returns with the native ACP path (agy issue #31).
computerMcp: config.fullAuto,
},
sendTurn,
interruptTurn: async (threadId) => active.get(threadId)?.stop(),
respondToRequest: async () => "unavailable" as const, // this engine has no asks to answer
Expand Down
Loading