diff --git a/packages/antigravity/README.md b/packages/antigravity/README.md index 6ee3eee..e69b45e 100644 --- a/packages/antigravity/README.md +++ b/packages/antigravity/README.md @@ -69,14 +69,24 @@ up. ## Requests The plugin sends every request to `v1internal:streamGenerateContent`, -wrapped in the app's envelope (`{model, project, userAgent: "antigravity", -requestType: "agent", requestId, request}`): +wrapped in the app's envelope, keys in the order the app's language server +sends them (`{project, requestId, request, model, userAgent: "antigravity", +requestType: "agent"}`, captured from 2.32.1): -- The User-Agent is `antigravity/hub/ /`. The version is +- The User-Agent is the language server's: `antigravity/hub/ + (aidev_client; os_type=; arch=; cl=)`. The version is read from the app's update manifest every 6 hours. Google lists Gemini 4 only to new enough releases, so a manifest that can't be read is asked again after a minute, and the model list is read again when the version - changes. + changes. The changelist is each release's own, from a table in the + plugin; a release newer than the table goes with the newest one known. +- A conversation is one cascade: `requestId` is + `agent////`, and `request.labels` carries the + cascade and trajectory ids, the step, the model's enum from + `fetchAvailableModels` and whether it is Claude or not Gemini, as the app + labels its requests. +- `onboardUser` is asked as the language server asks it: + `{tierId, metadata: {ideType: "ANTIGRAVITY"}}`. - The session id is a number made from the host's session header when named, else the conversation's first real user prompt (skipping injected `AGENTS.md` and environment preambles), so unrelated conversations that diff --git a/packages/antigravity/index.mjs b/packages/antigravity/index.mjs index 8ce6541..d1c0f12 100644 --- a/packages/antigravity/index.mjs +++ b/packages/antigravity/index.mjs @@ -38,6 +38,7 @@ const SCOPES = [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/cclog", "https://www.googleapis.com/auth/experimentsandconfigs", + "https://www.googleapis.com/auth/aicode", ] const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth" const TOKEN_URL = "https://oauth2.googleapis.com/token" @@ -53,9 +54,14 @@ const BASE = DAILY + "/v1beta" const NPM = "@ai-sdk/google" const VERSION_URL = "https://antigravity-hub-auto-updater-974169037036.us-central1.run.app/manifest/latest-arm64-mac.yml" -// the manifest's version on 2026-11-12; Google serves Gemini 4 only to +// the manifest's version on 2026-11-14; Google serves Gemini 4 only to // releases about this new (2.9.1 got no Gemini 4, #1057) -const DEFAULT_VERSION = "2.31.2" +const DEFAULT_VERSION = "2.32.1" +// CLS is the build changelist each release's language server puts in its +// User-Agent (cl=), read from the shipped binary's requests. The manifest +// names only the version, so a newer release goes with the newest known +// changelist until it is added here. +const CLS = { "2.32.1": "1021296516" } const SIGN_IN_TIMEOUT = 10 * 60 * 1000 const MODELS_TTL = 10 * 60 * 1000 @@ -107,7 +113,8 @@ class SignedOut extends Error {} const GOOS = { darwin: "darwin", linux: "linux", win32: "windows" } const GOARCH = { arm64: "arm64", x64: "amd64" } -const platform = () => `${GOOS[process.platform] ?? process.platform}/${GOARCH[process.arch] ?? process.arch}` +const goos = () => GOOS[process.platform] ?? process.platform +const goarch = () => GOARCH[process.arch] ?? process.arch const ver = { v: "", at: 0, pending: null } @@ -146,7 +153,28 @@ async function version() { return ver.pending } -const userAgent = async () => `antigravity/hub/${await version()} ${platform()}` +// clOf is the changelist of a release: its own when known, else the +// newest known release's +function clOf(v) { + if (CLS[v]) return CLS[v] + const newest = Object.keys(CLS).sort((a, b) => cmpVersion(b, a))[0] + return CLS[newest] +} + +function cmpVersion(a, b) { + const x = a.split(".").map(Number) + const y = b.split(".").map(Number) + for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0) + return 0 +} + +// userAgent is the app's language server's, as 2.32.1 sends it on every +// Code Assist call: +// antigravity/hub/2.32.1 (aidev_client; os_type=darwin; arch=arm64; cl=1021296516) +const userAgent = async () => { + const v = await version() + return `antigravity/hub/${v} (aidev_client; os_type=${goos()}; arch=${goarch()}; cl=${clOf(v)})` +} // ---- the sign-in as it is kept --------------------------------------------------------- @@ -284,12 +312,9 @@ async function resolveProject(s) { if (own) return { id: own, plan: planOf(load), tier, paid, credits, at: Date.now() } const t = { ...defaultTier(load) } if (!t.id || t.id === "legacy-tier") t.id = "free-tier" - const ua = await userAgent() - const id = await onboard( - s, - { tier_id: t.id, metadata: { ide_type: "ANTIGRAVITY", ide_version: await version(), ide_name: "antigravity" } }, - { "User-Agent": ua + " google-api-nodejs-client/10.3.0", "X-Goog-Api-Client": "gl-node/22.21.1" }, - ) + // as the app's language server asks it: camelCase, the IDE type only, + // and no headers of its own + const id = await onboard(s, { tierId: t.id, metadata: { ideType: "ANTIGRAVITY" } }) if (!id) { const why = (load.ineligibleTiers ?? []).find((x) => x?.reasonMessage)?.reasonMessage throw new Error(why ? "Antigravity won't serve this Google account: " + why : "Antigravity hasn't set this Google account up (it gave no project); sign in to the Antigravity app with it once, then try again") @@ -415,6 +440,7 @@ function listed(res) { let out = [] for (const id of Object.keys(models).sort()) { const m = models[id] ?? {} + if (typeof m.model === "string" && m.model) enums.set(id, { model: m.model, provider: typeof m.modelProvider === "string" ? m.modelProvider : "" }) if (HIDDEN.has(id) || id.startsWith("chat_") || id.startsWith("tab_") || m.disabled) continue const mi = { id, name: m.displayName ?? "", context: m.maxTokens || 0, output: m.maxOutputTokens || 0, imageInput: typeof m.supportsImages === "boolean" ? m.supportsImages : undefined, remaining: -1, resets: "" } if (isObj(m.quotaInfo)) { @@ -1202,15 +1228,58 @@ function sessionOf(req, headers) { return "-" + n.toString() } +// enums is each model id's enum and maker, as fetchAvailableModels lists +// them (gemini-3-flash is MODEL_PLACEHOLDER_M18, made by +// MODEL_PROVIDER_GOOGLE); the app labels each request with them +const enums = new Map() + +// uuidOf is a UUID-shaped id made from text, the same for the same text +function uuidOf(text) { + const h = crypto.createHash("sha256").update(text).digest("hex") + return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}` +} + +// envelope is the request as the app's language server sends it, keys in +// its order (2.32.1): project, requestId, request, model, userAgent, +// requestType. A conversation is one cascade with one trajectory, so its +// ids are made from its session; the step is how far into it the request +// is. function envelope(req, sent, projectID, credits = false, headers = undefined) { + const sessionId = sessionOf(req, headers) + const rawSession = headerOf(headers, SESSION).trim() + const cascade = uuidOf("cascade\0" + sessionId) + const root = headerOf(headers, SUBAGENT).trim() && rawSession ? uuidOf("cascade\0" + rawSession) : cascade + const trajectory = uuidOf("trajectory\0" + sessionId) + const contents = Array.isArray(req?.contents) ? req.contents : [] + const step = Math.max(0, contents.length - 1) + const turns = contents.filter((c) => c?.role === "model").length + const known = enums.get(sent) + const claude = known?.provider === "MODEL_PROVIDER_ANTHROPIC" || /^claude/.test(sent) + const gemini = known ? known.provider === "MODEL_PROVIDER_GOOGLE" : /^gemini/.test(sent) + const labels = { + cascade_id: cascade, + last_step_index: String(step), + ...(known ? { model_enum: known.model } : {}), + request_id: `${trajectory}-${turns}`, + root_cascade_id: root, + trajectory_id: trajectory, + used_claude: String(claude), + used_claude_conservative: String(claude), + used_non_gemini_model: String(!gemini), + } + // the request's own keys in the app's order, labels before + // generationConfig, the session last + const { sessionId: _, labels: __, contents: c, systemInstruction, tools, toolConfig, generationConfig, ...rest } = isObj(req) ? req : {} + const request = { contents: c, systemInstruction, tools, toolConfig, ...rest, labels, generationConfig, sessionId } + for (const k of Object.keys(request)) if (request[k] === undefined) delete request[k] return { - model: sent, project: projectID, + requestId: `agent/${cascade}/${Date.now()}/${trajectory}/${step + 1}`, + request, + model: sent, ...(credits ? { enabled_credit_types: [CREDIT] } : {}), userAgent: "antigravity", requestType: "agent", - requestId: "agent-" + crypto.randomBytes(6).toString("hex"), - request: { ...req, sessionId: sessionOf(req, headers) }, } } @@ -1452,7 +1521,7 @@ async function complete(s, url, init, magpie) { const send = (credits) => fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { method: "POST", - headers: { "Content-Type": "application/json", Accept: "text/event-stream", Authorization: "Bearer " + tok, "User-Agent": ua }, + headers: { "Content-Type": "application/json", Authorization: "Bearer " + tok, "User-Agent": ua }, body: JSON.stringify(envelope(req, sent, l.project.id, credits, init?.headers)), signal: init?.signal, }) @@ -2048,7 +2117,7 @@ async function webSearch({ query, count } = {}, ctx = {}) { const ua = await userAgent() const res = await fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { method: "POST", - headers: { "Content-Type": "application/json", Accept: "text/event-stream", Authorization: "Bearer " + tok, "User-Agent": ua }, + headers: { "Content-Type": "application/json", Authorization: "Bearer " + tok, "User-Agent": ua }, body: JSON.stringify(envelope(req, sent, l.project.id, false)), signal: ctx.abort, }) @@ -2191,4 +2260,8 @@ export const _internal = { VERSION_TTL, VERSION_RETRY, DEFAULT_VERSION, + CLS, + clOf, + enums, + userAgent, } diff --git a/packages/antigravity/package.json b/packages/antigravity/package.json index 78f712f..dd27e22 100644 --- a/packages/antigravity/package.json +++ b/packages/antigravity/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-antigravity-auth", - "version": "0.1.14", + "version": "0.1.15", "description": "Sign in to Antigravity with a Google account from OpenCode or magpie: Gemini, and the Claude and GPT-OSS models Google hosts for it", "type": "module", "main": "./opencode.mjs", diff --git a/packages/antigravity/requests.test.mjs b/packages/antigravity/requests.test.mjs index 828b5f2..6d31330 100644 --- a/packages/antigravity/requests.test.mjs +++ b/packages/antigravity/requests.test.mjs @@ -39,8 +39,11 @@ test("a request goes in Antigravity's envelope, and its stream comes back Gemini const sent = seen.find((s) => s.name === "streamGenerateContent") expect(sent.url).toBe("https://daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse") expect(sent.headers.authorization).toBe("Bearer tok") - expect(sent.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \w+\/\w+$/) + // as the app's language server sends it (2.32.1, captured) + expect(sent.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \(aidev_client; os_type=(darwin|linux|windows); arch=(arm64|amd64); cl=\d+\)$/) + expect(sent.headers.accept).toBeUndefined() expect(sent.json).toMatchObject({ model: "gemini-3.7-flash-low", project: "ag-proj", userAgent: "antigravity", requestType: "agent" }) + expect(Object.keys(sent.json)).toEqual(["project", "requestId", "request", "model", "userAgent", "requestType"]) expect(sent.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: "low" }) expect(sent.json.request.sessionId).toMatch(/^-\d+$/) // models are read once @@ -128,9 +131,10 @@ test("an account with no project is set up for its default tier", async () => { expect(load.url).toBe("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist") expect(load.json).toEqual({ metadata: { ideType: "ANTIGRAVITY" } }) const on = seen.find((s) => s.name === "onboardUser") - expect(on.json).toEqual({ tier_id: "free-tier", metadata: { ide_type: "ANTIGRAVITY", ide_version: "3.1.4", ide_name: "antigravity" } }) - expect(on.headers["user-agent"]).toEndWith(" google-api-nodejs-client/10.3.0") - expect(on.headers["x-goog-api-client"]).toBe("gl-node/22.21.1") + // as 2.32.1's language server asks it (captured) + expect(on.json).toEqual({ tierId: "free-tier", metadata: { ideType: "ANTIGRAVITY" } }) + expect(on.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \(aidev_client; [^)]*\)$/) + expect(on.headers["x-goog-api-client"]).toBeUndefined() expect(seen.find((s) => s.name === "streamGenerateContent").json.project).toBe("ag-new") }) diff --git a/packages/antigravity/shape.test.mjs b/packages/antigravity/shape.test.mjs index f458170..acf6839 100644 --- a/packages/antigravity/shape.test.mjs +++ b/packages/antigravity/shape.test.mjs @@ -216,10 +216,41 @@ test("a conversation keeps its session", () => { expect(sessionOf({ contents: [{ role: "user", parts: [{ text: "other" }] }] })).not.toBe(sessionOf(a)) const env = envelope(a, "gemini-3-flash", "ag-proj") expect(env).toMatchObject({ model: "gemini-3-flash", project: "ag-proj", userAgent: "antigravity", requestType: "agent" }) - expect(env.requestId).toMatch(/^agent-[0-9a-f]{12}$/) expect(env.request.sessionId).toBe(sessionOf(a)) }) +test("the envelope is the app's: key order, request id and labels", () => { + const { enums } = _internal + enums.set("gemini-3-flash", { model: "MODEL_PLACEHOLDER_M18", provider: "MODEL_PROVIDER_GOOGLE" }) + enums.set("claude-sonnet-4-6", { model: "MODEL_PLACEHOLDER_M35", provider: "MODEL_PROVIDER_ANTHROPIC" }) + const a = { generationConfig: { maxOutputTokens: 9 }, contents: [{ role: "user", parts: [{ text: "hello there" }] }], systemInstruction: { role: "user", parts: [{ text: "s" }] } } + const env = envelope(a, "gemini-3-flash", "ag-proj") + expect(Object.keys(env)).toEqual(["project", "requestId", "request", "model", "userAgent", "requestType"]) + expect(Object.keys(env.request)).toEqual(["contents", "systemInstruction", "labels", "generationConfig", "sessionId"]) + const u = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" + expect(env.requestId).toMatch(new RegExp(`^agent/${u}/\\d{13}/${u}/1$`)) + const l = env.request.labels + expect(Object.keys(l)).toEqual(["cascade_id", "last_step_index", "model_enum", "request_id", "root_cascade_id", "trajectory_id", "used_claude", "used_claude_conservative", "used_non_gemini_model"]) + expect(l).toMatchObject({ last_step_index: "0", model_enum: "MODEL_PLACEHOLDER_M18", request_id: l.trajectory_id + "-0", root_cascade_id: l.cascade_id, used_claude: "false", used_non_gemini_model: "false" }) + expect(env.requestId).toBe(`agent/${l.cascade_id}/${env.requestId.split("/")[2]}/${l.trajectory_id}/1`) + // the same conversation, further on: same ids, later step + const b = { contents: [...a.contents, { role: "model", parts: [{ text: "hi" }] }, { role: "user", parts: [{ text: "more" }] }] } + const later = envelope(b, "claude-sonnet-4-6", "ag-proj").request.labels + expect(later).toMatchObject({ cascade_id: l.cascade_id, trajectory_id: l.trajectory_id, last_step_index: "2", request_id: l.trajectory_id + "-1", model_enum: "MODEL_PLACEHOLDER_M35", used_claude: "true", used_non_gemini_model: "true" }) + // a model not listed yet has no enum, and its maker is read from its id + const unknown = envelope(a, "gpt-oss-120b-medium", "ag-proj").request.labels + expect(unknown.model_enum).toBeUndefined() + expect(unknown.used_non_gemini_model).toBe("true") +}) + +test("the user agent is the language server's, with the release's changelist", async () => { + const { clOf, CLS } = _internal + expect(clOf("2.32.1")).toBe(CLS["2.32.1"]) + // a release newer than every known one goes with the newest known changelist + const newest = Object.keys(CLS).sort((x, y) => (x < y ? 1 : -1))[0] + expect(clOf("9.0.0")).toBe(CLS[newest]) +}) + test("sessions with shared AGENTS.md preambles or distinct host headers don't collide", () => { const preamble = [ { text: "# AGENTS.md instructions\n\nglobal" },