From 34343854b61a08eb03c0b05fa50dcc9a3c20e697 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:34:16 -0500 Subject: [PATCH 1/9] feat(gateway-clients): connect Antigravity app and agy CLI to the OpenCodex gateway Adds src/integrations/gateway-clients with a connector per client. The app connector edits ~/.antigravity/settings.json behind a stash and restores it byte for byte (path-wise when the user edited since). The agy connector writes a marked shell function into bash, zsh and PowerShell profiles. --- src/integrations/gateway-clients/agy.ts | 174 ++++++++++++++++++ .../gateway-clients/antigravity.ts | 163 ++++++++++++++++ src/integrations/gateway-clients/index.ts | 60 ++++++ src/integrations/gateway-clients/io.ts | 102 ++++++++++ src/integrations/gateway-clients/types.ts | 47 +++++ tests/clients/gateway-clients.test.ts | 156 ++++++++++++++++ 6 files changed, 702 insertions(+) create mode 100644 src/integrations/gateway-clients/agy.ts create mode 100644 src/integrations/gateway-clients/antigravity.ts create mode 100644 src/integrations/gateway-clients/index.ts create mode 100644 src/integrations/gateway-clients/io.ts create mode 100644 src/integrations/gateway-clients/types.ts create mode 100644 tests/clients/gateway-clients.test.ts diff --git a/src/integrations/gateway-clients/agy.ts b/src/integrations/gateway-clients/agy.ts new file mode 100644 index 00000000000..57317f7f5bd --- /dev/null +++ b/src/integrations/gateway-clients/agy.ts @@ -0,0 +1,174 @@ +/** + * agy CLI: a marked shell function per profile that exports the AGY_LLM_GATEWAY_* variables for agy only. + * No agy settings file is changed. Idea follows Magpie (MIT, (c) yetone), internal/agent/agy.go. + */ +import { existsSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { + adminGatewayOverride, dropStash, envGatewayOverride, mkdirTracked, readBytes, readStash, removeFile, rmdirsIfEmpty, + sha256, writeBytes, writeStash, +} from "./io"; +import type { GatewayClientConnector, GatewayClientContext, GatewayClientResult, GatewayClientStatus, GatewayTarget } from "./types"; + +const ID = "agy"; +const START = "# >>> opencodex agy >>>"; +const END = "# <<< opencodex agy <<<"; +type Kind = "posix" | "powershell"; +interface Entry { path: string; kind: Kind; originalBytes: string | null; createdDirs: string[]; writtenSha256: string } +interface Stash { version: 1; files: Entry[] } + +const posixQuote = (v: string) => `'${v.replace(/'/g, "'\\''")}'`; +const psQuote = (v: string) => `'${v.replace(/'/g, "''")}'`; + +export function agyBlock(kind: Kind, target: GatewayTarget): string { + if (kind === "posix") { + return [START, `agy() { AGY_LLM_GATEWAY_URL=${posixQuote(target.url)} AGY_LLM_GATEWAY_API_KEY=${posixQuote(target.apiKey)} AGY_LLM_GATEWAY_WIRE_PROTOCOL='genai' command agy "$@"; }`, END].join("\n"); + } + return [ + START, + "function agy {", + " $real = Get-Command agy -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1", + " if (-not $real) { Write-Error 'agy was not found on PATH'; return }", + " $names = 'AGY_LLM_GATEWAY_URL', 'AGY_LLM_GATEWAY_API_KEY', 'AGY_LLM_GATEWAY_WIRE_PROTOCOL'", + " $saved = @{}", + " foreach ($n in $names) { $saved[$n] = [Environment]::GetEnvironmentVariable($n, 'Process') }", + ` $env:AGY_LLM_GATEWAY_URL = ${psQuote(target.url)}`, + ` $env:AGY_LLM_GATEWAY_API_KEY = ${psQuote(target.apiKey)}`, + " $env:AGY_LLM_GATEWAY_WIRE_PROTOCOL = 'genai'", + " try { & $real @args } finally { foreach ($n in $names) { [Environment]::SetEnvironmentVariable($n, $saved[$n], 'Process') } }", + "}", + END, + ].join("\n"); +} + +/** Profile files this connector writes, per platform. Existing files first; one is created when none exists. */ +function targets(ctx: GatewayClientContext): { path: string; kind: Kind }[] { + const win = ctx.platform === "win32"; + const out: { path: string; kind: Kind }[] = []; + const posix = [join(ctx.home, ".bashrc"), ...(win ? [] : [join(ctx.home, ".zshrc")])]; + for (const path of posix) if (existsSync(path)) out.push({ path, kind: "posix" }); + if (!win && out.length === 0) { + const zsh = basename(ctx.env.SHELL ?? "") === "zsh"; + out.push({ path: join(ctx.home, zsh ? ".zshrc" : ".bashrc"), kind: "posix" }); + } + const ps7 = win ? join(ctx.home, "Documents", "PowerShell", "Microsoft.PowerShell_profile.ps1") : join(ctx.home, ".config", "powershell", "Microsoft.PowerShell_profile.ps1"); + const ps5 = join(ctx.home, "Documents", "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1"); + const psExisting = (win ? [ps7, ps5] : [ps7]).filter(p => existsSync(p)); + for (const path of psExisting) out.push({ path, kind: "powershell" }); + if (win && psExisting.length === 0) out.push({ path: ps7, kind: "powershell" }); + return out; +} + +function blockSpan(text: string): { start: number; end: number } | null { + const start = text.indexOf(START); + if (start < 0) return null; + const endMark = text.indexOf(END, start); + if (endMark < 0) return null; + let end = endMark + END.length; + if (text.startsWith("\r\n", end)) end += 2; else if (text[end] === "\n") end += 1; + return { start, end }; +} + +const eolOf = (text: string) => (text.includes("\r\n") ? "\r\n" : "\n"); +const withBlock = (text: string, block: string): string => { + const eol = eolOf(text); + const b = block.replace(/\n/g, eol) + eol; + const span = blockSpan(text); + if (span) return text.slice(0, span.start) + b + text.slice(span.end); + if (text === "") return b; + let head = text; + if (!/\n$/.test(head)) head += eol; + if (!/(\r?\n){2}$/.test(head)) head += eol; + return head + b; +}; +const withoutBlock = (text: string): string => { const s = blockSpan(text); return s ? text.slice(0, s.start) + text.slice(s.end) : text; }; +const blockIn = (text: string): string | null => { const s = blockSpan(text); return s ? text.slice(s.start, s.end).replace(/\r\n/g, "\n").replace(/\n$/, "") : null; }; + +function status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus { + const stash = readStash(ctx, ID); + const files = targets(ctx); + const known = new Map(files.map(f => [f.path, f.kind])); + for (const e of stash?.files ?? []) if (!known.has(e.path)) known.set(e.path, e.kind); + let withBlocks = 0; + let current = 0; + const rows: GatewayClientStatus["files"] = []; + for (const [path, kind] of known) { + const bytes = readBytes(path); + const block = bytes ? blockIn(bytes.toString("utf8")) : null; + if (block !== null) { withBlocks++; if (!target || block === agyBlock(kind, target)) current++; } + rows.push({ path, role: kind === "posix" ? "shell profile" : "PowerShell profile", exists: bytes !== null }); + } + const state = withBlocks > 0 && current === known.size ? "connected" : withBlocks > 0 || stash ? "drifted" : "disconnected"; + const overrides: GatewayClientStatus["overrides"] = []; + const admin = adminGatewayOverride(ctx); + if (admin) overrides.push({ source: "admin_settings", detail: admin }); + const env = envGatewayOverride(ctx, target?.url); + if (env) overrides.push({ source: "env", detail: env }); + const notes = ["Open a new terminal to pick up the agy function.", "Gateway support needs agy 1.2.15 or newer."]; + if (ctx.platform === "win32") notes.push("Google lists agy for macOS and Linux only; on Windows this works only where an agy build runs, so treat it as untested."); + if (ctx.env.AGY_LLM_GATEWAY_URL?.trim()) notes.push("AGY_LLM_GATEWAY_URL is exported globally in the environment OpenCodex sees; the agy function overrides it for agy only."); + return { id: ID, label: "agy CLI", state, files: rows, overrides, notes }; +} + +function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClientResult { + const old = readStash(ctx, ID); + const entries: Entry[] = []; + const changedFiles: string[] = []; + const staged: { entry: Entry; out: Buffer; changed: boolean }[] = []; + for (const t of targets(ctx)) { + const bytes = readBytes(t.path); + const prev = old?.files.find(e => e.path === t.path); + const hasBlock = bytes !== null && blockIn(bytes.toString("utf8")) !== null; + const text = bytes ? bytes.toString("utf8") : ""; + const out = Buffer.from(withBlock(text, agyBlock(t.kind, target))); + const keep = prev !== undefined && hasBlock; + staged.push({ + entry: { path: t.path, kind: t.kind, originalBytes: keep ? prev.originalBytes : bytes ? bytes.toString("base64") : null, createdDirs: prev?.createdDirs ?? [], writtenSha256: sha256(out) }, + out, changed: bytes === null || sha256(bytes) !== sha256(out), + }); + } + try { + for (const s of staged) { + if (!existsSync(dirname(s.entry.path))) s.entry.createdDirs = [...s.entry.createdDirs, ...mkdirTracked(dirname(s.entry.path))]; + entries.push(s.entry); + } + writeStash(ctx, ID, { version: 1, files: entries } satisfies Stash); + for (const s of staged) { if (s.changed) { writeBytes(s.entry.path, s.out); changedFiles.push(s.entry.path); } } + } catch (error) { + return { ok: false, code: "io-error", message: `Could not update the shell profiles: ${(error as Error).message}`, changed: changedFiles.length > 0, changedFiles, notes: [] }; + } + return { ok: true, changed: changedFiles.length > 0, changedFiles, message: "The agy command now starts on the OpenCodex gateway. Open a new terminal to use it.", notes: status(ctx, target).notes }; +} + +function disconnect(ctx: GatewayClientContext): GatewayClientResult { + const stash = readStash(ctx, ID); + const paths = new Map(); + for (const t of targets(ctx)) paths.set(t.path, undefined); + for (const e of stash?.files ?? []) paths.set(e.path, e); + const changedFiles: string[] = []; + let pathWise = false; + for (const [path, entry] of paths) { + const bytes = readBytes(path); + if (bytes && entry && sha256(bytes) === entry.writtenSha256) { + if (entry.originalBytes === null) { removeFile(path); rmdirsIfEmpty(entry.createdDirs); } + else writeBytes(path, Buffer.from(entry.originalBytes, "base64")); + changedFiles.push(path); + continue; + } + if (!bytes) { if (entry) rmdirsIfEmpty(entry.createdDirs); continue; } + const text = bytes.toString("utf8"); + if (blockIn(text) === null) continue; + writeBytes(path, Buffer.from(withoutBlock(text))); + changedFiles.push(path); + pathWise = true; + } + if (!stash && changedFiles.length === 0) return { ok: true, changed: false, changedFiles: [], restore: "none", message: "Not connected by OpenCodex; nothing was changed.", notes: [] }; + dropStash(ctx, ID); + return { + ok: true, changed: changedFiles.length > 0, changedFiles, restore: changedFiles.length === 0 ? "none" : pathWise ? "path-wise" : "exact", + message: pathWise ? "Removed the OpenCodex agy block; the rest of each edited profile was kept as it is." : "Shell profiles restored byte for byte.", + notes: ["Open a new terminal to apply it."], + }; +} + +export const AGY_CONNECTOR: GatewayClientConnector = { id: ID, label: "agy CLI", status, connect, disconnect }; diff --git a/src/integrations/gateway-clients/antigravity.ts b/src/integrations/gateway-clients/antigravity.ts new file mode 100644 index 00000000000..86a65b99e9a --- /dev/null +++ b/src/integrations/gateway-clients/antigravity.ts @@ -0,0 +1,163 @@ +/** + * Antigravity desktop app (2.15+): ~/.antigravity/settings.json "gateway" block. + * Field facts and the stash-and-restore idea follow Magpie (MIT, (c) yetone), internal/agent/antigravity.go. + */ +import { join } from "node:path"; +import { + GATEWAY_PLACEHOLDER_KEY, adminGatewayOverride, dropStash, envGatewayOverride, mkdirTracked, normalizeUrl, + readBytes, readStash, removeFile, rmdirsIfEmpty, sha256, writeBytes, writeStash, +} from "./io"; +import type { GatewayClientConnector, GatewayClientContext, GatewayClientResult, GatewayClientStatus, GatewayTarget } from "./types"; + +type Json = Record; +interface Prior { present: boolean; value?: unknown } +interface Stash { + version: 1; + path: string; + originalBytes: string | null; + createdDirs: string[]; + prior: { gateway: Prior; defaultModelId: Prior; list: Prior; modelsPresent: boolean }; + written: { gateway: unknown; defaultModelId: string | null }; + writtenSha256: string; +} + +const ID = "antigravity"; +const BOM = String.fromCharCode(0xfeff); +const settingsPath = (ctx: GatewayClientContext) => join(ctx.home, ".antigravity", "settings.json"); +const isObj = (v: unknown): v is Json => !!v && typeof v === "object" && !Array.isArray(v); +const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); +const prior = (o: Json | undefined, k: string): Prior => o && k in o ? { present: true, value: o[k] } : { present: false }; + +interface Parsed { doc: Json; indent: string | number | undefined; eol: string; trailing: boolean; bom: boolean } +function parseSettings(bytes: Buffer | null): Parsed | string { + if (!bytes) return { doc: {}, indent: 2, eol: "\n", trailing: true, bom: false }; + let text = bytes.toString("utf8"); + const bom = text.startsWith(BOM); + if (bom) text = text.slice(1); + const eol = text.includes("\r\n") ? "\r\n" : "\n"; + let doc: unknown = {}; + if (text.trim() !== "") { + try { doc = JSON.parse(text); } catch { + return "settings.json is not strict JSON (comments, trailing commas or a syntax error). OpenCodex will not rewrite a file it cannot round-trip; fix or simplify it, then connect again."; + } + } + if (!isObj(doc)) return "settings.json does not hold a JSON object, so OpenCodex left it untouched."; + const m = /\n([ \t]+)\S/.exec(text); + const indent = m ? m[1] : text.trim().includes("\n") || text.trim().length <= 2 ? 2 : undefined; + return { doc, indent, eol, trailing: text === "" || /\n\s*$/.test(text), bom }; +} + +function serialize(p: Parsed): Buffer { + let text = JSON.stringify(p.doc, null, p.indent); + if (p.eol === "\r\n") text = text.replace(/\n/g, "\r\n"); + return Buffer.from((p.bom ? BOM : "") + text + (p.trailing ? p.eol : "")); +} + +function ours(gw: unknown, target?: GatewayTarget): "match" | "other-url" | "no" { + if (!isObj(gw) || gw.enabled !== true) return "no"; + if (target && normalizeUrl(gw.url) === normalizeUrl(target.url)) return "match"; + if (!target) return gw.apiKey === GATEWAY_PLACEHOLDER_KEY ? "match" : "no"; + return gw.apiKey === GATEWAY_PLACEHOLDER_KEY ? "other-url" : "no"; +} + +function status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus { + const path = settingsPath(ctx); + const bytes = readBytes(path); + const parsed = parseSettings(bytes); + const gw = typeof parsed === "string" ? undefined : parsed.doc.gateway; + const stash = readStash(ctx, ID); + const match = ours(gw, target) === "match"; + const state = match ? "connected" : stash ? "drifted" : "disconnected"; + const overrides: GatewayClientStatus["overrides"] = []; + const admin = adminGatewayOverride(ctx); + if (admin) overrides.push({ source: "admin_settings", detail: admin }); + const env = envGatewayOverride(ctx, target?.url); + if (env) overrides.push({ source: "env", detail: env }); + const notes = ["Restart Antigravity to apply a change.", "In gateway mode the app does not use the Google sign-in.", "agy follows this file unless it is connected on its own."]; + if (typeof parsed === "string") notes.push(parsed); + if (match && !stash) notes.push("No restore record exists (connected outside OpenCodex), so disconnect cannot restore your previous settings."); + return { id: ID, label: "Antigravity", state, files: [{ path, role: "user settings", exists: bytes !== null }], overrides, notes }; +} + +const fail = (code: GatewayClientResult["code"], message: string): GatewayClientResult => + ({ ok: false, code, message, changed: false, changedFiles: [], notes: [] }); + +function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClientResult { + const path = settingsPath(ctx); + const bytes = readBytes(path); + const parsed = parseSettings(bytes); + if (typeof parsed === "string") return fail("unsupported-file", parsed); + const { doc } = parsed; + let stash = readStash(ctx, ID); + const keep = stash !== null && ours(doc.gateway, undefined) === "match"; + const models = isObj(doc.models) ? doc.models : undefined; + const dir = join(ctx.home, ".antigravity"); + let newDirs: string[] = []; + try { newDirs = mkdirTracked(dir); } catch (error) { return fail("io-error", `Could not create ${dir}: ${(error as Error).message}`); } + if (!keep) { + stash = { + version: 1, path, originalBytes: bytes ? bytes.toString("base64") : null, createdDirs: [...(stash?.createdDirs ?? []), ...newDirs], + prior: { gateway: prior(doc, "gateway"), defaultModelId: prior(models, "defaultModelId"), list: prior(models, "list"), modelsPresent: models !== undefined }, + written: { gateway: null, defaultModelId: null }, writtenSha256: "", + }; + } + const gateway = { enabled: true, url: target.url, apiKey: target.apiKey, wireProtocol: "openai" }; + doc.gateway = gateway; + if (target.defaultModel || models?.list !== undefined) { + const m: Json = models ?? {}; + if (target.defaultModel) m.defaultModelId = target.defaultModel; + delete m.list; + doc.models = m; + } + const out = serialize(parsed); + const next = stash as Stash; + next.written = { gateway, defaultModelId: target.defaultModel ?? (keep ? next.written.defaultModelId : null) }; + next.writtenSha256 = sha256(out); + try { + writeStash(ctx, ID, next); + writeBytes(path, out); + } catch (error) { return fail("io-error", `Could not write ${path}: ${(error as Error).message}`); } + const unchanged = bytes !== null && sha256(bytes) === next.writtenSha256; + return { ok: true, changed: !unchanged, changedFiles: unchanged ? [] : [path], message: "Antigravity now uses the OpenCodex gateway. Restart Antigravity to apply it.", notes: status(ctx, target).notes }; +} + +function disconnect(ctx: GatewayClientContext): GatewayClientResult { + const stash = readStash(ctx, ID); + if (!stash) return { ok: true, changed: false, changedFiles: [], restore: "none", message: "Not connected by OpenCodex; nothing was changed.", notes: [] }; + const path = stash.path; + const bytes = readBytes(path); + const done = (restore: "exact" | "path-wise" | "none", message: string, files: string[]): GatewayClientResult => { + dropStash(ctx, ID); + return { ok: true, changed: files.length > 0, changedFiles: files, restore, message, notes: ["Restart Antigravity to apply it."] }; + }; + if (bytes && sha256(bytes) === stash.writtenSha256) { + if (stash.originalBytes === null) { removeFile(path); rmdirsIfEmpty(stash.createdDirs); } + else writeBytes(path, Buffer.from(stash.originalBytes, "base64")); + return done("exact", "Antigravity settings restored byte for byte.", [path]); + } + if (!bytes) return done("none", "The settings file is already gone; the restore record was cleared.", []); + const parsed = parseSettings(bytes); + if (typeof parsed === "string") return { ok: false, code: "unsupported-file", message: `${parsed} The restore record was kept.`, changed: false, changedFiles: [], notes: [] }; + const { doc } = parsed; + const kept: string[] = []; + if (same(doc.gateway, stash.written.gateway)) { + if (stash.prior.gateway.present) doc.gateway = stash.prior.gateway.value; else delete doc.gateway; + } else kept.push("gateway"); + const models = isObj(doc.models) ? doc.models : undefined; + if (models && stash.written.defaultModelId !== null) { + if (models.defaultModelId === stash.written.defaultModelId) { + if (stash.prior.defaultModelId.present) models.defaultModelId = stash.prior.defaultModelId.value; else delete models.defaultModelId; + } else kept.push("models.defaultModelId"); + } + if (stash.prior.list.present) { + const m: Json = models ?? {}; + if (!("list" in m)) m.list = stash.prior.list.value; else kept.push("models.list"); + doc.models = m; + } + const finalModels = isObj(doc.models) ? doc.models : undefined; + if (finalModels && Object.keys(finalModels).length === 0 && !stash.prior.modelsPresent) delete doc.models; + writeBytes(path, serialize(parsed)); + return done("path-wise", `The file changed after OpenCodex wrote it, so only the gateway, models.defaultModelId and models.list entries were restored; your other edits were kept.${kept.length ? ` Left as you had them: ${kept.join(", ")}.` : ""}`, [path]); +} + +export const ANTIGRAVITY_CONNECTOR: GatewayClientConnector = { id: ID, label: "Antigravity", status, connect, disconnect }; diff --git a/src/integrations/gateway-clients/index.ts b/src/integrations/gateway-clients/index.ts new file mode 100644 index 00000000000..6c96d1b0222 --- /dev/null +++ b/src/integrations/gateway-clients/index.ts @@ -0,0 +1,60 @@ +import { homedir } from "node:os"; +import type { OcxConfig } from "../../types"; +import { getConfigDir } from "../../config/paths"; +import { localInferenceDestination } from "../../lib/local-destinations"; +import { AGY_CONNECTOR } from "./agy"; +import { ANTIGRAVITY_CONNECTOR } from "./antigravity"; +import { GATEWAY_PLACEHOLDER_KEY } from "./io"; +import type { GatewayClientConnector, GatewayClientContext, GatewayClientId, GatewayClientResult, GatewayClientStatus, GatewayTarget } from "./types"; + +export type * from "./types"; +export { GATEWAY_PLACEHOLDER_KEY } from "./io"; + +export const GATEWAY_CLIENTS: Readonly> = { + antigravity: ANTIGRAVITY_CONNECTOR, + agy: AGY_CONNECTOR, +}; + +export const GATEWAY_CLIENT_IDS = Object.keys(GATEWAY_CLIENTS) as GatewayClientId[]; +export const isGatewayClientId = (value: unknown): value is GatewayClientId => + typeof value === "string" && Object.hasOwn(GATEWAY_CLIENTS, value); + +export function productionGatewayClientContext(): GatewayClientContext { + return { home: homedir(), platform: process.platform, env: process.env, stateDir: getConfigDir() }; +} + +export type GatewayTargetResolution = { ok: true; target: GatewayTarget } | { ok: false; code: "requires-admission-token" | "invalid-model"; message: string }; + +/** The URL a local client dials plus a non-secret placeholder key; refuses binds that demand a real credential. */ +export function resolveGatewayTarget(config: Pick, port: number, model?: string): GatewayTargetResolution { + const destination = localInferenceDestination(config, port); + if (destination.requiresAdmissionToken) { + return { ok: false, code: "requires-admission-token", message: `${destination.origin} requires an opencodex data-plane credential, and OpenCodex will not write a real secret into client files. Enable \`unauthenticatedLoopbackListener\` or bind the proxy to loopback.` }; + } + const defaultModel = model?.trim(); + // eslint-disable-next-line no-control-regex + if (defaultModel !== undefined && (defaultModel.length === 0 || defaultModel.length > 200 || /[\x00-\x1f\x7f]/.test(defaultModel))) { + return { ok: false, code: "invalid-model", message: "The model selector must be a non-empty single-line string of at most 200 characters." }; + } + return { ok: true, target: { url: destination.origin, apiKey: GATEWAY_PLACEHOLDER_KEY, ...(defaultModel ? { defaultModel } : {}) } }; +} + +export function gatewayClientsStatus(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus[] { + return GATEWAY_CLIENT_IDS.map(id => GATEWAY_CLIENTS[id].status(ctx, target)); +} + +export type GatewayActionOutcome = + | (GatewayClientResult & { id: GatewayClientId; action: "connect" | "disconnect"; status: GatewayClientStatus }) + | { ok: false; id: GatewayClientId; action: "connect"; code: "requires-admission-token" | "invalid-model"; message: string }; + +export function connectGatewayClient(id: GatewayClientId, ctx: GatewayClientContext, config: Pick, port: number, model?: string): GatewayActionOutcome { + const resolved = resolveGatewayTarget(config, port, model); + if (!resolved.ok) return { ok: false, id, action: "connect", code: resolved.code, message: resolved.message }; + const result = GATEWAY_CLIENTS[id].connect(ctx, resolved.target); + return { ...result, id, action: "connect", status: GATEWAY_CLIENTS[id].status(ctx, resolved.target) }; +} + +export function disconnectGatewayClient(id: GatewayClientId, ctx: GatewayClientContext, target?: GatewayTarget): GatewayActionOutcome { + const result = GATEWAY_CLIENTS[id].disconnect(ctx); + return { ...result, id, action: "disconnect", status: GATEWAY_CLIENTS[id].status(ctx, target) }; +} diff --git a/src/integrations/gateway-clients/io.ts b/src/integrations/gateway-clients/io.ts new file mode 100644 index 00000000000..51f5b16ecfd --- /dev/null +++ b/src/integrations/gateway-clients/io.ts @@ -0,0 +1,102 @@ +import { createHash } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { atomicWriteFileStreamed } from "../../config/atomic-write"; +import { parseJsonc } from "../../lib/jsonc"; +import type { GatewayClientContext } from "./types"; + +export const GATEWAY_PLACEHOLDER_KEY = "opencodex-local"; + +export const sha256 = (bytes: Uint8Array | Buffer): string => createHash("sha256").update(bytes).digest("hex"); + +export function readBytes(path: string): Buffer | null { + try { return readFileSync(path); } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +/** Atomic byte-exact write that follows a dotfile symlink and keeps the old permission bits. */ +export function writeBytes(path: string, bytes: Uint8Array, createMode = 0o644): void { + let mode: number | undefined; + try { mode = statSync(path).mode & 0o777; } catch { mode = undefined; } + atomicWriteFileStreamed(path, fd => { writeFileSync(fd, bytes); }); + if (process.platform !== "win32") { + try { chmodSync(path, mode ?? createMode); } catch { /* best effort */ } + } +} + +/** Create `dir` (and parents); returns the directories that did not exist before, outermost first. */ +export function mkdirTracked(dir: string): string[] { + const created: string[] = []; + for (let cur = dir; !existsSync(cur); cur = dirname(cur)) created.unshift(cur); + mkdirSync(dir, { recursive: true }); + return created; +} + +/** Remove the directories this connector created, deepest first, only while empty. */ +export function rmdirsIfEmpty(dirs: readonly string[]): void { + for (const dir of [...dirs].reverse()) { + try { if (readdirSync(dir).length === 0) rmdirSync(dir); } catch { /* gone or not empty */ } + } +} + +export const removeFile = (path: string): void => rmSync(path, { force: true }); + +export function stashPath(ctx: GatewayClientContext, id: string): string { + return join(ctx.stateDir, "gateway-clients", `${id}.json`); +} + +export function readStash(ctx: GatewayClientContext, id: string): T | null { + const bytes = readBytes(stashPath(ctx, id)); + if (!bytes) return null; + try { + const value = JSON.parse(bytes.toString("utf8")) as { version?: number } & T; + return value && value.version === 1 ? value : null; + } catch { return null; } +} + +export function writeStash(ctx: GatewayClientContext, id: string, value: object): void { + const path = stashPath(ctx, id); + mkdirSync(dirname(path), { recursive: true }); + writeBytes(path, Buffer.from(`${JSON.stringify(value, null, 2)}\n`), 0o600); +} + +export const dropStash = (ctx: GatewayClientContext, id: string): void => removeFile(stashPath(ctx, id)); + +export const normalizeUrl = (url: unknown): string => typeof url === "string" ? url.trim().replace(/\/+$/, "") : ""; + +/** Where an organisation's admin_settings.json lives (Google's enterprise gateway docs). */ +export function adminSettingsPath(ctx: GatewayClientContext): string | undefined { + if (ctx.adminSettingsPath) return ctx.adminSettingsPath; + if (ctx.platform === "win32") { + const base = ctx.env.ProgramData; + return base ? join(base, "Antigravity", "admin_settings.json") : undefined; + } + return ctx.platform === "darwin" + ? "/Library/Application Support/Antigravity/admin_settings.json" + : "/etc/antigravity/admin_settings.json"; +} + +/** A one-line description of what admin_settings.json sets under `gateway`, or null when nothing. */ +export function adminGatewayOverride(ctx: GatewayClientContext): string | null { + const path = adminSettingsPath(ctx); + if (!path) return null; + const bytes = readBytes(path); + if (!bytes) return null; + let gateway: unknown; + try { gateway = (parseJsonc(bytes.toString("utf8")) as { gateway?: unknown } | null)?.gateway; } + catch { return "admin_settings.json exists but could not be read, so its gateway settings are unknown"; } + if (!gateway || typeof gateway !== "object" || Object.keys(gateway).length === 0) return null; + return "organization admin_settings.json sets the gateway and wins over the user settings and AGY_LLM_GATEWAY_* variables"; +} + +/** The env override note, or null. Only the environment of the process OpenCodex runs in is visible. */ +export function envGatewayOverride(ctx: GatewayClientContext, targetUrl?: string): string | null { + const raw = ctx.env.AGY_LLM_GATEWAY_URL?.trim(); + if (!raw) return null; + if (targetUrl && normalizeUrl(raw) === normalizeUrl(targetUrl)) return null; + let shown = "an unparseable value"; + try { shown = new URL(raw).origin; } catch { /* keep generic */ } + return `AGY_LLM_GATEWAY_URL is set to ${shown} in the environment OpenCodex sees (other shells are not checked) and wins over ~/.antigravity/settings.json`; +} diff --git a/src/integrations/gateway-clients/types.ts b/src/integrations/gateway-clients/types.ts new file mode 100644 index 00000000000..0ad4606cc6c --- /dev/null +++ b/src/integrations/gateway-clients/types.ts @@ -0,0 +1,47 @@ +/** Connectors that point a Google client at OpenCodex's gateway (Antigravity app, agy CLI). */ +export type GatewayClientId = "antigravity" | "agy"; + +export interface GatewayClientContext { + home: string; + platform: NodeJS.Platform; + env: NodeJS.ProcessEnv; + /** OpenCodex config dir; stash files live in `/gateway-clients/`. */ + stateDir: string; + /** Override for tests; defaults to the platform's admin_settings.json location. */ + adminSettingsPath?: string; +} + +export interface GatewayTarget { + url: string; + apiKey: string; + defaultModel?: string; +} + +export interface GatewayClientStatus { + id: GatewayClientId; + label: string; + state: "connected" | "disconnected" | "drifted"; + files: { path: string; role: string; exists: boolean }[]; + overrides: { source: "admin_settings" | "env"; detail: string }[]; + notes: string[]; +} + +export type GatewayRefusalCode = "unsupported-file" | "io-error"; + +export interface GatewayClientResult { + ok: boolean; + code?: GatewayRefusalCode; + message: string; + changed: boolean; + changedFiles: string[]; + restore?: "exact" | "path-wise" | "none"; + notes: string[]; +} + +export interface GatewayClientConnector { + id: GatewayClientId; + label: string; + status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus; + connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClientResult; + disconnect(ctx: GatewayClientContext): GatewayClientResult; +} diff --git a/tests/clients/gateway-clients.test.ts b/tests/clients/gateway-clients.test.ts new file mode 100644 index 00000000000..8d2670e4c5d --- /dev/null +++ b/tests/clients/gateway-clients.test.ts @@ -0,0 +1,156 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + GATEWAY_CLIENTS, connectGatewayClient, disconnectGatewayClient, gatewayClientsStatus, resolveGatewayTarget, + type GatewayClientContext, type GatewayTarget, +} from "../../src/integrations/gateway-clients"; + +const target: GatewayTarget = { url: "http://127.0.0.1:10100", apiKey: "opencodex-local" }; +let root: string; +let ctx: GatewayClientContext; +const settings = () => join(ctx.home, ".antigravity", "settings.json"); +const read = (p: string) => readFileSync(p, "utf8"); + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-gw-")); + mkdirSync(join(root, "home")); + ctx = { home: join(root, "home"), platform: "linux", env: { SHELL: "/bin/zsh" }, stateDir: join(root, "state"), adminSettingsPath: join(root, "admin_settings.json") }; +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const USER_SETTINGS = `{\n "theme": "dark",\n "gateway": { "enabled": true, "url": "https://corp.example", "apiKey": "user-key", "customHeaders": { "x": "1" } },\n "models": { "defaultModelId": "mine", "list": [{ "modelId": "mine" }] },\n "other": [1, 2]\n}\n`; + +describe("antigravity connector", () => { + test("connect then disconnect restores a user file byte for byte, and re-connect is idempotent", () => { + mkdirSync(join(ctx.home, ".antigravity")); + writeFileSync(settings(), USER_SETTINGS); + const a = GATEWAY_CLIENTS.antigravity; + expect(a.connect(ctx, { ...target, defaultModel: "gemini-3" }).ok).toBe(true); + const doc = JSON.parse(read(settings())); + expect(doc.gateway).toEqual({ enabled: true, url: target.url, apiKey: "opencodex-local", wireProtocol: "openai" }); + expect(doc.models).toEqual({ defaultModelId: "gemini-3" }); + expect(doc.theme).toBe("dark"); + expect(read(settings())).toContain('\n "theme"'); + const once = read(settings()); + expect(a.connect(ctx, { ...target, defaultModel: "gemini-3" }).changed).toBe(false); + expect(read(settings())).toBe(once); + expect(a.status(ctx, target).state).toBe("connected"); + const result = a.disconnect(ctx); + expect(result.restore).toBe("exact"); + expect(read(settings())).toBe(USER_SETTINGS); + expect(a.status(ctx, target).state).toBe("disconnected"); + expect(existsSync(join(ctx.stateDir, "gateway-clients", "antigravity.json"))).toBe(false); + }); + + test("an absent file and directory are removed again on disconnect", () => { + const a = GATEWAY_CLIENTS.antigravity; + a.connect(ctx, target); + expect(existsSync(settings())).toBe(true); + a.disconnect(ctx); + expect(existsSync(join(ctx.home, ".antigravity"))).toBe(false); + }); + + test("a user edit after connect is kept and only the three stashed paths are restored", () => { + mkdirSync(join(ctx.home, ".antigravity")); + writeFileSync(settings(), USER_SETTINGS); + const a = GATEWAY_CLIENTS.antigravity; + a.connect(ctx, { ...target, defaultModel: "gemini-3" }); + const edited = JSON.parse(read(settings())); + edited.theme = "light"; + edited.added = true; + writeFileSync(settings(), JSON.stringify(edited, null, 4)); + const result = a.disconnect(ctx); + expect(result.restore).toBe("path-wise"); + const doc = JSON.parse(read(settings())); + expect(doc.theme).toBe("light"); + expect(doc.added).toBe(true); + expect(doc.gateway.apiKey).toBe("user-key"); + expect(doc.models).toEqual({ defaultModelId: "mine", list: [{ modelId: "mine" }] }); + }); + + test("a file with comments is refused and left untouched; disconnect without a record changes nothing", () => { + mkdirSync(join(ctx.home, ".antigravity")); + writeFileSync(settings(), '{\n // note\n "a": 1\n}\n'); + const a = GATEWAY_CLIENTS.antigravity; + const result = a.connect(ctx, target); + expect(result).toMatchObject({ ok: false, code: "unsupported-file" }); + expect(read(settings())).toBe('{\n // note\n "a": 1\n}\n'); + expect(a.disconnect(ctx)).toMatchObject({ ok: true, changed: false, restore: "none" }); + }); + + test("admin_settings and env overrides surface in status without leaking secrets", () => { + writeFileSync(ctx.adminSettingsPath!, JSON.stringify({ gateway: { url: "https://corp.example", apiKey: "SECRET" } })); + ctx.env.AGY_LLM_GATEWAY_URL = "https://other.example/path?token=SECRET"; + const status = GATEWAY_CLIENTS.antigravity.status(ctx, target); + expect(status.overrides.map(o => o.source).sort()).toEqual(["admin_settings", "env"]); + expect(JSON.stringify(status)).not.toContain("SECRET"); + }); +}); + +describe("agy connector", () => { + test("zsh profile created when none exists, then removed with its file on disconnect", () => { + const agy = GATEWAY_CLIENTS.agy; + expect(agy.connect(ctx, target).ok).toBe(true); + const zshrc = join(ctx.home, ".zshrc"); + expect(read(zshrc)).toContain("agy() { AGY_LLM_GATEWAY_URL='http://127.0.0.1:10100'"); + expect(agy.status(ctx, target).state).toBe("connected"); + expect(agy.disconnect(ctx).restore).toBe("exact"); + expect(existsSync(zshrc)).toBe(false); + }); + + test("existing CRLF profile gets a CRLF block, is replaced in place, and restores byte for byte", () => { + const zshrc = join(ctx.home, ".zshrc"); + const original = "export A=1\r\nalias x=y\r\n"; + writeFileSync(zshrc, original); + const agy = GATEWAY_CLIENTS.agy; + agy.connect(ctx, target); + const first = read(zshrc); + expect(first).toContain("# >>> opencodex agy >>>\r\n"); + expect(first.replace(/\r\n/g, "").includes("\n")).toBe(false); + agy.connect(ctx, { ...target, url: "http://127.0.0.1:10200" }); + expect(read(zshrc).match(/opencodex agy >>>/g)).toHaveLength(1); + expect(agy.status(ctx, target).state).toBe("drifted"); + agy.disconnect(ctx); + expect(read(zshrc)).toBe(original); + }); + + test("a profile edited after connect loses only the marked block", () => { + const bashrc = join(ctx.home, ".bashrc"); + writeFileSync(bashrc, "echo hi\n"); + const agy = GATEWAY_CLIENTS.agy; + agy.connect(ctx, target); + writeFileSync(bashrc, `${read(bashrc)}echo later\n`); + expect(agy.disconnect(ctx).restore).toBe("path-wise"); + expect(read(bashrc)).toBe("echo hi\n\necho later\n"); + }); + + test("Windows writes PowerShell 7 profile and only an existing .bashrc", () => { + const win: GatewayClientContext = { ...ctx, platform: "win32", env: {} }; + const agy = GATEWAY_CLIENTS.agy; + agy.connect(win, target); + const ps = join(win.home, "Documents", "PowerShell", "Microsoft.PowerShell_profile.ps1"); + expect(read(ps)).toContain("Get-Command agy -CommandType Application"); + expect(existsSync(join(win.home, ".bashrc"))).toBe(false); + agy.disconnect(win); + expect(existsSync(join(win.home, "Documents"))).toBe(false); + }); +}); + +describe("target resolution and actions", () => { + test("a bind that needs an admission token is refused before any file is written", () => { + const config = { hostname: "100.64.0.9" } as Parameters[0]; + expect(resolveGatewayTarget(config, 10100)).toMatchObject({ ok: false, code: "requires-admission-token" }); + expect(connectGatewayClient("antigravity", ctx, config, 10100)).toMatchObject({ ok: false }); + expect(existsSync(join(ctx.home, ".antigravity"))).toBe(false); + }); + + test("loopback resolves to a placeholder key and actions return status", () => { + const config = {} as Parameters[0]; + const outcome = connectGatewayClient("antigravity", ctx, config, 10100, "gemini-3"); + expect(outcome).toMatchObject({ ok: true, id: "antigravity", action: "connect", status: { state: "connected" } }); + expect(gatewayClientsStatus(ctx).map(s => s.id)).toEqual(["antigravity", "agy"]); + expect(disconnectGatewayClient("antigravity", ctx)).toMatchObject({ ok: true, restore: "exact" }); + }); +}); From 315204600445199fc0a81ff18ea372c2672d98f5 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:43:18 -0500 Subject: [PATCH 2/9] feat(management): add /api/gateway-clients routes for Antigravity and agy connect --- src/integrations/gateway-clients/index.ts | 10 +++ src/server/management-api.ts | 7 ++ src/server/management/context.ts | 2 + .../management/gateway-client-routes.ts | 59 ++++++++++++++ src/server/management/route-registry.ts | 4 + src/server/management/sibling-guard.ts | 3 +- tests/server/gateway-client-routes.test.ts | 80 +++++++++++++++++++ 7 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 src/server/management/gateway-client-routes.ts create mode 100644 tests/server/gateway-client-routes.test.ts diff --git a/src/integrations/gateway-clients/index.ts b/src/integrations/gateway-clients/index.ts index 6c96d1b0222..25482af1db0 100644 --- a/src/integrations/gateway-clients/index.ts +++ b/src/integrations/gateway-clients/index.ts @@ -58,3 +58,13 @@ export function disconnectGatewayClient(id: GatewayClientId, ctx: GatewayClientC const result = GATEWAY_CLIENTS[id].disconnect(ctx); return { ...result, id, action: "disconnect", status: GATEWAY_CLIENTS[id].status(ctx, target) }; } + +/** The JSON both the management route and `ocx connect agy` return for an action. */ +export function gatewayActionBody(outcome: GatewayActionOutcome): Record { + if (!outcome.ok) { + const files = "changedFiles" in outcome ? outcome.changedFiles : []; + return { ok: false, code: outcome.code, message: outcome.message, ...(files.length ? { changedFiles: files } : {}) }; + } + const { ok, id, action, changed, changedFiles, restore, message, notes, status } = outcome; + return { ok, id, action, changed, changedFiles, ...(restore ? { restore } : {}), message, notes, status }; +} diff --git a/src/server/management-api.ts b/src/server/management-api.ts index 2c77513135b..b22ac7405b0 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -238,6 +238,12 @@ async function handleRemoteWorkspaceRoutesOnDemand(ctx: ManagementContext): Prom return handleRemoteWorkspaceRoutes(ctx); } +async function handleGatewayClientRoutesOnDemand(ctx: ManagementContext): Promise { + if (!pathInManagementNamespace(ctx.url.pathname, "/api/gateway-clients")) return null; + const { handleGatewayClientRoutes } = await import("./management/gateway-client-routes"); + return handleGatewayClientRoutes(ctx); +} + async function handleLinkRoutesOnDemand(ctx: ManagementContext): Promise { if (!pathInManagementNamespace(ctx.url.pathname, "/api/link")) return null; const { handleLinkRoutes } = await import("./management/link-routes"); @@ -396,6 +402,7 @@ export async function handleManagementAPI( ?? (await handleIntegrationRoutes(ctx)) ?? (await handleNativeIntegrationRoutes(ctx)) ?? (await handleCursorIntegrationRoutes(ctx)) + ?? (await handleGatewayClientRoutesOnDemand(ctx)) ?? (await handleClaudeDesktopPickerRoutes(ctx)) ?? (await handleDesktopCompatibilityRoutes(ctx)) ?? (await handleDesktopCompatibilityRuntimeRoutes(ctx)) diff --git a/src/server/management/context.ts b/src/server/management/context.ts index f44eaff848e..056dcb8138f 100644 --- a/src/server/management/context.ts +++ b/src/server/management/context.ts @@ -175,6 +175,8 @@ export interface ManagementApiDeps { revokeApiKey?: (config: OcxConfig, id: string) => boolean; loadLinkCandidates?: () => Array<{ alias: string; source: "ssh_config" | "tailscale" }>; resolveChildBinarySource?: typeof import("../../link/child-binary-source").resolveChildBinarySource; + /** Home, platform and state dir for the Antigravity gateway connectors; route tests point it at temp homes. */ + gatewayClientContext?: () => import("../../integrations/gateway-clients").GatewayClientContext; /** Bound public inference port, not the ingress receiving this management request. */ liveListenPort?: () => number | undefined; now?: () => number; diff --git a/src/server/management/gateway-client-routes.ts b/src/server/management/gateway-client-routes.ts new file mode 100644 index 00000000000..a0838bf2468 --- /dev/null +++ b/src/server/management/gateway-client-routes.ts @@ -0,0 +1,59 @@ +/** + * Dashboard and CLI routes that point Google's Antigravity clients (desktop app, `agy`) + * at this proxy. Adapter only: what is written, stashed and restored lives in + * `src/integrations/gateway-clients`. Auth and origin checks run before dispatch, so a + * mutation here is gated like every other management POST. + */ +import { GATEWAY_CLIENT_IDS, connectGatewayClient, gatewayActionBody, disconnectGatewayClient, gatewayClientsStatus, isGatewayClientId, productionGatewayClientContext, resolveGatewayTarget, type GatewayClientContext } from "../../integrations/gateway-clients"; +import { jsonResponse } from "../auth-cors"; +import { readOptionalManagementJsonBody, rethrowManagementBodyTooLarge } from "./body"; +import { managementInferencePort, type ManagementContext } from "./context"; + +const COLLECTION_PATH = "/api/gateway-clients"; +const ACTION_PATH = /^\/api\/gateway-clients\/([^/]+)\/(connect|disconnect)$/; + +function refusal(ctx: ManagementContext, status: number, code: string, message: string): Response { + return jsonResponse({ ok: false, code, message }, status, ctx.req, ctx.config); +} + +async function connectModel(ctx: ManagementContext): Promise<{ model?: string } | Response> { + let body: unknown; + try { body = await readOptionalManagementJsonBody(ctx.req); } catch (error) { + rethrowManagementBodyTooLarge(error); + return refusal(ctx, 400, "invalid-body", "The request body must be a JSON object."); + } + if (body === null || typeof body !== "object" || Array.isArray(body)) return refusal(ctx, 400, "invalid-body", "The request body must be a JSON object."); + const model = (body as { model?: unknown }).model; + if (model === undefined || model === null) return {}; + if (typeof model !== "string") return refusal(ctx, 400, "invalid-body", "model must be a string."); + return { model }; +} + +export async function handleGatewayClientRoutes(ctx: ManagementContext): Promise { + const { req, url, config, deps } = ctx; + const clientCtx: GatewayClientContext = deps.gatewayClientContext?.() ?? productionGatewayClientContext(); + if (url.pathname === "/api/gateway-clients" && req.method === "GET") { + const resolved = resolveGatewayTarget(config, managementInferencePort(ctx)); + return jsonResponse({ clients: gatewayClientsStatus(clientCtx, resolved.ok ? resolved.target : undefined) }, 200, req, config); + } + const match = req.method === "POST" ? ACTION_PATH.exec(url.pathname) : null; + if (!match) return null; + const id = match[1]!; + if (!isGatewayClientId(id)) { + return refusal(ctx, 404, "unknown-client", `Unknown gateway client "${id.slice(0, 40)}". Known: ${GATEWAY_CLIENT_IDS.join(", ")}.`); + } + try { + if (match[2] === "disconnect") { + const resolved = resolveGatewayTarget(config, managementInferencePort(ctx)); + const outcome = disconnectGatewayClient(id, clientCtx, resolved.ok ? resolved.target : undefined); + return jsonResponse(gatewayActionBody(outcome), outcome.ok ? 200 : 409, req, config); + } + const parsed = await connectModel(ctx); + if (parsed instanceof Response) return parsed; + const outcome = connectGatewayClient(id, clientCtx, config, managementInferencePort(ctx), parsed.model); + return jsonResponse(gatewayActionBody(outcome), outcome.ok ? 200 : 409, req, config); + } catch (error) { + rethrowManagementBodyTooLarge(error); + return refusal(ctx, 409, "io-error", `Could not update the client files: ${error instanceof Error ? error.message : String(error)}`); + } +} diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index 789d947e632..71574538513 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -339,6 +339,10 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ // server/management/cursor-integration-routes { method: "GET", path: "/api/native-integrations/cursor", module: "server/management/cursor-integration-routes", mutates: false }, { method: "GET", path: "/api/native-integrations/cursor/local-installer", module: "server/management/cursor-integration-routes", mutates: false }, + // server/management/gateway-client-routes + { method: "GET", path: "/api/gateway-clients", module: "server/management/gateway-client-routes", mutates: false }, + { method: "POST", path: "/api/gateway-clients/{id}/connect", module: "server/management/gateway-client-routes", mutates: true, mechanism: "regex" }, + { method: "POST", path: "/api/gateway-clients/{id}/disconnect", module: "server/management/gateway-client-routes", mutates: true, mechanism: "regex" }, // server/management/oauth-account-routes { method: "DELETE", path: "/api/keys", module: "server/management/oauth-account-routes", mutates: true }, { method: "DELETE", path: "/api/keys/rotate", module: "server/management/oauth-account-routes", mutates: true }, diff --git a/src/server/management/sibling-guard.ts b/src/server/management/sibling-guard.ts index 5f1754eb4f5..f4db6700d42 100644 --- a/src/server/management/sibling-guard.ts +++ b/src/server/management/sibling-guard.ts @@ -8,7 +8,7 @@ import { CODEX_RESTART_PATH } from "../../lib/codex-restart-contract"; * convergence, owned-catalog refresh, the Claude roster, system env and the stop teardown. These * routes reach shared client state through paths those gates do not cover, so the sibling's own * management API refuses them outright: toggling or stripping the live owner's Codex, Grok or Claude - * integrations, rewriting client files at this port, the Codex prompt layers and `[features]` + * integrations, rewriting client files at this port (including the Antigravity gateway connectors), the Codex prompt layers and `[features]` * written into the shared `config.toml`, killing the user's Codex app-servers, joining a link (which * writes the shared catalog and restarts as a client), staging or switching the physical native-main * login, baking the machine service, PATH shim or tray from this home, replacing the global package @@ -29,6 +29,7 @@ export const SIBLING_REFUSED_MANAGEMENT_PATHS: readonly { readonly path: string; { path: "/api/sync", children: false }, { path: "/api/client-integrations", children: true }, { path: "/api/native-integrations", children: true }, + { path: "/api/gateway-clients", children: true }, { path: "/api/claude-desktop", children: true }, { path: "/api/codex/desktop-compatibility", children: true }, { path: "/api/claude-code", children: false }, diff --git a/tests/server/gateway-client-routes.test.ts b/tests/server/gateway-client-routes.test.ts new file mode 100644 index 00000000000..3f7b916bc68 --- /dev/null +++ b/tests/server/gateway-client-routes.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleManagementAPI } from "../../src/server/management-api"; +import type { GatewayClientContext } from "../../src/integrations/gateway-clients"; +import type { OcxConfig } from "../../src/types"; + +let root: string; +let gateway: GatewayClientContext; +const settings = () => join(gateway.home, ".antigravity", "settings.json"); + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-gw-routes-")); + mkdirSync(join(root, "home")); + gateway = { home: join(root, "home"), platform: "linux", env: { SHELL: "/bin/bash" }, stateDir: join(root, "state"), adminSettingsPath: join(root, "admin_settings.json") }; +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const config = (extra: Partial = {}): OcxConfig => ({ port: 10100, defaultProvider: "alpha", providers: {}, ...extra } as OcxConfig); + +async function call(method: string, path: string, body?: unknown, c: OcxConfig = config(), headers: Record = {}) { + const req = new Request(`http://localhost${path}`, { + method, + headers: { host: "localhost", ...(body === undefined ? {} : { "content-type": "application/json" }), ...headers }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const response = await handleManagementAPI(req, new URL(req.url), c, { gatewayClientContext: () => gateway, liveListenPort: () => 10100 }); + return { status: response?.status, json: (await response?.json()) as any }; +} + +describe("gateway client management routes", () => { + test("status lists both clients, connect writes the fake home, disconnect restores it", async () => { + const initial = await call("GET", "/api/gateway-clients"); + expect(initial.status).toBe(200); + expect(initial.json.clients.map((c: { id: string; state: string }) => `${c.id}:${c.state}`)).toEqual(["antigravity:disconnected", "agy:disconnected"]); + + const connected = await call("POST", "/api/gateway-clients/antigravity/connect", { model: "gemini-3" }); + expect(connected).toMatchObject({ status: 200, json: { ok: true, id: "antigravity", action: "connect", changed: true, changedFiles: [settings()], status: { state: "connected" } } }); + expect(JSON.parse(readFileSync(settings(), "utf8")).gateway.url).toBe("http://127.0.0.1:10100"); + + const viaAgy = await call("POST", "/api/gateway-clients/agy/connect", {}); + expect(viaAgy.json).toMatchObject({ ok: true, id: "agy", status: { state: "connected" } }); + expect(readFileSync(join(gateway.home, ".bashrc"), "utf8")).toContain("agy() {"); + + const status = await call("GET", "/api/gateway-clients"); + expect(status.json.clients.map((c: { state: string }) => c.state)).toEqual(["connected", "connected"]); + + const off = await call("POST", "/api/gateway-clients/antigravity/disconnect"); + expect(off).toMatchObject({ status: 200, json: { ok: true, action: "disconnect", restore: "exact", status: { state: "disconnected" } } }); + expect(existsSync(join(gateway.home, ".antigravity"))).toBe(false); + expect((await call("POST", "/api/gateway-clients/agy/disconnect")).json.restore).toBe("exact"); + expect(existsSync(join(gateway.home, ".bashrc"))).toBe(false); + }); + + test("refusals are 409 with a code and write nothing", async () => { + const lan = config({ hostname: "100.64.0.9" }); + const admission = await call("POST", "/api/gateway-clients/antigravity/connect", {}, lan); + expect(admission).toMatchObject({ status: 409, json: { ok: false, code: "requires-admission-token" } }); + const model = await call("POST", "/api/gateway-clients/antigravity/connect", { model: "a\nb" }); + expect(model).toMatchObject({ status: 409, json: { ok: false, code: "invalid-model" } }); + mkdirSync(join(gateway.home, ".antigravity")); + writeFileSync(settings(), '{\n // note\n}\n'); + const unsupported = await call("POST", "/api/gateway-clients/antigravity/connect", {}); + expect(unsupported).toMatchObject({ status: 409, json: { ok: false, code: "unsupported-file" } }); + expect(readFileSync(settings(), "utf8")).toBe('{\n // note\n}\n'); + }); + + test("unknown ids are 404 and malformed bodies 400", async () => { + expect(await call("POST", "/api/gateway-clients/nope/connect", {})).toMatchObject({ status: 404, json: { ok: false, code: "unknown-client" } }); + expect(await call("POST", "/api/gateway-clients/antigravity/connect", { model: 7 })).toMatchObject({ status: 400, json: { code: "invalid-body" } }); + expect(await call("POST", "/api/gateway-clients/antigravity/connect", [1])).toMatchObject({ status: 400 }); + }); + + test("a cross-origin mutation is blocked before the handler runs", async () => { + const blocked = await call("POST", "/api/gateway-clients/antigravity/connect", {}, config(), { origin: "https://evil.example" }); + expect(blocked.status).toBe(403); + expect(existsSync(join(gateway.home, ".antigravity"))).toBe(false); + }); +}); From ee467a1403bc220c9c76972eebb69ce591d6e7d5 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:43:26 -0500 Subject: [PATCH 3/9] feat(cli): add ocx connect|disconnect antigravity|agy with local fallback --- .../ocx/references/01_management_surface.md | 18 ++- .../references/01_surface_access-remote.md | 60 ++++++++- src/cli/capabilities-integrations.ts | 30 +++++ src/cli/dispatch.ts | 4 + src/cli/gateway-client-command.ts | 119 ++++++++++++++++++ 5 files changed, 227 insertions(+), 4 deletions(-) create mode 100644 src/cli/gateway-client-command.ts diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 367504a2daf..6cdee1b9f96 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -31,7 +31,7 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | [agents-routing](01_surface_agents-routing.md) | 71 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | -| [access-remote](01_surface_access-remote.md) | 51 | +| [access-remote](01_surface_access-remote.md) | 54 | | [lab](01_surface_lab.md) | 21 | ## Read-only capabilities @@ -1043,6 +1043,18 @@ Original invocation order. These headings preserve links to the previous single- [Read-oriented task](01_surface_integrations.md#ocx-integration-native-cursor-local-installer) +### `ocx connect antigravity` + +[State-changing task](01_surface_access-remote.md#ocx-connect-antigravity) + +### `ocx connect antigravity status` + +[Read-oriented task](01_surface_access-remote.md#ocx-connect-antigravity-status) + +### `ocx disconnect antigravity` + +[State-changing task](01_surface_access-remote.md#ocx-disconnect-antigravity) + ### `ocx stop` [State-changing task](01_surface_lifecycle.md#ocx-stop) @@ -1645,6 +1657,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 399 -- of those, state-changing: 250 +- declared capabilities: 402 +- of those, state-changing: 252 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_access-remote.md b/skills/ocx/references/01_surface_access-remote.md index 5ea65c5da02..119b2d1d2d8 100644 --- a/skills/ocx/references/01_surface_access-remote.md +++ b/skills/ocx/references/01_surface_access-remote.md @@ -8,7 +8,7 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 51. +Declared capabilities: 54. ### `ocx link probe` @@ -387,6 +387,64 @@ State-changing: yes. JSON mode: `payload`. - A bare invocation reads and never writes. - A setting flag changes the operator's config; run it only when the operator asks for that change. +### `ocx connect antigravity` + +Usage: `ocx connect antigravity|agy [--model ] [--json]` + +Point Google's Antigravity desktop app or the agy CLI at this proxy, keeping a restore record. + +State-changing: yes. JSON mode: `payload`. + +| Method | Route | +|---|---| +| POST | `/api/gateway-clients/{id}/connect` | + +| Flag | Value | Meaning | +|---|---|---| +| `--model` | string | Default model selector written to the Antigravity settings. | +| `--json` | boolean | Emit the result as JSON. | + +- agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy). +- With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files. + +### `ocx connect antigravity status` + +Usage: `ocx connect antigravity|agy status [--json]` + +Show whether Antigravity or agy is connected, which files carry it, and any admin_settings or environment override that wins. + +State-changing: no. JSON mode: `payload`. + +| Method | Route | +|---|---| +| GET | `/api/gateway-clients` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit the client status as JSON. | + +- agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy). +- With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files. + +### `ocx disconnect antigravity` + +Usage: `ocx disconnect antigravity|agy [--json]` + +Undo the Antigravity or agy connection: restore byte for byte, or path by path when the files changed since. + +State-changing: yes. JSON mode: `payload`. + +| Method | Route | +|---|---| +| POST | `/api/gateway-clients/{id}/disconnect` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit the result as JSON. | + +- agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy). +- With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files. + ### `ocx disconnect` Usage: `ocx disconnect [--keep-catalog] [--recover-config --yes] [--json] [--expect-link ] | ocx disconnect --orphaned-token --yes [--json]` diff --git a/src/cli/capabilities-integrations.ts b/src/cli/capabilities-integrations.ts index 5df20204675..a84b3af9c35 100644 --- a/src/cli/capabilities-integrations.ts +++ b/src/cli/capabilities-integrations.ts @@ -277,4 +277,34 @@ export const INTEGRATION_CAPABILITIES: readonly Capability[] = [ json: "payload", details: ["May fetch the public update manifest. available:false and nullable reason are valid observations; no installation or trust change is performed."], }, + { + command: ["connect","antigravity"], + usage: "ocx connect antigravity|agy [--model ] [--json]", + summary: "Point Google's Antigravity desktop app or the agy CLI at this proxy, keeping a restore record.", + routes: [{"method":"POST","path":"/api/gateway-clients/{id}/connect"}], + flags: [{"name":"--model","value":"string","summary":"Default model selector written to the Antigravity settings."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."}], + mutates: true, + json: "payload", + details: ["agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy).", "With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files."], + }, + { + command: ["connect","antigravity","status"], + usage: "ocx connect antigravity|agy status [--json]", + summary: "Show whether Antigravity or agy is connected, which files carry it, and any admin_settings or environment override that wins.", + routes: [{"method":"GET","path":"/api/gateway-clients"}], + flags: [{"name":"--json","value":"boolean","summary":"Emit the client status as JSON."}], + mutates: false, + json: "payload", + details: ["agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy).", "With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files."], + }, + { + command: ["disconnect","antigravity"], + usage: "ocx disconnect antigravity|agy [--json]", + summary: "Undo the Antigravity or agy connection: restore byte for byte, or path by path when the files changed since.", + routes: [{"method":"POST","path":"/api/gateway-clients/{id}/disconnect"}], + flags: [{"name":"--json","value":"boolean","summary":"Emit the result as JSON."}], + mutates: true, + json: "payload", + details: ["agy is an alias of antigravity. Works on this machine only; the files are the Antigravity user settings (antigravity) or shell profiles (agy).", "With no running proxy the same change is made locally. Refused when the proxy bind needs a data-plane credential: no real secret is written into client files."], + }, ]; diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index 1f5b420bb13..a557e5c0b4e 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -420,6 +420,8 @@ const commandRunners: Record = { return await cmdV2(deps.args.slice(1), { runtimeApi: { findLiveProxy: deps.findLiveProxy } }, async () => (await deps.findLiveProxy())?.port); }, connect: async deps => { + const { isGatewayClientOperand, runGatewayClientFromArgs } = await import("./gateway-client-command"); + if (isGatewayClientOperand(deps.args[1])) return await runGatewayClientFromArgs("connect", deps.args.slice(1), { findLiveProxy: deps.findLiveProxy }); const { handleConnectCommand } = await import("./connect"); return await handleConnectCommand(deps.args.slice(1)); }, @@ -432,6 +434,8 @@ const commandRunners: Record = { return await runRemoteWorkspaceCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy }); }, disconnect: async deps => { + const { isGatewayClientOperand, runGatewayClientFromArgs } = await import("./gateway-client-command"); + if (isGatewayClientOperand(deps.args[1])) return await runGatewayClientFromArgs("disconnect", deps.args.slice(1), { findLiveProxy: deps.findLiveProxy }); const { handleDisconnectCommand } = await import("./connect"); const code = await handleDisconnectCommand(deps.args.slice(1)); // Token recovery refuses any live client runtime and leaves nothing to restart. diff --git a/src/cli/gateway-client-command.ts b/src/cli/gateway-client-command.ts new file mode 100644 index 00000000000..cdebec26dd3 --- /dev/null +++ b/src/cli/gateway-client-command.ts @@ -0,0 +1,119 @@ +/** + * `ocx connect|disconnect antigravity|agy` and `ocx connect antigravity|agy status`. + * + * Points Google's Antigravity desktop app and `agy` CLI at this proxy. The running proxy owns the + * work (`/api/gateway-clients`); when none is running the same connectors run in this process, so + * a first-time setup does not need `ocx start` first. + */ +import { loadConfig } from "../config"; +import { + connectGatewayClient, disconnectGatewayClient, gatewayActionBody, gatewayClientsStatus, isGatewayClientId, + productionGatewayClientContext, resolveGatewayTarget, type GatewayClientContext, type GatewayClientId, type GatewayClientStatus, +} from "../integrations/gateway-clients"; +import { CliUsageError, RuntimeApiError, printData, rejectArgs, runCliAction, runtimeRequest, takeJsonFlag, takeOption, terminalSafeText, type RuntimeApiDeps } from "./runtime-api"; + +type GatewayClientVerb = "connect" | "disconnect" | "status"; + +export interface GatewayClientCommandDeps extends RuntimeApiDeps { + /** Local-fallback seams; production reads the real home and config. */ + context?: () => GatewayClientContext; + loadConfig?: typeof loadConfig; +} + +const USAGE: Record = { + connect: "ocx connect antigravity|agy [--model ] [--json]", + disconnect: "ocx disconnect antigravity|agy [--json]", + status: "ocx connect antigravity|agy status [--json]", +}; + +/** True when the first operand after `connect` or `disconnect` names a gateway client. */ +export const isGatewayClientOperand = (operand: string | undefined): operand is GatewayClientId => isGatewayClientId(operand); + +type Body = Record & { ok: boolean; message?: string; notes?: string[]; changedFiles?: string[]; restore?: string; status?: GatewayClientStatus }; + +function actionLines(body: Body, offlinePort: number | null): string[] { + const out = [body.message ?? (body.ok ? "Done." : "Failed.")]; + for (const file of body.changedFiles ?? []) out.push(` changed: ${file}`); + if (body.restore) out.push(` restore: ${body.restore}`); + for (const override of body.status?.overrides ?? []) out.push(` warning (${override.source}): ${override.detail}`); + for (const note of body.notes ?? []) out.push(` ${note}`); + if (offlinePort !== null && body.ok) out.push(` The proxy is not running. Start it so the client has something to talk to: ocx start (port ${offlinePort}).`); + return out; +} + +function statusLines(status: GatewayClientStatus, offline: boolean): string[] { + const out = [`${status.label}: ${status.state}`]; + for (const file of status.files) out.push(` ${file.exists ? "found " : "missing"} ${file.role}: ${file.path}`); + for (const override of status.overrides) out.push(` warning (${override.source}): ${override.detail}`); + for (const note of status.notes) out.push(` ${note}`); + if (offline) out.push(" The proxy is not running."); + return out; +} + +const isOffline = (error: unknown): boolean => error instanceof RuntimeApiError && error.code === "proxy_not_running"; + +function refusalBody(error: unknown): Body | null { + if (!(error instanceof RuntimeApiError) || error.status !== 409) return null; + const body = error.body as Body | null; + return body && typeof body === "object" && body.ok === false ? body : null; +} + +/** Exit 5 is the CLI's "refused" code, the same one runCliAction gives any 409. */ +function refuse(body: Body, wantsJson: boolean): void { + if (wantsJson) console.log(JSON.stringify(body, null, 2)); + else console.error(`Error: ${terminalSafeText(String(body.message ?? "refused"))}`); +} + +async function runLocally(verb: GatewayClientVerb, id: GatewayClientId, model: string | undefined, wantsJson: boolean, deps: GatewayClientCommandDeps): Promise { + const config = (deps.loadConfig ?? loadConfig)(); + const ctx = (deps.context ?? productionGatewayClientContext)(); + const resolved = resolveGatewayTarget(config, config.port, model); + const target = resolved.ok ? resolved.target : undefined; + if (verb === "status") { + const mine = gatewayClientsStatus(ctx, target).find(client => client.id === id)!; + printData(mine, wantsJson, statusLines(mine, true)); + return 0; + } + const outcome = verb === "connect" ? connectGatewayClient(id, ctx, config, config.port, model) : disconnectGatewayClient(id, ctx, target); + const body = gatewayActionBody(outcome) as Body; + if (!outcome.ok) { refuse(body, wantsJson); return 5; } + printData(body, wantsJson, actionLines(body, verb === "connect" ? config.port : null)); + return 0; +} + +export async function runGatewayClientCommand(verb: GatewayClientVerb, id: GatewayClientId, argv: string[], deps: GatewayClientCommandDeps = {}): Promise { + const args = [...argv]; + let exit = 0; + const code = await runCliAction(async () => { + const wantsJson = takeJsonFlag(args); + const model = verb === "connect" ? takeOption(args, "--model") : undefined; + rejectArgs(args, USAGE[verb], { redactValues: true }); + if (model !== undefined && model.trim() === "") throw new CliUsageError("--model requires a non-empty value", USAGE[verb]); + try { + if (verb === "status") { + const { clients } = await runtimeRequest<{ clients: GatewayClientStatus[] }>("/api/gateway-clients", {}, deps); + const mine = clients.find(client => client.id === id); + if (!mine) throw new RuntimeApiError(`The proxy did not report ${id}.`, 404, null); + printData(mine, wantsJson, statusLines(mine, false)); + return; + } + const init: RequestInit = { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(verb === "connect" && model ? { model } : {}) }; + const body = await runtimeRequest(`/api/gateway-clients/${id}/${verb}`, init, deps); + printData(body, wantsJson, actionLines(body, null)); + } catch (error) { + const refusal = refusalBody(error); + if (refusal) { refuse(refusal, wantsJson); exit = 5; return; } + if (!isOffline(error)) throw error; + exit = await runLocally(verb, id, model, wantsJson, deps); + } + }); + return code !== 0 ? code : exit; +} + +/** Route `connect|disconnect ...` here; `args` is argv after the command word. */ +export function runGatewayClientFromArgs(command: "connect" | "disconnect", args: string[], deps: GatewayClientCommandDeps = {}): Promise { + const id = args[0] as GatewayClientId; + const rest = args.slice(1); + if (command === "connect" && rest[0] === "status") return runGatewayClientCommand("status", id, rest.slice(1), deps); + return runGatewayClientCommand(command, id, rest, deps); +} From 3f3e2534687169f4b62e3dd6e36a86783526d5b4 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:47:33 -0500 Subject: [PATCH 4/9] test(cli): cover gateway client dispatch, local fallback and refusals --- scripts/test-layout/layout.json | 1 + structure/INDEX.md | 4 ++ structure/clients/antigravity-gateway.md | 60 ++++++++++++++++ structure/manifest.json | 11 +++ tests/cli/gateway-client-command.test.ts | 87 ++++++++++++++++++++++++ tests/fixtures/test-layout-expected.json | 1 + 6 files changed, 164 insertions(+) create mode 100644 structure/clients/antigravity-gateway.md create mode 100644 tests/cli/gateway-client-command.test.ts diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 05605249cbe..120953e60fd 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -4,6 +4,7 @@ "explicitShards": ["layout-route-intent.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json"], "explicit": { "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", "stop-restore-history-ownership.test.ts": "service", + "gateway-clients.test.ts": "clients", "gateway-client-routes.test.ts": "server", "gateway-client-command.test.ts": "cli", "cli-stop-refusal-transport.test.ts": "cli", "service-proxy-env.test.ts": "service", "openai-chat-standalone-bare-block.test.ts": "adapters/openai", "owner-registry-isolation.test.ts": "config", "server-combo-stream-required-tool.test.ts": "server", "combo-required-tool-stream-preflight.test.ts": "routing", diff --git a/structure/INDEX.md b/structure/INDEX.md index 2bea8d6e528..b16fcc009b6 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -143,6 +143,7 @@ The dashboard, the management API, and third-party client config ownership. | [`clients/claude-desktop.md`](clients/claude-desktop.md) | Claude Desktop profile ownership and config-library resolution. | | [`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md) | Verified regular-file reads of Claude Desktop config-library metadata, profiles and snapshots. | | [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md) | Per-client selection of the rows the Claude Desktop 3P model list carries. | +| [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | One-click connect and disconnect of the Antigravity app and agy CLI to the OpenCodex gateway: files written, stash and restore, override precedence, refusal rules. | | [`clients/hermes.md`](clients/hermes.md) | Hermes profile discovery, per-profile selection, ownership stores, and boundaries. | | [`clients/qoder.md`](clients/qoder.md) | Qoder settings.json provider and custom-model ownership, export and loopback placeholder rules. | | [`clients/client-support-matrix.md`](clients/client-support-matrix.md) | Generated client support page: registry sources, curated protocol and test claims, drift checks. | @@ -259,6 +260,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/cli/codex-provider.ts` | [`codex-provider-routing.md`](codex-provider-routing.md) | | `src/cli/desktop-runtime-guidance.ts` | [`ops/desktop-supervision.md`](ops/desktop-supervision.md) | | `src/cli/ensure-desktop-cold-start.ts` | [`desktop-recovery.md`](desktop-recovery.md) | +| `src/cli/gateway-client-command.ts` | [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | | `src/cli/link-apply-restart.ts` | [`remote-link.md`](remote-link.md) | | `src/cli/link-child-ops.ts` | [`remote-link.md`](remote-link.md) | | `src/cli/link-local-control.ts` | [`remote-link.md`](remote-link.md) | @@ -355,6 +357,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/images/` | [`runtime.md`](runtime.md)
[`transports/inventory.md`](transports/inventory.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md) | | `src/index.ts` | [`runtime.md`](runtime.md) | | `src/integrations/` | [`clients/export-model-names.md`](clients/export-model-names.md)
[`clients/integrations.md`](clients/integrations.md)
[`clients/hermes.md`](clients/hermes.md)
[`clients/qoder.md`](clients/qoder.md)
[`clients/client-support-matrix.md`](clients/client-support-matrix.md)
[`clients/t3code.md`](clients/t3code.md) | +| `src/integrations/gateway-clients/` | [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | | `src/lab/` | [`runtime.md`](runtime.md)
[`adapters/compatibility-lab.md`](adapters/compatibility-lab.md) | | `src/lib/` | [`overview.md`](overview.md)
[`runtime.md`](runtime.md)
[`transports/byte-accounting.md`](transports/byte-accounting.md)
[`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
[`transports/responses-failover.md`](transports/responses-failover.md)
[`transports/responses-spend.md`](transports/responses-spend.md)
[`transports/inventory.md`](transports/inventory.md)
[`gui-and-management-api.md`](gui-and-management-api.md)
[`dashboard-and-usage.md`](dashboard-and-usage.md)
[`clients/integrations.md`](clients/integrations.md)
[`ops/service-and-sidecars.md`](ops/service-and-sidecars.md)
[`ops/docs-and-release.md`](ops/docs-and-release.md) | | `src/lib/abort.ts` | [`transports/timeouts.md`](transports/timeouts.md) | @@ -472,6 +475,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/management/codex-cli-update-routes.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/server/management/companion-routes.ts` | [`desktop-shell.md`](desktop-shell.md) | | `src/server/management/consent-session.ts` | [`telemetry.md`](telemetry.md) | +| `src/server/management/gateway-client-routes.ts` | [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | | `src/server/management/link-child-ops-routes.ts` | [`remote-link.md`](remote-link.md) | | `src/server/management/link-enrollment.ts` | [`remote-link.md`](remote-link.md) | | `src/server/management/link-recover-route.ts` | [`remote-link.md`](remote-link.md) | diff --git a/structure/clients/antigravity-gateway.md b/structure/clients/antigravity-gateway.md new file mode 100644 index 00000000000..752777e906a --- /dev/null +++ b/structure/clients/antigravity-gateway.md @@ -0,0 +1,60 @@ +# Antigravity Gateway Connect + +OpenCodex points Google's official Antigravity clients at its own gateway so a user can run the desktop +app or the `agy` CLI through any provider OpenCodex routes. It is for a person on the machine that runs +the proxy. It does not use the client-integration store described in [integrations](integrations.md): +these clients are configured through Google's gateway settings, not through a provider catalog file. + +## The two clients + +| Id | What it is | Where the gateway setting lives | +| --- | --- | --- | +| `antigravity` | The desktop app (2.15 and newer) | the `gateway` block and `models.defaultModelId` in `~/.antigravity/settings.json` | +| `agy` | The command-line client (1.2.15 and newer) | a marked shell function in the bash, zsh and PowerShell profiles, exporting `AGY_LLM_GATEWAY_*` for `agy` only | + +The `agy` connector never edits an `agy` settings file. On Windows it writes the PowerShell 7 profile and +only an existing `.bashrc`; elsewhere it writes the existing bash and zsh profiles, or creates the one the +login shell names when neither exists. Google lists `agy` for macOS and Linux only, so the Windows path is +reported as untested. + +## Target and the secret rule + +`resolveGatewayTarget` in `src/integrations/gateway-clients/index.ts` asks `localInferenceDestination` for +the URL a local client dials and writes the fixed placeholder key `opencodex-local`. When that destination +requires a data-plane credential, the connect is refused with `requires-admission-token` before any file is +touched: OpenCodex never writes a real secret into a client file. A model selector must be one line of at +most 200 characters, otherwise `invalid-model`. + +## Stash and restore + +Every connect records what it replaced in `/gateway-clients/.json` (mode 0600): the original +bytes of each file (or that the file was absent), the directories it created, and the SHA-256 of what it +wrote. Disconnect then restores in one of three ways. + +- **exact.** The file still equals what OpenCodex wrote, so the original bytes are written back, or the file + and the directories OpenCodex created are removed when it did not exist. +- **path-wise.** The user edited the file since. Only OpenCodex's own entries are reverted: `gateway`, + `models.defaultModelId` and `models.list` in the app settings, the marked block in a profile. Every other + edit is kept, and an entry the user changed after connecting is left as the user set it. +- **none.** There is no record, or the file is already gone; nothing is changed. + +Connecting again while connected keeps the first record, so disconnect still returns to the user's own +state. A settings file with comments, trailing commas or a non-object root is refused with +`unsupported-file` and left untouched, because it cannot be round-tripped. + +## Which setting wins + +Antigravity resolves the gateway as `admin_settings.json` over `AGY_LLM_GATEWAY_*` variables over the user +settings file. Status reports an organisation `admin_settings.json` that sets `gateway` and an +`AGY_LLM_GATEWAY_URL` in the environment OpenCodex itself sees, as `overrides`, without echoing values. A +connected client under an override is therefore reported with a warning rather than as working. + +## Surfaces + +`src/server/management/gateway-client-routes.ts` serves `GET /api/gateway-clients` and +`POST /api/gateway-clients/{id}/connect|disconnect`. A refusal is HTTP 409 with `{ok, code, message}`, an +unknown id is 404. The routes sit behind the ordinary management auth and origin checks, and a sibling +instance refuses the mutations. `ocx connect|disconnect antigravity|agy` and +`ocx connect antigravity|agy status` in `src/cli/gateway-client-command.ts` call those routes through the +running proxy and run the same connectors in-process when the proxy is not running. The dispatch branch sits +before the hub `connect` logic and the disconnect restart flow, which are about a remote hub and do not apply. diff --git a/structure/manifest.json b/structure/manifest.json index efe4a5bbca4..81ef608d214 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -1147,6 +1147,17 @@ "src/server/" ] }, + { + "path": "clients/antigravity-gateway.md", + "tier": 5, + "title": "Antigravity Gateway Connect", + "scope": "One-click connect and disconnect of the Antigravity app and agy CLI to the OpenCodex gateway: files written, stash and restore, override precedence, refusal rules.", + "documents": [ + "src/integrations/gateway-clients/", + "src/server/management/gateway-client-routes.ts", + "src/cli/gateway-client-command.ts" + ] + }, { "path": "clients/hermes.md", "tier": 5, diff --git a/tests/cli/gateway-client-command.test.ts b/tests/cli/gateway-client-command.test.ts new file mode 100644 index 00000000000..bab59222e7b --- /dev/null +++ b/tests/cli/gateway-client-command.test.ts @@ -0,0 +1,87 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { dispatchCommand, type CliDispatchDeps } from "../../src/cli/dispatch"; +import { runGatewayClientCommand, runGatewayClientFromArgs, type GatewayClientCommandDeps } from "../../src/cli/gateway-client-command"; +import type { GatewayClientContext } from "../../src/integrations/gateway-clients"; +import type { OcxConfig } from "../../src/types"; + +let root: string; +let ctx: GatewayClientContext; +const offline = (): GatewayClientCommandDeps => ({ + findLiveProxy: async () => null, + context: () => ctx, + loadConfig: () => ({ port: 10100, providers: {} }) as unknown as OcxConfig, +}); + +function capture() { + const out: string[] = []; + const err: string[] = []; + const log = spyOn(console, "log").mockImplementation((...a) => { out.push(a.join(" ")); }); + const error = spyOn(console, "error").mockImplementation((...a) => { err.push(a.join(" ")); }); + return { out, err, restore: () => { log.mockRestore(); error.mockRestore(); } }; +} + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-gw-cli-")); + mkdirSync(join(root, "home")); + ctx = { home: join(root, "home"), platform: "linux", env: { SHELL: "/bin/bash" }, stateDir: join(root, "state"), adminSettingsPath: join(root, "admin_settings.json") }; +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe("ocx connect|disconnect antigravity|agy", () => { + test("dispatch sends the client operand to the gateway command and never reaches the hub connect", async () => { + const hub = spyOn(await import("../../src/cli/connect"), "handleConnectCommand").mockResolvedValue(99); + const gateway = spyOn(await import("../../src/cli/gateway-client-command"), "runGatewayClientFromArgs").mockResolvedValue(0); + try { + for (const operand of ["agy", "antigravity"]) { + const args = ["connect", operand, "status", "--json"]; + expect(await dispatchCommand({ kind: "command", command: "connect", args }, { args } as unknown as CliDispatchDeps)).toBe(0); + expect(gateway).toHaveBeenLastCalledWith("connect", [operand, "status", "--json"], expect.anything()); + } + expect(hub).not.toHaveBeenCalled(); + } finally { hub.mockRestore(); gateway.mockRestore(); } + }); + + test("with no running proxy connect and disconnect run locally and restore the file", async () => { + const io = capture(); + try { + expect(await runGatewayClientFromArgs("connect", ["antigravity", "--model", "gemini-3", "--json"], offline())).toBe(0); + const body = JSON.parse(io.out.join("\n")); + expect(body).toMatchObject({ ok: true, id: "antigravity", action: "connect", status: { state: "connected" } }); + expect(JSON.parse(readFileSync(join(ctx.home, ".antigravity", "settings.json"), "utf8")).models.defaultModelId).toBe("gemini-3"); + io.out.length = 0; + expect(await runGatewayClientFromArgs("connect", ["antigravity", "status", "--json"], offline())).toBe(0); + expect(JSON.parse(io.out.join("\n"))).toMatchObject({ id: "antigravity", state: "connected" }); + expect(await runGatewayClientFromArgs("disconnect", ["antigravity"], offline())).toBe(0); + expect(existsSync(join(ctx.home, ".antigravity"))).toBe(false); + expect(io.out.join("\n")).toContain("restore: exact"); + } finally { io.restore(); } + }); + + test("a running proxy gets the POST, and a 409 refusal exits 5 with the message", async () => { + const io = capture(); + const calls: { url: string; method?: string; body?: unknown }[] = []; + const reply = (status: number, json: unknown) => async (url: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(url), method: init?.method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); + return new Response(JSON.stringify(json), { status, headers: { "content-type": "application/json" } }); + }; + try { + const ok = { ok: true, id: "agy", action: "connect", changed: true, changedFiles: ["/h/.bashrc"], message: "The agy command now starts on the OpenCodex gateway.", notes: [], status: { id: "agy", label: "agy CLI", state: "connected", files: [], overrides: [], notes: [] } }; + expect(await runGatewayClientCommand("connect", "agy", ["--model", "m1"], { baseUrl: "http://127.0.0.1:10100", fetchImpl: reply(200, ok) as typeof fetch })).toBe(0); + expect(calls[0]).toMatchObject({ url: "http://127.0.0.1:10100/api/gateway-clients/agy/connect", method: "POST", body: { model: "m1" } }); + const refused = { ok: false, code: "requires-admission-token", message: "needs a credential" }; + expect(await runGatewayClientCommand("connect", "agy", [], { baseUrl: "http://127.0.0.1:10100", fetchImpl: reply(409, refused) as typeof fetch })).toBe(5); + expect(io.err.join("\n")).toContain("needs a credential"); + } finally { io.restore(); } + }); + + test("bad arguments are a usage error", async () => { + const io = capture(); + try { + expect(await runGatewayClientCommand("disconnect", "agy", ["--model", "x"], offline())).toBe(2); + expect(await runGatewayClientCommand("connect", "agy", ["--model", " "], offline())).toBe(2); + } finally { io.restore(); } + }); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ebfabf37355..e83af07e138 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -562,6 +562,7 @@ "cli-codex-log-guard.test.ts": "cli", "cli-companion.test.ts": "cli", "cli-config-bom.test.ts": "cli", "cli-config-command.test.ts": "cli", "cli-config-show-client.test.ts": "cli", "cli-connect-readiness.test.ts": "cli", + "gateway-clients.test.ts": "clients", "gateway-client-routes.test.ts": "server", "gateway-client-command.test.ts": "cli", "cli-dispatch.test.ts": "cli", "cli-client-start-fence.test.ts": "cli", "cli-ensure-client-state.test.ts": "cli", "cli-client-start-owner-e2e.test.ts": "cli", "cli-dto-fidelity.test.ts": "cli", "cli-export-command.test.ts": "cli", From dfd8e07b4e6b779c3c886ad0515753636eb26e72 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:47:53 -0500 Subject: [PATCH 5/9] docs(site): describe connecting Antigravity and agy --- .../src/content/docs/guides/integrations.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index 1071e0170ac..fd487d6ec71 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1228,3 +1228,25 @@ OpenCodex refuses those ambiguous settings. It also refuses an unsafe target or a row edited since apply. The integration is loopback only and never copies provider credentials. Factory documents the [BYOK schema](https://docs.factory.ai/model-independence/byok) and [personal settings path](https://docs.factory.ai/droid-cli/settings). + +## Antigravity app and agy CLI + +Google's Antigravity desktop app (2.15 and newer) and the `agy` CLI (1.2.15 and newer) can run through +OpenCodex's gateway. Connect from the dashboard, or from a terminal: + +```bash +ocx connect antigravity --model # desktop app: ~/.antigravity/settings.json +ocx connect agy # agy CLI: a marked shell function in your profiles +ocx connect antigravity status # or: ocx connect agy status +ocx disconnect antigravity # or: ocx disconnect agy +``` + +Connect records what it replaced. Disconnect puts the original bytes back when the file is unchanged, and +otherwise reverts only OpenCodex's own entries and keeps your edits. Restart Antigravity, or open a new +terminal for `agy`, to apply a change. + +OpenCodex writes a placeholder key, never a real credential, so it refuses to connect when the proxy bind +requires one. A file with comments or trailing commas is also refused and left untouched. Antigravity reads +an organization `admin_settings.json` first, then the `AGY_LLM_GATEWAY_*` variables, then the user settings; +status shows a warning when one of the first two overrides the connection. On Windows `agy` is untested +because Google lists it for macOS and Linux only. From c19ce0056110e3f2f23668fa3e3d38a8d747c649 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:28:13 -0500 Subject: [PATCH 6/9] feat(gui): add Antigravity tab to connect and disconnect Antigravity and agy The Integrations page gets an Antigravity tab backed by /api/gateway-clients. Each client shows its state, the files it changes, override warnings from admin_settings.json or the environment, and the server's notes. Connect (with an optional default model for the desktop app) and Disconnect relay the server's message, including refusals, and reread status. The tab label is allowlisted as a product name in the zh-TW and French placeholder guards. --- gui/src/app-routing.ts | 1 + gui/src/components/integration-marks.ts | 4 +- gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/gateway-clients-copy.ts | 35 +++++ gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/Integrations.tsx | 2 + .../pages/integrations/GatewayClientsPage.tsx | 147 ++++++++++++++++++ .../pages/integrations/gateway-clients-api.ts | 59 +++++++ .../pages/integrations/integration-tabs.ts | 2 + gui/tests/fr-localization.test.ts | 2 + gui/tests/locale-parity.test.ts | 2 + 20 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 gui/src/i18n/gateway-clients-copy.ts create mode 100644 gui/src/pages/integrations/GatewayClientsPage.tsx create mode 100644 gui/src/pages/integrations/gateway-clients-api.ts diff --git a/gui/src/app-routing.ts b/gui/src/app-routing.ts index 1a92cf20bfe..cb8e734ab65 100644 --- a/gui/src/app-routing.ts +++ b/gui/src/app-routing.ts @@ -136,6 +136,7 @@ export const INTEGRATION_TAB_HASHES = [ "integrations/claude/desktop", "integrations/grok", "integrations/cursor", + "integrations/antigravity", "integrations/opencode", "integrations/pi", "integrations/gentle-shell", diff --git a/gui/src/components/integration-marks.ts b/gui/src/components/integration-marks.ts index 08006a3769c..ac172cca54e 100644 --- a/gui/src/components/integration-marks.ts +++ b/gui/src/components/integration-marks.ts @@ -43,7 +43,7 @@ const NATIVE_MARKS: Record, string> = * vendor publishes nothing usable, and `ClientMark` renders a monogram for it. * Gentle Shell uses that fallback, which `integration-marks.test.ts` pins. */ -export const INTEGRATION_MARKS: Record = { +export const INTEGRATION_MARKS: Record = { ...NATIVE_MARKS, opencode: CLIENT_MARKS.opencode ?? null, pi: CLIENT_MARKS.pi ?? null, @@ -70,6 +70,8 @@ export const INTEGRATION_MARKS: Record = { workbuddy: null, "workbuddy-ai": null, t3code: CLIENT_MARKS.t3code ?? null, + // The Antigravity tab is a gateway-client switch, not an overview row. + antigravity: "/provider-icons/antigravity-color.svg", }; /** diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 234541ce8ca..5d89fb8c942 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -137,6 +138,7 @@ export const de: Record = { ...shellV2Copy("de"), ...codexCliUpdateCopy("de"), ...remoteLinkDiagnosticsCopy("de"), + ...gatewayClientsCopy("de"), ...modelsV2Copy("de"), ...accountsV2Copy("de"), ...subagentsV2Copy("de"), diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 76381be2404..9aa4b159c3c 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -138,6 +139,7 @@ export const en = { ...shellV2Copy("en"), ...codexCliUpdateCopy("en"), ...remoteLinkDiagnosticsCopy("en"), + ...gatewayClientsCopy("en"), ...modelsV2Copy("en"), ...accountsV2Copy("en"), ...subagentsV2Copy("en"), diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f0314b0c16e..0b2a70c1a8e 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -136,6 +137,7 @@ export const fr: Record = { ...shellV2Copy("fr"), ...codexCliUpdateCopy("fr"), ...remoteLinkDiagnosticsCopy("fr"), + ...gatewayClientsCopy("fr"), ...modelsV2Copy("fr"), ...accountsV2Copy("fr"), ...subagentsV2Copy("fr"), diff --git a/gui/src/i18n/gateway-clients-copy.ts b/gui/src/i18n/gateway-clients-copy.ts new file mode 100644 index 00000000000..679da790927 --- /dev/null +++ b/gui/src/i18n/gateway-clients-copy.ts @@ -0,0 +1,35 @@ +/* + * Copy for the Antigravity and agy connect tab. One row per key, columns in the order of + * `locales`, kept apart from the per-locale files like remote-link-diagnostics-copy.ts. Paths, + * roles, notes and refusal messages come from the server and are shown as sent. + */ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; + +const rows = { + tab: ["Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity"], + title: ["Antigravity and agy","Antigravity 및 agy","Antigravity und agy","Antigravity et agy","Antigravity 和 agy","Antigravity 與 agy","Antigravity и agy","Antigravity と agy","Antigravity ve agy","Antigravity và agy","Antigravity e agy"], + intro: ["Send Google's Antigravity desktop app and the agy CLI through this proxy. Connect writes their gateway settings and keeps a copy of what was there; Disconnect puts it back.","Google의 Antigravity 데스크톱 앱과 agy CLI가 이 프록시를 거치게 해요. 연결하면 게이트웨이 설정을 쓰고 기존 내용을 보관하며, 연결 해제하면 되돌려요.","Leitet Googles Antigravity-Desktop-App und die agy-CLI über diesen Proxy. Verbinden schreibt ihre Gateway-Einstellungen und sichert den vorherigen Stand; Trennen stellt ihn wieder her.","Fait passer l’application de bureau Antigravity de Google et la CLI agy par ce proxy. Connecter écrit leurs réglages de passerelle et conserve l’état précédent ; Déconnecter le rétablit.","让 Google 的 Antigravity 桌面应用和 agy 命令行经由此代理。连接会写入它们的网关设置并保留原有内容;断开会恢复原样。","讓 Google 的 Antigravity 桌面應用程式和 agy 命令列經由此代理。連線會寫入它們的閘道設定並保留原有內容;中斷連線會還原。","Направляет настольное приложение Google Antigravity и CLI agy через этот прокси. Подключение записывает настройки шлюза и сохраняет прежнее содержимое; отключение возвращает его.","Google の Antigravity デスクトップアプリと agy CLI をこのプロキシ経由にします。接続するとゲートウェイ設定を書き込み、元の内容を保管します。切断すると元に戻します。","Google'ın Antigravity masaüstü uygulamasını ve agy CLI'ını bu proxy üzerinden geçirir. Bağlan, ağ geçidi ayarlarını yazar ve önceki hâlini saklar; Bağlantıyı kes onu geri yükler.","Cho ứng dụng Antigravity trên máy tính của Google và CLI agy đi qua proxy này. Kết nối sẽ ghi cài đặt cổng và giữ bản cũ; Ngắt kết nối sẽ khôi phục lại.","Faz o app de desktop Antigravity do Google e a CLI agy passarem por este proxy. Conectar grava as configurações de gateway e guarda o estado anterior; Desconectar o restaura."], + loading: ["Reading client status…","클라이언트 상태를 읽는 중…","Clientstatus wird gelesen…","Lecture de l’état des clients…","正在读取客户端状态…","正在讀取用戶端狀態…","Чтение состояния клиентов…","クライアントの状態を読み込み中…","İstemci durumu okunuyor…","Đang đọc trạng thái máy khách…","Lendo o status dos clientes…"], + unavailable: ["Could not read the Antigravity and agy status.","Antigravity 및 agy 상태를 읽지 못했어요.","Der Status von Antigravity und agy konnte nicht gelesen werden.","Impossible de lire l’état d’Antigravity et d’agy.","无法读取 Antigravity 和 agy 的状态。","無法讀取 Antigravity 與 agy 的狀態。","Не удалось прочитать состояние Antigravity и agy.","Antigravity と agy の状態を読み取れませんでした。","Antigravity ve agy durumu okunamadı.","Không đọc được trạng thái của Antigravity và agy.","Não foi possível ler o status do Antigravity e do agy."], + files: ["Files it changes","변경하는 파일","Geänderte Dateien","Fichiers modifiés","会修改的文件","會修改的檔案","Изменяемые файлы","変更するファイル","Değiştirdiği dosyalar","Các tệp sẽ thay đổi","Arquivos alterados"], + fileMissing: ["not created yet","아직 없음","noch nicht angelegt","pas encore créé","尚未创建","尚未建立","ещё не создан","未作成","henüz oluşturulmadı","chưa được tạo","ainda não criado"], + overrideAdmin: ["Your organization's admin_settings.json sets a gateway, so this setting has no effect:","조직의 admin_settings.json이 게이트웨이를 지정하고 있어 이 설정은 적용되지 않아요:","Die admin_settings.json Ihrer Organisation legt ein Gateway fest, daher wirkt diese Einstellung nicht:","Le fichier admin_settings.json de votre organisation définit une passerelle ; ce réglage n’a donc aucun effet :","你所在组织的 admin_settings.json 指定了网关,因此此设置不会生效:","你所屬組織的 admin_settings.json 指定了閘道,因此此設定不會生效:","admin_settings.json вашей организации задаёт шлюз, поэтому эта настройка не действует:","組織の admin_settings.json がゲートウェイを指定しているため、この設定は効きません:","Kuruluşunuzun admin_settings.json dosyası bir ağ geçidi belirliyor, bu yüzden bu ayarın etkisi yok:","admin_settings.json của tổ chức bạn đã đặt cổng, nên cài đặt này không có tác dụng:","O admin_settings.json da sua organização define um gateway, então esta configuração não tem efeito:"], + overrideEnv: ["An environment variable takes precedence over this setting:","환경 변수가 이 설정보다 우선해요:","Eine Umgebungsvariable hat Vorrang vor dieser Einstellung:","Une variable d’environnement prime sur ce réglage :","有环境变量优先于此设置:","有環境變數優先於此設定:","Переменная окружения имеет приоритет над этой настройкой:","環境変数がこの設定より優先されます:","Bir ortam değişkeni bu ayarın önüne geçiyor:","Một biến môi trường được ưu tiên hơn cài đặt này:","Uma variável de ambiente tem prioridade sobre esta configuração:"], + model: ["Default model (optional)","기본 모델(선택)","Standardmodell (optional)","Modèle par défaut (facultatif)","默认模型(可选)","預設模型(選填)","Модель по умолчанию (необязательно)","デフォルトモデル(任意)","Varsayılan model (isteğe bağlı)","Mô hình mặc định (không bắt buộc)","Modelo padrão (opcional)"], + modelHint: ["Leave empty to keep the app's own choice.","비워 두면 앱의 기존 선택을 유지해요.","Leer lassen, um die Auswahl der App zu behalten.","Laissez vide pour garder le choix de l’application.","留空则保留应用自己的选择。","留空則保留應用程式自己的選擇。","Оставьте пустым, чтобы сохранить выбор приложения.","空欄にするとアプリ側の選択を保ちます。","Uygulamanın kendi seçimini korumak için boş bırakın.","Để trống để giữ lựa chọn của ứng dụng.","Deixe vazio para manter a escolha do próprio app."], + connect: ["Connect","연결","Verbinden","Connecter","连接","連線","Подключить","接続","Bağlan","Kết nối","Conectar"], + disconnect: ["Disconnect","연결 해제","Trennen","Déconnecter","断开","中斷連線","Отключить","切断","Bağlantıyı kes","Ngắt kết nối","Desconectar"], + working: ["Working…","처리 중…","Wird ausgeführt…","En cours…","处理中…","處理中…","Выполняется…","処理中…","İşleniyor…","Đang xử lý…","Processando…"], + actionFailed: ["The request did not reach the proxy. Check that it is running and try again.","요청이 프록시에 닿지 않았어요. 실행 중인지 확인하고 다시 시도하세요.","Die Anfrage hat den Proxy nicht erreicht. Prüfen Sie, ob er läuft, und versuchen Sie es erneut.","La requête n’a pas atteint le proxy. Vérifiez qu’il tourne et réessayez.","请求没有到达代理。请确认它正在运行后重试。","請求沒有到達代理。請確認它正在執行後重試。","Запрос не дошёл до прокси. Убедитесь, что он запущен, и повторите попытку.","リクエストがプロキシに届きませんでした。起動しているか確認して、もう一度お試しください。","İstek proxy'ye ulaşmadı. Çalıştığını kontrol edip yeniden deneyin.","Yêu cầu không tới được proxy. Hãy kiểm tra proxy đang chạy rồi thử lại.","A solicitação não chegou ao proxy. Verifique se ele está em execução e tente novamente."], +} satisfies Record; + +export type GatewayClientsCopyKey = `gatewayClients.${keyof typeof rows}`; + +export function gatewayClientsCopy(locale: Locale): Record { + const column = locales.indexOf(locale); + return Object.fromEntries( + Object.entries(rows).map(([key, row]) => [`gatewayClients.${key}`, row[column]!]), + ) as Record; +} diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index b71b131dd49..74755a04e41 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -136,6 +137,7 @@ export const ja: Record = { ...shellV2Copy("ja"), ...codexCliUpdateCopy("ja"), ...remoteLinkDiagnosticsCopy("ja"), + ...gatewayClientsCopy("ja"), ...modelsV2Copy("ja"), ...accountsV2Copy("ja"), ...subagentsV2Copy("ja"), diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 399a227c363..75d11a0a495 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -136,6 +137,7 @@ export const ko: Record = { ...shellV2Copy("ko"), ...codexCliUpdateCopy("ko"), ...remoteLinkDiagnosticsCopy("ko"), + ...gatewayClientsCopy("ko"), ...modelsV2Copy("ko"), ...accountsV2Copy("ko"), ...subagentsV2Copy("ko"), diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 1b5c4960b76..d665f437773 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -138,6 +139,7 @@ export const pt: Record = { ...shellV2Copy("pt"), ...codexCliUpdateCopy("pt"), ...remoteLinkDiagnosticsCopy("pt"), + ...gatewayClientsCopy("pt"), ...modelsV2Copy("pt"), ...accountsV2Copy("pt"), ...subagentsV2Copy("pt"), diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 2771adadf00..29802b761fa 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -136,6 +137,7 @@ export const ru: Record = { ...shellV2Copy("ru"), ...codexCliUpdateCopy("ru"), ...remoteLinkDiagnosticsCopy("ru"), + ...gatewayClientsCopy("ru"), ...modelsV2Copy("ru"), ...accountsV2Copy("ru"), ...subagentsV2Copy("ru"), diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index c27997fc8b4..20468e5ca15 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -137,6 +138,7 @@ export const tr: Record = { ...shellV2Copy("tr"), ...codexCliUpdateCopy("tr"), ...remoteLinkDiagnosticsCopy("tr"), + ...gatewayClientsCopy("tr"), ...modelsV2Copy("tr"), ...accountsV2Copy("tr"), ...subagentsV2Copy("tr"), diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 930028388dc..cb675bf4a10 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -138,6 +139,7 @@ export const vi: Record = { ...shellV2Copy("vi"), ...codexCliUpdateCopy("vi"), ...remoteLinkDiagnosticsCopy("vi"), + ...gatewayClientsCopy("vi"), ...modelsV2Copy("vi"), ...accountsV2Copy("vi"), ...subagentsV2Copy("vi"), diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 33da090ccc0..9e0fb995eb5 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -134,6 +135,7 @@ export const zhTW: Record = { ...shellV2Copy("zh-TW"), ...codexCliUpdateCopy("zh-TW"), ...remoteLinkDiagnosticsCopy("zh-TW"), + ...gatewayClientsCopy("zh-TW"), ...modelsV2Copy("zh-TW"), ...accountsV2Copy("zh-TW"), ...subagentsV2Copy("zh-TW"), diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index fe8f2d4c4d9..bd2272de4de 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; @@ -136,6 +137,7 @@ export const zh: Record = { ...shellV2Copy("zh"), ...codexCliUpdateCopy("zh"), ...remoteLinkDiagnosticsCopy("zh"), + ...gatewayClientsCopy("zh"), ...modelsV2Copy("zh"), ...accountsV2Copy("zh"), ...subagentsV2Copy("zh"), diff --git a/gui/src/pages/Integrations.tsx b/gui/src/pages/Integrations.tsx index 34e9ca0764f..72290bf1175 100644 --- a/gui/src/pages/Integrations.tsx +++ b/gui/src/pages/Integrations.tsx @@ -9,6 +9,7 @@ import Claude from "./Claude"; import ClaudeDesktop from "./ClaudeDesktop"; import Grok from "./Grok"; import CursorIntegrationPage from "./integrations/CursorIntegrationPage"; +import GatewayClientsPage from "./integrations/GatewayClientsPage"; import IntegrationsOverview from "./integrations/IntegrationsOverview"; import AsideProfilesPage from "./integrations/AsideProfilesPage"; import HermesProfilesPage from "./integrations/HermesProfilesPage"; @@ -214,6 +215,7 @@ export default function Integrations({ apiBase, machineApiBase = apiBase, connec )} {definition.id === "cursor" && } + {definition.id === "antigravity" && } {FILE_CLIENTS.has(definition.id as FileIntegrationClientId) && ( definition.id === "aside" ? : definition.id === "hermes" ? : ; + +function GatewayClientCard({ + apiBase, + client, + onSettled, +}: { + apiBase: string; + client: GatewayClientStatus; + onSettled: () => void; +}) { + const t = useT(); + const [model, setModel] = useState(""); + const [pending, setPending] = useState(null); + const [outcome, setOutcome] = useState(null); + const modelId = useId(); + + const run = async (action: GatewayClientAction) => { + setPending(action); + setOutcome(null); + const result = await runGatewayClientAction(apiBase, client.id, action, action === "connect" ? model.trim() || undefined : undefined); + setOutcome(result); + setPending(null); + onSettled(); + }; + + return ( +
+

+ {client.label}{" "} + +

+ + {client.overrides.map(override => ( + + {t(override.source === "admin_settings" ? "gatewayClients.overrideAdmin" : "gatewayClients.overrideEnv")}{" "} + {override.detail} + + ))} + + {t("gatewayClients.files")} +
    + {client.files.map(file => ( +
  • + {file.path} {file.role}{file.exists ? "" : ` · ${t("gatewayClients.fileMissing")}`} +
  • + ))} +
+ + {client.notes.length > 0 && ( +
    + {client.notes.map(note =>
  • {note}
  • )} +
+ )} + + {client.id === "antigravity" && ( +
+ + setModel(event.target.value)} + disabled={pending !== null} + spellCheck={false} + autoComplete="off" + /> + {t("gatewayClients.modelHint")} +
+ )} + +
+ + +
+ + {outcome && ( + + {outcome.message ?? t("gatewayClients.actionFailed")} + {outcome.notes.map(note =>
{note}
)} +
+ )} +
+ ); +} + +export default function GatewayClientsPage({ apiBase, active }: { apiBase: string; active: boolean }) { + const t = useT(); + const fetchClients = useCallback(async (signal: AbortSignal) => { + const clients = await loadGatewayClients(apiBase, signal); + if (!clients) throw new Error("gateway client status unavailable"); + return clients; + }, [apiBase]); + const resource = useDataSurface( + `integration-gateway-clients:${apiBase}`, + [apiBase], + fetchClients, + { isEmpty: () => false, enabled: active }, + ); + const clients = resource.state.data ?? null; + + return ( +
+

{t("gatewayClients.title")}

+

{t("gatewayClients.intro")}

+ {resource.state.showError && {t("gatewayClients.unavailable")}} + {!clients && !resource.state.showError && } + {clients?.map(client => ( + resource.refresh()} /> + ))} +
+ ); +} diff --git a/gui/src/pages/integrations/gateway-clients-api.ts b/gui/src/pages/integrations/gateway-clients-api.ts new file mode 100644 index 00000000000..fb77c30f0b9 --- /dev/null +++ b/gui/src/pages/integrations/gateway-clients-api.ts @@ -0,0 +1,59 @@ +/** + * Wire types for the Antigravity and agy connect routes + * (src/server/management/gateway-client-routes.ts). + */ +import { readJsonIfOk } from "../../fetch-json"; + +export type GatewayClientId = "antigravity" | "agy"; +export type GatewayClientState = "connected" | "disconnected" | "drifted"; +export type GatewayClientAction = "connect" | "disconnect"; + +export interface GatewayClientStatus { + id: GatewayClientId; + label: string; + state: GatewayClientState; + files: { path: string; role: string; exists: boolean }[]; + overrides: { source: "admin_settings" | "env"; detail: string }[]; + notes: string[]; +} + +/** `message` is null when the request never produced a readable answer from the proxy. */ +export interface GatewayClientActionOutcome { + ok: boolean; + message: string | null; + notes: string[]; +} + +export async function loadGatewayClients(apiBase: string, signal?: AbortSignal): Promise { + try { + const response = await fetch(`${apiBase}/api/gateway-clients`, { signal }); + const body = await readJsonIfOk<{ clients?: unknown }>(response); + return Array.isArray(body?.clients) ? body.clients as GatewayClientStatus[] : null; + } catch { + return null; + } +} + +/** A refusal (409, 400, 404) carries its own message, so it is read rather than discarded. */ +export async function runGatewayClientAction( + apiBase: string, + id: GatewayClientId, + action: GatewayClientAction, + model?: string, +): Promise { + try { + const response = await fetch(`${apiBase}/api/gateway-clients/${id}/${action}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(model ? { model } : {}), + }); + const body = await response.json() as { ok?: unknown; message?: unknown; notes?: unknown }; + return { + ok: response.ok && body.ok === true, + message: typeof body.message === "string" && body.message ? body.message : null, + notes: Array.isArray(body.notes) ? body.notes.filter((note): note is string => typeof note === "string") : [], + }; + } catch { + return { ok: false, message: null, notes: [] }; + } +} diff --git a/gui/src/pages/integrations/integration-tabs.ts b/gui/src/pages/integrations/integration-tabs.ts index 54ee415be23..af3184bb6a0 100644 --- a/gui/src/pages/integrations/integration-tabs.ts +++ b/gui/src/pages/integrations/integration-tabs.ts @@ -20,6 +20,7 @@ export type IntegrationTab = | "claudeDesktop" | "grok" | "cursor" + | "antigravity" | FileIntegrationClientId; export interface TabDefinition { @@ -38,6 +39,7 @@ export const TABS: readonly TabDefinition[] = [ { id: "claudeDesktop", hash: "claude/desktop", labelKey: "claudeDesktop.title" }, { id: "grok", hash: "integrations/grok", labelKey: "integrations.tab.grok" }, { id: "cursor", hash: "integrations/cursor", labelKey: "integrations.tab.cursor" }, + { id: "antigravity", hash: "integrations/antigravity", labelKey: "gatewayClients.tab" }, { id: "opencode", hash: "integrations/opencode", labelKey: "integrations.tab.opencode" }, { id: "pi", hash: "integrations/pi", labelKey: "integrations.tab.pi" }, { id: "gentle-shell", hash: "integrations/gentle-shell", labelKey: "integrations.tab.gentleShell" }, diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index f58f8ecec7b..869ecb7f75f 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -181,6 +181,8 @@ const INTENTIONAL_ENGLISH = new Set([ "integrations.tab.workbuddyAi", // T3 Code is a product name, identical in every locale. "integrations.tab.t3code", + // Antigravity is a product name, identical in every locale. + "gatewayClients.tab", "api.clientConfig.clientT3code", "models.reasoningEffort.minimal", "models.reasoningEffort.max", diff --git a/gui/tests/locale-parity.test.ts b/gui/tests/locale-parity.test.ts index 1a4df8e754d..9feef269ee8 100644 --- a/gui/tests/locale-parity.test.ts +++ b/gui/tests/locale-parity.test.ts @@ -182,6 +182,8 @@ const ZH_TW_KEEP_ENGLISH: ReadonlySet = new Set([ "integrations.tab.workbuddyAi", // T3 Code is a product name, identical in every locale. "integrations.tab.t3code", + // Antigravity is a product name, identical in every locale. + "gatewayClients.tab", "api.clientConfig.clientT3code", // Command Code is a product name, identical in every locale. "integrations.tab.commandcode", From 9da8ec58bdebcddff932b7509e2b7514bc919fbe Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:28:17 -0500 Subject: [PATCH 7/9] test(gui): cover the Antigravity gateway client tab Drives the page against a fetch mock for status, a connect with a model, and a 409 refusal. --- gui/tests/gateway-clients-page.test.tsx | 164 ++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 gui/tests/gateway-clients-page.test.tsx diff --git a/gui/tests/gateway-clients-page.test.tsx b/gui/tests/gateway-clients-page.test.tsx new file mode 100644 index 00000000000..709cf4e3965 --- /dev/null +++ b/gui/tests/gateway-clients-page.test.tsx @@ -0,0 +1,164 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import type { GatewayClientStatus } from "../src/pages/integrations/gateway-clients-api"; + +/** + * The Antigravity tab drives the gateway-client routes. These tests run the real component + * against a fetch mock and assert what the user sees: the status the server reports, the + * override warning, and the message an action answers with, success or refusal. + */ + +const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT"] as const; + +let previousGlobals: Record<(typeof globals)[number], unknown>; +let testWindow: Window; +let container: HTMLElement; +let root: Root | null = null; +let requests: { method: string; url: string; body: string | null }[] = []; +let mountCount = 0; +let apiBase = ""; +let clients: GatewayClientStatus[]; +let actionResponse: () => Response; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); +} + +function client(overrides: Partial & Pick): GatewayClientStatus { + return { state: "disconnected", files: [], overrides: [], notes: [], ...overrides }; +} + +beforeEach(() => { + previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/#integrations/antigravity" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + }); + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + + requests = []; + mountCount += 1; + apiBase = `http://ocx-gateway-clients-${mountCount}.invalid`; + clients = [ + client({ + id: "antigravity", + label: "Antigravity", + files: [{ path: "/home/u/.antigravity/settings.json", role: "gateway settings", exists: true }], + overrides: [{ source: "admin_settings", detail: "/etc/antigravity/admin_settings.json" }], + }), + client({ + id: "agy", + label: "agy CLI", + state: "connected", + files: [{ path: "/home/u/.gemini/agy.json", role: "CLI config", exists: false }], + notes: ["Restart agy to pick up the change."], + }), + ]; + actionResponse = () => json({ ok: true, id: "antigravity", action: "connect", changed: true, changedFiles: [], message: "Antigravity now uses OpenCodex.", notes: [], status: clients[0] }); + const mockFetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input); + const method = init?.method ?? "GET"; + requests.push({ method, url, body: typeof init?.body === "string" ? init.body : null }); + return method === "POST" ? actionResponse() : json({ clients }); + }) as typeof fetch; + Object.defineProperty(globalThis, "fetch", { configurable: true, value: mockFetch }); + Object.defineProperty(testWindow, "fetch", { configurable: true, value: mockFetch }); + + container = testWindow.document.createElement("div") as unknown as HTMLElement; + testWindow.document.body.appendChild(container as never); +}); + +afterEach(async () => { + if (root) { + const current = root; + await act(async () => { current.unmount(); }); + root = null; + } + testWindow.close(); + for (const key of globals) Object.defineProperty(globalThis, key, { configurable: true, value: previousGlobals[key] }); +}); + +async function settle(): Promise { + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 30)); }); +} + +async function mount(): Promise { + const [{ createRoot }, { LanguageProvider }, { default: GatewayClientsPage }] = await Promise.all([ + import("react-dom/client"), + import("../src/i18n/provider"), + import("../src/pages/integrations/GatewayClientsPage"), + ]); + await act(async () => { + root = createRoot(container); + root.render( + + + , + ); + }); + await settle(); +} + +function card(id: string): HTMLElement { + const found = container.querySelector(`[data-gateway-client='${id}']`) as HTMLElement | null; + if (!found) throw new Error(`no card for ${id}`); + return found; +} + +function button(scope: HTMLElement, label: string): HTMLButtonElement { + const found = Array.from(scope.querySelectorAll("button")).find(candidate => (candidate.textContent ?? "").trim() === label); + if (!found) throw new Error(`no ${label} button`); + return found as HTMLButtonElement; +} + +test("lists both clients with state, files, notes and the admin_settings warning", async () => { + await mount(); + const antigravity = card("antigravity"); + expect(antigravity.querySelector("[data-integration-state='absent']")).not.toBeNull(); + expect(antigravity.textContent).toContain("/home/u/.antigravity/settings.json"); + expect(antigravity.querySelector(".notice-warn")?.textContent).toContain("admin_settings.json sets a gateway"); + expect(antigravity.querySelector("input")).not.toBeNull(); + + const agy = card("agy"); + expect(agy.querySelector("[data-integration-state='current']")).not.toBeNull(); + expect(agy.textContent).toContain("not created yet"); + expect(agy.textContent).toContain("Restart agy to pick up the change."); + expect(agy.querySelector("input")).toBeNull(); + expect(button(antigravity, "Disconnect").disabled).toBe(true); +}); + +test("connect sends the typed model, shows the server message and rereads status", async () => { + await mount(); + const antigravity = card("antigravity"); + const input = antigravity.querySelector("input") as HTMLInputElement; + const setValue = Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!; + await act(async () => { + setValue.call(input, " gemini-3.8-flash "); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); + }); + const readsBefore = requests.filter(request => request.method === "GET").length; + await act(async () => { button(antigravity, "Connect").click(); }); + await settle(); + + const post = requests.find(request => request.method === "POST"); + expect(post?.url).toBe(`${apiBase}/api/gateway-clients/antigravity/connect`); + expect(JSON.parse(post?.body ?? "{}")).toEqual({ model: "gemini-3.8-flash" }); + expect(card("antigravity").querySelector(".notice-ok")?.textContent).toContain("Antigravity now uses OpenCodex."); + expect(requests.filter(request => request.method === "GET").length).toBeGreaterThan(readsBefore); +}); + +test("a refusal shows the server's own message", async () => { + actionResponse = () => json({ ok: false, code: "unsupported-file", message: "settings.json is not a JSON object; left untouched." }, 409); + await mount(); + await act(async () => { button(card("agy"), "Disconnect").click(); }); + await settle(); + expect(requests.find(request => request.method === "POST")?.url).toBe(`${apiBase}/api/gateway-clients/agy/disconnect`); + expect(card("agy").querySelector(".notice-err")?.textContent).toContain("settings.json is not a JSON object; left untouched."); +}); From 9cb1ce31a6b18291bc3f9767d7a2512991a912c0 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:32:53 -0500 Subject: [PATCH 8/9] fix(gateway-clients): state what is known about agy's gateway support on Windows --- src/integrations/gateway-clients/agy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/integrations/gateway-clients/agy.ts b/src/integrations/gateway-clients/agy.ts index 57317f7f5bd..8af133da64c 100644 --- a/src/integrations/gateway-clients/agy.ts +++ b/src/integrations/gateway-clients/agy.ts @@ -105,7 +105,7 @@ function status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClien const env = envGatewayOverride(ctx, target?.url); if (env) overrides.push({ source: "env", detail: env }); const notes = ["Open a new terminal to pick up the agy function.", "Gateway support needs agy 1.2.15 or newer."]; - if (ctx.platform === "win32") notes.push("Google lists agy for macOS and Linux only; on Windows this works only where an agy build runs, so treat it as untested."); + if (ctx.platform === "win32") notes.push("Google documents the agy gateway for macOS and Linux. The Windows build also reads the AGY_LLM_GATEWAY_* settings, but this path has not been verified end to end on Windows."); if (ctx.env.AGY_LLM_GATEWAY_URL?.trim()) notes.push("AGY_LLM_GATEWAY_URL is exported globally in the environment OpenCodex sees; the agy function overrides it for agy only."); return { id: ID, label: "agy CLI", state, files: rows, overrides, notes }; } From f68ec45de13c47270f65a3528ecdc09a421d9b52 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:45:46 -0500 Subject: [PATCH 9/9] fix(gateway-clients): reject control characters in the model selector without a lint suppression --- src/integrations/gateway-clients/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/integrations/gateway-clients/index.ts b/src/integrations/gateway-clients/index.ts index 25482af1db0..99743868cab 100644 --- a/src/integrations/gateway-clients/index.ts +++ b/src/integrations/gateway-clients/index.ts @@ -32,8 +32,8 @@ export function resolveGatewayTarget(config: Pick 200 || /[\x00-\x1f\x7f]/.test(defaultModel))) { + const hasControlChar = defaultModel !== undefined && [...defaultModel].some((ch) => ch.charCodeAt(0) < 0x20 || ch.charCodeAt(0) === 0x7f); + if (defaultModel !== undefined && (defaultModel.length === 0 || defaultModel.length > 200 || hasControlChar)) { return { ok: false, code: "invalid-model", message: "The model selector must be a non-empty single-line string of at most 200 characters." }; } return { ok: true, target: { url: destination.origin, apiKey: GATEWAY_PLACEHOLDER_KEY, ...(defaultModel ? { defaultModel } : {}) } };