Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(antigravity): address review of the agy acp provider (CHOO-4114)
switch-bug-fixercae535219195
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5742ce2e0..e15a2b3e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2541,8 +2541,11 @@ version of their own to them without also giving them a release of their own.Google's installers, runs sessions with `agy acp`, and checks the sign-in youmade with `agy acp --login` or a `GEMINI_API_KEY`, instead of a separateAntigravity ACP profile that a Google sign-in never reached. Antigravity's- questions now reach you, too. A machine that only has the older- `antigravity-acp` runtime keeps using it until `agy` is installed.+ questions now reach you, too, including typed answers. A machine that only+ has the older `antigravity-acp` runtime keeps using it until `agy` is+ installed, and Update installs `agy` there. An Antigravity sign-in Switch+ holds for the older runtime cannot sign `agy` in: a session given one now+ says how to sign in on the machine instead of starting signed out.- **Console no longer opens to a blank window on a database a newer buildhas changed.** Stable and Canary share one database, so after Canary added amigration, an older build found tables it was not written for, applieddiff --git a/console/apps/switch-console-desktop/src/main/core/providers/provider-login.ts b/console/apps/switch-console-desktop/src/main/core/providers/provider-login.tsindex 6fe4fcdf2..9780cb1dd 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/provider-login.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/provider-login.ts@@ -2,10 +2,12 @@ import { type ChildProcess, spawn } from 'node:child_process';import { randomUUID } from 'node:crypto';import { homedir } from 'node:os';import { createInterface } from 'node:readline';+import { loginCommandOf, providerRuntime } from '@switch-console/agent-providers';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { requireProvider } from '@shared/core/providers/agent-provider-registry';import { providerLoginExitChannel, providerLoginLineChannel } from '@shared/events/appEvents';+import { localDependencyManager } from '../dependencies/dependency-managers';/*** Runs a provider's own sign-in command on this computer, one attempt at a@@ -20,24 +22,26 @@ class ProviderLoginRunner {private current: { attemptId: string; child: ChildProcess } | null = null;start(providerId: string): { attemptId: string } {- const provider = requireProvider(providerId);+ requireProvider(providerId);+ // The command for the CLI found here: an older runtime of a provider can+ // sign in with a command of its own.+ const loginCommand = loginCommandOf(+ providerRuntime(providerId),+ localDependencyManager.get(providerId)?.path ?? ''+ );this.cancel();const attemptId = randomUUID();const windows = process.platform === 'win32';const shell = windows? (process.env.ComSpec ?? 'cmd.exe'): (process.env.SHELL ?? (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash'));- const child = spawn(- shell,- windows ? ['/c', provider.loginCommand] : ['-lc', provider.loginCommand],- {- cwd: homedir(),- env: process.env,- stdio: ['pipe', 'pipe', 'pipe'],- detached: !windows,- windowsHide: true,- }- );+ const child = spawn(shell, windows ? ['/c', loginCommand] : ['-lc', loginCommand], {+ cwd: homedir(),+ env: process.env,+ stdio: ['pipe', 'pipe', 'pipe'],+ detached: !windows,+ windowsHide: true,+ });this.current = { attemptId, child };log.info('Running a provider sign-in command', { provider: providerId, attemptId });const relay = (stream: NodeJS.ReadableStream | null) => {@@ -56,11 +60,9 @@ class ProviderLoginRunner {if (error) log.warn('A provider sign-in command failed', { provider: providerId, error });events.emit(providerLoginExitChannel, { attemptId, exitCode, error });};- child.once('error', (error) =>- end(null, `Could not run ${provider.loginCommand}: ${error.message}`)- );+ child.once('error', (error) => end(null, `Could not run ${loginCommand}: ${error.message}`));child.once('exit', (code, signal) =>- end(code, signal ? `${provider.loginCommand} was stopped (${signal}).` : null)+ end(code, signal ? `${loginCommand} was stopped (${signal}).` : null));return { attemptId };}diff --git a/console/apps/switch-console-desktop/src/main/utils/userEnv.test.ts b/console/apps/switch-console-desktop/src/main/utils/userEnv.test.tsindex d64d5bb13..5c3828b3e 100644--- a/console/apps/switch-console-desktop/src/main/utils/userEnv.test.ts+++ b/console/apps/switch-console-desktop/src/main/utils/userEnv.test.ts@@ -70,7 +70,7 @@ describe('ensureWindowsNpmGlobalBinInPath', () => {});describe('ensureWindowsUserBinDirsInPath', () => {- it('prepends the folder Google’s agy installer writes to, once', () => {+ it('adds the folder Google’s agy installer writes to, once, after the PATH as the controller does', () => {const env: NodeJS.ProcessEnv = {localappdata: 'C:\\Users\\test\\AppData\\Local',Path: 'C:\\Windows\\System32',@@ -79,7 +79,7 @@ describe('ensureWindowsUserBinDirsInPath', () => {expect(ensureWindowsUserBinDirsInPath(env)).toEqual(['C:\\Users\\test\\AppData\\Local\\agy\\bin',]);- expect(env.Path).toBe('C:\\Users\\test\\AppData\\Local\\agy\\bin;C:\\Windows\\System32');+ expect(env.Path).toBe('C:\\Windows\\System32;C:\\Users\\test\\AppData\\Local\\agy\\bin');expect(ensureWindowsUserBinDirsInPath(env)).toEqual([]);});diff --git a/console/apps/switch-console-desktop/src/main/utils/userEnv.ts b/console/apps/switch-console-desktop/src/main/utils/userEnv.tsindex 6fefbe9cb..8fc5b9332 100644--- a/console/apps/switch-console-desktop/src/main/utils/userEnv.ts+++ b/console/apps/switch-console-desktop/src/main/utils/userEnv.ts@@ -3,9 +3,10 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { getWindowsEnvValue } from '@switch-console/core/exec';+import { withWindowsAgyBinDir } from '@switch-console/plugins/agents';import { log } from '@main/lib/logger';import { buildExternalToolEnv } from './childProcessEnv';-import { prependWindowsPathEntry } from './windows-env';+import { getWindowsPathEnvKey, prependWindowsPathEntry } from './windows-env';/*** Keys that must never be overwritten from the shell env capture.@@ -101,13 +102,16 @@ export function ensureWindowsNpmGlobalBinInPath(* Adds the folders Windows provider installers write CLIs to without telling* a running app: Google's Antigravity installer puts `agy.exe` in* `%LOCALAPPDATA%\agy\bin` and adds it to the user's PATH, which an app- * started before the install does not see.+ * started before the install does not see. Added last, in the same order as+ * the agent controller adds it (`withWindowsAgyBinDir`).*/export function ensureWindowsUserBinDirsInPath(env: NodeJS.ProcessEnv = process.env): string[] {- const localAppData = getWindowsEnvValue(env, 'LOCALAPPDATA');- if (!localAppData) return [];- const agyBin = path.win32.join(localAppData, 'agy', 'bin');- return prependWindowsPathEntry(env, agyBin) ? [agyBin] : [];+ const pathKey = getWindowsPathEnvKey(env);+ const before = env[pathKey] ?? '';+ const after = withWindowsAgyBinDir(before, getWindowsEnvValue(env, 'LOCALAPPDATA'));+ if (after === before) return [];+ env[pathKey] = after;+ return [after.split(path.win32.delimiter).at(-1)!];}/**diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsxindex 1e7b83e05..14c9c3422 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx@@ -77,6 +77,11 @@ export function ProviderConnectionStatus({mutationFn: (command: string) => navigator.clipboard.writeText(command),});const data = query.data;+ // The executable checked may sign in with a command of its own.+ const loginCommand =+ (data && 'loginCommand' in data ? data.loginCommand : undefined) ??+ provider?.loginCommand ??+ '';const checking = query.isFetching;const missing = data?.installed === false;const ready = data?.installed === true && data.status === 'authenticated';@@ -151,13 +156,11 @@ export function ProviderConnectionStatus({<div className="mt-2 space-y-1"><p>Run in a terminal {sshHost ? `on ${sshHost}` : 'on this computer'}, then Recheck:</p><div className="flex items-center gap-2 rounded bg-background px-2 py-1">- <code className="min-w-0 flex-1 text-xs break-all select-all">- {provider.loginCommand}- </code>+ <code className="min-w-0 flex-1 text-xs break-all select-all">{loginCommand}</code><Buttonsize="sm"variant="ghost"- onClick={() => copy.mutate(provider.loginCommand)}+ onClick={() => copy.mutate(loginCommand)}aria-label="Copy sign-in command">{copy.isSuccess ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}diff --git a/console/docs/sdk-sessions.md b/console/docs/sdk-sessions.mdindex aa049f7d4..bc1b1d10d 100644--- a/console/docs/sdk-sessions.md+++ b/console/docs/sdk-sessions.md@@ -288,9 +288,12 @@ and Windows. Install it with Google's installer (`curl -fsSLhttps://antigravity.google/cli/install.sh | bash`, or on Windows `irmhttps://antigravity.google/cli/install.ps1 | iex`, which puts `agy.exe` in`%LOCALAPPDATA%\agy\bin`). It uses the person's own `agy` sign-in: sign in with-`agy acp --login` on the execution host, or set `GEMINI_API_KEY`. The sign-in-check asks `agy acp` for its sessions, which it refuses while signed out, and-never signs in itself. Approvals and cancellation use ACP; questions arrive as+`agy acp --login` on the execution host, or set `GEMINI_API_KEY`, which a+session uses only when `agy` is not signed in itself. The sign-in check asks+`agy acp` for its sessions, which it refuses while signed out, and never signs+in itself. A hosted Antigravity login made for the older runtime cannot sign+`agy` in; a session given one fails with an error saying how to sign in on the+machine instead. Approvals and cancellation use ACP; questions arrive asACP form elicitations. A machine that only has the `antigravity-acp` runtimeSwitch Console used to install keeps using it, with its own `antigravity-acp--login`, until `agy` is installed. Conversations saved by that runtime, or bydiff --git a/console/packages/agent-controller/src/login-path.test.ts b/console/packages/agent-controller/src/login-path.test.tsindex 9317e95ab..8faca3b3a 100644--- a/console/packages/agent-controller/src/login-path.test.ts+++ b/console/packages/agent-controller/src/login-path.test.ts@@ -2,7 +2,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { delimiter, join } from 'node:path';import { afterEach, describe, expect, it } from 'vitest';-import { loginShellPath, withUserBinDirs, withWindowsUserBinDirs } from './login-path';+import { loginShellPath, withUserBinDirs } from './login-path';const dirs: string[] = [];@@ -73,18 +73,3 @@ describe('withUserBinDirs', () => {expect(withUserBinDirs(already, home)).toBe(already);});});--describe('withWindowsUserBinDirs', () => {- it('adds the folder Google’s agy installer writes to, once, after the PATH', () => {- const local = 'C:\\Users\\u\\AppData\\Local';- const agy = 'C:\\Users\\u\\AppData\\Local\\agy\\bin';- expect(withWindowsUserBinDirs('C:\\Windows\\System32', local)).toBe(- `C:\\Windows\\System32;${agy}`- );- const already = `${agy.toUpperCase()};C:\\Windows\\System32`;- expect(withWindowsUserBinDirs(already, local)).toBe(already);- expect(withWindowsUserBinDirs('C:\\Windows\\System32', undefined)).toBe(- 'C:\\Windows\\System32'- );- });-});diff --git a/console/packages/agent-controller/src/login-path.ts b/console/packages/agent-controller/src/login-path.tsindex e80be2ac4..65a06b021 100644--- a/console/packages/agent-controller/src/login-path.ts+++ b/console/packages/agent-controller/src/login-path.ts@@ -1,6 +1,6 @@import { spawn } from 'node:child_process';import { statSync } from 'node:fs';-import { delimiter, join, win32 } from 'node:path';+import { delimiter, join } from 'node:path';const MARKER = '__SWITCH_LOGIN_PATH__';@@ -95,20 +95,6 @@ export function withUserBinDirs(path: string, home: string): string {return [...entries, ...additions].join(delimiter);}-/**- * A Windows `path` with the folders provider installers put CLIs in that it- * lacks, added after it: Google's Antigravity installer writes `agy.exe` to- * `%LOCALAPPDATA%\agy\bin` and adds that to the user's PATH, which a- * controller started before the install does not see.- */-export function withWindowsUserBinDirs(path: string, localAppData: string | undefined): string {- const entries = path.split(win32.delimiter).filter(Boolean);- if (!localAppData) return entries.join(win32.delimiter);- const agyBin = win32.join(localAppData, 'agy', 'bin');- const present = entries.some((entry) => entry.toLowerCase() === agyBin.toLowerCase());- return [...entries, ...(present ? [] : [agyBin])].join(win32.delimiter);-}-function isDirectory(path: string): boolean {try {return statSync(path).isDirectory();diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.tsindex 0902fe6dd..b56ad047a 100644--- a/console/packages/agent-controller/src/main.ts+++ b/console/packages/agent-controller/src/main.ts@@ -13,6 +13,7 @@ import {SESSION_STARTED_KIND,type SessionStartedNotice,} from '@switch-console/agent-providers';+import { withWindowsAgyBinDir } from '@switch-console/plugins/agents';import packageJson from '../package.json' with { type: 'json' };import {AccessTokens,@@ -47,7 +48,7 @@ import {resolveSharedHostBundle,} from './handover';import { createLogger, errorMessage, type Logger } from './log';-import { loginShellPath, withUserBinDirs, withWindowsUserBinDirs } from './login-path';+import { loginShellPath, withUserBinDirs } from './login-path';import { dataLayout, ensureDataDir, resolveDataDir, serverWorkspacesDir } from './paths';import { ProviderRechecks } from './provider-rechecks';import { readProviderSeed, writeProviderSeed } from './provider-seed';@@ -398,7 +399,7 @@ async function setInfoCommand(args: string[]): Promise<number> {function pathRefresher(log: Logger): () => Promise<void> {return async () => {if (process.platform === 'win32') {- process.env.PATH = withWindowsUserBinDirs(process.env.PATH ?? '', process.env.LOCALAPPDATA);+ process.env.PATH = withWindowsAgyBinDir(process.env.PATH ?? '', process.env.LOCALAPPDATA);return;}const shell = process.env.SHELL ?? (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');diff --git a/console/packages/agent-providers/README.md b/console/packages/agent-providers/README.mdindex f9f731787..91047e1b3 100644--- a/console/packages/agent-providers/README.md+++ b/console/packages/agent-providers/README.md@@ -105,16 +105,25 @@ AskQuestion tool, so `user-input` is skipped in its conformance run.**Antigravity** runs Google's `agy` as `agy acp`, with the user's own profileand sign-in (the OS keychain), so the launch sets nothing up. `agy` signs-itself in when it starts; Switch sends `authenticate` only with-`gemini-api-key` when the session environment has `GEMINI_API_KEY`. The-sign-in check asks for `session/list`, which a signed-out `agy` refuses with-`Authentication required`, and never calls `authenticate` with a Google-method, which would open a browser. Questions arrive as ACP form elicitations-(`elicitation/create`), which the adapter announces it can answer. `agy`'s-modes are `default`, `accept-edits` and `plan`: auto mode is `accept-edits`,-and full access is `default` with every request approved by the adapter.+itself in when it starts, and refuses `session/list` with `Authentication+required` when it could not. The sign-in check asks exactly that and never+calls `authenticate`: Google's methods open a browser, and `agy` keeps the+method it is sent, so even the API key method would move a user signed in+with Google onto the key for good. A session start sends `authenticate` with+`gemini-api-key` only when the environment has `GEMINI_API_KEY` and+`session/list` was refused. Questions arrive as ACP form elicitations+(`elicitation/create`), which the adapter announces it can answer: each field+with offered answers is a question, the `<field>_other` text `agy` adds beside+it is that question's typed answer, and any other text field is a question+answered by typing. `agy`'s modes are `default`, `accept-edits` and `plan`:+auto mode is `accept-edits`, and full access is `default` with every request+approved by the adapter. A session that advertises no modes is left in its+own. A hosted Antigravity login (the token file of the legacy runtime) is+refused for an `agy` target with an error saying how to sign in there,+rather than written where `agy` never reads it.A legacy `antigravity-acp` install still runs in its own profile directory(`GEMINI_HOME`) with its `auto_edit` and `yolo` modes, questions as permissionrequests whose tool call id starts with `interaction_`, and its old sign-in-check. Native session ids are stored with an `acp:` prefix; a conversation-saved by the retired CLI runtime starts fresh.+check; its sign-in command is `antigravity-acp --login`, and Update installs+`agy` over it. Native session ids are stored with an `acp:` prefix; a+conversation saved by the retired CLI runtime starts fresh.diff --git a/console/packages/agent-providers/src/acp/acp-adapter.ts b/console/packages/agent-providers/src/acp/acp-adapter.tsindex da0548159..b0460ec49 100644--- a/console/packages/agent-providers/src/acp/acp-adapter.ts+++ b/console/packages/agent-providers/src/acp/acp-adapter.ts@@ -18,7 +18,14 @@ import type {UserInputAnswers,UserInputQuestion,} from '../events';-import { readiness, signInWith, type ProviderReadiness, type SignInCheckInput } from '../readiness';+import {+ loginCommandOf,+ readiness,+ SIGNED_OUT_ERROR,+ signInWith,+ type ProviderReadiness,+ type SignInCheckInput,+} from '../readiness';import {JsonRpcError,noopLogger,@@ -88,7 +95,7 @@ export async function checkAcpSignIn(await handshake();return readiness('unknown',- `${hooks.label} started but has no sign-in check. If its sessions fail, sign in on the execution machine with ${hooks.loginCommand}.`+ `${hooks.label} started but has no sign-in check. If its sessions fail, sign in on the execution machine with ${loginCommandOf(hooks, input.binaryPath)}.`);} finally {await client?.dispose();@@ -239,7 +246,15 @@ export class AcpAdapter implements ProviderAdapter {// for, so a browser opening is an answer to something they did. Sign-in// checks stop at the handshake above.const authMethodId = hooks.authMethodId?.(input.env, binaryPath);- if (authMethodId) await client.request('authenticate', { methodId: authMethodId });+ if (+ authMethodId &&+ !(await hooks.alreadySignedIn?.({+ binaryPath,+ env: input.env,+ request: <T>(method: string, params: unknown) => client.request<T>(method, params),+ }))+ )+ await client.request('authenticate', { methodId: authMethodId });const mcpServers = acpMcpServers(input.mcpServers, input.env);let method = 'session/new';if (input.resume) {@@ -287,8 +302,10 @@ export class AcpAdapter implements ProviderAdapter {? String(cause.data.details): '';const signIn =- cause instanceof JsonRpcError && cause.code === -32000 && /auth/i.test(cause.message)- ? `. ${signInWith(hooks.loginCommand)}`+ cause instanceof JsonRpcError &&+ cause.code === -32000 &&+ SIGNED_OUT_ERROR.test(cause.message)+ ? `. ${signInWith(loginCommandOf(hooks, binaryPath))}`: '';throw new ProviderSessionError(hooks.provider,@@ -437,20 +454,23 @@ export class AcpAdapter implements ProviderAdapter {const pending = state.questions.get(requestId);if (!pending)throw new ProviderSessionError(this.provider, id, `No pending question ${requestId}`);- const selected = pending.questions.map((question) => {+ const selected = pending.questions.map((question): AcpSelectedAnswer => {const answer = answers[question.id];- const values = Array.isArray(answer) ? answer : typeof answer === 'string' ? [answer] : [];+ const given = Array.isArray(answer) ? answer : typeof answer === 'string' ? [answer] : [];+ const offered = (value: string) => question.options.some((option) => option.value === value);+ const values = given.filter(offered);+ const typed = given.filter((value) => !offered(value));if (- !values.length ||- (!question.multiSelect && values.length !== 1) ||- values.some((value) => !question.options.some((option) => option.value === value))+ !given.length ||+ (!question.multiSelect && given.length !== 1) ||+ typed.length > (question.allowCustomAnswer ? 1 : 0))throw new ProviderSessionError(this.provider,id,`Invalid answer for ${question.id}: choose one of the offered answers.`);- return { questionId: question.id, values };+ return { questionId: question.id, values, ...(typed.length ? { custom: typed[0]! } : {}) };});state.questions.delete(requestId);pending.settle(pending.answer(selected));diff --git a/console/packages/agent-providers/src/acp/hooks.ts b/console/packages/agent-providers/src/acp/hooks.tsindex face35350..a5b65a73a 100644--- a/console/packages/agent-providers/src/acp/hooks.ts+++ b/console/packages/agent-providers/src/acp/hooks.ts@@ -36,10 +36,14 @@ export interface AcpLaunchInput {env: Record<string, string>;}-/** One answered question: the option values chosen, already checked against what was offered. */+/**+ * One answered question: the option values chosen, already checked against+ * what was offered, and the text typed where the question takes it.+ */export interface AcpSelectedAnswer {questionId: string;values: string[];+ custom?: string;}/**@@ -99,6 +103,11 @@ export interface AcpProviderHooks {launch(input: AcpLaunchInput): Promise<AcpLaunch> | AcpLaunch;/** The command a person runs on the execution machine to sign the CLI in. */loginCommand: string;+ /**+ * The sign-in command for the executable at `binaryPath`, where it is not+ * `loginCommand` for every one (an older runtime of the same provider, say).+ */+ loginCommandFor?(binaryPath: string): string;/*** Environment variables the CLI reads (an API key, an endpoint) that a* session host should pass through from the machine's environment. The@@ -122,6 +131,13 @@ export interface AcpProviderHooks {* never needs a sign-in call. `binaryPath` is the executable the session runs.*/authMethodId?(env: Record<string, string>, binaryPath: string): string | undefined;+ /**+ * Whether the agent is signed in already, asked after `initialize` and+ * before `authenticate` is sent for `authMethodId`; true sends none. For an+ * agent that keeps the method it is sent, where `authenticate` would move a+ * signed-in CLI onto another method for good. Absent always sends it.+ */+ alreadySignedIn?(input: AcpSignedInQuery): Promise<boolean>;/*** Prompt content the agent accepts whether or not it advertises it. What it* advertises in `initialize` is always honoured as well.@@ -129,9 +145,10 @@ export interface AcpProviderHooks {promptCapabilities?: AcpPromptCapabilities;/*** The ACP mode to put a new session in for Switch's runtime mode, given the- * modes the session advertised. Omit to leave the agent's default.+ * modes the session advertised. Omit, or return undefined, to leave the+ * agent's default.*/- sessionMode?(runtimeMode: RuntimeMode, modes: AcpSessionModes | undefined): string;+ sessionMode?(runtimeMode: RuntimeMode, modes: AcpSessionModes | undefined): string | undefined;/*** Native session ids are stored with this prefix, telling them apart from* ids an earlier, non-ACP runtime of the same provider stored. A resume id@@ -159,6 +176,13 @@ export interface AcpProviderHooks {extensions?(context: AcpSessionContext, on: AcpExtensionRegistrar): void;}+export interface AcpSignedInQuery {+ binaryPath: string;+ env: Record<string, string>;+ /** A request to the agent the session started. */+ request<T>(method: string, params: unknown): Promise<T>;+}+export interface AcpSignInInput extends SignInCheckInput {handshake(): Promise<AcpInitializeResult>;/** A request to the process `handshake` started; fails when it has not run. */diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.tsindex 0865172fd..f5a7122d9 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts@@ -11,7 +11,12 @@ vi.mock('node:fs/promises', async (original) => ({}));const servers: FakeAppServer[] = [];/** What the fake agent declares in `initialize`. */-const acp = { http: true, signedOut: false };+const acp = {+ http: true,+ signedOut: false,+ listSignedOut: false,+ newError: 'Authentication required',+};const spawned: Array<{ command: string; args: string[] }> = [];vi.mock('node:child_process', () => ({spawn: (command: string, args: string[]) => {@@ -24,11 +29,19 @@ vi.mock('node:child_process', () => ({},}));server.replyAlways('authenticate', () => ({}));+ server.on('message', (message: { id?: number; method?: string }) => {+ if (message.method !== 'session/list' || message.id === undefined) return;+ server.send(+ acp.listSignedOut+ ? { id: message.id, error: { code: -32000, message: 'Authentication required' } }+ : { id: message.id, result: { sessions: [] } }+ );+ });server.on('message', (message: { id?: number; method?: string }) => {if (message.method !== 'session/new' || message.id === undefined) return;server.send(acp.signedOut- ? { id: message.id, error: { code: -32000, message: 'Authentication required' } }+ ? { id: message.id, error: { code: -32000, message: acp.newError } }: {id: message.id,result: {@@ -53,6 +66,8 @@ beforeEach(() => {servers.length = 0;spawned.length = 0;acp.signedOut = false;+ acp.listSignedOut = false;+ acp.newError = 'Authentication required';acp.http = true;});async function setup(@@ -258,14 +273,27 @@ it('runs Google’s agy as `agy acp`, signed in by agy itself', async () => {expect(spawned).toEqual([{ command: 'agy', args: ['acp'] }]);expect(server.received.slice(0, 2).map((m) => m.method)).toEqual(['initialize', 'session/new']);});-it('signs agy in with the Gemini API key the session environment carries', async () => {+it('signs agy in with the Gemini API key only when agy could not sign itself in', async () => {+ acp.listSignedOut = true;const { server } = await setup(false, true, { env: { GEMINI_API_KEY: 'placeholder' } });- expect(server.received.slice(0, 3).map((m) => m.method)).toEqual([+ expect(server.received.slice(0, 4).map((m) => m.method)).toEqual(['initialize',+ 'session/list','authenticate','session/new',]);- expect(server.received[1]?.params).toEqual({ methodId: 'gemini-api-key' });+ expect(server.received[2]?.params).toEqual({ methodId: 'gemini-api-key' });+});+it('leaves a signed-in agy on its own sign-in when GEMINI_API_KEY is also set', async () => {+ // agy keeps the method it is sent: authenticating would replace the+ // user's Google sign-in with the key for every later run.+ const { server } = await setup(false, true, { env: { GEMINI_API_KEY: 'placeholder' } });+ expect(server.received.slice(0, 3).map((m) => m.method)).toEqual([+ 'initialize',+ 'session/list',+ 'session/new',+ ]);+ expect(server.received.some((m) => m.method === 'authenticate')).toBe(false);});it('authenticates a legacy antigravity-acp install once before creating the session', async () => {const { server } = await setup(false, true, { binaryPath: '/home/u/.local/bin/antigravity-acp' });@@ -293,7 +321,19 @@ it('keeps the legacy runtime’s auto-edit and yolo modes', () => {expect(antigravityAcp.sessionMode?.('auto-accept-edits', legacy)).toBe('auto_edit');expect(antigravityAcp.sessionMode?.('auto', legacy)).toBe('auto_edit');expect(antigravityAcp.sessionMode?.('full-access', legacy)).toBe('yolo');- expect(antigravityAcp.sessionMode?.('auto', undefined)).toBe('auto_edit');+});+it('sends no mode when the session advertised none, whichever runtime it is', () => {+ expect(antigravityAcp.sessionMode?.('auto', undefined)).toBeUndefined();+ expect(antigravityAcp.sessionMode?.('full-access', { availableModes: [] })).toBeUndefined();+});+it('tells each runtime’s own sign-in command', () => {+ expect(antigravityAcp.loginCommandFor?.('/home/u/.local/bin/agy')).toBe('agy acp --login');+ expect(antigravityAcp.loginCommandFor?.('C:\\Users\\u\\AppData\\Local\\agy\\bin\\agy.exe')).toBe(+ 'agy acp --login'+ );+ expect(antigravityAcp.loginCommandFor?.('/home/u/.local/bin/antigravity-acp')).toBe(+ 'antigravity-acp --login'+ );});it('tells a signed-out agy session how to sign in', async () => {acp.signedOut = true;@@ -308,6 +348,33 @@ it('tells a signed-out agy session how to sign in', async () => {})).rejects.toThrow('Sign in on the execution machine with agy acp --login.');});+it('does not send someone to sign in for an MCP server’s or tool’s authorization failing', async () => {+ acp.signedOut = true;+ acp.newError = 'authorization denied for MCP server github';+ const start = createAntigravityAdapter().startSession({+ sessionId: 'mcp-auth',+ cwd: '/work',+ runtimeMode: 'approval-required',+ env: {},+ mcpServers: {},+ connectorMcpServers: [],+ });+ await expect(start).rejects.toThrow('authorization denied for MCP server github');+ await expect(start).rejects.not.toThrow('Sign in on the execution machine');+});+it('points a signed-out legacy session at the legacy sign-in command', async () => {+ acp.signedOut = true;+ await expect(+ createAntigravityAdapter({ binaryPath: '/home/u/.local/bin/antigravity-acp' }).startSession({+ sessionId: 'legacy-signed-out',+ cwd: '/work',+ runtimeMode: 'approval-required',+ env: {},+ mcpServers: {},+ connectorMcpServers: [],+ })+ ).rejects.toThrow('Sign in on the execution machine with antigravity-acp --login.');+});it('refuses legacy CLI conversation IDs before starting a process', async () => {await expect(createAntigravityAdapter().startSession({@@ -374,7 +441,11 @@ const agyQuestion = {{ const: '3', title: 'blue' },],},- q1_other: { type: 'string', title: 'Other', description: 'Optional free-form answer' },+ q1_other: {+ type: 'string',+ title: 'Other',+ description: 'Optional free-form answer to: Which color?',+ },},},};@@ -398,7 +469,7 @@ it('announces form elicitation and answers agy questions through it', async () ={ value: '3', label: 'blue' },],multiSelect: false,- allowCustomAnswer: false,+ allowCustomAnswer: true,},]);await adapter.respondToUserInput('s', event.requestId, { q1: '2' });@@ -408,6 +479,107 @@ it('announces form elicitation and answers agy questions through it', async () =content: { q1: '2' },});});+it('sends a typed answer to agy as the question’s Other field', async () => {+ // Measured against agy 1.5.1: it takes `q1_other` with `q1` left out.+ const { adapter, server, events } = await setup();+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'question' });+ server.send({ id: 96, method: 'elicitation/create', params: agyQuestion });+ await flush();+ const event = events.find((e) => e.type === 'user-input.requested');+ if (!event || event.type !== 'user-input.requested') throw new Error('Missing question');+ await adapter.respondToUserInput('s', event.requestId, { q1: 'purple' });+ await flush();+ expect(server.received.find((m) => m.id === 96)?.result).toEqual({+ action: 'accept',+ content: { q1_other: 'purple' },+ });+});+it('refuses typed text for a question that offers none', async () => {+ const { adapter, server, events } = await setup();+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'question' });+ const { q1 } = agyQuestion.requestedSchema.properties;+ server.send({+ id: 95,+ method: 'elicitation/create',+ params: { ...agyQuestion, requestedSchema: { type: 'object', properties: { q1 } } },+ });+ await flush();+ const event = events.find((e) => e.type === 'user-input.requested');+ if (!event || event.type !== 'user-input.requested') throw new Error('Missing question');+ expect(event.questions[0]?.allowCustomAnswer).toBe(false);+ await expect(adapter.respondToUserInput('s', event.requestId, { q1: 'purple' })).rejects.toThrow(+ 'choose one of the offered answers'+ );+});+it('asks a form’s free-text fields too, rather than declining the form', () => {+ const request = {+ message: 'Details?',+ requestedSchema: {+ properties: {+ name: { type: 'string', title: 'Your name' },+ count: { type: 'integer', title: 'How many?' },+ },+ },+ };+ expect(elicitationQuestions(request)).toEqual([+ {+ id: 'name',+ question: 'Your name',+ options: [],+ multiSelect: false,+ allowCustomAnswer: true,+ },+ {+ id: 'count',+ question: 'How many?',+ options: [],+ multiSelect: false,+ allowCustomAnswer: true,+ },+ ]);+ expect(+ elicitationAnswer(request, [+ { questionId: 'name', values: [], custom: 'Ada' },+ { questionId: 'count', values: [], custom: '3' },+ ])+ ).toEqual({ action: 'accept', content: { name: 'Ada', count: 3 } });+});+it('answers with the values the schema offered, numbers and booleans included', () => {+ const request = {+ requestedSchema: {+ properties: {+ size: { type: 'number', title: 'Size', enum: [1, 2] },+ level: { type: 'integer', oneOf: [{ const: 5, title: 'High' }] },+ ok: { type: 'boolean', title: 'Proceed?' },+ },+ },+ };+ expect(elicitationQuestions(request).map((q) => q.options)).toEqual([+ [+ { value: '1', label: '1' },+ { value: '2', label: '2' },+ ],+ [{ value: '5', label: 'High' }],+ [+ { value: 'true', label: 'Yes' },+ { value: 'false', label: 'No' },+ ],+ ]);+ expect(+ elicitationAnswer(request, [+ { questionId: 'size', values: ['2'] },+ { questionId: 'level', values: ['5'] },+ { questionId: 'ok', values: ['false'] },+ ])+ ).toEqual({ action: 'accept', content: { size: 2, level: 5, ok: false } });+});+it('leaves out a question answered with nothing rather than sending undefined', () => {+ const request = agyQuestion;+ expect(elicitationAnswer(request, [{ questionId: 'q1', values: [] }])).toEqual({+ action: 'accept',+ content: {},+ });+});it('answers several choices for an array field', () => {const questions = elicitationQuestions({requestedSchema: {@@ -420,7 +592,18 @@ it('answers several choices for an array field', () => {multiSelect: true,options: [{ value: 'a' }, { value: 'b' }],});- expect(elicitationAnswer(questions, [{ questionId: 'q1', values: ['a', 'b'] }])).toEqual({+ expect(+ elicitationAnswer(+ {+ requestedSchema: {+ properties: {+ q1: { type: 'array', items: { anyOf: [{ const: 'a' }, { const: 'b' }] } },+ },+ },+ },+ [{ questionId: 'q1', values: ['a', 'b'] }]+ )+ ).toEqual({action: 'accept',content: { q1: ['a', 'b'] },});diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.tsindex 7850a6678..69d526983 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts@@ -3,19 +3,18 @@ import type { AcpAdapterOptions, AcpProviderHooks, AcpSelectedAnswer } from '../import { ACP_CANCELLED, type AcpSessionModes } from '../acp/protocol';import type { RuntimeMode } from '../adapter';import type { UserInputQuestion } from '../events';-import { readiness } from '../readiness';+import { readiness, SIGNED_OUT_ERROR } from '../readiness';import {AGY_LOGIN,ANTIGRAVITY_SIGN_IN,LEGACY_ANTIGRAVITY_SIGN_IN,antigravityLaunch,+ antigravityLoginCommand,antigravityProfile,antigravitySignedIn,isLegacyAntigravityRuntime,} from './runtime';-const SIGNED_OUT = /sign in|auth required|authentication required|unauthenticated|not logged in/i;-/*** The modes to try for each runtime mode, best first. `agy acp` offers* `default`, `accept-edits` and `plan`; the retired `antigravity-acp` offered@@ -29,13 +28,17 @@ const MODE_PREFERENCES: Record<RuntimeMode, readonly string[]> = {'approval-required': ['default'],};-/** The session mode for `runtimeMode` among those the session advertised. */+/**+ * The session mode for `runtimeMode` among those the session advertised, or+ * none when it advertised none: the ids differ between runtimes, so one is+ * only sent when the session named it.+ */export function antigravitySessionMode(runtimeMode: RuntimeMode,modes: AcpSessionModes | undefined-): string {+): string | undefined {const preferences = MODE_PREFERENCES[runtimeMode];- if (!modes?.availableModes.length) return preferences[0]!;+ if (!modes?.availableModes.length) return undefined;return (preferences.find((id) => modes.availableModes.some((mode) => mode.id === id)) ??preferences.at(-1)!@@ -64,58 +67,132 @@ export interface AcpElicitationRequest {requestedSchema?: { properties?: Record<string, ElicitationProperty> };}-function choices(property: ElicitationProperty | undefined): UserInputQuestion['options'] {+type ElicitationValue = string | number | boolean;++/** The answers `property` offers, each with the value the schema takes for it. */+function choices(+ property: ElicitationProperty | undefined+): Array<{ value: ElicitationValue; label: string }> {const offered = property?.oneOf ?? property?.anyOf;if (offered)return offered.map((choice) => ({- value: String(choice.const),+ value: choice.const,label: choice.title ?? String(choice.const),}));- return (property?.enum ?? []).map((value) => ({ value: String(value), label: String(value) }));+ if (property?.enum) return property.enum.map((value) => ({ value, label: String(value) }));+ if (property?.type === 'boolean')+ return [+ { value: true, label: 'Yes' },+ { value: false, label: 'No' },+ ];+ return [];+}++/** One question a form elicitation asks, and the fields its answer fills. */+interface ElicitationField {+ question: UserInputQuestion;+ /** Option value as offered to the user → the value the schema takes. */+ values: Map<string, ElicitationValue>;+ /** The field typed text goes into, if any: the question's own, or its "Other". */+ textField?: { id: string; property: ElicitationProperty };}/**- * The questions a form elicitation asks: each field with offered answers, one- * of them or (an array field) several. A free-text field, such as the- * optional "Other" agy adds beside each question, is left unanswered.+ * The questions a form elicitation asks. A field with offered answers is one+ * question, choosing one of them or (an array field) several; the free-text+ * "Other" agy adds beside it as `<field>_other` becomes that question's own+ * typed answer. Any other free-text field is a question answered by typing.*/-export function elicitationQuestions(request: AcpElicitationRequest): UserInputQuestion[] {+function elicitationFields(request: AcpElicitationRequest): ElicitationField[] {if (request.mode !== undefined && request.mode !== 'form') return [];- return Object.entries(request.requestedSchema?.properties ?? {}).flatMap(([id, property]) => {- const multiSelect = property.type === 'array';- const options = choices(multiSelect ? property.items : property);- if (!options.length) return [];+ const properties = request.requestedSchema?.properties ?? {};+ const offeredBy = (property: ElicitationProperty) =>+ choices(property.type === 'array' ? property.items : property);+ const freeText = (property: ElicitationProperty | undefined): property is ElicitationProperty =>+ property !== undefined && !offeredBy(property).length;+ return Object.entries(properties).flatMap(([id, property]): ElicitationField[] => {+ const base = id.endsWith('_other') ? properties[id.slice(0, -'_other'.length)] : undefined;+ if (freeText(property) && base && !freeText(base)) return [];+ const offered = offeredBy(property);+ const other = properties[`${id}_other`];+ const textField = !offered.length+ ? { id, property }+ : freeText(other)+ ? { id: `${id}_other`, property: other }+ : undefined;return [{- id,- question: property.title ?? property.description ?? request.message ?? 'Choose an option.',- options,- multiSelect,- allowCustomAnswer: false,+ question: {+ id,+ question:+ property.title ?? property.description ?? request.message ?? 'Choose an option.',+ options: offered.map((choice) => ({ value: String(choice.value), label: choice.label })),+ multiSelect: property.type === 'array' && offered.length > 0,+ allowCustomAnswer: Boolean(textField),+ },+ values: new Map(offered.map((choice) => [String(choice.value), choice.value])),+ ...(textField ? { textField } : {}),},];});}-/** The elicitation result for the answers chosen. */+export function elicitationQuestions(request: AcpElicitationRequest): UserInputQuestion[] {+ return elicitationFields(request).map((field) => field.question);+}++/** Typed text as the schema of the field it fills takes it. */+function typedValue(+ text: string,+ property: ElicitationProperty+): ElicitationValue | ElicitationValue[] {+ if (property.type === 'array')+ return [typedValue(text, property.items ?? {}) as ElicitationValue];+ if (property.type === 'number' || property.type === 'integer') {+ const number = Number(text);+ // Text that is no number is passed as typed, for the agent to refuse.+ return text.trim() && Number.isFinite(number) ? number : text;+ }+ return text;+}++/** The elicitation result for the answers given. */export function elicitationAnswer(- questions: UserInputQuestion[],+ request: AcpElicitationRequest,selected: AcpSelectedAnswer[]-): { action: 'accept'; content: Record<string, string | string[]> } {- return {- action: 'accept',- content: Object.fromEntries(- selected.map(({ questionId, values }) => [- questionId,- questions.find((question) => question.id === questionId)?.multiSelect ? values : values[0]!,- ])- ),- };+): { action: 'accept'; content: Record<string, ElicitationValue | ElicitationValue[]> } {+ const fields = new Map(elicitationFields(request).map((field) => [field.question.id, field]));+ const content: Record<string, ElicitationValue | ElicitationValue[]> = {};+ for (const { questionId, values, custom } of selected) {+ const field = fields.get(questionId);+ if (!field) continue;+ const chosen = values.map((value) => field.values.get(value) ?? value);+ if (field.question.multiSelect) {+ if (chosen.length) content[questionId] = chosen;+ } else if (chosen.length) content[questionId] = chosen[0]!;+ if (custom !== undefined && field.textField)+ content[field.textField.id] = typedValue(custom, field.textField.property);+ }+ return { action: 'accept', content };+}++/** Whether a running agy answers as signed in, asked without signing it in. */+async function agySignedIn(+ request: <T>(method: string, params: unknown) => Promise<T>+): Promise<boolean> {+ try {+ await request('session/list', {});+ return true;+ } catch (error) {+ if (SIGNED_OUT_ERROR.test(String(error))) return false;+ throw error;+ }}/*** Antigravity over ACP: Google's `agy acp`, or a legacy `antigravity-acp`- * install. Questions arrive as permission requests.+ * install. agy asks its questions as form elicitations; the legacy runtime+ * asked them as permission requests.*/export const antigravityAcp: AcpProviderHooks = {provider: 'antigravity',@@ -130,18 +207,24 @@ export const antigravityAcp: AcpProviderHooks = {},launch: antigravityLaunch,loginCommand: AGY_LOGIN,- // A check must never sign in: `authenticate` with Google's methods opens a- // browser. `agy` signs itself in from the user's keychain when it starts,- // and refuses `session/list` with "Authentication required" when it could- // not, so that request answers the question without changing anything.+ loginCommandFor: antigravityLoginCommand,+ // A check must never sign in, nor change how the CLI signs in: `authenticate`+ // with Google's methods opens a browser, and agy keeps the method it is+ // sent, so an API key chosen once would replace the user's Google sign-in.+ // agy signs itself in when it starts, and refuses `session/list` with+ // "Authentication required" when it could not.checkSignIn: async ({ binaryPath, env, handshake, request }) => {try {if (!isLegacyAntigravityRuntime(binaryPath)) {await handshake();- const method = antigravityAcp.authMethodId?.(env, binaryPath);- if (method) await request('authenticate', { methodId: method });- await request('session/list', {});- return readiness('authenticated', 'Signed in to Antigravity.');+ if (await agySignedIn(request))+ return readiness('authenticated', 'Signed in to Antigravity.');+ return env.GEMINI_API_KEY+ ? readiness(+ 'authenticated',+ 'Antigravity is not signed in itself; sessions sign it in with GEMINI_API_KEY, which is checked when one starts.'+ )+ : readiness('unauthenticated', ANTIGRAVITY_SIGN_IN);}// Antigravity ACP 1.3 lists every method whether or not one is in use,// so an outstanding method is only signed out when the profile holds no@@ -151,7 +234,7 @@ export const antigravityAcp: AcpProviderHooks = {? readiness('authenticated', 'Signed in to Antigravity ACP.'): readiness('unauthenticated', LEGACY_ANTIGRAVITY_SIGN_IN);} catch (error) {- if (SIGNED_OUT.test(String(error)))+ if (SIGNED_OUT_ERROR.test(String(error)))return readiness('unauthenticated',isLegacyAntigravityRuntime(binaryPath) ? LEGACY_ANTIGRAVITY_SIGN_IN : ANTIGRAVITY_SIGN_IN@@ -159,16 +242,17 @@ export const antigravityAcp: AcpProviderHooks = {throw error;}},- // `agy` needs no call when it signed itself in from the keychain; an API- // key in the environment is only used once it is chosen. The legacy runtime- // opens a browser when its profile holds no usable token, which is why only- // a session start sends it.+ // The legacy runtime opens a browser when its profile holds no usable+ // token, which is why only a session start sends it. agy is sent the API key+ // method only when it could not sign itself in: see `checkSignIn`.authMethodId: (env, binaryPath) =>isLegacyAntigravityRuntime(binaryPath)? 'oauth-personal': env.GEMINI_API_KEY? 'gemini-api-key': undefined,+ alreadySignedIn: async ({ binaryPath, request }) =>+ !isLegacyAntigravityRuntime(binaryPath) && (await agySignedIn(request)),promptCapabilities: { image: true, audio: true, embeddedContext: true },// Antigravity has no reviewer of its own, so auto mode is its auto-edit// mode: edits run, commands and connector calls still ask.@@ -191,10 +275,12 @@ export const antigravityAcp: AcpProviderHooks = {clientCapabilities: { elicitation: { form: {} } },extensions: (context, on) => {on.request('elicitation/create', async (params) => {- const questions = elicitationQuestions(params as AcpElicitationRequest);+ const request = params as AcpElicitationRequest;+ const questions = elicitationQuestions(request);+ // A form with no fields, or a mode other than a form (a URL to open).if (!questions.length) return { action: 'decline' };const result = await context.askQuestions(questions, (selected) =>- elicitationAnswer(questions, selected)+ elicitationAnswer(request, selected));return result === ACP_CANCELLED ? { action: 'cancel' } : result;});diff --git a/console/packages/agent-providers/src/antigravity/runtime.test.ts b/console/packages/agent-providers/src/antigravity/runtime.test.tsindex 9b78b4b28..299abc2e8 100644--- a/console/packages/agent-providers/src/antigravity/runtime.test.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.test.ts@@ -34,6 +34,17 @@ it('runs agy as `agy acp` in the user’s own profile, on every OS', async () =>}});+it('refuses the Antigravity IDE launcher, which would take `acp` for a folder to open', async () => {+ for (const binaryPath of [+ 'antigravity',+ '/usr/bin/antigravity',+ 'C:\\Users\\u\\AppData\\Local\\Programs\\Antigravity\\bin\\antigravity.cmd',+ ])+ await expect(antigravityLaunch({ binaryPath, cwd: '/work', env: {} })).rejects.toThrow(+ 'Antigravity IDE launcher'+ );+});+it('tells a legacy wrapper install from Google’s agy', () => {expect(isLegacyAntigravityRuntime('/home/u/.local/bin/antigravity-acp')).toBe(true);expect(isLegacyAntigravityRuntime('/opt/acp/agy_acp_server.par')).toBe(true);diff --git a/console/packages/agent-providers/src/antigravity/runtime.ts b/console/packages/agent-providers/src/antigravity/runtime.tsindex 97ada9c63..95ae4f8a7 100644--- a/console/packages/agent-providers/src/antigravity/runtime.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.ts@@ -9,8 +9,10 @@ export const AGY_LOGIN = 'agy acp --login';export const ANTIGRAVITY_SIGN_IN = `Sign in to Antigravity on the execution host with ${AGY_LOGIN}, or set GEMINI_API_KEY.`;/** How a retired Switch wrapper install is signed in: it keeps a profile of its own. */-export const LEGACY_ANTIGRAVITY_SIGN_IN =- 'Sign in to Antigravity ACP on the execution host with antigravity-acp --login, or install Google’s agy CLI and sign in with agy acp --login.';+/** The command that signs a retired Switch wrapper install in, into its own profile. */+export const LEGACY_ANTIGRAVITY_LOGIN = 'antigravity-acp --login';++export const LEGACY_ANTIGRAVITY_SIGN_IN = `Sign in to Antigravity ACP on the execution host with ${LEGACY_ANTIGRAVITY_LOGIN}, or install Google’s agy CLI and sign in with ${AGY_LOGIN}.`;/*** Whether `binaryPath` is the ACP runtime Switch Console used to install@@ -23,6 +25,21 @@ export function isLegacyAntigravityRuntime(binaryPath: string): boolean {return name.startsWith('antigravity-acp') || name.startsWith('agy_acp_server');}+/** The command that signs in the Antigravity runtime at `binaryPath`. */+export function antigravityLoginCommand(binaryPath: string): string {+ return isLegacyAntigravityRuntime(binaryPath) ? LEGACY_ANTIGRAVITY_LOGIN : AGY_LOGIN;+}++/**+ * Whether `binaryPath` is the Antigravity IDE's command-line launcher, which+ * opens the editor (and would take `acp` for a folder to open) rather than+ * serving ACP.+ */+function isAntigravityIdeLauncher(binaryPath: string): boolean {+ const name = basename(binaryPath.replaceAll('\\', '/')).toLowerCase();+ return /^antigravity(\.(exe|cmd|bat))?$/.test(name);+}+/** The Gemini home a legacy Antigravity ACP server runs with: its sign-in and settings live under it. */export function antigravityProfile(env: Record<string, string>): string {return (@@ -59,6 +76,10 @@ export async function antigravitySignedIn(profile: string): Promise<boolean> {* first use, and is killed when it prints a sign-in link instead of answering.*/export async function antigravityLaunch(input: AcpLaunchInput): Promise<AcpLaunch> {+ if (isAntigravityIdeLauncher(input.binaryPath))+ throw new Error(+ 'The selected executable is the Antigravity IDE launcher, which does not serve ACP. Install Google’s agy CLI and select it in provider setup.'+ );if (!isLegacyAntigravityRuntime(input.binaryPath))return {command: input.binaryPath,diff --git a/console/packages/agent-providers/src/host/hosted-provider.test.ts b/console/packages/agent-providers/src/host/hosted-provider.test.tsindex e31fb8c1e..fc016e5fa 100644--- a/console/packages/agent-providers/src/host/hosted-provider.test.ts+++ b/console/packages/agent-providers/src/host/hosted-provider.test.ts@@ -69,16 +69,21 @@ it('does not follow an authentication directory symlink', async () => {});it('keeps the different providers in their native authentication locations', async () => {- for (const [provider, variable, relative] of [- ['opencode', 'XDG_DATA_HOME', 'opencode/auth.json'],- ['antigravity', 'GEMINI_HOME', 'antigravity-acp/acp_token.json'],+ for (const [provider, variable, relative, binaryPath] of [+ ['opencode', 'XDG_DATA_HOME', 'opencode/auth.json', 'fixture-cli'],+ [+ 'antigravity',+ 'GEMINI_HOME',+ 'antigravity-acp/acp_token.json',+ '/home/u/.local/bin/antigravity-acp',+ ],] as const) {const env: Record<string, string> = {};await materializeHostedProvider(root,env,{ ...credential('{"fixture":true}'), provider },- 'fixture-cli'+ binaryPath);expect(JSON.parse(await readFile(join(env[variable]!, relative), 'utf8'))).toEqual({fixture: true,@@ -86,6 +91,21 @@ it('keeps the different providers in their native authentication locations', asy}});+it('refuses an Antigravity ACP token for agy, which would never read it', async () => {+ const env: Record<string, string> = {};+ for (const binaryPath of ['agy', 'C:\\Users\\u\\AppData\\Local\\agy\\bin\\agy.exe'])+ await expect(+ materializeHostedProvider(+ root,+ env,+ { ...credential('{"fixture":true}'), provider: 'antigravity' },+ binaryPath+ )+ ).rejects.toThrow('agy acp --login');+ expect(env.GEMINI_HOME).toBeUndefined();+ await expect(stat(join(root, 'provider-home'))).rejects.toMatchObject({ code: 'ENOENT' });+});+it('keeps the prepared Codex home and refreshes its auth before provider startup', async () => {const env: Record<string, string> = {};const original = credential('{"fixture":"original"}');diff --git a/console/packages/agent-providers/src/host/hosted-provider.ts b/console/packages/agent-providers/src/host/hosted-provider.tsindex 2c287c582..74049c2fe 100644--- a/console/packages/agent-providers/src/host/hosted-provider.ts+++ b/console/packages/agent-providers/src/host/hosted-provider.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';import { constants } from 'node:fs';import { lstat, mkdir, open, readFile } from 'node:fs/promises';import { join } from 'node:path';+import { AGY_LOGIN, isLegacyAntigravityRuntime } from '../antigravity/runtime';import { refreshCodexAuthentication } from '../codex/home';import { parseVertexLogin, VERTEX_CREDENTIALS_FILE } from '../vertex-login';import { importOpenCodeConsole } from './opencode-console';@@ -149,6 +150,14 @@ export async function materializeHostedProvider(await writeAuthentication(env.XDG_DATA_HOME, 'opencode/auth.json', credential.credential);}} else if (credential.provider === 'antigravity') {+ // The login Switch holds is the token file of the runtime Switch Console+ // used to install. Google's agy keeps its sign-in in the system keychain+ // and never reads that file, so handing it the token would leave the+ // session signed out, or signed in as whoever the machine already has.+ if (!isLegacyAntigravityRuntime(binaryPath))+ throw new Error(+ `This agent's Antigravity sign-in was made for Antigravity ACP (antigravity-acp), which Google's agy CLI cannot use. Sign in on the execution machine with ${AGY_LOGIN}, or set GEMINI_API_KEY there, and disconnect the Antigravity login Switch holds for the agent.`+ );env.GEMINI_HOME = join(root, 'provider-home');await writeAuthentication(env.GEMINI_HOME,diff --git a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.tsindex b59871a4e..6a18c3a06 100644--- a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts@@ -84,19 +84,26 @@ it('reports a signed-out agy as unauthenticated, pointing at agy acp --login', aexpect(mock.request.mock.calls.map((call) => call[0])).not.toContain('authenticate');expect(mock.dispose).toHaveBeenCalledOnce();});-it('checks agy with the Gemini API key the environment carries', async () => {- mock.request- .mockResolvedValueOnce({})- .mockResolvedValueOnce({})- .mockResolvedValueOnce({ sessions: [] });+// agy keeps the method it is sent: authenticating with the key, even once,+// would move a user signed in with Google onto the key for good.+it('checks agy without choosing the Gemini API key the environment carries', async () => {+ mock.request.mockResolvedValueOnce({}).mockResolvedValueOnce({ sessions: [] });const result = await checkProviderReadiness({ ...agy, env: { GEMINI_API_KEY: 'placeholder' } });expect(result.status).toBe('authenticated');expect(mock.request.mock.calls).toEqual([['initialize', expect.anything()],- ['authenticate', { methodId: 'gemini-api-key' }],['session/list', {}],]);});+it('counts on the Gemini API key for an agy not signed in itself, saying it is unchecked', async () => {+ mock.request+ .mockResolvedValueOnce({})+ .mockRejectedValueOnce(new JsonRpcError(-32000, 'Authentication required'));+ const result = await checkProviderReadiness({ ...agy, env: { GEMINI_API_KEY: 'placeholder' } });+ expect(result).toMatchObject({ status: 'authenticated' });+ expect(result.message).toContain('checked when one starts');+ expect(mock.request.mock.calls.map((call) => call[0])).toEqual(['initialize', 'session/list']);+});// A legacy `antigravity-acp` install keeps its own profile and is checked as before.const legacy = { ...input, binaryPath: '/home/u/.local/bin/antigravity-acp' };it('answers legacy Antigravity ACP sign-in from the handshake, without signing in', async () => {@@ -116,8 +123,14 @@ it('reports an outstanding legacy sign-in as unauthenticated', async () => {const result = await checkProviderReadiness({ ...legacy, provider: 'antigravity' });expect(result.status).toBe('unauthenticated');expect(result.message).toContain('antigravity-acp --login');+ // Console's sign-in hint and button follow the executable checked.+ expect(result.loginCommand).toBe('antigravity-acp --login');expect(mock.dispose).toHaveBeenCalledOnce();});+it('names no login command of its own for agy, the provider’s usual one', async () => {+ mock.request.mockResolvedValueOnce({}).mockResolvedValueOnce({ sessions: [] });+ expect(await checkProviderReadiness(agy)).not.toHaveProperty('loginCommand');+});// Antigravity ACP 1.3 lists every sign-in method in its handshake, signed in or// not: the token --login wrote is what says.it('counts the token --login wrote as signed in when the handshake lists methods', async () => {diff --git a/console/packages/agent-providers/src/host/provider-readiness.ts b/console/packages/agent-providers/src/host/provider-readiness.tsindex a518816ed..631c55a76 100644--- a/console/packages/agent-providers/src/host/provider-readiness.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.ts@@ -1,5 +1,5 @@import { providerRuntime } from '../providers/registry';-import { readiness, signInWith, type ProviderReadiness } from '../readiness';+import { loginCommandOf, readiness, signInWith, type ProviderReadiness } from '../readiness';import { JsonRpcError } from '../transport/stdio-json-rpc';export { providerReadinessSchema, type ProviderReadiness } from '../readiness';@@ -16,18 +16,22 @@ export async function checkProviderReadiness(input: {env: Record<string, string>;}): Promise<ProviderReadiness> {const runtime = providerRuntime(input.provider);- try {- return await runtime.checkSignIn(input);- } catch (error) {- if (- error instanceof JsonRpcError &&- error.code === -32000 &&- /auth|log.?in|sign.?in|API key is missing|no API key/i.test(error.message)- )- return readiness('unauthenticated', signInWith(runtime.loginCommand));- return readiness(- 'unknown',- 'Could not verify authentication. Check the connection and provider setup, then retry.'- );- }+ const loginCommand = loginCommandOf(runtime, input.binaryPath);+ const result = await (async () => {+ try {+ return await runtime.checkSignIn(input);+ } catch (error) {+ if (+ error instanceof JsonRpcError &&+ error.code === -32000 &&+ /auth|log.?in|sign.?in|API key is missing|no API key/i.test(error.message)+ )+ return readiness('unauthenticated', signInWith(loginCommand));+ return readiness(+ 'unknown',+ 'Could not verify authentication. Check the connection and provider setup, then retry.'+ );+ }+ })();+ return loginCommand === runtime.loginCommand ? result : { ...result, loginCommand };}diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex 47ca2a7a7..e07dba51b 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -178,7 +178,7 @@ export { codexSourceHome, prepareCodexSessionHome, withManagedCodexSandbox } froexport { readSharedCredentials, sharedConfigSchema } from './host/shared-config';export type { SharedHostConfig } from './host/shared-config';-export { providerReadinessSchema } from './readiness';+export { loginCommandOf, providerReadinessSchema } from './readiness';export {cliConversationListSchema,deletedCliConversationCopiesSchema,diff --git a/console/packages/agent-providers/src/providers/registry.ts b/console/packages/agent-providers/src/providers/registry.tsindex a26d13c27..b7dc84222 100644--- a/console/packages/agent-providers/src/providers/registry.ts+++ b/console/packages/agent-providers/src/providers/registry.ts@@ -36,6 +36,11 @@ export interface ProviderRuntime {id: string;/** The command a person runs on the execution machine to sign the CLI in. */loginCommand: string;+ /**+ * The sign-in command for the executable at `binaryPath`, where it is not+ * `loginCommand` for every one. Read it through `loginCommandOf`.+ */+ loginCommandFor?(binaryPath: string): string;/*** Environment variables the CLI reads (credentials, endpoints) that a* session host passes through from the machine's environment.@@ -53,6 +58,7 @@ export function acpProviderRuntime(hooks: AcpProviderHooks): ProviderRuntime {return {id: hooks.provider,loginCommand: hooks.loginCommand,+ ...(hooks.loginCommandFor ? { loginCommandFor: hooks.loginCommandFor } : {}),inheritEnv: hooks.inheritEnv ?? [],unsupportedPlatforms: hooks.unsupportedPlatforms ?? {},createAdapter: ({ binaryPath, logger }) => createAcpAdapter(hooks, { binaryPath, logger }),diff --git a/console/packages/agent-providers/src/readiness.ts b/console/packages/agent-providers/src/readiness.tsindex 3d6e7d8e5..a0dbfc6c2 100644--- a/console/packages/agent-providers/src/readiness.ts+++ b/console/packages/agent-providers/src/readiness.ts@@ -10,6 +10,11 @@ export const providerReadinessSchema = z.object({* older than this field, and wherever signing in may help.*/loginHelps: z.boolean().optional(),+ /**+ * The command that signs in the executable checked, where it differs from+ * the provider's usual login command (an older runtime of the provider).+ */+ loginCommand: z.string().optional(),});export type ProviderReadiness = z.infer<typeof providerReadinessSchema>;@@ -29,6 +34,22 @@ export function loginWontHelp(result: ProviderReadiness): ProviderReadiness {return { ...result, loginHelps: false };}+/**+ * What an agent's error says when it refused because it is not signed in.+ * Narrower than any mention of "auth": an MCP server's or a tool's+ * authorization failing is not the provider's sign-in.+ */+export const SIGNED_OUT_ERROR =+ /sign in|auth required|authentication required|unauthenticated|not logged in|not signed in/i;++/** The command that signs in `provider`'s executable at `binaryPath`. */+export function loginCommandOf(+ provider: { loginCommand: string; loginCommandFor?(binaryPath: string): string },+ binaryPath: string+): string {+ return provider.loginCommandFor?.(binaryPath) ?? provider.loginCommand;+}+export function signInWith(loginCommand: string): string {return `Sign in on the execution machine with ${loginCommand}.`;}diff --git a/console/packages/plugins/src/agents/impl/antigravity/index.test.ts b/console/packages/plugins/src/agents/impl/antigravity/index.test.tsindex de7f09727..5a38d8fc9 100644--- a/console/packages/plugins/src/agents/impl/antigravity/index.test.ts+++ b/console/packages/plugins/src/agents/impl/antigravity/index.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { AGY_INSTALL_UNIX, AGY_INSTALL_WINDOWS, plugin } from './index';+import {+ AGY_INSTALL_UNIX,+ AGY_INSTALL_WINDOWS,+ antigravityUpdateCommand,+ plugin,+ provider,+} from './index';const dependency = plugin.capabilities.hostDependency;@@ -28,4 +34,23 @@ describe('Antigravity host dependency', () => {it('updates agy with its own update command', () => {expect(dependency.updates).toMatchObject({ update: { kind: 'cli', args: ['update'] } });});++ it('runs `agy update` for agy, wherever it is installed', () => {+ for (const binaryPath of [+ '/home/u/.local/bin/agy',+ 'C:\\Users\\u\\AppData\\Local\\agy\\bin\\agy.exe',+ ])+ expect(antigravityUpdateCommand(binaryPath)).toEqual({+ command: binaryPath,+ args: ['update'],+ });+ expect(provider.behavior.hostDependency?.buildUpdateCommand).toBe(antigravityUpdateCommand);+ });++ it('updates a legacy antigravity-acp install by installing agy, which it takes no update command for', () => {+ expect(antigravityUpdateCommand('/home/u/.local/bin/antigravity-acp')).toEqual({+ command: 'bash',+ args: ['-c', AGY_INSTALL_UNIX],+ });+ });});diff --git a/console/packages/plugins/src/agents/impl/antigravity/index.ts b/console/packages/plugins/src/agents/impl/antigravity/index.tsindex 63d98dea0..4a8890bf4 100644--- a/console/packages/plugins/src/agents/impl/antigravity/index.ts+++ b/console/packages/plugins/src/agents/impl/antigravity/index.ts@@ -79,7 +79,21 @@ export const plugin = definePlugin({ icon });+/**+ * How the Antigravity CLI at `binaryPath` updates. agy updates itself; the+ * legacy `antigravity-acp` launcher takes no update command, so updating it+ * installs agy with Google's installer, which then takes over. That launcher+ * was only ever installed on macOS and Linux.+ */+export function antigravityUpdateCommand(binaryPath: string): { command: string; args: string[] } {+ const name = binaryPath.replaceAll('\\', '/').split('/').at(-1)!.toLowerCase();+ return name.startsWith('antigravity-acp')+ ? { command: 'bash', args: ['-c', AGY_INSTALL_UNIX] }+ : { command: binaryPath, args: ['update'] };+}+export const provider = registerPluginBehavior(plugin, {+ hostDependency: { buildUpdateCommand: antigravityUpdateCommand },prompt: {buildCommand: () => {throw new Error('Antigravity runs through the ACP session host.');diff --git a/console/packages/plugins/src/agents/impl/antigravity/windows-path.test.ts b/console/packages/plugins/src/agents/impl/antigravity/windows-path.test.tsnew file mode 100644index 000000000..bee55181a--- /dev/null+++ b/console/packages/plugins/src/agents/impl/antigravity/windows-path.test.ts@@ -0,0 +1,24 @@+import { expect, it } from 'vitest';+import { withWindowsAgyBinDir } from './windows-path';++const local = 'C:\\Users\\u\\AppData\\Local';+const agy = 'C:\\Users\\u\\AppData\\Local\\agy\\bin';++it('adds the folder Google’s agy installer writes to after the PATH, so an agy already on it wins', () => {+ expect(withWindowsAgyBinDir('C:\\scoop\\shims;C:\\Windows\\System32', local)).toBe(+ `C:\\scoop\\shims;C:\\Windows\\System32;${agy}`+ );+ expect(withWindowsAgyBinDir('C:\\Windows', `${local}\\`)).toBe(`C:\\Windows;${agy}`);+});++it('leaves a PATH that has the folder, in any case or with a trailing slash, as it is', () => {+ for (const path of [+ `${agy.toUpperCase()};C:\\Windows\\System32`,+ `C:\\Windows\\System32;;${agy}\\`,+ ])+ expect(withWindowsAgyBinDir(path, local)).toBe(path);+});++it('adds nothing without LOCALAPPDATA', () => {+ expect(withWindowsAgyBinDir('C:\\Windows\\System32;', undefined)).toBe('C:\\Windows\\System32;');+});diff --git a/console/packages/plugins/src/agents/impl/antigravity/windows-path.ts b/console/packages/plugins/src/agents/impl/antigravity/windows-path.tsnew file mode 100644index 000000000..d9f2d6c22--- /dev/null+++ b/console/packages/plugins/src/agents/impl/antigravity/windows-path.ts@@ -0,0 +1,18 @@+/**+ * A Windows PATH value with the folder Google's Antigravity installer puts+ * `agy.exe` in, `%LOCALAPPDATA%\agy\bin`, added after its entries when it is+ * missing, and `path` unchanged otherwise. The installer adds that folder to+ * the user's PATH, which an app or controller started before the install does+ * not see. It goes last, as it does in a terminal opened since: an `agy`+ * already on PATH (Scoop's, say) still wins, so Switch Console and the agent+ * controller resolve the same one.+ */+export function withWindowsAgyBinDir(path: string, localAppData: string | undefined): string {+ if (!localAppData) return path;+ const agyBin = `${localAppData.replace(/[\\/]+$/, '')}\\agy\\bin`;+ const entries = path.split(';').filter(Boolean);+ const present = entries.some(+ (entry) => entry.replace(/[\\/]+$/, '').toLowerCase() === agyBin.toLowerCase()+ );+ return present ? path : [...entries, agyBin].join(';');+}diff --git a/console/packages/plugins/src/agents/registry.ts b/console/packages/plugins/src/agents/registry.tsindex 195d511a5..4247e2255 100644--- a/console/packages/plugins/src/agents/registry.ts+++ b/console/packages/plugins/src/agents/registry.ts@@ -1,2 +1,3 @@export { pluginRegistry } from './plugin-registry';export * from './session-launch';+export { withWindowsAgyBinDir } from './impl/antigravity/windows-path';