From e7b4f296e945facc12bb97c63dd612f7d77c626e Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Sun, 22 Nov 2026 17:30:10 +0300 Subject: [PATCH] feat(antigravity): add Antigravity CLI over native ACP Add Antigravity CLI (`agy acp`) as a built-in Subturn harness so callers can spawn and resume Antigravity models through the same five-tool surface without learning its flags, auth layout, or config options. - `src/plugins/antigravity.ts`: `antigravity` plugin discovering `agy`, applying `model` then `thought_level` via `session/set_config_option` on every turn, isolating session state under `--gemini-dir` / `GEMINI_HOME`, copying file-based OAuth tokens privately (0600, reconciled on resume so refreshes stay in the shadow and account/method switches clear stale state), and falling back to ACP `authenticate` (`gemini-api-key`) when `GEMINI_API_KEY` is set. - `src/core/acp-turn.ts`: optional `authMethodId` for ACP `authenticate`, treat `stopReason=refusal` as a failed turn, and emit an `exit` event on clean child shutdown. - `src/plugins/acp-models-probe.ts`: prefer deduplicated `configOptions[id="model"]` values (including grouped select options) over legacy `models.availableModels`, check `protocolVersion === 1`, and support optional `authMethodId`. - `src/faces/cli.ts`: size the `status` name column dynamically so longer harness names stay aligned. - `test/antigravity.test.ts`, `test/live.test.ts`, `README.md`, `package.json`: offline tests against a stateful fake `agy`, cheap live bundle entry, and docs. Model and harness: Gemini 4 Neon (High) in Antigravity. --- README.md | 19 +- package.json | 1 + src/core/acp-turn.ts | 21 +- src/faces/cli.ts | 19 +- src/plugins/acp-models-probe.ts | 75 +++-- src/plugins/antigravity.ts | 338 ++++++++++++++++++++ src/plugins/index.ts | 1 + test/antigravity.test.ts | 537 ++++++++++++++++++++++++++++++++ test/live.test.ts | 1 + 9 files changed, 965 insertions(+), 47 deletions(-) create mode 100644 src/plugins/antigravity.ts create mode 100644 test/antigravity.test.ts diff --git a/README.md b/README.md index 11543ee..f33660e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Run subagents in any coding agent you have installed, from any MCP client. You pick the harness and model, it handles the rest. -It is an MCP server. A coding agent calls it with a harness, a model and effort, a prompt, and a working directory; Subturn starts a session in that harness with the logins you already have, hands back the harness's own session id, and the caller collects the answer later. Codex, Claude Code, Grok, and OpenCode are supported today. The npm package, the MCP server name, and the CLI binary are all called `subturn`. Why it is shaped this way is in [AGENTS.md](AGENTS.md). +It is an MCP server. A coding agent calls it with a harness, a model and effort, a prompt, and a working directory; Subturn starts a session in that harness with the logins you already have, hands back the harness's own session id, and the caller collects the answer later. Codex, Claude Code, Grok, OpenCode, and Antigravity are supported today. The npm package, the MCP server name, and the CLI binary are all called `subturn`. Why it is shaped this way is in [AGENTS.md](AGENTS.md). ## Install and wire up @@ -37,7 +37,7 @@ Here is a whole file, as an example. Give it the same scope as the server: your ```markdown Delegate through the `subturn` MCP server. Never call the harness CLIs from Bash. -Spawn with a harness (`claude`, `codex`, `grok`, `opencode`), a full model id and a reasoning effort (both passed verbatim), a prompt, and an absolute cwd. After the few seconds the harness needs to come up you get its own session id back while the subagent runs on; if anything fails before the session exists, the spawn itself errors with the full detail inline. `await` the id for the outcome, waiting up to `timeout` seconds (default and max 300, `0` for a snapshot; the turn keeps running if the wait runs out): final text, usage, and the model and effort the harness acknowledged on success, bare `failed` or `cancelled` otherwise. `resume` the id with a new prompt to continue the conversation once its turn is no longer running; harness, model, effort, and cwd carry over, the id stays the same, and the conversation stays resumable for 7 days after its last turn. `cancel` kills a running turn and keeps the session. Every "why" is in `inspect`, which returns the raw evidence and works mid-run. Turns die at their deadline (default 3600 s), so fire-and-forget is safe; fan-out is just several spawns. Give the subagent a disposable cwd or worktree when cleanliness matters and diff it afterwards. +Spawn with a harness (`claude`, `codex`, `grok`, `opencode`, `antigravity`), a full model id and a reasoning effort (both passed verbatim), a prompt, and an absolute cwd. After the few seconds the harness needs to come up you get its own session id back while the subagent runs on; if anything fails before the session exists, the spawn itself errors with the full detail inline. `await` the id for the outcome, waiting up to `timeout` seconds (default and max 300, `0` for a snapshot; the turn keeps running if the wait runs out): final text, usage, and the model and effort the harness acknowledged on success, bare `failed` or `cancelled` otherwise. `resume` the id with a new prompt to continue the conversation once its turn is no longer running; harness, model, effort, and cwd carry over, the id stays the same, and the conversation stays resumable for 7 days after its last turn. `cancel` kills a running turn and keeps the session. Every "why" is in `inspect`, which returns the raw evidence and works mid-run. Turns die at their deadline (default 3600 s), so fire-and-forget is safe; fan-out is just several spawns. Give the subagent a disposable cwd or worktree when cleanliness matters and diff it afterwards. - The prompt is all the subagent sees. Put everything it needs in it. - Subagents cannot delegate further. Cross-checks and reviews are separate spawns from here. @@ -67,7 +67,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio ## How it works -**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's auth file, the `credential` table in OpenCode's database). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence. +**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's auth file, the `credential` table in OpenCode's database, Antigravity's OAuth token / keychain / `GEMINI_API_KEY`). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence. **Sessions** live under `~/.local/state/subturn/sessions//` (`SUBTURN_STATE_DIR` overrides). The directory holds the record, the prompt, the spawn command, the event stream as it happens, stderr, the acknowledged bundle where the harness echoes one, and the final text, so `inspect` works on a running session. Retention is 7 days after the last turn (`SUBTURN_RETENTION_DAYS`), swept on each spawn or on demand by `prune`; the resume window is the retention window, because the harness state needed for resume lives in the same directory. The deadline default is 3600 s (`SUBTURN_DEADLINE_S`), the maximum six hours. @@ -77,12 +77,13 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio **Plugins** (`src/plugins`) answer a small interface per harness: detection hints, auth, advertised models, shadow home, launch, and post-turn hygiene. Adding a harness is one entry in the registry; plugin modules load on first use. -| harness | transport | bundle | resume | session hygiene | -|----------|-----------|--------|--------|-----------------| -| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; the user's credentials snapshotted into a private `opencode.db` with the session tables emptied | -| grok | native ACP (`grok agent … stdio`) | `-m` / `--reasoning-effort` every turn; ack read from `session/new` | ACP `session/load` | shadow home via `GROK_HOME`; `auth.json` symlinked back | -| codex | headless `codex exec --json` | `-m` / `-c model_reasoning_effort=` every turn | `codex exec resume ` in the session's `CODEX_HOME` shadow | shadow home via `CODEX_HOME`; `auth.json` symlinked back; the user's `config.toml` deliberately not shared | -| claude | headless `claude -p --output-format stream-json` | `--model` / `--effort` every turn | `claude -p --resume ` after restoring parked files | default config dir, because keychain auth is bound to it; session files parked out of `~/.claude/projects` the moment a turn ends | +| harness | transport | bundle | resume | session hygiene | +|-------------|-----------|--------|--------|-----------------| +| antigravity | native ACP (`agy acp`) | `session/set_config_option` `model` then `thought_level`, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow home via `--gemini-dir` + `GEMINI_HOME`; file OAuth token copied privately (`0600`) when present, desktop keyring shared automatically; `--include-default-customizations=false` | +| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; the user's credentials snapshotted into a private `opencode.db` with the session tables emptied | +| grok | native ACP (`grok agent … stdio`) | `-m` / `--reasoning-effort` every turn; ack read from `session/new` | ACP `session/load` | shadow home via `GROK_HOME`; `auth.json` symlinked back | +| codex | headless `codex exec --json` | `-m` / `-c model_reasoning_effort=` every turn | `codex exec resume ` in the session's `CODEX_HOME` shadow | shadow home via `CODEX_HOME`; `auth.json` symlinked back; the user's `config.toml` deliberately not shared | +| claude | headless `claude -p --output-format stream-json` | `--model` / `--effort` every turn | `claude -p --resume ` after restoring parked files | default config dir, because keychain auth is bound to it; session files parked out of `~/.claude/projects` the moment a turn ends | Every plugin launches its harness in a validated permissive posture (`--dangerously-bypass-approvals-and-sandbox`, `--dangerously-skip-permissions`, `--always-approve`, or Subturn's own allow-everything ACP permission handler). Concurrent sessions of one harness do not collide: shadow state is per session. diff --git a/package.json b/package.json index 2449a37..ffdcbe0 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "claude-code", "grok", "opencode", + "antigravity", "acp" ], "type": "module", diff --git a/src/core/acp-turn.ts b/src/core/acp-turn.ts index b350b1b..1ed34ec 100644 --- a/src/core/acp-turn.ts +++ b/src/core/acp-turn.ts @@ -23,6 +23,9 @@ const SESSION_LOAD_TIMEOUT_MS = 120_000; // replay of a long history takes time export interface AcpTurnPlan { argv: string[]; + /** Optional ACP `authenticate` methodId sent right after `initialize` + * (e.g. antigravity's `gemini-api-key` when authenticating via env var). */ + authMethodId?: string; /** Applied after session/new or session/load; returns the * acknowledged-bundle record for ack.json, or null when the harness * echoes nothing. Throw to fail. Runs on resumed turns too — this is @@ -160,6 +163,11 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise throw new Error(`initialize: unexpected protocolVersion in ${JSON.stringify(initResult)}`); } + if (plan.authMethodId !== undefined) { + const authResult = await client.request("authenticate", { methodId: plan.authMethodId }, INITIALIZE_TIMEOUT_MS); + ctx.emit({ type: "authenticate_result", methodId: plan.authMethodId, result: authResult ?? null }); + } + let sessionNewResult: Record | null = null; if (ctx.nativeSessionId !== undefined) { // Non-forking resume: same session id, conversation continues. @@ -247,8 +255,8 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise const stopReason = isRecord(promptResult) ? promptResult["stopReason"] : undefined; const finalText = finalChunks.join(""); - if (stopReason === "cancelled") { - return { ok: false, error: `prompt stopReason=cancelled\nstderr tail:\n${spawned.stderrTail()}` }; + if (stopReason === "cancelled" || stopReason === "refusal") { + return { ok: false, error: `prompt stopReason=${stopReason}\nstderr tail:\n${spawned.stderrTail()}` }; } const outcome: LaunchOutcome = { ok: true, finalText }; const usage = extractUsage(usageCandidates); @@ -266,11 +274,12 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise client.close(); // Graceful: give the harness a moment to exit on stdin close, then kill // the group (adapter children can outlive the leader). - const exited = await Promise.race([ - spawned.waitExit().then(() => true), - new Promise((r) => setTimeout(r, 3000, false)), + const exit = await Promise.race([ + spawned.waitExit(), + new Promise((r) => setTimeout(r, 3000, null)), ]); - if (!exited) ctx.emit({ type: "close_forced_kill", pid: spawned.pid }); + if (exit === null) ctx.emit({ type: "close_forced_kill", pid: spawned.pid }); + else ctx.emit({ type: "exit", code: exit.code, signal: exit.signal }); spawned.killGroup(); } } diff --git a/src/faces/cli.ts b/src/faces/cli.ts index 473feb1..d6ce4d2 100644 --- a/src/faces/cli.ts +++ b/src/faces/cli.ts @@ -122,11 +122,14 @@ async function cmdStatus(): Promise { // Human-only. Probes: version/auth/handshake — never a prompt. const { loadPlugins } = await import("../plugins/index.ts"); const { resolvePin } = await import("../core/discovery.ts"); + const plugins = await loadPlugins(); + const col = Math.max(9, ...[...plugins.keys()].map((n) => n.length)); + const pad = " ".repeat(col + 1); const rows: string[] = []; - for (const [name, plugin] of await loadPlugins()) { + for (const [name, plugin] of plugins) { const pin = await resolvePin(name, plugin.hints); if (pin === null) { - rows.push(`${name.padEnd(9)} not installed`); + rows.push(`${name.padEnd(col)} not installed`); continue; } const auth = await plugin.auth(); @@ -134,18 +137,18 @@ async function cmdStatus(): Promise { if (auth.ok) { const models = await plugin.models(pin.binPath); modelsLine = models !== null - ? `\n${" ".repeat(10)}models: ${models.join(", ")}` - : `\n${" ".repeat(10)}models: (no cheap advertisement for this harness)`; + ? `\n${pad}models: ${models.join(", ")}` + : `\n${pad}models: (no cheap advertisement for this harness)`; } const others = pin.candidates.filter((c) => c.binPath !== pin.binPath); const othersLine = others.length > 0 - ? `${" ".repeat(10)}also installed, older: ${others.map((c) => `${c.binPath} (${c.version})`).join(", ")}\n` + ? `${pad}also installed, older: ${others.map((c) => `${c.binPath} (${c.version})`).join(", ")}\n` : ""; rows.push( - `${name.padEnd(9)} ${pin.version}\n` + - `${" ".repeat(10)}binary: ${pin.binPath}\n` + + `${name.padEnd(col)} ${pin.version}\n` + + `${pad}binary: ${pin.binPath}\n` + othersLine + - `${" ".repeat(10)}auth: ${auth.ok ? "ok" : "NOT AUTHORIZED"} — ${auth.detail}` + + `${pad}auth: ${auth.ok ? "ok" : "NOT AUTHORIZED"} — ${auth.detail}` + modelsLine, ); } diff --git a/src/plugins/acp-models-probe.ts b/src/plugins/acp-models-probe.ts index 6d8d566..5ab039c 100644 --- a/src/plugins/acp-models-probe.ts +++ b/src/plugins/acp-models-probe.ts @@ -1,9 +1,10 @@ // plugins/acp-models-probe.ts — throwaway ACP handshake for CLI `status`: // spawn the agent, initialize + session/new in a temp cwd, read the // advertised models, kill. Never sends a prompt; costs no quota. Models are -// read from either shape a harness advertises them in: grok's -// `models.availableModels[].modelId`, or opencode's `configOptions[]` entry -// with id "model" (`options[].value`). +// read preferentially from `configOptions[]` entry with id "model" +// (`options[].value`, used by opencode and antigravity where +// `models.availableModels` may carry legacy effort-suffixed ids), falling +// back to `models.availableModels[].modelId` (grok). import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -13,9 +14,50 @@ import { AcpClient } from "../core/acp.ts"; import { spawnHarness } from "../core/child.ts"; import { isRecord } from "../core/json.ts"; +/** Extract deduplicated model ids from a `session/new` response, preferring + * `configOptions[id="model"]` when it yields at least one id and falling back + * to `models.availableModels[].modelId`. */ +export function extractAcpModels(res: unknown): string[] | null { + if (!isRecord(res)) return null; + const fromConfig: string[] = []; + const configOptions = res["configOptions"]; + if (Array.isArray(configOptions)) { + for (const o of configOptions) { + if (!isRecord(o) || o["id"] !== "model" || !Array.isArray(o["options"])) continue; + for (const entry of o["options"]) { + if (!isRecord(entry)) continue; + if (typeof entry["value"] === "string" && entry["value"] !== "") { + fromConfig.push(entry["value"]); + } else if (Array.isArray(entry["options"])) { + // Grouped select option (ACP v1): flatten nested options. + for (const nested of entry["options"]) { + if (isRecord(nested) && typeof nested["value"] === "string" && nested["value"] !== "") { + fromConfig.push(nested["value"]); + } + } + } + } + } + } + if (fromConfig.length > 0) return [...new Set(fromConfig)]; + + const fromAvailable: string[] = []; + const models = isRecord(res["models"]) ? res["models"] : null; + const available = models?.["availableModels"]; + if (Array.isArray(available)) { + for (const m of available) { + if (isRecord(m) && typeof m["modelId"] === "string" && m["modelId"] !== "") { + fromAvailable.push(m["modelId"]); + } + } + } + return fromAvailable.length > 0 ? [...new Set(fromAvailable)] : null; +} + export async function probeAcpModels( argv: string[], env: Record, + opts?: { authMethodId?: string }, ): Promise { const cwd = mkdtempSync(path.join(tmpdir(), "subturn-probe-")); const stderrFile = path.join(cwd, "stderr.log"); @@ -31,31 +73,16 @@ export async function probeAcpModels( onSessionUpdate: () => { /* none expected before a prompt */ }, }); try { - await client.request("initialize", { + const init = await client.request("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, }, 20_000); - const res = await client.request("session/new", { cwd, mcpServers: [] }, 30_000); - if (!isRecord(res)) return null; - const ids: string[] = []; - const models = isRecord(res["models"]) ? res["models"] : null; - const available = models?.["availableModels"]; - if (Array.isArray(available)) { - for (const m of available) { - if (isRecord(m) && typeof m["modelId"] === "string") ids.push(m["modelId"]); - } + if (!isRecord(init) || init["protocolVersion"] !== 1) return null; + if (opts?.authMethodId !== undefined) { + await client.request("authenticate", { methodId: opts.authMethodId }, 20_000); } - const configOptions = res["configOptions"]; - if (Array.isArray(configOptions)) { - for (const o of configOptions) { - if (!isRecord(o) || o["id"] !== "model" || !Array.isArray(o["options"])) continue; - for (const v of o["options"]) { - if (isRecord(v) && typeof v["value"] === "string") ids.push(v["value"]); - } - } - } - // grok advertises the same ids in both shapes. - return ids.length > 0 ? [...new Set(ids)] : null; + const res = await client.request("session/new", { cwd, mcpServers: [] }, 30_000); + return extractAcpModels(res); } catch { return null; } finally { diff --git a/src/plugins/antigravity.ts b/src/plugins/antigravity.ts new file mode 100644 index 0000000..a4b9b01 --- /dev/null +++ b/src/plugins/antigravity.ts @@ -0,0 +1,338 @@ +// plugins/antigravity.ts — Antigravity CLI over native ACP (`agy acp`). +// +// Bundle: applied via session/set_config_option — configId "model" first, +// then configId "thought_level" (agy's spelling of effort). Both are +// mandatory on fresh and resumed turns: if a model or thinking level is +// unknown or unsupported, agy refuses with -32602 before any prompt runs, +// and the raw RPC error lands in evidence. +// +// Posture: `--dangerously-skip-permissions` on the CLI plus Subturn's own +// allow-everything ACP permission handler (core/acp.ts) as a backstop. +// `--disable-telemetry` and `--include-default-customizations=false` keep +// telemetry off and prevent default customizations from leaking in. +// +// Shadow home: `--gemini-dir --app-data-dir antigravity-cli` plus +// `GEMINI_HOME=` isolate conversations, brain, annotations, logs, +// and caches per session, invisible to the user's `~/.gemini/antigravity-cli` +// history (principle 5). `AGY_CLI_DISABLE_AUTO_UPDATE=1` keeps the CLI from +// self-updating mid-turn. +// +// Auth: `GEMINI_API_KEY` takes precedence when set (like OPENAI_API_KEY in +// codex and XAI_API_KEY in grok) and authenticates via ACP `authenticate` +// (`gemini-api-key`). Otherwise agy 1.5 uses Google OAuth: the OS keyring on +// desktop (shared across `--gemini-dir`s automatically), or +// `antigravity-oauth-token` (legacy `acp_token.json`) inside the app-data dir +// over SSH / headless profiles (including T3 Code's `GEMINI_HOME` + +// `SSH_CONNECTION` profiles). File tokens are COPIED (0o600, atomic rename) +// into the shadow rather than symlinked: agy writes refreshes with +// `os.WriteFile`, so a symlink would mutate the user's profile and race +// concurrent sessions. Each turn reconciles the shadow's token files with the +// active credential source. On desktop Linux without a file token or cache +// hint, the OS keyring cannot be inspected cheaply without native bindings, so +// auth returns ok with an honest "unverified" note and lets `session/new` +// confirm (agy fails fast with -32000 when logged out). + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import path from "node:path"; + +import type { AuthResult, LaunchContext, LaunchOutcome, Plugin, ShadowHome } from "./types.ts"; +import { ensureDir } from "./shadow.ts"; +import { configuredValue, runAcpTurn } from "../core/acp-turn.ts"; +import type { AcpClient } from "../core/acp.ts"; +import { isRecord } from "../core/json.ts"; +import { probeAcpModels } from "./acp-models-probe.ts"; + +const SET_CONFIG_TIMEOUT_MS = 30_000; +const APP_DATA_DIR = "antigravity-cli"; +const TOKEN_FILES = ["antigravity-oauth-token", "acp_token.json"] as const; + +type CredentialSource = + | { kind: "api-key"; detail: string } + | { kind: "file"; files: string[]; detail: string } + | { kind: "keyring"; detail: string } + | { kind: "keyring-unverified"; detail: string } + | { kind: "none"; detail: string }; + +function hasApiKey(): boolean { + const apiKey = process.env["GEMINI_API_KEY"]; + return apiKey !== undefined && apiKey.trim() !== ""; +} + +function isSshSession(): boolean { + const ssh = process.env["SSH_CONNECTION"]; + return ssh !== undefined && ssh.trim() !== ""; +} + +function realGeminiRoot(): { root: string; explicit: boolean } { + const env = process.env["GEMINI_HOME"]; + if (env !== undefined && env.trim() !== "") return { root: path.resolve(env), explicit: true }; + return { root: path.join(homedir(), ".gemini"), explicit: false }; +} + +function candidateAppDirs(root: string, explicit: boolean): string[] { + // Explicit GEMINI_HOME (e.g. T3 Code) stores its token in antigravity-acp + // first; default ~/.gemini uses antigravity-cli first. Never fall back from + // an explicit profile root to ~/.gemini. + return explicit + ? [path.join(root, "antigravity-acp"), path.join(root, APP_DATA_DIR)] + : [path.join(root, APP_DATA_DIR), path.join(root, "antigravity-acp")]; +} + +function isReadableNonEmptyFile(filePath: string): boolean { + try { + if (!statSync(filePath).isFile()) return false; + return readFileSync(filePath, "utf8").trim().length > 0; + } catch { + return false; + } +} + +function readOauthStateHint(appDir: string): { methodId: string; file: string } | null { + const file = path.join(appDir, "cache", "acp-auth-state.json"); + try { + const parsed: unknown = JSON.parse(readFileSync(file, "utf8")); + if (isRecord(parsed) && typeof parsed["methodId"] === "string" && parsed["methodId"].startsWith("oauth-")) { + return { methodId: parsed["methodId"], file }; + } + } catch { /* absent or unreadable */ } + return null; +} + +function hasMacKeychainItem(): boolean { + const res = spawnSync("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity"], { + stdio: "ignore", + timeout: 10_000, + }); + return res.status === 0; +} + +/** Single credential-source resolver shared by auth(), home(), and models(). */ +export function resolveCredentialSource(platform: NodeJS.Platform = process.platform): CredentialSource { + // 1. Explicit API key takes deterministic precedence (matches codex and grok). + if (hasApiKey()) { + return { kind: "api-key", detail: "GEMINI_API_KEY set" }; + } + + const { root, explicit } = realGeminiRoot(); + const appDirs = candidateAppDirs(root, explicit); + + // 2. File-based OAuth token(s) in the selected profile. + for (const dir of appDirs) { + const found = TOKEN_FILES.map((f) => path.join(dir, f)).filter(isReadableNonEmptyFile); + if (found.length > 0) { + return { kind: "file", files: found, detail: `oauth token at ${found[0]}` }; + } + } + + const ssh = isSshSession(); + + // 3. Desktop OS keyring (macOS keychain check, or Linux cache hint / unverified). + if (!ssh) { + if (platform === "darwin" && hasMacKeychainItem()) { + return { kind: "keyring", detail: 'keychain item "gemini"/"antigravity" present' }; + } + if (platform === "linux") { + for (const dir of appDirs) { + const hint = readOauthStateHint(dir); + if (hint !== null) { + return { kind: "keyring", detail: `oauth hint (${hint.methodId}) at ${hint.file}` }; + } + } + return { kind: "keyring-unverified", detail: "desktop keyring unverified — agy will confirm on launch" }; + } + } + + const where = ssh + ? `no oauth token under ${appDirs.join(" or ")} (SSH file storage)` + : platform === "darwin" + ? `no keychain item "gemini"/"antigravity" or oauth token under ${appDirs.join(" or ")}` + : `no oauth token under ${appDirs.join(" or ")}`; + return { + kind: "none", + detail: `${where} and GEMINI_API_KEY unset — run \`agy\` or \`agy acp --login\` to log in`, + }; +} + +function shadowGeminiDir(sessionDir: string): string { + return path.join(sessionDir, "home", "gemini"); +} + +function acpArgv(binPath: string, shadow: string): string[] { + return [ + binPath, + "acp", + "--gemini-dir", shadow, + "--app-data-dir", APP_DATA_DIR, + "--dangerously-skip-permissions", + "--disable-telemetry", + "--include-default-customizations=false", + ]; +} + +/** Write a private 0o600 copy atomically so agy's in-place token refreshes + * never escape the shadow into the user's real profile. */ +function copySecretFile(data: Buffer, dest: string): void { + const tmp = `${dest}.${process.pid}.tmp`; + try { + writeFileSync(tmp, data, { mode: 0o600 }); + chmodSync(tmp, 0o600); + renameSync(tmp, dest); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } +} + +/** Reconcile the shadow's private credential files with the active source. + * When the source path and bytes are unchanged on resume, keep the shadow's + * own (possibly refreshed) copy; when the source changes, replace or clear + * stale token files and clear agy's persisted `cache/acp-auth-state.json` + * so switching between API key and OAuth never gets stuck on the old method. */ +function prepareShadow(shadow: string, source: CredentialSource): { copied: string[]; reused: boolean } { + ensureDir(shadow); + const appDir = ensureDir(path.join(shadow, APP_DATA_DIR)); + const stampFile = path.join(shadow, ".subturn-auth-source.json"); + const authStateFile = path.join(appDir, "cache", "acp-auth-state.json"); + + const fileEntries = source.kind === "file" + ? source.files.map((src) => { + const data = readFileSync(src); + const hash = createHash("sha256").update(data).digest("hex"); + return { src, name: path.basename(src), data, hash }; + }) + : []; + const nextStamp = JSON.stringify({ + kind: source.kind, + files: fileEntries.map((f) => ({ src: f.src, hash: f.hash })), + }); + + let prevStamp = ""; + try { prevStamp = readFileSync(stampFile, "utf8"); } catch { /* fresh shadow */ } + + const allPresent = fileEntries.every((f) => existsSync(path.join(appDir, f.name))); + if (prevStamp === nextStamp && allPresent) { + // Still guard against a stale gemini-api-key state file when not in api-key mode. + if (source.kind !== "api-key") rmSync(authStateFile, { force: true }); + return { copied: fileEntries.map((f) => f.src), reused: true }; + } + + const keepNames = new Set(fileEntries.map((f) => f.name)); + for (const entry of fileEntries) { + copySecretFile(entry.data, path.join(appDir, entry.name)); + } + for (const name of TOKEN_FILES) { + if (!keepNames.has(name)) { + rmSync(path.join(appDir, name), { force: true }); + } + } + rmSync(authStateFile, { force: true }); + writeFileSync(stampFile, nextStamp); + return { copied: fileEntries.map((f) => f.src), reused: false }; +} + +async function applyConfig( + ctx: LaunchContext, + client: AcpClient, + sessionId: string, + configId: string, + value: string, +): Promise { + try { + const res = await client.request( + "session/set_config_option", + { sessionId, configId, value }, + SET_CONFIG_TIMEOUT_MS, + ); + ctx.emit({ type: "set_config_result", configId, value, result: res ?? null }); + return res; + } catch (err) { + ctx.emit({ + type: "set_config_error", + configId, + value, + error: err instanceof Error ? err.message : String(err), + }); + throw err; + } +} + +export const antigravityPlugin: Plugin = { + name: "antigravity", + hints: { + // Only `agy`, never `antigravity` (which can be the Antigravity IDE binary). + binaryNames: ["agy"], + wellKnownDirs: ["~/.local/bin", "/opt/homebrew/bin", "/usr/local/bin"], + }, + + auth(): Promise { + const source = resolveCredentialSource(); + return Promise.resolve({ ok: source.kind !== "none", detail: source.detail }); + }, + + async models(binPath: string): Promise { + // Throwaway ACP handshake in a disposable shadow: `session/new` creates a + // session, so it must never touch the user's ~/.gemini/antigravity-cli. + const tmp = mkdtempSync(path.join(tmpdir(), "subturn-antigravity-models-")); + try { + const source = resolveCredentialSource(); + prepareShadow(tmp, source); + return await probeAcpModels( + acpArgv(binPath, tmp), + { GEMINI_HOME: tmp, AGY_CLI_DISABLE_AUTO_UPDATE: "1" }, + source.kind === "api-key" ? { authMethodId: "gemini-api-key" } : undefined, + ); + } catch { + return null; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } + }, + + home(sessionDir: string): Promise { + const shadow = shadowGeminiDir(sessionDir); + const source = resolveCredentialSource(); + const { copied, reused } = prepareShadow(shadow, source); + const authNote = + source.kind === "file" + ? `private oauth copy (0600) ${reused ? "reused" : "copied"} from ${copied.join(", ")}` + : source.detail; + return Promise.resolve({ + env: { + GEMINI_HOME: shadow, + AGY_CLI_DISABLE_AUTO_UPDATE: "1", + }, + note: + `GEMINI_HOME=${shadow} (--gemini-dir + --app-data-dir ${APP_DATA_DIR}; sessions invisible to \`agy\`); ` + + `AGY_CLI_DISABLE_AUTO_UPDATE=1; ${authNote}`, + }); + }, + + launch(ctx: LaunchContext): Promise { + const shadow = ctx.env["GEMINI_HOME"] ?? shadowGeminiDir(ctx.sessionDir); + return runAcpTurn(ctx, { + argv: acpArgv(ctx.binPath, shadow), + ...(hasApiKey() ? { authMethodId: "gemini-api-key" } : {}), + configure: async (client, sessionId) => { + // Model FIRST — available thought_level values depend on the model. + // Always send thought_level even if absent from configOptions so an + // unsupported effort fails loudly with -32602 rather than silently + // running without the requested bundle. Emit each exchange as it + // happens so a failed step still leaves prior evidence intact. + const modelRes = await applyConfig(ctx, client, sessionId, "model", ctx.model); + const effortRes = await applyConfig(ctx, client, sessionId, "thought_level", ctx.effort); + const model = configuredValue(effortRes, "model") ?? configuredValue(modelRes, "model"); + const effort = configuredValue(effortRes, "thought_level"); + return { + harness: "antigravity", + requested: { model: ctx.model, effort: ctx.effort }, + ...(model !== undefined ? { acknowledged_model: model } : {}), + ...(effort !== undefined ? { acknowledged_effort: effort } : {}), + set_config_responses: { model: modelRes ?? null, thought_level: effortRes ?? null }, + }; + }, + }); + }, +}; diff --git a/src/plugins/index.ts b/src/plugins/index.ts index 61902b0..64c5e6d 100644 --- a/src/plugins/index.ts +++ b/src/plugins/index.ts @@ -16,6 +16,7 @@ const builtIn: Entry[] = [ { name: "claude", load: () => import("./claude.ts").then((m) => m.claudePlugin) }, { name: "grok", load: () => import("./grok.ts").then((m) => m.grokPlugin) }, { name: "opencode", load: () => import("./opencode.ts").then((m) => m.opencodePlugin) }, + { name: "antigravity", load: () => import("./antigravity.ts").then((m) => m.antigravityPlugin) }, ]; // Test seam: the fake plugin exists only when SUBTURN_FAKE_AGENT names a diff --git a/test/antigravity.test.ts b/test/antigravity.test.ts new file mode 100644 index 0000000..9dea63e --- /dev/null +++ b/test/antigravity.test.ts @@ -0,0 +1,537 @@ +// test/antigravity.test.ts — antigravity auth, shadow home, model probe, and +// ACP turn behavior, offline against a stateful fake `agy` script. No real +// harness is launched. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { antigravityPlugin, resolveCredentialSource } from "../src/plugins/antigravity.ts"; +import { extractAcpModels } from "../src/plugins/acp-models-probe.ts"; +import type { LaunchContext } from "../src/plugins/types.ts"; + +const root = mkdtempSync(path.join(tmpdir(), "subturn-antigravity-test-")); +const workDir = path.join(root, "work"); +mkdirSync(workDir, { recursive: true }); + +// Stateful fake `agy` binary speaking ACP ndjson on stdio. Persists sessions +// under --gemini-dir/--app-data-dir, refreshes its shadow token in place with +// writeFileSync (mirroring agy's os.WriteFile), and validates GEMINI_API_KEY +// when authenticate("gemini-api-key") is called. +const fakeAgy = path.join(root, "agy"); +writeFileSync( + fakeAgy, + `#!${process.execPath} +const fs = require("node:fs"); +const path = require("node:path"); + +const argv = process.argv.slice(2); +const flag = (name) => { + const i = argv.indexOf(name); + return i >= 0 ? argv[i + 1] : ""; +}; +const geminiDir = flag("--gemini-dir"); +const appDataDir = flag("--app-data-dir") || "antigravity-cli"; +const appRoot = path.join(geminiDir, appDataDir); +const convDir = path.join(appRoot, "conversations"); +const authStatePath = path.join(appRoot, "cache", "acp-auth-state.json"); + +const mode = process.env.FAKE_AGY_MODE ?? "ok"; +const calls = []; +let authedMethod = null; +let buf = ""; +const send = (o) => process.stdout.write(JSON.stringify(o) + "\\n"); +const ok = (id, r) => send({ jsonrpc: "2.0", id, result: r }); +const fail = (id, code, message) => send({ jsonrpc: "2.0", id, error: { code, message } }); +const config = { model: "gemini-4-neon", thought_level: "high" }; +const configOptions = () => [ + { id: "model", type: "select", currentValue: config.model, options: [{ value: "gemini-4-neon" }, { value: "gemini-3.8-flash" }, { value: "gemini-4-neon" }] }, + { id: "thought_level", type: "select", currentValue: config.thought_level, options: [{ value: "low" }, { value: "medium" }, { value: "high" }] }, +]; + +function silentAuthOk() { + // Mirror agy's persisted auth-method behavior: if cache/acp-auth-state.json + // recorded gemini-api-key, silent auth fails when GEMINI_API_KEY is absent. + if (fs.existsSync(authStatePath)) { + try { + const saved = JSON.parse(fs.readFileSync(authStatePath, "utf8")); + if (saved.methodId === "gemini-api-key" && !process.env.GEMINI_API_KEY) return false; + } catch {} + } + for (const name of ["antigravity-oauth-token", "acp_token.json"]) { + const p = path.join(appRoot, name); + if (fs.existsSync(p) && fs.readFileSync(p, "utf8").trim().length > 0) { + // Simulate agy's os.WriteFile token refresh inside the shadow. + fs.writeFileSync(p, '{"token":{"access_token":"refreshed-in-shadow"}}'); + return true; + } + } + return false; +} + +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (d) => { + buf += d; + for (;;) { + const nl = buf.indexOf("\\n"); + if (nl < 0) break; + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + const msg = JSON.parse(line); + const { id, method, params } = msg; + calls.push({ method, params }); + if (method === "initialize") { + // Deliberately omit authMethods / loadSession to cover unadvertised-method compatibility. + ok(id, { protocolVersion: 1, agentCapabilities: {}, authMethods: [] }); + } else if (method === "authenticate") { + if (params.methodId === "gemini-api-key") { + if (!process.env.GEMINI_API_KEY) { + fail(id, -32000, "GEMINI_API_KEY missing in child env"); + continue; + } + fs.mkdirSync(path.dirname(authStatePath), { recursive: true }); + fs.writeFileSync(authStatePath, JSON.stringify({ methodId: "gemini-api-key" })); + authedMethod = "gemini-api-key"; + ok(id, {}); + } else { + fail(id, -32602, "unsupported auth method: " + params.methodId); + } + } else if (method === "session/new") { + if (authedMethod === null && !silentAuthOk()) { + fail(id, -32000, "Authentication required"); + continue; + } + const sessionId = "agy-sess-1234"; + fs.mkdirSync(convDir, { recursive: true }); + fs.writeFileSync(path.join(convDir, sessionId + ".json"), JSON.stringify({ cwd: params.cwd, created: true })); + ok(id, { + sessionId, + models: { availableModels: [{ modelId: "gemini-4-neon-high" }, { modelId: "gemini-3.8-flash-low" }], currentModelId: "gemini-4-neon-high" }, + configOptions: configOptions(), + }); + } else if (method === "session/load") { + if (authedMethod === null && !silentAuthOk()) { + fail(id, -32000, "Authentication required"); + continue; + } + const savedPath = path.join(convDir, params.sessionId + ".json"); + if (!fs.existsSync(savedPath)) { + fail(id, -32602, "session not found in shadow: " + savedPath); + continue; + } + send({ jsonrpc: "2.0", method: "session/update", params: { sessionId: params.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "REPLAYED " } } } }); + ok(id, { sessionId: params.sessionId, configOptions: configOptions() }); + } else if (method === "session/set_config_option") { + if (mode === "bad-model" && params.configId === "model") { + fail(id, -32602, "Unknown model ID: " + params.value); + continue; + } + if (mode === "bad-effort" && params.configId === "thought_level") { + fail(id, -32602, 'Thinking level "' + params.value + '" is not offered'); + continue; + } + config[params.configId] = params.value; + ok(id, { configOptions: configOptions() }); + } else if (method === "session/prompt") { + if (mode === "refusal") { + send({ jsonrpc: "2.0", method: "session/update", params: { sessionId: params.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "quota exhausted" } } } }); + ok(id, { stopReason: "refusal" }); + continue; + } + const order = calls.map((c) => c.method + (c.params?.configId ? ":" + c.params.configId : "")).join(","); + send({ jsonrpc: "2.0", method: "session/update", params: { sessionId: params.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok:" + order } } } }); + ok(id, { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 5, thoughtTokens: 2 } }); + } + } +}); +process.stdin.on("end", () => process.exit(0)); +`, +); +chmodSync(fakeAgy, 0o755); + +const envKeys = ["GEMINI_HOME", "SSH_CONNECTION", "GEMINI_API_KEY", "FAKE_AGY_MODE"] as const; +const savedEnv = Object.fromEntries(envKeys.map((k) => [k, process.env[k]])); + +function restoreEnv(): void { + for (const k of envKeys) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } +} + +async function withEnv( + overrides: Partial>, + fn: () => Promise | T, +): Promise { + for (const k of envKeys) delete process.env[k]; + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } + try { + return await fn(); + } finally { + restoreEnv(); + } +} + +test.after(() => { + restoreEnv(); + rmSync(root, { recursive: true, force: true }); +}); + +test("auth honors explicit GEMINI_HOME (antigravity-acp before antigravity-cli), legacy acp_token.json, and refuses empty SSH profile", async () => { + const profile = path.join(root, "explicit-profile"); + const acpDir = path.join(profile, "antigravity-acp"); + const cliDir = path.join(profile, "antigravity-cli"); + mkdirSync(acpDir, { recursive: true }); + mkdirSync(cliDir, { recursive: true }); + writeFileSync(path.join(cliDir, "antigravity-oauth-token"), '{"token":{"access_token":"cli"}}'); + writeFileSync(path.join(acpDir, "antigravity-oauth-token"), '{"token":{"access_token":"acp"}}'); + + await withEnv({ GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "file"); + assert.deepEqual(src.files, [path.join(acpDir, "antigravity-oauth-token")]); + const auth = await antigravityPlugin.auth(); + assert.equal(auth.ok, true); + }); + + // Legacy acp_token.json is detected when antigravity-oauth-token is absent. + const legacyProfile = path.join(root, "legacy-profile"); + mkdirSync(path.join(legacyProfile, "antigravity-acp"), { recursive: true }); + const legacyFile = path.join(legacyProfile, "antigravity-acp", "acp_token.json"); + writeFileSync(legacyFile, '{"refresh_token":"r"}'); + await withEnv({ GEMINI_HOME: legacyProfile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "file"); + assert.deepEqual(src.files, [legacyFile]); + }); + + // Empty explicit profile over SSH must fail, never silently use ~/.gemini. + const emptyProfile = path.join(root, "empty-explicit"); + mkdirSync(path.join(emptyProfile, "antigravity-cli"), { recursive: true }); + writeFileSync(path.join(emptyProfile, "antigravity-cli", "antigravity-oauth-token"), " \n"); + await withEnv({ GEMINI_HOME: emptyProfile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "none"); + const auth = await antigravityPlugin.auth(); + assert.equal(auth.ok, false); + assert.match(auth.detail, /agy/); + }); + + // Non-linux/non-darwin platform without token or API key fails cleanly. + await withEnv({ GEMINI_HOME: emptyProfile }, () => { + const src = resolveCredentialSource("win32"); + assert.equal(src.kind, "none"); + }); +}); + +test("auth gives deterministic precedence to GEMINI_API_KEY and handles desktop Linux cache hints cleanly", async () => { + const profile = path.join(root, "linux-hint-profile"); + const cacheDir = path.join(profile, "antigravity-cli", "cache"); + mkdirSync(cacheDir, { recursive: true }); + writeFileSync(path.join(cacheDir, "acp-auth-state.json"), JSON.stringify({ methodId: "oauth-personal" })); + + // Explicit GEMINI_API_KEY wins deterministically even if a stale cache hint exists. + await withEnv({ GEMINI_HOME: profile, GEMINI_API_KEY: "test-key" }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "api-key"); + }); + + // Without GEMINI_API_KEY on desktop Linux, cache hint reports keyring. + await withEnv({ GEMINI_HOME: profile }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "keyring"); + assert.match(src.detail, /oauth-personal/); + }); + + // Under SSH, a desktop cache hint is ignored. + await withEnv({ GEMINI_HOME: profile, SSH_CONNECTION: "10.0.0.1 22 10.0.0.2 50000" }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "none"); + }); + + // Without file token, hint, or API key on desktop Linux -> ok with unverified keyring note. + const blank = path.join(root, "linux-blank-profile"); + mkdirSync(blank, { recursive: true }); + await withEnv({ GEMINI_HOME: blank }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "keyring-unverified"); + assert.match(src.detail, /unverified/); + }); + + // Non-OAuth methodId in acp-auth-state.json is not treated as an OAuth hint. + const nonOauth = path.join(root, "linux-non-oauth"); + mkdirSync(path.join(nonOauth, "antigravity-cli", "cache"), { recursive: true }); + writeFileSync(path.join(nonOauth, "antigravity-cli", "cache", "acp-auth-state.json"), JSON.stringify({ methodId: "gemini-api-key" })); + await withEnv({ GEMINI_HOME: nonOauth }, () => { + const src = resolveCredentialSource("linux"); + assert.equal(src.kind, "keyring-unverified"); + }); +}); + +test("home makes private 0600 copies, reconciles account switches on resume, and handles relative GEMINI_HOME", async () => { + const profileA = path.join(root, "profile-a"); + const profileB = path.join(root, "profile-b"); + mkdirSync(path.join(profileA, "antigravity-acp"), { recursive: true }); + mkdirSync(path.join(profileB, "antigravity-acp"), { recursive: true }); + const tokenA = path.join(profileA, "antigravity-acp", "antigravity-oauth-token"); + const tokenB = path.join(profileB, "antigravity-acp", "antigravity-oauth-token"); + writeFileSync(tokenA, '{"token":{"access_token":"account-A"}}'); + writeFileSync(tokenB, '{"token":{"access_token":"account-B"}}'); + writeFileSync(path.join(profileA, "AGENTS.md"), "user instructions that must not leak"); + + const sessionDir = path.join(root, "session-reconcile"); + const shadow = path.join(sessionDir, "home", "gemini"); + const shadowToken = path.join(shadow, "antigravity-cli", "antigravity-oauth-token"); + + // Relative GEMINI_HOME resolves cleanly and produces a private 0600 file (not a symlink). + const relA = path.relative(process.cwd(), profileA); + await withEnv({ GEMINI_HOME: relA, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + const homeA = await antigravityPlugin.home(sessionDir); + assert.equal(homeA.env["GEMINI_HOME"], shadow); + assert.equal(homeA.env["AGY_CLI_DISABLE_AUTO_UPDATE"], "1"); + assert.equal(lstatSync(shadowToken).isSymbolicLink(), false, "must be a private copy, not a symlink"); + assert.equal(statSync(shadowToken).mode & 0o777, 0o600); + assert.equal(readFileSync(shadowToken, "utf8"), '{"token":{"access_token":"account-A"}}'); + assert.equal(existsSync(path.join(shadow, "AGENTS.md")), false); + }); + + // Same-profile resume preserves a refreshed shadow token when source is unchanged. + writeFileSync(shadowToken, '{"token":{"access_token":"refreshed-in-shadow"}}'); + await withEnv({ GEMINI_HOME: profileA, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + const homeReused = await antigravityPlugin.home(sessionDir); + assert.match(homeReused.note, /reused/); + assert.equal(readFileSync(shadowToken, "utf8"), '{"token":{"access_token":"refreshed-in-shadow"}}'); + }); + + // Updating the source token file replaces the shadow copy. + writeFileSync(tokenA, '{"token":{"access_token":"account-A-v2"}}'); + await withEnv({ GEMINI_HOME: profileA, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + await antigravityPlugin.home(sessionDir); + assert.equal(readFileSync(shadowToken, "utf8"), '{"token":{"access_token":"account-A-v2"}}'); + }); + + // Switching to profile B on resume replaces the shadow copy with B. + await withEnv({ GEMINI_HOME: profileB, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, async () => { + await antigravityPlugin.home(sessionDir); + assert.equal(readFileSync(shadowToken, "utf8"), '{"token":{"access_token":"account-B"}}'); + assert.equal(readFileSync(tokenA, "utf8"), '{"token":{"access_token":"account-A-v2"}}', "profile A untouched"); + }); + + // Switching to API-key mode removes the stale file token from the shadow. + await withEnv({ GEMINI_HOME: profileB, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", GEMINI_API_KEY: "k" }, async () => { + await antigravityPlugin.home(sessionDir); + assert.equal(existsSync(shadowToken), false, "stale token file must be removed"); + }); +}); + +test("extractAcpModels prefers flat or grouped configOptions model ids and falls back cleanly", () => { + const mixed = { + models: { + availableModels: [ + { modelId: "gemini-4-neon-high" }, + { modelId: "gemini-4-neon-low" }, + ], + }, + configOptions: [ + { + id: "model", + options: [ + { value: "gemini-4-neon" }, + { group: "recommended", name: "Recommended", options: [{ value: "gemini-3.8-flash" }, { value: "gemini-4-neon" }] }, + ], + }, + { id: "thought_level", options: [{ value: "low" }] }, + ], + }; + assert.deepEqual(extractAcpModels(mixed), ["gemini-4-neon", "gemini-3.8-flash"]); + + const emptyConfigFallback = { + models: { + availableModels: [{ modelId: "grok-4.6" }, { modelId: "grok-4.7" }], + }, + configOptions: [{ id: "model", options: [] }], + }; + assert.deepEqual(extractAcpModels(emptyConfigFallback), ["grok-4.6", "grok-4.7"]); + assert.equal(extractAcpModels({}), null); +}); + +test("launch runs stateful ACP turns across shadow rename, keeps user token untouched, validates API key, bad effort, refusal, and models()", async () => { + const profile = path.join(root, "launch-profile"); + mkdirSync(path.join(profile, "antigravity-cli"), { recursive: true }); + const realTokenPath = path.join(profile, "antigravity-cli", "antigravity-oauth-token"); + const originalToken = '{"token":{"access_token":"real-user-token"}}'; + writeFileSync(realTokenPath, originalToken); + + const runTurn = async (opts: { + sessionDir: string; + nativeSessionId?: string; + envOverrides: Partial>; + }) => { + mkdirSync(opts.sessionDir, { recursive: true }); + const events: Array> = []; + const evidence: Record = {}; + let reportedId = ""; + return withEnv(opts.envOverrides, async () => { + const home = await antigravityPlugin.home(opts.sessionDir); + const ctx: LaunchContext = { + binPath: fakeAgy, + model: "gemini-3.8-flash", + effort: "low", + prompt: "hi", + cwd: workDir, + sessionDir: opts.sessionDir, + turn: opts.nativeSessionId === undefined ? 1 : 2, + nativeSessionId: opts.nativeSessionId, + deadlineMs: Date.now() + 30_000, + env: home.env, + emit: (e) => events.push(e), + writeEvidence: (file, content) => { evidence[file] = content; }, + onChildPid: () => {}, + onNativeSessionId: (id) => { reportedId = id; }, + }; + const outcome = await antigravityPlugin.launch(ctx); + return { outcome, events, evidence, reportedId, shadow: home.env["GEMINI_HOME"]! }; + }); + }; + + // 1. Fresh turn with OAuth file token: argv, order, ack, usage, exit event, + // and user's real token is NOT mutated by agy's in-place refresh. + const stagingDir = path.join(root, "staging-turn-1"); + const fresh = await runTurn({ + sessionDir: stagingDir, + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, + }); + assert.equal(fresh.outcome.ok, true, fresh.outcome.error); + assert.equal(fresh.reportedId, "agy-sess-1234"); + assert.equal(readFileSync(realTokenPath, "utf8"), originalToken, "refresh in shadow must never mutate real profile"); + assert.equal( + fresh.outcome.finalText, + "ok:initialize,session/new,session/set_config_option:model,session/set_config_option:thought_level,session/prompt", + ); + assert.deepEqual(fresh.outcome.usage, { input_tokens: 10, output_tokens: 5, reasoning_tokens: 2 }); + assert.ok(fresh.events.some((e) => e["type"] === "exit"), "exit event recorded in evidence"); + const spawnEvent = fresh.events.find((e) => e["type"] === "spawn"); + assert.deepEqual(spawnEvent?.["argv"], [ + fakeAgy, + "acp", + "--gemini-dir", fresh.shadow, + "--app-data-dir", "antigravity-cli", + "--dangerously-skip-permissions", + "--disable-telemetry", + "--include-default-customizations=false", + ]); + const ack = JSON.parse(fresh.evidence["ack.json"] ?? "{}") as Record; + assert.equal(ack["harness"], "antigravity"); + assert.equal(ack["acknowledged_model"], "gemini-3.8-flash"); + assert.equal(ack["acknowledged_effort"], "low"); + + // 2. Rename session dir (like supervisor's adoptStaged), then resume: + // stateful session/load reads the persisted session in the moved shadow. + const adoptedDir = path.join(root, "adopted-agy-sess-1234"); + renameSync(stagingDir, adoptedDir); + const resumed = await runTurn({ + sessionDir: adoptedDir, + nativeSessionId: "agy-sess-1234", + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, + }); + assert.equal(resumed.outcome.ok, true, resumed.outcome.error); + assert.equal( + resumed.outcome.finalText, + "ok:initialize,session/load,session/set_config_option:model,session/set_config_option:thought_level,session/prompt", + ); + assert.equal(resumed.outcome.finalText?.includes("REPLAYED"), false); + + // 3. API key auth sends authenticate before session/new (validated in child env), + // and switching from API key to OAuth on resume in the same shadow clears + // persisted `cache/acp-auth-state.json` so silent OAuth resume succeeds. + const emptyProfile = path.join(root, "apikey-empty"); + mkdirSync(emptyProfile, { recursive: true }); + const apiKeySessionDir = path.join(root, "turn-apikey"); + const apiKeyRun = await runTurn({ + sessionDir: apiKeySessionDir, + envOverrides: { GEMINI_HOME: emptyProfile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", GEMINI_API_KEY: "test-key" }, + }); + assert.equal(apiKeyRun.outcome.ok, true, apiKeyRun.outcome.error); + assert.equal( + apiKeyRun.outcome.finalText, + "ok:initialize,authenticate,session/new,session/set_config_option:model,session/set_config_option:thought_level,session/prompt", + ); + assert.equal( + existsSync(path.join(apiKeyRun.shadow, "antigravity-cli", "cache", "acp-auth-state.json")), + true, + "fake agy persisted gemini-api-key auth state", + ); + const apiKeyToOauthResume = await runTurn({ + sessionDir: apiKeySessionDir, + nativeSessionId: "agy-sess-1234", + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, + }); + assert.equal(apiKeyToOauthResume.outcome.ok, true, apiKeyToOauthResume.outcome.error); + assert.equal( + apiKeyToOauthResume.outcome.finalText, + "ok:initialize,session/load,session/set_config_option:model,session/set_config_option:thought_level,session/prompt", + ); + + // 4. Rejected model and unsupported thought_level both fail loudly with -32602 + // before any prompt, preserving per-config evidence. + const badModel = await runTurn({ + sessionDir: path.join(root, "turn-bad-model"), + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", FAKE_AGY_MODE: "bad-model" }, + }); + assert.equal(badModel.outcome.ok, false); + assert.match(badModel.outcome.error ?? "", /rpc error -32602/); + assert.ok(badModel.events.some((e) => e["type"] === "set_config_error" && e["configId"] === "model")); + + const badEffort = await runTurn({ + sessionDir: path.join(root, "turn-bad-effort"), + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", FAKE_AGY_MODE: "bad-effort" }, + }); + assert.equal(badEffort.outcome.ok, false); + assert.match(badEffort.outcome.error ?? "", /rpc error -32602/); + assert.ok( + badEffort.events.some((e) => e["type"] === "set_config_result" && e["configId"] === "model"), + "successful model config exchange must remain in evidence", + ); + assert.ok( + badEffort.events.some((e) => e["type"] === "set_config_error" && e["configId"] === "thought_level"), + "failed thought_level config exchange must be recorded in evidence", + ); + + // 5. stopReason=refusal fails the turn cleanly with raw reason. + const refused = await runTurn({ + sessionDir: path.join(root, "turn-refusal"), + envOverrides: { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", FAKE_AGY_MODE: "refusal" }, + }); + assert.equal(refused.outcome.ok, false); + assert.match(refused.outcome.error ?? "", /stopReason=refusal/); + + // 6. models() works with both file token (without mutating user's file) and GEMINI_API_KEY. + const modelsFromFile = await withEnv( + { GEMINI_HOME: profile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0" }, + () => antigravityPlugin.models(fakeAgy), + ); + assert.deepEqual(modelsFromFile, ["gemini-4-neon", "gemini-3.8-flash"]); + assert.equal(readFileSync(realTokenPath, "utf8"), originalToken, "models() probe must never mutate real profile"); + + const modelsFromKey = await withEnv( + { GEMINI_HOME: emptyProfile, SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0", GEMINI_API_KEY: "test-key" }, + () => antigravityPlugin.models(fakeAgy), + ); + assert.deepEqual(modelsFromKey, ["gemini-4-neon", "gemini-3.8-flash"]); +}); diff --git a/test/live.test.ts b/test/live.test.ts index eec86df..83e6fe3 100644 --- a/test/live.test.ts +++ b/test/live.test.ts @@ -22,6 +22,7 @@ const cancelProbe = process.env["SUBTURN_LIVE_CANCEL"] === "1"; const harness = process.env["SUBTURN_LIVE_HARNESS"] ?? "opencode"; const cheapBundles: Record = { + antigravity: { model: "gemini-3.8-flash", effort: "low" }, claude: { model: "claude-haiku-4-5-20251001", effort: "low" }, codex: { model: "gpt-6-luna", effort: "low" }, grok: { model: "grok-4.6", effort: "low" },