From 003a38ff44734982e690a5f768108a5a655a7095 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 11:10:03 +0800 Subject: [PATCH] antigravity 0.2.0: retired, sends nothing and points to Antigravity (local agy CLI) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Google bans accounts it sees calling Code Assist the way this plugin did (Antigravity's own OAuth client, straight to cloudcode-pa), and as the plugin magpie offered for Antigravity it was the one everyone installed (the owner, 11-15: 全部下线,改推 agy-cli). Antigravity is served by @magpie-community/opencode-agy-cli-auth now, which drives the user's own agy over ACP. From 0.2.0 the package makes no request at all. Every request gets a 410 {"error":{"status":"ModelDeprecated","message":"Antigravity: this model has been retired. …"}} naming Antigravity (local agy CLI) and its magpie plugin add command; magpie's modelRetired reads that as a retired model, so a routing group asks its next member. Signing in throws the same words; there are no models, usage, options or web search. The provider id stays, so magpie's mover (raised to 0.2.0 there) lands moved users here and their account rows show the message. registry.json drops the antigravity entry, so Discover no longer offers it. agy-cli's cloak.mjs was a copy kept equal to antigravity's by cloak.test.mjs; it is the only copy now, and the parity tests become tests of cloak.mjs alone (the invisible-character and REWORDED cases are kept). agy-cli's version is unchanged (comments and tests only). What users lose: multi-account rotation, the in-plugin Google sign-in and account import, AI-credit spending, Antigravity web search, and a provider that works without agy installed. Run (mote, temp HOME): bun scripts/check.mjs all ✓; bun test packages/antigravity packages/agy-cli scripts: 79 pass, 0 fail. retired.test.mjs replaces fetch with one that throws and checks nothing was asked on any path. Not tried: a magpie with a moved account on 0.2.0 (done on the magpie side's commit). --- packages/agy-cli/cloak.mjs | 4 +- packages/agy-cli/cloak.test.mjs | 41 +- packages/antigravity/README.md | 194 +- packages/antigravity/fake.mjs | 44 - packages/antigravity/index.mjs | 2346 +----------------------- packages/antigravity/models.test.mjs | 111 -- packages/antigravity/package.json | 4 +- packages/antigravity/requests.test.mjs | 482 ----- packages/antigravity/retired.test.mjs | 54 + packages/antigravity/schema.test.mjs | 123 -- packages/antigravity/search.test.mjs | 173 -- packages/antigravity/shape.test.mjs | 339 ---- packages/antigravity/usage.test.mjs | 188 -- packages/antigravity/version.test.mjs | 61 - registry.json | 2 - 15 files changed, 134 insertions(+), 4032 deletions(-) delete mode 100644 packages/antigravity/fake.mjs delete mode 100644 packages/antigravity/models.test.mjs delete mode 100644 packages/antigravity/requests.test.mjs create mode 100644 packages/antigravity/retired.test.mjs delete mode 100644 packages/antigravity/schema.test.mjs delete mode 100644 packages/antigravity/search.test.mjs delete mode 100644 packages/antigravity/shape.test.mjs delete mode 100644 packages/antigravity/usage.test.mjs delete mode 100644 packages/antigravity/version.test.mjs diff --git a/packages/agy-cli/cloak.mjs b/packages/agy-cli/cloak.mjs index 9364f7a..f16036a 100644 --- a/packages/agy-cli/cloak.mjs +++ b/packages/agy-cli/cloak.mjs @@ -1,8 +1,8 @@ // System prompt lines Antigravity turns away, and paragraphs it answers // badly, the same lists and the same rewrites as -// packages/antigravity/index.mjs (TURNED_AWAY, SAID_AS, cloak, hint, +// packages/antigravity/index.mjs up to 0.1.18 (TURNED_AWAY, SAID_AS, cloak, hint, // REWORDED, reword, outgoing). Each package ships on its own, so the code is -// a copy; cloak.test.mjs fails when the two give a different answer. +// a copy, and since antigravity 0.2.0 sends nothing this is the only one. // // Antigravity answers a 429 "Resource has been exhausted" to a request whose // system prompt has one of these lines, whatever quota is left, and lets the diff --git a/packages/agy-cli/cloak.test.mjs b/packages/agy-cli/cloak.test.mjs index da7a9a7..d378ddc 100644 --- a/packages/agy-cli/cloak.test.mjs +++ b/packages/agy-cli/cloak.test.mjs @@ -1,9 +1,8 @@ -// cloak.mjs is a copy of packages/antigravity's TURNED_AWAY, cloak and hint -// (#980) and its REWORDED (#1028): these fail when the two packages stop -// agreeing. +// cloak.mjs began as a copy of packages/antigravity's TURNED_AWAY, cloak and +// hint (#980) and its REWORDED (#1028). antigravity 0.2.0 sends nothing any +// more, so cloak.mjs is the one copy now. import { expect, test } from "bun:test" import { REWORDED, TURNED_AWAY, cloak, cloakUser, hint, outgoing, turnsAway } from "./cloak.mjs" -import { _internal as antigravity } from "../antigravity/index.mjs" const ZW = "​" @@ -57,25 +56,15 @@ test("a turned-away line wrapped or widened by white space is reworded too", () expect(turnsAway(samples[10])).toBe(false) }) -test("agy-cli and antigravity reword and explain the same lines", () => { +test("a turned-away line broken up by invisible characters is reworded too", () => { for (const line of [...TURNED_AWAY, ...samples.filter((s) => turnsAway(s)).map((s) => s.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + ZW + w[1] + ZW + w.slice(2)))]) { - expect(antigravity.turnsAway(line)).toBe(true) - expect(cloak(line)).toBe(antigravity.cloak(line)) - expect(hint(line)).toBe(antigravity.hint(line)) - } - for (const s of samples) { - expect(turnsAway(s)).toBe(antigravity.turnsAway(s)) - expect(cloak(s)).toBe(antigravity.cloak(s)) - expect(hint(s)).toBe(antigravity.hint(s)) + expect(turnsAway(line)).toBe(true) + expect(turnsAway(cloak(line))).toBe(false) } }) const DSH = "Tokens prefixed with @ are paths the user explicitly referenced. Relative paths resolve from the workspace root; absolute paths identify files or directories on the host. A trailing slash marks a directory: list it when its contents matter. Anything else is a file: use the read tool when its contents are needed, and do not claim to have inspected it before reading. @\"...\" quotes a path containing spaces." -// the system text antigravity sends for s (its shape() runs outgoing on it) -const antigravitySends = (s) => - antigravity.shape({ systemInstruction: { parts: [{ text: s }] }, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts[0].text - test("DeepSeek Harness's @-path paragraph goes reworded, the rest as written (#1028)", () => { const sys = "You are DeepSeek Harness.\n\n" + DSH + "\n\nBe brief." expect(outgoing(sys)).toBe("You are DeepSeek Harness.\n\nWhen the user writes @ followed by a path, they are pointing at that file or folder. Relative paths start at the workspace root; absolute paths are host paths. A path ending in a slash is a folder, so list it if its contents matter; otherwise it is a file, so open it with the read tool before relying on it. Paths with spaces appear as @\"...\".\n\nBe brief.") @@ -85,23 +74,11 @@ test("DeepSeek Harness's @-path paragraph goes reworded, the rest as written (#1 expect(both).toContain("When the user writes @ followed by a path") }) -test("agy-cli and antigravity send the same system text, reworded", () => { - for (const [from, to] of REWORDED) { - expect(outgoing(from)).toBe(to) - expect(antigravitySends(from)).toBe(to) - } - for (const s of [...samples.filter(Boolean), DSH, "Lead.\n" + DSH + "\n" + DSH, "x-anthropic-billing-header: cc\n" + DSH]) { - expect(outgoing(s)).toBe(antigravitySends(s)) - } +test("each reworded paragraph goes as REWORDED says", () => { + for (const [from, to] of REWORDED) expect(outgoing(from)).toBe(to) }) -// the user's text antigravity sends for s (its shape() rewords Codex's -// GPT-5 lines in every non-model part) -const antigravitySendsUser = (s) => - antigravity.shape({ contents: [{ role: "user", parts: [{ text: s }] }] }, "gemini-3-flash", "", "").contents[0].parts[0].text - -test("a user's turn goes with Codex's GPT-5 lines reworded, as antigravity sends it", () => { +test("a user's turn goes with Codex's GPT-5 lines reworded, the others as written", () => { expect(cloakUser("Read AGENTS.md:\nYou are Codex, a coding agent based on GPT-5.")).toBe("Read AGENTS.md:\nYou are Codex, a coding agent built on GPT-5.") expect(cloakUser("You are Hermes Agent, built by Nous Research.")).toBe("You are Hermes Agent, built by Nous Research.") - for (const s of samples.filter(Boolean)) expect(cloakUser(s)).toBe(antigravitySendsUser(s)) }) diff --git a/packages/antigravity/README.md b/packages/antigravity/README.md index 3daadb6..7045799 100644 --- a/packages/antigravity/README.md +++ b/packages/antigravity/README.md @@ -1,178 +1,30 @@ -# @magpie-community/opencode-antigravity-auth +# @magpie-community/opencode-antigravity-auth (retired) -Signs in to **Antigravity** with a Google account (Google AI Pro, Ultra or -the free tier) and calls the models Antigravity serves: Gemini, and the -Claude and GPT-OSS models Google hosts for it. Requests go through Google's -Code Assist API (`daily-cloudcode-pa.googleapis.com`) the way the -Antigravity app sends them. Provider id: `antigravity`. Ported from -magpie's built-in Antigravity account. +**Retired in 0.2.0. Use [Antigravity (local agy CLI)](../agy-cli/README.md), +`@magpie-community/opencode-agy-cli-auth`, instead.** -## Sign-in +Up to 0.1.18 this plugin signed in to Antigravity with a Google account and +sent requests to Google's Code Assist API (`cloudcode-pa.googleapis.com`) +the way the Antigravity app does. Google bans accounts it sees used that +way. Antigravity (local agy CLI) runs the `agy` CLI you installed and signed +in to, over the Agent Client Protocol (`agy acp`), so the requests Google +sees are agy's own. -There are two ways to sign in: +From 0.2.0 this package sends no request at all: -- **Sign in with Google (browser)** is Antigravity's own Google sign-in: - 1. The plugin listens on a port of `127.0.0.1` (and `::1`). - 2. It opens Google's consent page with PKCE and Antigravity's client and - scopes. - 3. Google sends the browser back to `/oauth-callback` with a code, which - the plugin trades for a refresh token. -- **Import an account** takes either a refresh token or the JSON an - account manager exports: - - one account (`{"email", "token": {"refresh_token", "project_id"}}`); - - a list of accounts, or an `{"accounts": […]}` object; - - plain lines of refresh tokens, where `#` starts a comment. +- every request is answered `410` with a message that says to install + Antigravity (local agy CLI). magpie reads it as a retired model, so a + routing group goes on to its next member; +- signing in is turned away with the same message; +- it lists no models, usage or web search. - The import signs in the first account it finds. An export of another - subscription (a `type` other than Antigravity) is refused. +To move: -The sign-in is kept as an `oauth` entry: -- `refresh` is `|`. -- `access` is the access token, minted again from the refresh token when - less than two minutes of it are left. -- `accountId` is the account's email. +```sh +magpie plugin add @magpie-community/opencode-agy-cli-auth +magpie plugin remove @magpie-community/opencode-antigravity-auth +``` -When Google refuses the refresh token (`invalid_grant`), magpie asks you to -sign in again. - -## Project and plan - -Code Assist serves an account under a project: - -- `loadCodeAssist` names the project. -- An account without one is set up for its default tier through - `onboardUser`, as the app does on first sign-in. -- The tiers are read again hourly, so a plan bought or lapsed shows up. -- The plan shown is the paid tier's name, else the current tier's. - -## Models - -`fetchAvailableModels` lists the account's models: - -- The plugin names the account's paid and current tiers, as the app does. -- A tier Google refuses with a 400 is left out for a day. -- The list is kept for 10 minutes. -- Antigravity's internal and retired models are left out. -- The list keeps the order of the app's picker. - -A model Antigravity lists at several levels (`gemini-3.7-flash-low`, -`-medium`, `-high`) is offered as one model, with a variant per level. -A request picks the level in this order: - -1. magpie's `x-magpie-effort` header; -2. the variant's `thinkingLevel`; -3. the model's default level, which is high. - -Asking for a level the model lacks picks the nearest one, and a tie goes -up. - -## Requests - -The plugin sends every request to `v1internal:streamGenerateContent`, -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 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. 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 - share a preamble don't collide on one session. -- Each reply chunk (`{response: …}`) is unwrapped back into Gemini's own. -- A `generateContent` request gets the stream read whole. - -The plugin also changes the request itself, as the built-in did: - -- **System prompt:** lines Antigravity turns away with a 429 whatever quota - is left go reworded with the same meaning, since Google's check reads past - zero-width spaces (11-14): Claude Code's billing header is left out, the - Claude Agent SDK's "built on Anthropic's Claude Agent SDK" (Claude - Desktop's Code tab and its subagents) goes as "built on the Claude Agent - SDK by Anthropic", Codex's GPT-5 lines say "built on GPT-5", omp's line - "RFC 2119 key words: …", Hermes Agent's persona, OpenCode's prompt and - Codex's prompt for a model it has none for go as "You're …" for "You are - Hermes Agent" / "You are OpenCode" / "You are a coding agent running in - the Codex CLI", and pi's default prompt as "running within pi" for - "running inside pi" (the last four turned away since 11-14). A copy - someone broke up with invisible characters is reworded the same way. - DeepSeek Harness's paragraph on `@` paths ("Tokens prefixed with @ are - paths…") goes reworded with the same meaning: word for word, it got most - `gemini-4-argon` answers fast, without thinking and shallow (#1028). -- **Tool calls:** - - Tool call ids are reduced to `[A-Za-z0-9_-]`. - - A tool's `{output}` or `{error}` response becomes `{result}`. -- **Schemas:** a tool's schema is flattened to the subset Antigravity takes. - - Unions keep their own shape. - - Every array gets `items`. - - `null` types become `nullable`. - - `$ref` is resolved. - - Blank enum values are dropped. -- **Claude:** - - A tool's images follow every function response. - - `AUTO` function calling becomes `VALIDATED`. - - A model without "thinking" in its name loses `thinkingConfig`. -- **Gemini:** - - `maxOutputTokens` is dropped. - - Gemini 3 and later think at a `thinkingLevel`. Earlier models lose a - level a variant put on them. - -## Errors - -| What Antigravity answers | What the plugin answers | -|---|---| -| 429 "Resource has been exhausted" to a system prompt with a turned-away line | 400 "turned this request away as from an unapproved channel", with what to change (it isn't a quota, so nothing is rested) | -| 429 from a plan's quota, the account having Google AI credits | with the Use AI credits switch on (off by default), the request is asked again once with `enabled_credit_types: ["GOOGLE_ONE_AI"]`, as the app's Use AI Credits does; with it off, the 429 says the switch would spend them | -| Gemini 4's 400 INVALID_ARGUMENT after it ran (in the stream after thinking, or a slow 400) | asked again, up to twice. A stream's thinking is held back for up to 10 seconds, or until the answer starts, so a retry sends nothing twice; past 10 seconds the thinking streams live, and a 400 after that reaches the client. Code Assist writes the stream's error as a bare JSON line with no `data:`, read as well. A 400 that still comes says the model turned down a call it built, and how many times it was asked, since Google's words alone read as a region or account block | -| 401 | 401, sign-in kept | -| 404 | 404 "model … not found" | -| Refresh refused | 401, `x-magpie-sign-in: expired` | - -## Usage - -Each model has a window from its `quotaInfo`: - -- The window reads 100% used when Antigravity leaves the fraction out. -- It says the model's family (Gemini, Claude, GPT-OSS). -- For a level, it also names the model magpie offers. - -Then `retrieveUserQuotaSummary`'s groups give the pools that models share, -each with a 5-hour and a 7-day window (`aside`). Each model is put in the -pool it reads from: - -- a group whose versioned name is the model's own (Gemini 4 Argon); -- else the group of its family, when the model reads like one of that - group's windows; -- else a pool of its own, named for the model, when it reads otherwise. - -## Web Search - -The plugin registers a magpie `search` hook (`antigravity:antigravity`) -backed by Antigravity's Google Search grounding (`tools: [{ googleSearch: {} }]` -on an available Flash model with minimal/zero thinking on the signed-in -Antigravity account), returning grounded pages with URLs and snippets. - -## Not carried over from the built-in - -- Resting an account that Antigravity turned away for 6 hours, and asking - its other accounts first. The 400 above makes magpie try the next - account at once. -- Image models (drawing) as an OpenAI images endpoint. -- `countTokens` answers 404, so magpie estimates the count. -- Sending the system prompt as written: the plugin always breaks up the - turned-away lines. -- Importing many accounts at once: an import signs in one account. -- Model names from models.dev: a model Antigravity leaves unnamed is named - for its id. +Then sign in to agy once (Plugins › Antigravity (local agy CLI) › Sign in, +or `agy` in a terminal). Antigravity (local agy CLI) serves the one Google +account agy is signed in to. diff --git a/packages/antigravity/fake.mjs b/packages/antigravity/fake.mjs deleted file mode 100644 index 92f1662..0000000 --- a/packages/antigravity/fake.mjs +++ /dev/null @@ -1,44 +0,0 @@ -// A fake Google for the tests: OAuth's token endpoint, the update -// manifest and Code Assist's methods, each answered from `replies`. -import { _internal } from "./index.mjs" - -export const real = globalThis.fetch - -export function reset() { - for (const m of [_internal.tokens, _internal.projects, _internal.lists, _internal.refused]) m.clear() - _internal.ver.v = "3.1.4" - _internal.ver.at = Date.now() - _internal.onboardPoll = 1 -} - -export function fake(replies = {}) { - const seen = [] - globalThis.fetch = async (input, init = {}) => { - const url = String(input) - const body = typeof init.body === "string" ? init.body : "" - const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v])) - const m = /\/v1internal:([a-zA-Z]+)/.exec(url) - const name = m ? m[1] : url.startsWith("https://oauth2.googleapis.com/token") ? "token" : url.includes("userinfo") ? "who" : url - seen.push({ name, url, body, headers, json: (() => { try { return JSON.parse(body) } catch { return undefined } })() }) - let r = replies[name] - if (typeof r === "function") r = r(seen[seen.length - 1], seen) - if (r === undefined) { - if (name === "token") r = { access_token: "tok-new", expires_in: 3600 } - else if (name === "loadCodeAssist") r = { cloudaicompanionProject: "ag-proj", currentTier: { id: "free-tier", name: "Antigravity" } } - else if (name === "fetchAvailableModels") r = { models: {} } - else if (name === "retrieveUserQuotaSummary") r = { groups: [] } - else return new Response("not found", { status: 404 }) - } - if (r instanceof Response) return r - return new Response(typeof r === "string" ? r : JSON.stringify(r), { status: 200, headers: { "content-type": "application/json" } }) - } - return seen -} - -export const auth = (project = "ag-proj") => ({ - type: "oauth", - access: "tok", - refresh: "rt-ag|" + project, - expires: Date.now() + 3600_000, - accountId: "ag@example.com", -}) diff --git a/packages/antigravity/index.mjs b/packages/antigravity/index.mjs index 12767d6..199bd45 100644 --- a/packages/antigravity/index.mjs +++ b/packages/antigravity/index.mjs @@ -1,2334 +1,76 @@ -// Antigravity (Google's agent IDE) for OpenCode and magpie: the models a -// Google account is served in Antigravity — Gemini, and the Claude and -// GPT-OSS models Google hosts for it — asked through Code Assist -// (cloudcode-pa.googleapis.com), as the Antigravity app asks them. Ported -// from magpie's built-in Antigravity account (internal/provider/google.go, -// antigravity_models.go, google_import.go and the Antigravity rules of -// internal/gateway/codeassist.go): +// Antigravity through a Google account, retired (0.2.0). // -// - Sign-in: Google's OAuth with Antigravity's own client, PKCE and a -// loopback redirect (http://localhost:/oauth-callback). The -// refresh token, and the Code Assist project the account is served -// under, are kept with the sign-in; access tokens are minted from it. -// - The project: loadCodeAssist names it, or onboardUser sets the -// account up for its default tier. -// - fetchAvailableModels lists the models and each one's share of its -// allowance left; retrieveUserQuotaSummary the shared pools. -// - streamGenerateContent takes the Gemini request wrapped in Code -// Assist's envelope ({model, project, request, …}) and streams each -// chunk wrapped as {response: }. +// Up to 0.1.18 this plugin signed in with Antigravity's own Google client +// and sent each request to Code Assist (cloudcode-pa) the way the +// Antigravity app does. Google bans accounts it sees used that way, and +// since this was the plugin magpie offered first, anyone who reached for +// Antigravity in magpie put their account at that risk. // -// Each model is declared on @ai-sdk/google, so the request the SDK writes -// (and the one magpie hands a plugin) is a plain Gemini request; the fetch -// below shapes it for Antigravity, wraps it, and unwraps the stream. - -import crypto from "node:crypto" -import http from "node:http" +// Antigravity is now served by "Antigravity (local agy CLI)", +// @magpie-community/opencode-agy-cli-auth, which runs the agy CLI the user +// installed and signed in to over the Agent Client Protocol (agy acp): the +// requests Google sees are agy's own. +// +// This version sends nothing anywhere. It keeps the provider id so an +// account moved onto it stays listed, and answers every request with a +// 410 that says where Antigravity went: magpie reads it as a retired model, +// so a routing group asks its next member. Signing in is turned away with +// the same words, and there are no models, usage or web search. const PROVIDER = "antigravity" - -// Antigravity's own installed-app OAuth client: it ships in the app, and -// Google says such a client's secret isn't one. Written in parts so secret -// scanners don't take it for a leak. -const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep" + ".apps.googleusercontent.com" -const CLIENT_SECRET = ["GOCSPX", "K58FWR486LdLJ1mLB8sXC4z6qDAf"].join("-") -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "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" -const WHO_URL = "https://www.googleapis.com/oauth2/v2/userinfo?alt=json" - -// loadCodeAssist is asked at the production endpoint, everything else at -// the daily one, as the app asks -const PROD = "https://cloudcode-pa.googleapis.com" -const DAILY = "https://daily-cloudcode-pa.googleapis.com" -// the base URL the AI SDK is given; the fetch sends every request to -// DAILY/v1internal, whatever path the SDK adds -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-14; Google serves Gemini 4 only to -// releases about this new (2.9.1 got no Gemini 4, #1057) -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 -const TIERS_TTL = 60 * 60 * 1000 -const TIER_REFUSED_FOR = 24 * 60 * 60 * 1000 -const VERSION_TTL = 6 * 60 * 60 * 1000 -// a manifest that couldn't be read is asked again this soon, not in six hours -const VERSION_RETRY = 60 * 1000 -const VERSION_TIMEOUT = 15 * 1000 - -// the header magpie names a request's effort in -const EFFORT = "x-magpie-effort" -const SESSION = "x-magpie-session" -const SUBAGENT = "x-magpie-subagent" - -// ---- small helpers ------------------------------------------------------------------ - -function parse(s) { - try { - return JSON.parse(s) - } catch { - return undefined - } -} - -const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) - -// apiError is what a failed reply says: its JSON error's message, or its -// body, or the status (magpie's APIError) -function apiError(body, status) { - const j = parse(body) - const m = isObj(j) ? (isObj(j.error) ? j.error.message : typeof j.error === "string" ? j.error : j.message) : undefined - if (typeof m === "string" && m.trim()) return m.trim() - const t = String(body ?? "").trim() - return t ? t.slice(0, 1000) : String(status) -} - -class StatusError extends Error { - constructor(status, message) { - super(message) - this.status = status - } -} - -class SignedOut extends Error {} - -// ---- the app's version and user agent ------------------------------------------------ - -const GOOS = { darwin: "darwin", linux: "linux", win32: "windows" } -const GOARCH = { arm64: "arm64", x64: "amd64" } -const goos = () => GOOS[process.platform] ?? process.platform -const goarch = () => GOARCH[process.arch] ?? process.arch - -const ver = { v: "", at: 0, pending: null } - -// version is the Antigravity release the requests say they come from, -// read from the app's own update manifest every six hours. Google lists -// and serves some models (Gemini 4) only to new enough releases, so a -// manifest that can't be read keeps the default for a minute only, and a -// version that changes drops the model lists read under the old one. -async function version() { - if (ver.v && Date.now() - ver.at < VERSION_TTL) return ver.v - if (ver.pending) return ver.pending - ver.at = Date.now() - if (!ver.v) ver.v = DEFAULT_VERSION - ver.pending = (async () => { - let read = "" - try { - const res = await fetch(VERSION_URL, { headers: { "User-Agent": "electron-builder" }, signal: AbortSignal.timeout(VERSION_TIMEOUT) }) - if (res.ok) { - const text = (await res.text()).slice(0, 64 << 10) - for (const line of text.split(/\r?\n/)) { - if (!line.startsWith("version:")) continue - const v = line.slice(8).trim().replace(/^['"]+|['"]+$/g, "") - if (v && /^[0-9.]+$/.test(v)) read = v - break - } - } - } catch {} - if (!read) ver.at = Date.now() - VERSION_TTL + VERSION_RETRY - else if (read !== ver.v) { - ver.v = read - lists.clear() - } - ver.pending = null - return ver.v - })() - return ver.pending -} - -// 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 --------------------------------------------------------- - -// A sign-in is kept as OpenCode's oauth entry: refresh is -// "|", access the last access token, accountId -// the Google account's email. -function stateOf(auth) { - if (auth?.type !== "oauth" || typeof auth.refresh !== "string" || !auth.refresh) return null - const i = auth.refresh.indexOf("|") - const rt = i < 0 ? auth.refresh : auth.refresh.slice(0, i) - const project = i < 0 ? "" : auth.refresh.slice(i + 1) - if (!rt) return null - return { rt, project, access: auth.access ?? "", expires: Number(auth.expires) || 0, who: auth.accountId ?? "" } -} - -const tokens = new Map() // refresh token → {access, expires} -const projects = new Map() // refresh token → project -const refused = new Map() // refresh token, project, tier → when Google refused the tier - -async function postForm(url, form) { - const res = await fetch(url, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams(form).toString(), - signal: AbortSignal.timeout(30_000), - }) - const text = await res.text() - if (!res.ok) throw new StatusError(res.status, apiError(text, res.status)) - return parse(text) ?? {} -} - -// token is an access token for s, minted again from its refresh token -// when less than two minutes of the last are left -async function token(s) { - let t = tokens.get(s.rt) - if (!t && s.access) t = { access: s.access, expires: s.expires } - if (t?.access && t.expires - Date.now() > 2 * 60 * 1000) return t.access - let fresh - try { - fresh = await postForm(TOKEN_URL, { grant_type: "refresh_token", refresh_token: s.rt, client_id: CLIENT_ID, client_secret: CLIENT_SECRET }) - } catch (e) { - // Google refusing the refresh token (invalid_grant) is a sign-in that - // is over; anything else (the network) may pass - if (e instanceof StatusError && (e.status === 400 || e.status === 401)) throw new SignedOut(`Antigravity is signed out (${e.message}); sign in again from magpie`) - throw e - } - if (!fresh.access_token) throw new SignedOut("Antigravity is signed out (no token); sign in again from magpie") - t = { access: fresh.access_token, expires: Date.now() + (Number(fresh.expires_in) || 3600) * 1000 } - tokens.set(s.rt, t) - return t.access -} - -// call is one of Code Assist's methods, its reply's JSON -async function call(s, base, method, body, headers = {}, signal) { - const tok = await token(s) - const res = await fetch(`${base}/v1internal:${method}`, { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer " + tok, "User-Agent": await userAgent(), ...headers }, - body: JSON.stringify(body), - signal: signal ?? AbortSignal.timeout(60_000), - }) - const text = (await res.text()).slice(0, 4 << 20) - if (res.status !== 200) throw new StatusError(res.status, `Antigravity: ${apiError(text, res.status)}`) - return parse(text) ?? {} -} - -// ---- the project and its tiers ------------------------------------------------------------- - -const companion = (p) => (typeof p === "string" ? p : isObj(p) && typeof p.id === "string" ? p.id : "") - -function tiersOf(load) { - return { tier: load?.currentTier?.id ?? "", paid: load?.paidTier?.id ?? "", credits: creditsOf(load) } -} - -// CREDIT is the credit type Google One plans (AI Pro, AI Ultra) buy for use -// after a plan's own quota is used up: the app's "Use AI Credits" -const CREDIT = "GOOGLE_ONE_AI" - -// creditsOf says whether a loadCodeAssist reply gives the account credits -// above the least amount that can pay for a request -function creditsOf(load) { - for (const c of load?.paidTier?.availableCredits ?? []) { - if (c?.creditType !== CREDIT) continue - // an amount the reply leaves out is not a lack of one - if (c.creditAmount == null) return true - const have = Number(c.creditAmount) - const need = Number(c.minimumCreditAmountForUsage ?? 0) - if (Number.isFinite(have) && have > 0 && (!Number.isFinite(need) || have >= need)) return true - } - return false -} - -// planOf is the plan a loadCodeAssist reply names: the paid tier's name, -// else the current tier's, else its id -function planOf(load) { - let t = load?.paidTier - if (!t || !t.name) t = load?.currentTier - if (!t) return "" - return t.name || t.id || "" -} - -function defaultTier(load) { - const allowed = Array.isArray(load?.allowedTiers) ? load.allowedTiers : [] - return allowed.find((t) => t?.isDefault) ?? allowed[0] ?? { id: "legacy-tier" } -} - -async function onboard(s, req, headers) { - for (let i = 0; i < 5; i++) { - const lro = await call(s, DAILY, "onboardUser", req, headers) - if (lro.done) return companion(lro.response?.cloudaicompanionProject) - await sleep(_internal.onboardPoll) - } - throw new Error("Antigravity: setting the account up for Code Assist is taking long; try again in a minute") -} - -const LOAD_BODY = { metadata: { ideType: "ANTIGRAVITY" } } - -// resolveProject finds the project the account is served under, setting -// the account up when Code Assist has none for it -async function resolveProject(s) { - let load, err - try { - load = await call(s, PROD, "loadCodeAssist", LOAD_BODY) - } catch (e) { - err = e - } - if (err instanceof SignedOut) throw err - const { tier, paid, credits } = tiersOf(load) - if (s.project) { - if (err) return { id: s.project, plan: "", tier: "", paid: "", credits: false, at: Date.now() } - return { id: s.project, plan: planOf(load), tier, paid, credits, at: Date.now() } - } - if (err) throw err - const own = companion(load.cloudaicompanionProject) - 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" - // 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") - } - return { id, plan: t.name ?? "", tier: t.id, paid, credits, at: Date.now() } -} - -async function project(s) { - let p = projects.get(s.rt) - if (!p) { - p = await resolveProject(s) - projects.set(s.rt, p) - return p - } - if (Date.now() - p.at < TIERS_TTL) return p - // the tiers, read again every hour: a plan bought or lapsed since - try { - const load = await call(s, PROD, "loadCodeAssist", LOAD_BODY) - const { tier, paid, credits } = tiersOf(load) - if (tier || paid) { - p = { ...p, tier, paid, credits } - const pl = planOf(load) - if (pl) p.plan = pl - } - } catch (e) { - if (e instanceof SignedOut) throw e - } - p = { ...p, at: Date.now() } - projects.set(s.rt, p) - return p -} - -function entitlements(p) { - const out = [] - for (const t of [p.paid, p.tier]) if (t && t !== "free-tier" && t !== "legacy-tier" && !out.includes(t)) out.push(t) - return out -} - -const tierKey = (s, p, t) => `${s.rt}\0${p.id}\0${t}` - -// askTiers are the tiers to name in the account's next -// fetchAvailableModels: those Google hasn't refused in a day, then none -function askTiers(s, p) { - const out = entitlements(p).filter((t) => { - const at = refused.get(tierKey(s, p, t)) - return !(at && Date.now() - at < TIER_REFUSED_FOR) - }) - return [...out, ""] -} - -// ---- models ------------------------------------------------------------------------------ - -// never offered: Antigravity's own internal models and retired ones -const HIDDEN = new Set(["chat_20706", "chat_23310", "tab_flash_lite_preview", "tab_jump_flash_lite_preview", "gemini-2.5-flash-thinking", "gemini-2.5-pro"]) - -// FALLBACK is the list when the account's own lists nothing -const FALLBACK = [ - { id: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" }, - { id: "gemini-3.1-pro-low", name: "Gemini 3.1 Pro (Low)" }, - { id: "gemini-3-flash", name: "Gemini 3 Flash" }, - { id: "gemini-3.1-flash-lite", name: "Gemini 3.1 Flash Lite" }, - { id: "claude-opus-4-6-thinking", name: "Claude Opus 4.6 (Thinking)" }, - { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, - { id: "gpt-oss-120b-medium", name: "GPT-OSS 120B (Medium)" }, -] - -const LEVELS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] - -const EFFORT_WORDS = [ - ["extra-high", "xhigh"], - ["extra-low", "minimal"], - ["xhigh", "xhigh"], - ["minimal", "minimal"], - ["low", "low"], - ["medium", "medium"], - ["high", "high"], -] - -// splitID is an id's family and the level its last word says -function splitID(id) { - for (const [w, l] of EFFORT_WORDS) { - if (id.endsWith("-" + w) && id.length > w.length + 1) return [id.slice(0, -(w.length + 1)), l] - } - return [id, ""] -} - -// nameEffort is a name without the level its last parenthesis says, and -// that level -function nameEffort(name) { - const open = name.lastIndexOf(" (") - if (open < 0 || !name.endsWith(")")) return [name, ""] - const level = { minimal: "minimal", "extra low": "minimal", low: "low", medium: "medium", high: "high", "extra high": "xhigh", xhigh: "xhigh" }[name.slice(open + 2, -1).toLowerCase()] - if (!level) return [name, ""] - return [name.slice(0, open).trim(), level] -} - -function nameSpells(name, id) { - const n = nameEffort(name)[0].split(/\s+/).filter(Boolean).join("-") - return n !== "" && n.toLowerCase() === splitID(id)[0].toLowerCase() -} - -function enumNames(e, id) { - if (typeof e !== "string" || !e.startsWith("MODEL_GOOGLE_")) return false - const rest = e.slice(13) - return rest !== "" && rest.toLowerCase() === id.replace(/[-.]/g, "_").toLowerCase() -} - -// pretty is a name made of an id, for a model whose own name is another's -function pretty(id) { - const special = { gpt: "GPT", oss: "OSS" } - return id - .split("-") - .filter(Boolean) - .map((w) => special[w.toLowerCase()] ?? (/^\d/.test(w) ? w : w[0].toUpperCase() + w.slice(1))) - .join(" ") -} - -// listed is fetchAvailableModels' reply as the account's models: each -// {id, name, context, output, images, enumName, remaining, resets}, in -// the app's picker order -function listed(res) { - const models = isObj(res?.models) ? res.models : {} - 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)) { - // Antigravity leaves the fraction out once none is left - mi.remaining = typeof m.quotaInfo.remainingFraction === "number" ? m.quotaInfo.remainingFraction : 0 - if (typeof m.quotaInfo.resetTime === "string" && !isNaN(Date.parse(m.quotaInfo.resetTime))) mi.resets = m.quotaInfo.resetTime - } - out.push(mi) - } - // a name that is another model's (two ids under one name) is the id's - const spelled = new Set(out.filter((mi) => nameSpells(mi.name, mi.id)).map((mi) => mi.name)) - for (const mi of out) { - if (mi.name === "" || nameSpells(mi.name, mi.id)) continue - if (spelled.has(mi.name) || enumNames(models[mi.id]?.model, mi.id)) mi.name = "" - } - const rank = new Map() - for (const s of res?.agentModelSorts ?? []) for (const g of s?.groups ?? []) for (const id of g?.modelIds ?? []) if (!rank.has(id)) rank.set(id, rank.size + 1) - for (const mi of out) mi.picker = rank.get(mi.id) ?? 0 - out = out.map((mi, i) => [mi, i]).sort(([a, i], [b, j]) => (a.picker === b.picker ? i - j : a.picker === 0 ? 1 : b.picker === 0 ? -1 : a.picker - b.picker)).map(([mi]) => mi) - return out -} - -// catalogOf is the account's models as magpie lists the variants: names -// filled, images said -function catalogOf(infos) { - const names = Object.fromEntries(FALLBACK.map((m) => [m.id, m.name])) - const out = infos.map((mi) => ({ - id: mi.id, - name: mi.name || names[mi.id] || "", - context: mi.context, - output: mi.output, - images: mi.imageInput ?? !mi.id.startsWith("gpt-oss"), - })) - if (!out.length) return FALLBACK.map((m) => ({ ...m, context: 0, output: 0, images: !m.id.startsWith("gpt-oss") })) - return out -} - -// families groups the variants of one model at its levels -// (gemini-3.7-flash-low, -medium, -high), in the order first seen -function families(raw) { - const out = [] - const by = new Map() - for (const m of raw) { - const [id] = splitID(m.id) - let f = by.get(id) - if (!f) { - f = { id, variants: [], efforts: [] } - by.set(id, f) - out.push(f) - } - f.variants.push(m) - } - for (const f of out) { - const named = [] - for (const v of f.variants) { - const l = nameEffort(v.name)[1] - if (l && !named.includes(l)) named.push(l) - } - for (const v of f.variants) f.efforts.push(named.length === f.variants.length ? nameEffort(v.name)[1] : splitID(v.id)[1]) - } - return out -} - -// byEffort is each level's variant, "" the one asked with no effort -function byEffort(f) { - const out = {} - f.variants.forEach((v, i) => { - if (!(f.efforts[i] in out)) out[f.efforts[i]] = v.id - }) - if (!out[""]) { - out[""] = out.high ?? "" - for (let i = LEVELS.length - 1; i >= 0 && !out[""]; i--) out[""] = out[LEVELS[i]] ?? "" - } - return out -} - -function familyModel(f) { - const def = byEffort(f)[""] - const m = { ...(f.variants.find((v) => v.id === def) ?? f.variants[f.variants.length - 1]) } - m.id = f.id - m.name = nameEffort(m.name ?? "")[0] - if (m.name === "" || m.name === def) m.name = f.id - for (const v of f.variants) { - if (v.context > 0 && (m.context === 0 || v.context < m.context)) m.context = v.context - if (v.output > 0 && (m.output === 0 || v.output < m.output)) m.output = v.output - m.images = m.images && v.images - } - m.efforts = LEVELS.filter((l) => f.efforts.includes(l)) - return m -} - -// collapse is the list magpie offers: a family of levels as one model -// that takes an effort, the rest as they are -function collapse(raw) { - const out = [] - for (const f of families(raw)) out.push(f.variants.length === 1 ? { ...f.variants[0], efforts: [] } : familyModel(f)) - const byID = new Map(out.map((m) => [m.id, m])) - for (const m of out) { - const tiered = m.id.endsWith("-tiered") - const b = tiered ? m.id.slice(0, -7) : "" - const base = tiered ? byID.get(b) : undefined - if (base && !m.efforts.length) m.efforts = [...base.efforts] - if (m.name) continue - m.name = m.id - if (base && base.name && base.name !== b) m.name = base.name + " (Tiered)" - } - return out -} - -// nearestEffort is the level of levels nearest want, a tie going up -function nearestEffort(want, levels) { - const at = LEVELS.indexOf(want) - if (!levels.length || at < 0 || levels.includes(want)) return want - let best = want - let dist = LEVELS.length - for (const l of levels) { - const i = LEVELS.indexOf(l) - if (i < 0 || l === "none") continue - const d = Math.abs(i - at) - if (d < dist || (d === dist && i > at)) { - best = l - dist = d - } - } - return best -} - -// sentID is the id a request for model at effort goes out under, and the -// level that id says it thinks at -function sentID(raw, model, effort) { - const fams = families(raw) - if (effort) { - for (const f of fams) { - if (f.variants.length < 2) continue - const i = f.variants.findIndex((v) => v.id === model && model !== f.id) - if (i >= 0) { - model = f.id - break - } - } - } - const f = fams.find((x) => x.id === model && x.variants.length > 1) - if (!f) { - const g = fams.find((x) => x.variants.length > 1 && x.variants.some((v) => v.id === model)) - return [model, g ? g.efforts[g.variants.findIndex((v) => v.id === model)] : ""] - } - const vs = byEffort(f) - let id = vs[""] - if (effort) { - const levels = LEVELS.filter((l) => vs[l]) - id = vs[nearestEffort(effort, levels)] || vs[""] - } - return [id, f.efforts[f.variants.findIndex((v) => v.id === id)] ?? ""] -} - -const lists = new Map() // refresh token → {at, infos, project} - -// modelInfo reads the account's models, naming its tiers as the app does -async function modelInfo(s, fresh = false) { - const l = lists.get(s.rt) - if (l && !fresh && Date.now() - l.at < MODELS_TTL) return l - const p = await project(s) - let res, err - for (const t of askTiers(s, p)) { - const body = { project: p.id } - if (t) body.entitlement = { userTier: t } - try { - res = await call(s, DAILY, "fetchAvailableModels", body) - err = undefined - break - } catch (e) { - err = e - if (e instanceof SignedOut) throw e - if (t && e.status === 400) refused.set(tierKey(s, p, t), Date.now()) - } - } - if (err) throw err - const out = { at: Date.now(), infos: listed(res), project: p } - lists.set(s.rt, out) - return out -} - -function variantsOf(m) { - return Object.fromEntries(m.efforts.map((e) => [e, { thinkingConfig: { thinkingLevel: e, includeThoughts: true } }])) -} - -function entry(m) { - return { - id: m.id, - name: m.name || m.id, - provider: { npm: NPM, api: BASE }, - reasoning: m.efforts.length > 0 || /thinking|gemini|pro-agent/i.test(m.id), - attachment: !!m.images, - tool_call: true, - temperature: true, - modalities: { input: m.images ? ["text", "image"] : ["text"], output: ["text"] }, - cost: { input: 0, output: 0 }, - limit: { context: m.context || 0, output: m.output || 0 }, - variants: variantsOf(m), - } -} - -function model(m) { - const e = entry(m) - return { - id: m.id, - providerID: PROVIDER, - name: e.name, - api: { id: m.id, url: BASE, npm: NPM }, - status: "active", - cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, - limit: e.limit, - options: {}, - headers: {}, - capabilities: { - temperature: true, - reasoning: e.reasoning, - attachment: e.attachment, - toolcall: true, - input: { text: true, image: e.attachment, audio: false, video: false, pdf: false }, - output: { text: true, image: false, audio: false, video: false, pdf: false }, - interleaved: false, - }, - release_date: "", - variants: e.variants, - } -} - -// ---- the schema Antigravity's function declarations take --------------------------------- - -const KEEP = new Set(["description", "nullable", "required", "pattern", "minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems", "minProperties", "maxProperties", "propertyOrdering"]) - -function requiredNames(v) { - return Array.isArray(v) ? v.filter((e) => typeof e === "string") : [] -} - -const distinct = (vs) => vs.filter((v, i) => vs.indexOf(v) === i) - -function ownShape(x) { - if (x.properties != null || x.items != null) return true - if (typeof x.type === "string") return x.type !== "null" - if (Array.isArray(x.type)) return x.type.some((t) => t !== "null") - return false -} - -function deepEqual(a, b) { - return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b)) -} - -function sortKeys(v) { - if (Array.isArray(v)) return v.map(sortKeys) - if (isObj(v)) return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])])) - return v -} - -function foldUnion(x, resolve) { - const out = {} - for (const [k, v] of Object.entries(x)) if (k !== "anyOf" && k !== "oneOf") out[k] = v - let object = x.type === "object" || x.properties != null - if (Array.isArray(x.type)) object = object || x.type.includes("object") - const props = { ...(isObj(x.properties) ? x.properties : {}) } - let common = [] - let branches = 0 - for (const k of ["anyOf", "oneOf"]) { - for (const a of Array.isArray(x[k]) ? x[k] : []) { - const m = resolve(a) - if (!m) continue - if (m.type === "null") { - out.nullable = true - continue - } - if (!object) continue - const bp = isObj(m.properties) ? m.properties : {} - for (const pk of Object.keys(bp).sort()) if (!(pk in props)) props[pk] = bp[pk] - const br = requiredNames(m.required) - common = branches === 0 ? [...br] : common.filter((n) => br.includes(n)) - branches++ - } - } - if (object) { - if (Object.keys(props).length) out.properties = props - const req = requiredNames(x.required) - if (req.length + common.length > 0) out.required = distinct([...req, ...common]) - } - return out -} - -// plainSchema is a JSON schema cut down to what Antigravity's function -// declarations take: an OpenAPI-style subset with no references, unions -// or keywords outside it -function plainSchema(root) { - if (!isObj(root)) return root - const defs = {} - for (const k of ["$defs", "definitions"]) if (isObj(root[k])) Object.assign(defs, root[k]) - const lastSeg = (ref) => ref.slice(ref.lastIndexOf("/") + 1) - const localRef = (ref) => { - if (ref.startsWith("#/")) { - let cur = root - for (let tok of ref.slice(2).split("/")) { - tok = tok.replaceAll("~1", "/").replaceAll("~0", "~") - if (isObj(cur)) cur = cur[tok] - else if (Array.isArray(cur)) { - const n = /^\d+$/.test(tok) ? Number(tok) : -1 - if (n < 0 || n >= cur.length) return [undefined, false] - cur = cur[n] - } else return [undefined, false] - if (cur == null) { - const d = defs[lastSeg(ref)] - return [d, d !== undefined] - } - } - return [cur, true] - } - if (ref === "#") return [root, true] - const d = defs[lastSeg(ref)] - return [d, d !== undefined] - } - const resolve = (v) => { - let m = isObj(v) ? v : null - if (m && typeof m.$ref === "string") { - const [d, ok] = localRef(m.$ref) - m = ok && isObj(d) ? d : null - } - return m - } - const selfRef = (ref, path) => { - if (!ref.startsWith("#")) return false - const r = ref.slice(1) - return r === "" || path === r || path.startsWith(r + "/") - } - const refPath = (ref, path) => (ref.startsWith("#") ? ref.slice(1) : path) - const expanding = new Set() - const schemaTypeOf = (m) => (typeof m.type === "string" ? m.type : m.properties != null ? "object" : m.items != null ? "array" : "object") - const oneSays = (members) => { - let one = null - for (const m of members) { - if (!isObj(m) || Object.keys(m).length === 0) continue - if (one && !deepEqual(one, m)) return null - one = m - } - return one - } - const walk = (v, depth, path) => { - if (typeof v === "boolean") return v ? {} : null - if (Array.isArray(v)) return v.map((e) => walk(e, depth, path)) - if (!isObj(v)) return v - const x = v - if (depth > 32) return { type: "object" } - if (typeof x.$ref === "string") { - const ref = x.$ref - const [d, found] = localRef(ref) - if (!found) return { type: "object" } - if (expanding.has(ref) || selfRef(ref, path)) return { type: isObj(d) ? schemaTypeOf(d) : "object" } - expanding.add(ref) - const out = walk(d, depth + 1, refPath(ref, path)) - expanding.delete(ref) - return out - } - if (Array.isArray(x.allOf)) { - const merged = {} - for (const [k, val] of Object.entries(x)) if (k !== "allOf") merged[k] = val - let required = requiredNames(x.required) - for (const e of x.allOf) { - required = [...required, ...requiredNames(resolve(e)?.required)] - const m = walk(e, depth + 1, path + "/allOf") - if (!isObj(m)) continue - for (const [k, val] of Object.entries(m)) { - if (k === "required") continue - if (k === "properties") merged.properties = { ...(isObj(merged.properties) ? merged.properties : {}), ...val } - else if (!(k in merged)) merged[k] = val - } - } - if (required.length) merged.required = distinct(required) - return walk(merged, depth + 1, path) - } - if ((x.anyOf != null || x.oneOf != null) && ownShape(x)) return walk(foldUnion(x, resolve), depth + 1, path) - for (const k of ["anyOf", "oneOf"]) { - if (!Array.isArray(x[k])) continue - let pick = null - let nullable = false - for (const a of x[k]) { - const m = isObj(a) ? a : null - if (m?.type === "null") nullable = true - else if (!pick && m) pick = m - } - let out = {} - if (pick) { - const m = walk(pick, depth + 1, path + "/" + k) - if (isObj(m)) out = m - } - if (typeof x.description === "string" && out.description == null) out.description = x.description - if (nullable) out.nullable = true - if (out.type == null) out.type = "string" - return out - } - const out = {} - for (const [k, val] of Object.entries(x)) { - if (KEEP.has(k)) out[k] = val - else if (k === "exclusiveMinimum" || k === "exclusiveMaximum") { - const b = k === "exclusiveMinimum" ? "minimum" : "maximum" - if (typeof val === "number" && x[b] == null) out[b] = val - } else if (k === "type") { - if (Array.isArray(val)) { - for (const t of val) { - if (t === "null") out.nullable = true - else if (out.type == null) out.type = t - } - for (const t of val) { - if ((t === "array" && x.items != null) || (t === "object" && x.properties != null)) { - out.type = t - break - } - } - } else out.type = val - } else if (k === "properties") { - const props = {} - if (isObj(val)) { - for (const [pk, pv] of Object.entries(val)) { - const at = pk.replaceAll("~", "~0").replaceAll("/", "~1") - const w = walk(pv, depth + 1, path + "/properties/" + at) - if (w != null) props[pk] = w - } - } - out.properties = props - } else if (k === "items") { - const w = walk(val, depth + 1, path + "/items") - if (w != null) out.items = w - else if (x.maxItems == null) { - out.items = {} - out.maxItems = 0 - } - } else if (k === "enum") { - if (Array.isArray(val) && val.every((e) => typeof e === "string")) { - const strs = val.filter((s) => s.trim() !== "") - if (strs.length) out.enum = strs - } - } - } - if ("const" in x && typeof x.const === "string" && x.const.trim() !== "") out.enum = [x.const] - if (out.type == null) { - if (out.properties != null) out.type = "object" - else if (out.items != null) out.type = "array" - } - if (out.type === "array") { - if (Array.isArray(out.items)) out.items = oneSays(out.items) - if (out.items == null) { - if (Array.isArray(x.prefixItems) && x.prefixItems.length) { - const s = oneSays(x.prefixItems) - if (s) out.items = walk(s, depth + 1, path + "/items") - } - if (out.items == null) out.items = {} - } - } - if (typeof out.type === "string") { - if (out.type !== "array") { - delete out.items - delete out.minItems - delete out.maxItems - } - if (out.type !== "object") { - delete out.properties - delete out.required - delete out.minProperties - delete out.maxProperties - delete out.propertyOrdering - } - } - if (Array.isArray(out.required)) { - const props = isObj(out.properties) ? out.properties : {} - const keep = out.required.filter((n) => typeof n === "string" && props[n] != null) - if (keep.length) out.required = keep - else delete out.required - } - return out - } - return walk(root, 0, "") -} - -// ---- system prompts Antigravity turns away ----------------------------------------------- - -// TURNED_AWAY are the lines, lower-cased, Antigravity answers a 429 to -// whatever quota is left. Each goes as SAID_AS says instead. The last four -// are turned away since the evening of 11-14 (Lmohn39 and ZhouYimingsjtu on -// X), each 3 of 3 or 5 of 5 on a real account, on gemini-3-flash and -// claude-sonnet-4-6 alike: -// - "You are Hermes Agent": Hermes' current persona ("You are Hermes -// Agent, built by Nous Research.") and its earlier one, and the earlier -// one as magpie reworded it up to 0.1.15 ("… built by Nous Research"). -// The earlier one ("…, an intelligent AI assistant created by Nous -// Research.") is turned away as "You're Hermes Agent, …" too, 3 of 3, -// so its "created by" goes "built by" as before as well. -// - "You are OpenCode", whichever of OpenCode 2.0.25's lines follows it -// ("a coding agent that helps users…", "an interactive CLI tool…", "the -// best coding agent on the planet"). -// - "You are a coding agent running in the Codex CLI", Codex's prompt for -// a model it has no prompt of its own for (Codex 0.165). -// - "a coding assistant running inside pi", pi 1.5.0's default prompt -// ("You are a coding assistant running inside pi, a coding agent -// harness."), as "agent" for "assistant" and "that runs inside pi" are. -// Codex's prompt for GPT-6 ("You are Codex, an agent based on GPT-6."), -// Claude Code's, Gemini CLI's, Qwen Code's, Cline's, Kilo's, goose's, Amp's, -// Droid's, Kimi CLI's, Aider's and Cursor's went through as written. -const TURNED_AWAY = [ - "x-anthropic-billing-header:", - "built on anthropic's claude agent sdk", - "you are codex, an agent based on gpt-5", - "you are codex, a coding agent based on gpt-5", - "rfc 2119 keywords: must, required, should, recommended, may, optional.", - "you are hermes agent", - "an intelligent ai assistant created by nous research", - "you are opencode", - "you are a coding agent running in the codex cli", - "a coding assistant running inside pi", -] - -// INVISIBLE are the characters Google's check reads past: since 11-14 a -// line with a zero-width space (U+200B) after the first and second -// character of each word, or after every character, or U+2060, is turned -// away as the line itself, 5 of 5 on a real account for every line here -// (hc295971796 on X, Claude Desktop's Code tab). A copy someone broke up -// that way (the antigravity-cloak middleware before 0.1.7, an older magpie) -// is matched as the line. -const INVISIBLE = "[\\u00ad\\u180e\\u200b-\\u200f\\u2060-\\u2064\\ufeff]" -const INVISIBLE_RE = new RegExp(INVISIBLE, "g") - -const escape = (c) => c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") - -// lineRe matches line in any case, with any run of white space between its -// words and any invisible characters inside them: Google's check reads a -// line break, a tab, two spaces or a no-break space where the line has one -// space, and turned omp's line away wrapped after "REQUIRED," or after -// "RFC 2119" as it did on one line, while a missing period, a space dropped -// after a comma or the words in another order went through (a real -// account, 11-14). Claude Code's billing line is matched to its end, since -// it goes whole. -const lineRe = (line) => { - const words = line.split(" ").map((w) => [...w].map(escape).join(`${INVISIBLE}*`)) - const tail = line === "x-anthropic-billing-header:" ? "[^\\n]*\\n?" : "" - return new RegExp(words.join(`${INVISIBLE}*\\s+${INVISIBLE}*`) + tail, "gi") -} -const TURNED_AWAY_RE = TURNED_AWAY.map(lineRe) -const has = (s, re) => { - re.lastIndex = 0 - const yes = re.test(s) - re.lastIndex = 0 - return yes -} -const said = (system, line) => has(system, TURNED_AWAY_RE[TURNED_AWAY.indexOf(line)]) - -const turnsAway = (system) => TURNED_AWAY_RE.some((re) => has(system, re)) - -// SAID_AS is how each line goes, with its invisible characters taken out -// and its white space as it was: a rewording that keeps its meaning, each -// answered 5 of 5 on a real account on 11-14 while the line itself, broken -// up or not, was turned away 5 of 5. -// - Claude Code's billing line is left out: it is Anthropic's, and no -// Antigravity model reads anything in it. -// - "built on Anthropic's Claude Agent SDK", the Agent SDK's identity -// line (Claude Desktop's Code tab and its subagents), goes as "built on -// the Claude Agent SDK by Anthropic". -// - Codex's GPT-5 lines go "built on GPT-5" for "based on GPT-5". -// - "You are Hermes Agent", "You are OpenCode" and Codex CLI's line go -// as "You're …" (5 of 5 each), and Hermes' earlier "created by Nous -// Research" as "built by" (3 of 3 together). -// - pi's line goes "running within pi" (5 of 5 on both models). -// - omp's RFC 2119 line goes as "key words", the RFC's own term (10 of 10 -// on 11-14, eric_li8983 on X). -const youre = (line) => line.replace(/^(you)\s+are/i, "$1're") -const SAID_AS = { - "x-anthropic-billing-header:": () => "", - "built on anthropic's claude agent sdk": (line) => line.replace(/^(built\s+on\s+)anthropic's(\s+)(claude\s+agent\s+sdk)$/i, "$1the$2$3 by Anthropic"), - "you are codex, an agent based on gpt-5": (line) => line.replace(/based(\s+)on/i, "built$1on"), - "you are codex, a coding agent based on gpt-5": (line) => line.replace(/based(\s+)on/i, "built$1on"), - "rfc 2119 keywords: must, required, should, recommended, may, optional.": (line) => line.replace(/(key)(words)/i, "$1 $2"), - "you are hermes agent": youre, - "an intelligent ai assistant created by nous research": (line) => line.replace(/created(\s+)by/i, "built$1by"), - "you are opencode": youre, - "you are a coding agent running in the codex cli": youre, - "a coding assistant running inside pi": (line) => line.replace(/inside/i, "within"), -} - -// USER_TURNED_AWAY are the lines Antigravity also turns away in a user's -// turn: since 11-14 Codex's GPT-5 lines there got a bare 429 "Resource has -// been exhausted" 3 of 3 on a real account, where a pasted AGENTS.md or a -// developer message told after a reply puts them, and went through -// reworded. The others went through as written there, 3 of 3 each, and so -// did all of them in the model's turns and in tool results. -const USER_TURNED_AWAY = TURNED_AWAY.filter((l) => l.startsWith("you are codex, ")) - -// cloak rewords the lines of only, or of TURNED_AWAY when only is left out -function cloak(system, only) { - if (!turnsAway(system)) return system - const at = [] - TURNED_AWAY_RE.forEach((re, i) => { - if (only && !only.includes(TURNED_AWAY[i])) return - for (const m of system.matchAll(re)) at.push([m.index, m.index + m[0].length, SAID_AS[TURNED_AWAY[i]]]) - }) - at.sort((a, b) => a[0] - b[0]) - let out = "" - let prev = 0 - for (const [from, to, as] of at) { - if (from < prev) continue - out += system.slice(prev, from) + as(system.slice(from, to).replace(INVISIBLE_RE, "")) - prev = to - } - return out + system.slice(prev) -} - -const HINT = - "Antigravity answers this 429 to the system prompt of Claude Code and the Claude Agent SDK (Claude Desktop's chats) whatever quota is left, so it is not a quota and waiting won't help; use another provider for these chats, or put one after Antigravity in a routing group" -const CODEX_HINT = - "Antigravity answers this 429 to Codex's own system prompt for GPT-5 models whatever quota is left, so it is not a quota and waiting won't help; a Codex chat begun on a GPT model keeps that prompt after a model switch or a fork, so start a new chat on this model" -const HERMES_HINT = - "Antigravity answers this 429 to Hermes Agent's default persona (\"You are Hermes Agent, …\" in its SOUL.md), the current one and the earlier one alike, whatever quota is left, so it is not a quota and waiting won't help; magpie sends it as \"You're Hermes Agent, …\", which goes through, so start SOUL.md another way, or use another provider for these chats" - -const PI_HINT = - "Antigravity answers this 429 to pi's default system prompt (\"You are a coding assistant running inside pi\") whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"running within pi\", which goes through, so give pi a system prompt of your own (--system-prompt) or use another provider for these chats" -const OPENCODE_HINT = - "Antigravity answers this 429 to OpenCode's system prompt (\"You are OpenCode, …\") whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"You're OpenCode, …\", which goes through, so use another provider for these chats, or put one after Antigravity in a routing group" -const CODEX_CLI_HINT = - "Antigravity answers this 429 to Codex's prompt for a model it has none of its own for (\"You are a coding agent running in the Codex CLI\") whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"You're …\", which goes through, so use another provider for these chats, or put one after Antigravity in a routing group" - -const RFC_HINT = - "Antigravity answers this 429 to the line \"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\" that starts oh-my-pi (omp)'s system prompt, and to any prompt that has it, whatever quota is left, so it is not a quota and waiting won't help; magpie sends that line as \"RFC 2119 key words: …\", which goes through, so this one came from a copy of it that was worded another way" - -function hint(system) { - if (said(system, "rfc 2119 keywords: must, required, should, recommended, may, optional.")) return RFC_HINT - if (said(system, "you are codex, an agent based on gpt-5") || said(system, "you are codex, a coding agent based on gpt-5")) return CODEX_HINT - if (said(system, "you are a coding agent running in the codex cli")) return CODEX_CLI_HINT - if (said(system, "you are hermes agent") || said(system, "an intelligent ai assistant created by nous research")) return HERMES_HINT - if (said(system, "you are opencode")) return OPENCODE_HINT - if (said(system, "a coding assistant running inside pi")) return PI_HINT - return HINT -} - -// ---- shaping the Gemini request for Antigravity ---------------------------------------------- - -const DRAWS = ["image", "imagen", "imagine", "dall-e", "flux", "seedream", "cogview", "stable-diffusion", "sdxl", "wanx", "kolors", "hidream", "banana", "sensenova-u1"] -const draws = (id) => DRAWS.some((w) => id.includes(w)) - -function generation(id) { - const m = /(?:^|\/)gemini-(\d+)/.exec(id) - return m ? Number(m[1]) : 0 -} - -const toolID = (id) => (typeof id === "string" ? id.replace(/[^a-zA-Z0-9_-]/g, "_") : id) - -const isImage = (p) => isObj(p) && (isObj(p.inlineData) || isObj(p.fileData)) && !p.functionResponse && !p.functionCall -const hasResponse = (parts) => Array.isArray(parts) && parts.some((p) => isObj(p?.functionResponse)) - -// systemText is a request's system instruction as one text -function systemText(req) { - const si = req.systemInstruction - if (typeof si === "string") return si - return (si?.parts ?? []).map((p) => (typeof p?.text === "string" ? p.text : "")).join("\n") -} - -// claudeTurns keeps a Claude model's tool turn as Anthropic reads one: -// every response first, the tools' images after them, each group after a -// line saying whose it is, then what the user said -function claudeTurns(contents) { - const out = [] - for (let i = 0; i < contents.length; i++) { - const c = contents[i] - if (c?.role !== "user" || !hasResponse(c.parts)) { - out.push(c) - continue - } - const lead = [] - const after = [] - const rest = [] - const ps = c.parts - for (let j = 0; j < ps.length; j++) { - const p = ps[j] - if (!isObj(p?.functionResponse)) { - rest.push(p) - continue - } - lead.push(p) - const ims = [] - while (j + 1 < ps.length && isImage(ps[j + 1])) ims.push(ps[++j]) - if (ims.length) { - const name = p.functionResponse.name || "tool" - const id = p.functionResponse.id ?? "" - after.push({ text: ims.length > 1 ? `${ims.length} images returned by tool ${name} (call ${id}):` : `Image returned by tool ${name} (call ${id}):` }, ...ims) - } - } - let parts = [...lead, ...after, ...rest] - // what the user said, a turn of its own after the tools' in Gemini's - // build, goes in the same turn - while (i + 1 < contents.length && contents[i + 1]?.role === "user" && !hasResponse(contents[i + 1].parts)) parts = [...parts, ...(contents[++i].parts ?? [])] - out.push({ ...c, parts }) - } - return out -} - -// REWORDED are paragraphs that go through but are answered badly, each with -// a rewording that keeps its meaning. DeepSeek Harness's desktop app puts -// the first in every system prompt. With it word for word, gemini-4-argon -// answered most requests in about 3s at about 300 tok/s with no thinking, -// and ended after one shallow step; with it removed or reworded, the same -// replayed request was answered normally 20 of 20 times (#1028). -const REWORDED = [ - [ - "Tokens prefixed with @ are paths the user explicitly referenced. Relative paths resolve from the workspace root; absolute paths identify files or directories on the host. A trailing slash marks a directory: list it when its contents matter. Anything else is a file: use the read tool when its contents are needed, and do not claim to have inspected it before reading. @\"...\" quotes a path containing spaces.", - "When the user writes @ followed by a path, they are pointing at that file or folder. Relative paths start at the workspace root; absolute paths are host paths. A path ending in a slash is a folder, so list it if its contents matter; otherwise it is a file, so open it with the read tool before relying on it. Paths with spaces appear as @\"...\".", - ], -] - -const reword = (system) => { - for (const [from, to] of REWORDED) if (system.includes(from)) system = system.split(from).join(to) - return system -} - -// outgoing is a system prompt as Antigravity is sent it -const outgoing = (system) => reword(cloak(system)) - -// shape is the Gemini request as Antigravity takes it for the model sent -// at the level at, asked at effort -function shape(req, sent, at, effort) { - req = structuredClone(req) - const m = sent.toLowerCase() - const claude = m.includes("claude") - if (isObj(req.systemInstruction)) { - for (const p of req.systemInstruction.parts ?? []) if (typeof p?.text === "string") p.text = outgoing(p.text) - // Claude Code's billing line, a block of its own, goes out whole and - // leaves an empty text, which a Claude model refuses - const parts = req.systemInstruction.parts - if (Array.isArray(parts) && parts.length > 1) req.systemInstruction.parts = parts.filter((p) => !(isObj(p) && p.text === "" && Object.keys(p).length === 1)) - } else if (typeof req.systemInstruction === "string") { - req.systemInstruction = { role: "user", parts: [{ text: outgoing(req.systemInstruction) }] } - } - if (Array.isArray(req.contents)) { - for (const c of req.contents) { - // since 11-14 Antigravity also answers a bare 429 to Codex's GPT-5 - // line in a user's turn (a pasted AGENTS.md, a developer message - // told after a reply), 3 of 3 on a real account, and lets it - // through reworded; the model's turns and tool results went through - // as written, so they stay - if (c?.role !== "model") for (const p of c?.parts ?? []) if (typeof p?.text === "string" && !p.thought) p.text = cloak(p.text, USER_TURNED_AWAY) - // an empty text (a stream's last chunk, sent back) is a block Claude - // refuses: "text: Field required" - if (Array.isArray(c?.parts) && c.parts.length > 1) c.parts = c.parts.filter((p) => !(isObj(p) && p.text === "" && Object.keys(p).length === 1)) - for (const p of c?.parts ?? []) { - if (isObj(p?.functionCall) && p.functionCall.id) p.functionCall.id = toolID(p.functionCall.id) - if (isObj(p?.functionResponse)) { - const fr = p.functionResponse - if (fr.id) fr.id = toolID(fr.id) - const r = fr.response - if (isObj(r) && Object.keys(r).length === 1 && ("output" in r || "error" in r)) fr.response = { result: r.output ?? r.error } - else if (isObj(r) && !("result" in r) && ("output" in r || "error" in r)) { - const { output, error, ...more } = r - fr.response = { result: output ?? error, ...more } - } - } - } - } - if (claude) req.contents = claudeTurns(req.contents) - } - for (const t of Array.isArray(req.tools) ? req.tools : []) { - for (const d of Array.isArray(t?.functionDeclarations) ? t.functionDeclarations : []) { - const s = d.parametersJsonSchema ?? d.parameters ?? { type: "object", properties: {} } - delete d.parametersJsonSchema - d.parameters = plainSchema(structuredClone(s)) - } - } - const fc = req.toolConfig?.functionCallingConfig - if (claude && isObj(fc) && (fc.mode ?? "AUTO") === "AUTO" && Array.isArray(req.tools) && req.tools.some((t) => t?.functionDeclarations?.length)) fc.mode = "VALIDATED" - const gen = isObj(req.generationConfig) ? req.generationConfig : null - if (gen) { - if (!claude) delete gen.maxOutputTokens - const tc = gen.thinkingConfig - if (m.startsWith("gpt-oss") || (claude && !m.includes("thinking"))) delete gen.thinkingConfig - else if (isObj(tc)) { - const g = generation(m) - if (g >= 3 || m.startsWith("gemini-pro-agent")) { - const e = at || effort - delete tc.thinkingBudget - tc.includeThoughts = true - if (e) { - let level = "high" - if (e === "low" || (e === "minimal" && at && !m.includes("flash"))) level = "low" - else if (e === "minimal" && at) level = "minimal" - else if ((e === "none" || e === "minimal") && !draws(m)) level = "low" - else if (e === "medium" && (m.includes("flash") || g > 3)) level = "medium" - // a variant at xhigh (Gemini 4 Hydrogen) is asked at xhigh, which - // Google lists for it (LOW, MEDIUM, HIGH, XHIGH); a model with no - // such variant stays at high (#1169) - if (at === "xhigh") level = "xhigh" - tc.thinkingLevel = level - } else delete tc.thinkingLevel - } else if (typeof tc.thinkingLevel === "string") { - // a level a variant put on a model told a budget - delete tc.thinkingLevel - if (Object.keys(tc).length === 1 && tc.includeThoughts && !("thinkingBudget" in tc)) delete gen.thinkingConfig - } - } - if (!Object.keys(gen).length) delete req.generationConfig - } - return req -} - -const INJECTED_USER_TEXT = /^(?:# AGENTS\.md\b|<(?:environment_context|permissions instructions|system-reminder|external_codex_apps_|subagent[-_]notification|turn_aborted)\b|\{"page_id":|Companion Page snapshot\b)/ - -function firstUserText(req) { - let first = "" - for (const c of req.contents ?? []) { - if (c?.role !== "user") continue - for (const p of c.parts ?? []) { - if (typeof p?.text !== "string" || p.text === "") continue - const trimmed = p.text.trimStart() - if (!trimmed) continue - if (!first) first = p.text - if (!INJECTED_USER_TEXT.test(trimmed)) return p.text - } - } - return first -} - -// sessionOf is the session id the app gives a conversation: from the host's -// session header when named, else the conversation's first real user prompt -function sessionOf(req, headers) { - const rawSession = headerOf(headers, SESSION).trim() - const session = /^magpie-[0-9a-f]{24}$/.test(rawSession) ? "" : rawSession.slice(0, 128) - const subagent = headerOf(headers, SUBAGENT).trim().slice(0, 64) - let text = session && !subagent ? session : [session, subagent, firstUserText(req)].filter(Boolean).join("\0") - if (!text) text = crypto.randomBytes(16).toString("hex") - const h = crypto.createHash("sha256").update(text).digest() - const n = h.readBigUInt64BE(0) & 0x7fffffffffffffffn - 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 { - project: projectID, - requestId: `agent/${cascade}/${Date.now()}/${trajectory}/${step + 1}`, - request, - model: sent, - ...(credits ? { enabled_credit_types: [CREDIT] } : {}), - userAgent: "antigravity", - requestType: "agent", - } -} - -// ---- requests --------------------------------------------------------------------------- - -async function bodyText(body) { - if (body == null) return "" - if (typeof body === "string") return body - if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return Buffer.from(body).toString("utf8") - return await new Response(body).text() -} - -function headerOf(headers, name) { - if (!headers) return "" - if (headers instanceof Headers) return headers.get(name) ?? "" - if (Array.isArray(headers)) return headers.find(([k]) => k.toLowerCase() === name)?.[1] ?? "" - for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === name) return String(v) - return "" -} - -function errorResponse(status, message, signIn) { - const statusName = { 400: "INVALID_ARGUMENT", 401: "UNAUTHENTICATED", 403: "PERMISSION_DENIED", 404: "NOT_FOUND", 429: "RESOURCE_EXHAUSTED" }[status] ?? "UNKNOWN" - return new Response(JSON.stringify({ error: { code: status, message, status: statusName } }), { - status, - headers: { "content-type": "application/json", ...(signIn ? { "x-magpie-sign-in": signIn } : {}) }, - }) -} - -// unwrap turns Code Assist's stream, each chunk {response: }, back -// into Gemini's own. With say, an INVALID_ARGUMENT error in it, as a data -// event or a bare line, is told in say's words -function unwrap(body, say) { - const dec = new TextDecoder() - const enc = new TextEncoder() - let buf = "" - const line = (l) => { - const data = l.startsWith("data:") - if (!data && !(say && l.trimStart().startsWith("{"))) return l - const j = parse(data ? l.slice(5).trim() : l) - if (say && isObj(j) && isObj(j.error) && badCall(JSON.stringify(j))) { - const e = { ...j.error, message: say(j.error.message) } - return (data ? "data: " : "") + JSON.stringify({ ...j, error: e }) - } - if (data && isObj(j) && isObj(j.response)) return "data: " + JSON.stringify(j.response) - return l - } - return body.pipeThrough( - new TransformStream({ - transform(chunk, ctl) { - buf += dec.decode(chunk, { stream: true }) - let i - while ((i = buf.indexOf("\n")) >= 0) { - const l = buf.slice(0, i).replace(/\r$/, "") - buf = buf.slice(i + 1) - ctl.enqueue(enc.encode(line(l) + "\n")) - } - }, - flush(ctl) { - buf += dec.decode() - if (buf) ctl.enqueue(enc.encode(line(buf))) - }, - }), - ) -} - -const RESPONSE_HEADERS = { "content-type": "text/event-stream", "cache-control": "no-cache" } - -// ---- Gemini 4's rejected calls -------------------------------------------------------------- - -const RETRY_BAD_CALL = 2 -// floorMs is how long a 400 must have taken to count as the backend's own -// rejection of what the model made: a request that is wrong in itself is -// refused at once, and isn't sent again -// holdMs is the longest a stream's thinking is held back: past it what was -// held goes out and the rest streams live, so a long-thinking turn never -// leaves its client silent long enough to time out (plugins #1078). A 400 -// after that reaches the client as it is. -const retry400 = { floorMs: 3000, pauseMs: 300, holdMax: 512 * 1024, holdMs: 10_000 } -const isGemini4 = (id) => /^gemini-4/i.test(String(id ?? "")) - -// badCallSaid is what the client is told of Gemini 4's INVALID_ARGUMENT -// after the model ran, asked n times: the vendor's words alone read as a -// request magpie got wrong, or a region block (Lawson0112 on X), which -// Google refuses at once and names (FAILED_PRECONDITION "User location is -// not supported…"). The words stay clear of what magpie's gateway reads as -// another fault: "model" before "invalid" reads as a model not served -const badCallSaid = (id, n) => (message) => - `${id} turned down a call it built while thinking, asked ${n} time${n === 1 ? "" : "s"} (Google: ${String(message ?? "").trim() || "INVALID_ARGUMENT"}). Not a region or account refusal: Google names those` - -// badCall is whether a reply's body is Google's INVALID_ARGUMENT -function badCall(text) { - const j = parse(text) - const e = isObj(j) ? (isObj(j.error) ? j.error : isObj(j.response?.error) ? j.response.error : undefined) : undefined - if (e) return e.status === "INVALID_ARGUMENT" || (e.code === 400 && /invalid argument/i.test(String(e.message ?? ""))) - return /INVALID_ARGUMENT|request contains an invalid argument/i.test(String(text)) -} - -// showsAnswer is whether a stream chunk carries something the client shows -// beyond thinking: text, a call, a file -function showsAnswer(j) { - const c = isObj(j?.response) ? j.response : j - for (const p of c?.candidates?.[0]?.content?.parts ?? []) { - if (!isObj(p) || p.thought) continue - if (p.functionCall || p.inlineData || p.fileData || p.executableCode || (typeof p.text === "string" && p.text !== "")) return true - } - return false -} - -// holdThoughts reads a stream until it shows its first non-thinking part, -// and holds what it read back until then. An INVALID_ARGUMENT error that -// comes first sends nothing to the client, so the caller can ask again -// ({bad: true}). Once an answer has begun the client has it, and the -// stream goes through as it is: a reply can't be taken back. -const LATE = Symbol("late") -async function holdThoughts(res, signal) { - const rd = res.body.getReader() - const dec = new TextDecoder() - const held = [] - let size = 0 - let buf = "" - let done = false - let release = false - let bad = false - let failure - // pending is a read still out when the hold's time ran out: the body - // takes it first, so no chunk is lost - let pending - let timer - const late = new Promise((r) => (timer = setTimeout(r, retry400.holdMs, LATE))) - // loose is the lines of a JSON value written with no "data:" before it, - // as Code Assist writes its late error: after the thinking events, a - // line of its own, {"error":{"code":400,…,"status":"INVALID_ARGUMENT"}} - // (zRain's capture, magpie's sse_bare.go), maybe over several lines - let loose = "" - const scan = (final) => { - let i - while (!release && !bad && ((i = buf.indexOf("\n")) >= 0 || (final && buf))) { - const l = (i >= 0 ? buf.slice(0, i) : buf).replace(/\r$/, "") - buf = i >= 0 ? buf.slice(i + 1) : "" - let j - if (l.startsWith("data:")) j = parse(l.slice(5).trim()) - else if (loose || l.trimStart().startsWith("{")) { - loose += l + "\n" - j = parse(loose) - if (j === undefined && loose.length <= retry400.holdMax) continue - loose = "" - } else continue - if (!isObj(j)) continue - if ((j.error || j.response?.error) && badCall(JSON.stringify(j))) bad = true - else if (showsAnswer(j)) release = true - } - } - try { - while (!release && !bad) { - const read = rd.read() - const r = await Promise.race([read, late]) - if (r === LATE) { - pending = read - release = true - break - } - if (r.done) { - done = true - break - } - held.push(r.value) - size += r.value.length - buf += dec.decode(r.value, { stream: true }) - scan(false) - if (size > retry400.holdMax) release = true - } - if (done && !bad && !release) scan(true) - } catch (e) { - if (signal?.aborted) { - clearTimeout(timer) - throw e - } - failure = e - } - clearTimeout(timer) - if (bad) { - await rd.cancel().catch(() => {}) - return { bad: true } - } - let i = 0 - const body = new ReadableStream({ - async pull(ctl) { - if (i < held.length) return ctl.enqueue(held[i++]) - if (failure) return ctl.error(failure) - if (done) return ctl.close() - try { - const read = pending ?? rd.read() - pending = undefined - const r = await read - if (r.done) ctl.close() - else ctl.enqueue(r.value) - } catch (e) { - ctl.error(e) - } - }, - cancel: (r) => rd.cancel(r), - }) - return { bad: false, body } -} - -// complete sends a Gemini request at url (…/models/:) to -// Antigravity for the account s -async function complete(s, url, init, magpie) { - const m = /\/models\/([^/:?]+):(streamGenerateContent|generateContent|countTokens)/.exec(url) - if (!m) return errorResponse(404, `Antigravity: no such API: ${url}`) - const model = decodeURIComponent(m[1]) - const method = m[2] - const raw = parse(await bodyText(init?.body)) - if (!isObj(raw)) return errorResponse(400, "Antigravity: the request isn't JSON") - if (method === "countTokens") return errorResponse(404, "Antigravity doesn't count tokens") - let effort = headerOf(init?.headers, EFFORT).toLowerCase() - // a variant's level, where OpenCode asked for one - const tl = raw.generationConfig?.thinkingConfig?.thinkingLevel - // Gemini's own clients write it in capitals ("XHIGH") - if (!effort && typeof tl === "string" && LEVELS.includes(tl.toLowerCase())) effort = tl.toLowerCase() - let l - try { - l = await modelInfo(s) - } catch (e) { - if (e instanceof SignedOut) return errorResponse(401, e.message, "expired") - return errorResponse(e.status || 502, e.message ?? String(e)) - } - const [sent, at] = sentID(catalogOf(l.infos), model, effort) - const system = systemText(raw) - const req = shape(raw, sent, at, effort) - let tok - try { - tok = await token(s) - } catch (e) { - if (e instanceof SignedOut) return errorResponse(401, e.message, "expired") - return errorResponse(502, e.message ?? String(e)) - } - const stream = method === "streamGenerateContent" - const ua = await userAgent() - const send = (credits) => - fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { - method: "POST", - 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, - }) - const attempt = async () => { - let res = await send(false) - let refusal - if (res.status === 429 && l.project.credits && usesCredits(magpie) && !turnsAway(system)) { - // the plan's quota is used up: the app asks before it spends AI - // credits, and the switch is that answer. Credits are asked for only - // after a refusal, so a request the plan covers never spends one. - // - // The refusal is read before the second ask: when that ask fails too, - // the refusal is what the agent is told. Its body can't be read after - // it was cancelled ("Body already used", a 502 on every retry). - refusal = await res.text() - let again - try { - again = await send(true) - } catch (e) { - if (init?.signal?.aborted) throw e - } - if (again?.ok) { - res = again - refusal = undefined - } else { - await again?.body?.cancel().catch(() => {}) - } - } - return { res, refusal } - } - // Gemini 4 now and then fails a request the same request later passes: - // its backend rejects a call the model built itself (a 400 - // INVALID_ARGUMENT after the model ran, or in the stream after thinking). - // Such a reply is asked again, up to RETRY_BAD_CALL times. A 400 that - // comes back fast is the request's own fault and is returned as it is. - const again400 = isGemini4(sent) || isGemini4(model) - let res, refusal - // asks is how many times the model was asked; slow, whether the last - // 400 took long enough to be the model's own (retry400.floorMs) - let asks = 0 - let slow = false - for (let n = 0; ; n++) { - const t0 = Date.now() - ;({ res, refusal } = await attempt()) - asks = n + 1 - slow = Date.now() - t0 >= retry400.floorMs - const left = again400 && n < RETRY_BAD_CALL && !init?.signal?.aborted - if (!left) break - if (!res.ok) { - if (res.status !== 400) break - const text = refusal ?? (await res.text()) - refusal = text - if (!badCall(text) || !slow) break - await sleep(retry400.pauseMs) - continue - } - const held = await holdThoughts(res, init?.signal) - if (held.bad) { - await sleep(retry400.pauseMs) - continue - } - res = new Response(held.body, { status: 200, headers: res.headers }) - break - } - if (!res.ok) { - const text = refusal ?? (await res.text()) - const msg = apiError(text, res.status) - if (again400 && res.status === 400 && slow && badCall(text)) return errorResponse(400, badCallSaid(sent, asks)(msg)) - if (res.status === 401) return errorResponse(401, `Antigravity: ${msg}`, "kept") - if (res.status === 404) return errorResponse(404, `model ${sent} not found`) - if (res.status === 429 && /resource has been exhausted/i.test(text) && turnsAway(system)) { - // the system prompt turned away, not a quota: a 400 the next member - // of a group is asked after, and the agent doesn't retry. It says - // what Antigravity answered (a 429), not that this is a channel - return errorResponse(400, `Antigravity answered 429 to this system prompt: ${msg} — ${hint(system)}`) - } - if (res.status === 429 && l.project.credits && !usesCredits(magpie)) { - // the credits note only where the model's quota may be what ran - // out: a 429 with quota left is something else, and credits would - // not change it (plugins#1148) - const left = await quotaLeft(s, sent) - const note = left > 0 ? quotaLeftNote(left) : CREDITS_NOTE - return new Response(withNote(text, note), { status: 429, headers: { "content-type": "application/json" } }) - } - return new Response(text, { status: res.status, headers: { "content-type": res.headers.get("content-type") ?? "application/json" } }) - } - if (stream) return new Response(unwrap(res.body, again400 ? badCallSaid(sent, asks) : undefined), { status: 200, headers: RESPONSE_HEADERS }) - return new Response(JSON.stringify(await whole(res)), { status: 200, headers: { "content-type": "application/json" } }) -} - -// ---- Google AI credits ---------------------------------------------------------------------- - -// CREDITS_OPTION is magpie's switch for the provider: off by default, since -// credits are money -const CREDITS_OPTION = "use-ai-credits" -const CREDITS_NOTE = - "this account has Google AI credits; turn on the Use AI credits switch in magpie's Antigravity editor to spend them when the plan's quota is used up, as the app's Use AI Credits does" - -// quotaLeft is the fraction of the model's quota fetchAvailableModels -// reads now, or -1 when it can't say. The cached list may be from before -// the quota ran out, so a failed read is unknown, not the cached value. -async function quotaLeft(s, model) { - try { - const mi = (await modelInfo(s, true)).infos.find((m) => m.id === model) - return mi ? mi.remaining : -1 - } catch { - return -1 - } -} - -function quotaLeftNote(left) { - return `this model still has ${Math.max(1, Math.round(left * 100))}% of its quota left, so this 429 is not the plan's quota running out, and Google AI credits would not change it` -} - -function usesCredits(magpie) { - try { - return magpie?.option?.(PROVIDER, CREDITS_OPTION) === true - } catch { - return false - } -} - -// withNote is an error body with a note added to its message -function withNote(text, note) { - const j = parse(text) - if (isObj(j) && isObj(j.error) && typeof j.error.message === "string") { - return JSON.stringify({ ...j, error: { ...j.error, message: j.error.message + " — " + note } }) - } - return text -} - -// mergeGrounding merges SSE groundingMetadata chunks without letting a -// trailing empty array overwrite chunks/supports from an earlier chunk -function mergeGrounding(prev, next) { - if (!isObj(prev)) return { ...next } - const out = { ...prev } - for (const [k, v] of Object.entries(next)) { - if (Array.isArray(v) && v.length === 0 && Array.isArray(prev[k]) && prev[k].length > 0) continue - out[k] = v - } - return out -} - -// whole is a stream read to its end, as one generateContent reply -async function whole(res) { - const text = await res.text() - const out = { candidates: [] } - const parts = [] - let last - let groundingMetadata - for (const l of text.split(/\r?\n/)) { - if (!l.startsWith("data:")) continue - let j = parse(l.slice(5).trim()) - if (isObj(j?.response)) j = j.response - if (!isObj(j)) continue - last = j - const c0 = j.candidates?.[0] - if (isObj(c0?.groundingMetadata)) groundingMetadata = mergeGrounding(groundingMetadata, c0.groundingMetadata) - for (const p of c0?.content?.parts ?? []) { - // a stream ends on an empty text, which Claude refuses sent back - if (p?.text === "" && !p.thoughtSignature && Object.keys(p).length === 1) continue - const prev = parts[parts.length - 1] - if (typeof p.text === "string" && prev && typeof prev.text === "string" && !!prev.thought === !!p.thought && !p.thoughtSignature) prev.text += p.text - else parts.push({ ...p }) - } - if (j.usageMetadata) out.usageMetadata = j.usageMetadata - if (j.modelVersion) out.modelVersion = j.modelVersion - if (j.responseId) out.responseId = j.responseId - } - const c = last?.candidates?.[0] ?? {} - out.candidates = [{ ...c, ...(groundingMetadata ? { groundingMetadata } : {}), content: { role: "model", parts } }] - return out -} - -// ---- usage ------------------------------------------------------------------------------ - -function vendorOf(id, name) { - const l = id.toLowerCase() - if (l.startsWith("gemini")) return "Gemini" - if (l.startsWith("claude")) return "Claude" - if (l.startsWith("gpt-oss")) return "GPT-OSS" - const f = String(name ?? "").trim().split(" ")[0] - if (f) return f - return id.split("-")[0] -} - -const FIVE = 5 * 3600 -const WEEK = 7 * 24 * 3600 - -function poolName(s) { - s = String(s ?? "").trim() - if (s.toLowerCase().endsWith(" models")) s = s.slice(0, -7).trim() - return s.replaceAll(" and ", " & ") -} - -const versioned = (pool) => /[0-9]/.test(pool) - -function poolNames(pool, w) { - if (!versioned(pool)) return false - const p = pool.toLowerCase() - for (let s of [w.name, (w.model ?? "").replaceAll("-", " ")]) { - s = String(s ?? "").toLowerCase() - if (s === p || s.startsWith(p + " ") || s.startsWith(p + "(")) return true - } - return false -} - -function sameReading(m, p) { - if (Math.abs(m.used - p.used) > 0.5) return false - if (!m.resetsAt || !p.resetsAt) return true - const d = Date.parse(m.resetsAt) - Date.parse(p.resetsAt) - return d < 60_000 && d > -60_000 -} - -function modelPool(w) { - let name = String(w.name ?? "").trim() - const i = name.indexOf(" (") - if (i > 0) name = name.slice(0, i).trim() - return name -} - -const resetSecs = (t) => Math.max(0, Math.floor((Date.parse(t) - Date.now()) / 1000)) - -// pools are the allowances a group of models shares, as the quota summary -// gives them, with each model's window put in the pool it reads from -function pools(summary, ws) { - const out = [] - const groups = [] - for (const gr of summary?.groups ?? []) { - const pool = poolName(gr?.displayName) - if (!pool) continue - let five = -1 - const all = [] - for (const b of gr.buckets ?? []) { - if (!b || b.disabled) continue - const w = { name: "", pool, used: 100, aside: true } - switch (String(b.window ?? "").toLowerCase()) { - case "5h": - w.name = "5 hours" - w.span = FIVE - break - case "weekly": - w.name = "7 days" - w.span = WEEK - break - default: - w.name = b.displayName || b.window || b.bucketId || "" - } - if (!w.name) continue - if (typeof b.remainingFraction === "number") w.used = (1 - b.remainingFraction) * 100 - if (typeof b.resetTime === "string" && !isNaN(Date.parse(b.resetTime))) { - w.resetsAt = b.resetTime - w.resetSecs = resetSecs(b.resetTime) - } - if (w.span === FIVE && five < 0) five = out.length - all.push(out.length) - out.push(w) - } - if (all.length) groups.push({ pool, about: `${gr.displayName ?? ""} ${gr.description ?? ""}`.toLowerCase(), five, all }) - } - const own = new Set() - for (const w of ws) { - if (w.pool || !w.family) continue - const g = groups.find((gr) => poolNames(gr.pool, w)) - if (g) { - w.pool = g.pool - continue - } - for (const gr of groups) { - if (!(gr.five >= 0 && !versioned(gr.pool) && gr.about.includes(w.family.toLowerCase()))) continue - if (sameReading(w, out[gr.five])) w.pool = gr.pool - else { - const k = gr.all.find((k) => k !== gr.five && sameReading(w, out[k])) - if (k !== undefined) { - w.pool = gr.pool - w.span = out[k].span - } else { - const name = modelPool(w) - if (name) { - w.pool = name - const p = { ...w, name: "5 hours", span: FIVE } - if (w.resetsAt && Date.parse(w.resetsAt) - Date.now() > (FIVE + 60) * 1000) { - p.name = "7 days" - p.span = WEEK - w.span = WEEK - } - if (!own.has(name)) { - own.add(name) - delete p.model - delete p.models - delete p.family - p.aside = true - out.push(p) - } - } - } - } - break - } - } - return out -} - -async function usage(auth) { - const s = stateOf(auth) - if (!s) return { error: "no such Antigravity account", signIn: "kept" } - let l - try { - l = await modelInfo(s, true) - } catch (e) { - if (e instanceof SignedOut) return { error: e.message, signIn: "expired" } - return { error: e?.message ?? String(e), signIn: "kept" } - } - const raw = catalogOf(l.infos) - const fams = families(raw) - const familyOf = (id) => fams.find((f) => f.variants.length > 1 && f.variants.some((v) => v.id === id))?.id ?? id - const ws = [] - for (const mi of l.infos) { - if (mi.remaining < 0) continue - const w = { name: mi.name || mi.id, used: (1 - mi.remaining) * 100, model: mi.id, family: vendorOf(mi.id, mi.name) } - const fam = familyOf(mi.id) - w.models = fam !== mi.id ? [mi.id, fam] : [mi.id] - if (mi.resets) { - w.resetsAt = mi.resets - w.resetSecs = resetSecs(mi.resets) - } - ws.push(w) - } - let summary - try { - summary = await call(s, DAILY, "retrieveUserQuotaSummary", { project: l.project.id }) - } catch {} - const out = { plan: l.project.plan || undefined, signIn: "kept", windows: [...ws, ...(summary ? pools(summary, ws) : [])] } - return out -} - -// ---- sign-in ------------------------------------------------------------------------------- - -const b64url = (b) => b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") - -// signedIn is a refresh token (and a project, when one is known) as the -// sign-in to keep: the account's email, its project found or set up -async function signedIn(rt, access, expires, projectID, email) { - const s = { rt, project: projectID ?? "", access: access ?? "", expires: expires ?? 0, who: email ?? "" } - if (!access) await token(s) - const tok = await token(s) - if (!email) { - const res = await fetch(WHO_URL, { headers: { Authorization: "Bearer " + tok }, signal: AbortSignal.timeout(30_000) }) - const who = res.ok ? parse(await res.text()) : undefined - email = who?.email - if (!email) throw new Error("Google didn't say whose account this is") - } - // the project, found now so requests don't wait on it; a sign-in is kept - // without one, found again on the first request - try { - const p = await resolveProject(s) - s.project = p.id - projects.set(rt, p) - } catch (e) { - if (e instanceof SignedOut) throw e - } - const t = tokens.get(rt) - return { type: "success", access: t?.access ?? tok, refresh: `${rt}|${s.project}`, expires: t?.expires ?? Date.now() + 3600_000, accountId: email } -} - -async function listen(handler) { - const server = http.createServer(handler) - await new Promise((resolve, reject) => { - server.once("error", reject) - server.listen(0, "127.0.0.1", resolve) - }) - const port = server.address().port - // localhost may be ::1 to the browser - const six = http.createServer(handler) - await new Promise((resolve) => { - six.once("error", () => resolve()) - six.listen(port, "::1", resolve) - }) - const close = () => { - for (const x of [server, six]) { - try { - x.close() - x.closeAllConnections?.() - } catch {} - } - } - return { port, close } -} - -const PAGE = (ok, msg) => - `Antigravity${ok ? "Signed in to Antigravity. You can close this tab." : "Sign-in failed: " + msg.replace(/[<>&]/g, "")}` - -async function signIn() { - const verifier = b64url(crypto.randomBytes(32)) - const challenge = b64url(crypto.createHash("sha256").update(verifier).digest()) - const state = b64url(crypto.randomBytes(16)) - let got - const back = new Promise((r) => (got = r)) - const { port, close } = await listen((req, res) => { - const u = new URL(req.url ?? "/", "http://localhost") - if (u.pathname !== "/oauth-callback") { - res.writeHead(404).end() - return - } - const err = u.searchParams.get("error") - const code = u.searchParams.get("code") - if (u.searchParams.get("state") !== state || (!code && !err)) { - res.writeHead(400, { "content-type": "text/html; charset=utf-8" }).end(PAGE(false, "this page isn't the sign-in magpie started")) - return - } - res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(PAGE(!err, err ?? "")) - got({ code, err }) - }) - const redirect = `http://localhost:${port}/oauth-callback` - const q = new URLSearchParams({ - client_id: CLIENT_ID, - redirect_uri: redirect, - response_type: "code", - scope: SCOPES.join(" "), - access_type: "offline", - prompt: "consent", - state, - code_challenge: challenge, - code_challenge_method: "S256", - }) - return { - url: `${AUTH_URL}?${q}`, - instructions: "Sign in with your Google account in the browser; it comes back here when you're done.", - method: "auto", - async callback() { - let timer - try { - const cb = await Promise.race([back, new Promise((r) => (timer = setTimeout(() => r(null), SIGN_IN_TIMEOUT)))]) - if (!cb) return { type: "failed", error: "the sign-in timed out" } - if (cb.err) return { type: "failed", error: `Google: ${cb.err}` } - const t = await postForm(TOKEN_URL, { grant_type: "authorization_code", code: cb.code, redirect_uri: redirect, client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code_verifier: verifier }) - if (!t.access_token || !t.refresh_token) return { type: "failed", error: "Google sent back no token" } - const expires = Date.now() + (Number(t.expires_in) || 3600) * 1000 - tokens.set(t.refresh_token, { access: t.access_token, expires }) - return await signedIn(t.refresh_token, t.access_token, expires, "") - } catch (e) { - return { type: "failed", error: e?.message ?? String(e) } - } finally { - clearTimeout(timer) - close() - } +const AGY_CLI = "@magpie-community/opencode-agy-cli-auth" + +export const RETIRED = + "Antigravity with a Google account has been retired in magpie: Google bans accounts it sees used this way. " + + `Install "Antigravity (local agy CLI)" from Plugins (magpie plugin add ${AGY_CLI}), which runs your own agy CLI over ACP, then remove this plugin.` + +// the reply to every request: Gemini's error shape, which magpie and the +// AI SDK read, saying the model has been retired +function retiredResponse() { + const body = { + error: { + code: 410, + status: "ModelDeprecated", + message: `Antigravity: this model has been retired. ${RETIRED}`, }, } + return new Response(JSON.stringify(body), { status: 410, headers: { "content-type": "application/json" } }) } -// imported is the first account of a pasted export: a JSON account or -// list of them (Antigravity tools' exports: refresh_token, project_id, -// email, perhaps under token or accounts), or bare refresh tokens, one a -// line -function imported(text) { - text = String(text ?? "").trim() - const j = parse(text) - const found = [] - const take = (o) => { - if (!isObj(o)) return - if (typeof o.type === "string" && o.type && o.type.toLowerCase() !== "antigravity") throw new Error(`this is a ${o.type} account, not Antigravity's`) - const t = isObj(o.token) ? o.token : o - const rt = t.refresh_token ?? t.refreshToken ?? o.refresh_token ?? o.refreshToken - if (typeof rt === "string" && rt) { - found.push({ rt, project: t.project_id ?? t.projectId ?? t.project ?? o.project_id ?? o.projectId ?? o.project ?? "", email: o.email ?? t.email ?? "" }) - return - } - if (Array.isArray(o.accounts)) o.accounts.forEach(take) - } - if (Array.isArray(j)) j.forEach(take) - else if (isObj(j)) take(j) - else if (j === undefined) { - for (const line of text.split(/\r?\n/)) { - const l = line.trim() - if (l && !l.startsWith("#")) found.push({ rt: l, project: "", email: "" }) - } - } - return found -} - -async function importAccount(inputs) { - let found - try { - found = imported(inputs?.account) - } catch (e) { - return { type: "failed", error: e.message } - } - if (!found.length) return { type: "failed", error: "no refresh token in what was pasted" } - const a = found[0] +export async function AntigravityAuthPlugin() { return { - url: "", - instructions: "Checking the account with Google…", - method: "auto", - async callback() { - try { - return await signedIn(a.rt, "", 0, typeof a.project === "string" ? a.project : "", a.email) - } catch (e) { - return { type: "failed", error: e?.message ?? String(e) } - } - }, - } -} - -// ---- web search (Google Search grounding) ----------------------------------------------- - -// Preference order for search calls; falls back to any non-image Flash or Gemini model in the live catalog -const SEARCH_MODELS = ["gemini-3-flash", "gemini-2.5-flash", "gemini-3.1-flash-lite", "gemini-2.5-flash-lite"] - -function pickSearchModel(infos) { - const raw = catalogOf(infos) - const remaining = new Map((Array.isArray(infos) ? infos : []).map((m) => [m.id, m.remaining])) - const pickFrom = (pool) => { - const ids = new Set(pool.map((m) => m.id)) - for (const id of SEARCH_MODELS) if (ids.has(id)) return id - const flash = pool.find((m) => m.id.startsWith("gemini-") && !draws(m.id) && m.id.includes("flash")) - if (flash) return flash.id - const anyGemini = pool.find((m) => m.id.startsWith("gemini-") && !draws(m.id)) - return anyGemini?.id ?? "" - } - const avail = raw.filter((m) => remaining.get(m.id) !== 0) - return pickFrom(avail) || pickFrom(raw) || SEARCH_MODELS[0] -} - -function searchThinkingConfig(sent) { - const m = String(sent ?? "").toLowerCase() - if (generation(m) >= 3 || m.startsWith("gemini-pro-agent")) { - return { includeThoughts: false, thinkingLevel: m.includes("flash") ? "minimal" : "low" } - } - return { includeThoughts: false, thinkingBudget: 0 } -} - -function pagesFromGrounding(reply, count) { - const cand = reply?.candidates?.[0] - const gm = cand?.groundingMetadata - const chunks = Array.isArray(gm?.groundingChunks) ? gm.groundingChunks : [] - if (!chunks.length) return [] - const supports = Array.isArray(gm?.groundingSupports) ? gm.groundingSupports : [] - const answer = (cand?.content?.parts ?? []) - .filter((p) => !p?.thought && typeof p?.text === "string") - .map((p) => p.text) - .join("") - .trim() - const textsByIdx = chunks.map(() => []) - for (const sup of supports) { - const seg = typeof sup?.segment?.text === "string" ? sup.segment.text.trim() : "" - if (!seg || !Array.isArray(sup?.groundingChunkIndices)) continue - for (const idx of sup.groundingChunkIndices) { - if (Number.isInteger(idx) && idx >= 0 && idx < chunks.length && !textsByIdx[idx].includes(seg)) { - textsByIdx[idx].push(seg) - } - } - } - const out = [] - const byKey = new Map() - for (let i = 0; i < chunks.length; i++) { - const url = typeof chunks[i]?.web?.uri === "string" ? chunks[i].web.uri.trim() : "" - const title = (typeof chunks[i]?.web?.title === "string" ? chunks[i].web.title.trim() : "") || url - if (!url && !title) continue - const key = url || title - const existing = byKey.get(key) - if (existing) { - for (const s of textsByIdx[i]) if (!existing._snippets.includes(s)) existing._snippets.push(s) - continue - } - const entry = { title: title || url, url, _snippets: [...textsByIdx[i]] } - byKey.set(key, entry) - out.push(entry) - } - const limit = Number.isInteger(Number(count)) && Number(count) > 0 ? Number(count) : out.length - const trimmed = out.slice(0, limit).map(({ title, url, _snippets }) => ({ - title, - url, - text: _snippets.join("\n"), - })) - if (answer && trimmed.length && trimmed.every((p) => !p.text)) trimmed[0].text = answer - return trimmed -} - -async function webSearch({ query, count } = {}, ctx = {}) { - const q = typeof query === "string" ? query.trim() : "" - if (!q) throw new Error("query is required") - const s = stateOf(await ctx.getAuth?.()) - if (!s) throw new Error("not signed in to Antigravity") - let l - try { - l = await modelInfo(s) - } catch (e) { - if (e instanceof SignedOut) throw new StatusError(401, e.message) - throw e - } - const picked = pickSearchModel(l.infos) - const [sent, at] = sentID(catalogOf(l.infos), picked, "minimal") - const n = Number.isInteger(Number(count)) && Number(count) > 0 ? Math.min(Number(count), 20) : 6 - const raw = { - systemInstruction: { - role: "user", - parts: [{ text: "You are a web search retrieval assistant. Always use Google Search to look up the user's query. Write concise bullet points summarizing concrete facts, dates, versions, and numbers, and ground each bullet in the retrieved sources so every major source is cited." }], - }, - contents: [{ - role: "user", - parts: [{ text: `Search the live web for: ${q}\nProvide up to ${n} diverse, authoritative web sources, ensuring each relevant source supports at least one concrete factual bullet point.` }], - }], - tools: [{ googleSearch: {} }], - } - const req = shape(raw, sent, at, "minimal") - req.generationConfig = { thinkingConfig: searchThinkingConfig(sent) } - let tok - try { - tok = await token(s) - } catch (e) { - if (e instanceof SignedOut) throw new StatusError(401, e.message) - throw e - } - const ua = await userAgent() - const res = await fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer " + tok, "User-Agent": ua }, - body: JSON.stringify(envelope(req, sent, l.project.id, false)), - signal: ctx.abort, - }) - if (!res.ok) { - const text = await res.text() - const err = new StatusError(res.status, `Antigravity: ${apiError(text, res.status)}`) - const ra = res.headers.get("retry-after") - if (ra) err.retryAfter = ra - throw err - } - const reply = await whole(res) - return pagesFromGrounding(reply, count) -} - -// ---- the plugin --------------------------------------------------------------------------- - -export async function AntigravityAuthPlugin({ client, magpie } = {}) { - return { - async "chat.headers"(input, output) { - if (input?.model?.providerID !== PROVIDER && input?.provider?.info?.id !== PROVIDER) return - const s = String(input?.sessionID ?? "").trim() - if (s && !/^magpie-[0-9a-f]{24}$/.test(s)) output.headers[SESSION] = s.slice(0, 128) - }, config: async (cfg) => { cfg.provider ??= {} const was = cfg.provider[PROVIDER] ?? {} - const fallback = collapse(catalogOf([])) - cfg.provider[PROVIDER] = { - name: "Antigravity", - npm: NPM, - api: BASE, - ...was, - models: { ...Object.fromEntries(fallback.map((m) => [m.id, entry(m)])), ...(was.models ?? {}) }, - } + cfg.provider[PROVIDER] = { ...was, name: "Antigravity (retired)", npm: "@ai-sdk/google", models: {} } }, provider: { id: PROVIDER, - async models(provider, { auth } = {}) { - const s = stateOf(auth) - if (!s) return provider.models - let l - try { - l = await modelInfo(s) - } catch (e) { - if (e instanceof SignedOut) throw Object.assign(e, { signIn: "expired" }) - throw /^Antigravity\b/.test(e?.message ?? "") ? e : new Error(`Antigravity: this account's models couldn't be read: ${e?.message ?? e}`) - } - return Object.fromEntries(collapse(catalogOf(l.infos)).map((m) => [m.id, model(m)])) + async models() { + return {} }, }, auth: { provider: PROVIDER, - // magpie's switches for the provider, read at each request - options: [ - { - key: CREDITS_OPTION, - label: "Use AI credits", - description: "When the plan's quota for a model is used up, spend the account's Google AI credits on the request, as the Antigravity app's Use AI Credits does. Off: the request fails with the quota's 429.", - labels: { zh: "使用 AI 额度" }, - descriptions: { zh: "套餐的模型额度用完后,用账号的 Google AI 积分继续请求,同 Antigravity 应用里的 Use AI Credits。关闭时请求以额度 429 失败。" }, - }, - ], methods: [ - { type: "oauth", label: "Sign in with Google (browser)", authorize: signIn }, { type: "oauth", - label: "Import an account (refresh token or JSON export)", - prompts: [{ type: "text", key: "account", message: "A refresh token, or an exported account's JSON" }], - authorize: importAccount, + label: "Use Antigravity (local agy CLI) instead", + async authorize() { + throw new Error(RETIRED) + }, }, ], - async loader(getAuth) { - if (!stateOf(await getAuth())) return {} + async loader() { return { - baseURL: BASE, - apiKey: "antigravity", // the access token is put on by the fetch below - async fetch(input, init) { - const s = stateOf(await getAuth()) - if (!s) throw new Error("not signed in to Antigravity") - const url = input instanceof Request ? input.url : String(input) - if (input instanceof Request) init = { method: input.method, headers: input.headers, body: await input.text(), signal: input.signal, ...init } - return complete(s, url, init, magpie) + apiKey: "antigravity", + async fetch() { + return retiredResponse() }, } }, - async usage(getAuth) { - return usage(await getAuth()) - }, - }, - search: { - antigravity: { - name: "Antigravity (Google Search)", - auth: PROVIDER, - execute: webSearch, - }, }, } } -export const _internal = { - onboardPoll: 2000, - stateOf, - listed, - catalogOf, - families, - byEffort, - collapse, - nearestEffort, - sentID, - plainSchema, - cloak, - turnsAway, - hint, - shape, - sessionOf, - envelope, - unwrap, - whole, - pools, - vendorOf, - poolName, - imported, - apiError, - planOf, - creditsOf, - entitlements, - complete, - pickSearchModel, - pagesFromGrounding, - webSearch, - retry400, - badCall, - usage, - tokens, - projects, - lists, - refused, - ver, - version, - VERSION_TTL, - VERSION_RETRY, - DEFAULT_VERSION, - CLS, - clOf, - enums, - userAgent, -} +export const _internal = { RETIRED, retiredResponse } diff --git a/packages/antigravity/models.test.mjs b/packages/antigravity/models.test.mjs deleted file mode 100644 index 7d4537e..0000000 --- a/packages/antigravity/models.test.mjs +++ /dev/null @@ -1,111 +0,0 @@ -// The account's models as the built-in lists them: one model per family of -// levels (internal/provider/antigravity_models_test.go), and the variant a -// request at an effort goes out under (codeassist_test.go's -// TestCodeAssistAntigravityLevels). -import { expect, test } from "bun:test" -import { _internal } from "./index.mjs" - -const { collapse, byEffort, families, sentID, listed, catalogOf } = _internal - -const raw = [ - ["claude-opus-4-6-thinking", "Claude Opus 4.6 (Thinking)"], - ["gemini-3-flash", "Gemini 3 Flash"], - ["gemini-3-flash-agent", "Gemini 3.5 Flash (High)"], - ["gemini-3.1-pro-high", "Gemini 3.1 Pro (High)"], - ["gemini-3.1-pro-low", "Gemini 3.1 Pro (Low)"], - ["gemini-3.5-flash-extra-low", "Gemini 3.5 Flash (Low)"], - ["gemini-3.5-flash-lite", "Gemini 3.5 Flash Lite"], - ["gemini-3.5-flash-low", "Gemini 3.5 Flash (Medium)"], - ["gemini-3.7-flash-high", "Gemini 3.7 Flash (High)"], - ["gemini-3.7-flash-low", "Gemini 3.7 Flash (Low)"], - ["gemini-3.7-flash-medium", "Gemini 3.7 Flash (Medium)"], - ["gemini-3.7-flash-tiered", ""], - ["gemini-pro-agent", "Gemini 3.1 Pro (High)"], - ["gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"], -].map(([id, name]) => ({ id, name, context: 0, output: 0, images: true })) - -test("a family of levels is one model", () => { - expect(collapse(raw).map((m) => `${m.id}|${m.name}|${m.efforts.join(",")}`)).toEqual([ - "claude-opus-4-6-thinking|Claude Opus 4.6 (Thinking)|", - "gemini-3-flash|Gemini 3 Flash|", - "gemini-3-flash-agent|Gemini 3.5 Flash (High)|", - "gemini-3.1-pro|Gemini 3.1 Pro|low,high", - "gemini-3.5-flash|Gemini 3.5 Flash|low,medium", - "gemini-3.5-flash-lite|Gemini 3.5 Flash Lite|", - "gemini-3.7-flash|Gemini 3.7 Flash|low,medium,high", - "gemini-3.7-flash-tiered|Gemini 3.7 Flash (Tiered)|low,medium,high", - "gemini-pro-agent|Gemini 3.1 Pro (High)|", - "gpt-oss-120b-medium|GPT-OSS 120B (Medium)|", - ]) - const vs = (id) => byEffort(families(raw).find((f) => f.id === id)) - expect(vs("gemini-3.7-flash")).toMatchObject({ "": "gemini-3.7-flash-high", high: "gemini-3.7-flash-high", low: "gemini-3.7-flash-low", medium: "gemini-3.7-flash-medium" }) - expect(vs("gemini-3.5-flash")).toMatchObject({ "": "gemini-3.5-flash-low", low: "gemini-3.5-flash-extra-low", medium: "gemini-3.5-flash-low" }) - // an id of no level is the default; without high, the highest - expect(byEffort(families([{ id: "m-low", name: "" }, { id: "m", name: "" }, { id: "m-high", name: "" }])[0])[""]).toBe("m") - expect(byEffort(families([{ id: "m-low", name: "" }, { id: "m-medium", name: "" }])[0])[""]).toBe("m-medium") -}) - -test("models Antigravity leaves unnamed (#955)", () => { - const got = collapse( - [["gemini-3.6-flash-high", "Gemini 3.6 Flash (High)"], ["gemini-3.6-flash-low", "Gemini 3.6 Flash (Low)"], ["gemini-3.6-flash-tiered", ""], ["gemini-9-flash-tiered", ""], ["mystery-model", ""]].map( - ([id, name]) => ({ id, name, images: true, context: 0, output: 0 }), - ), - ).map((m) => `${m.id}|${m.name}|${m.efforts.join(",")}`) - expect(got).toEqual([ - "gemini-3.6-flash|Gemini 3.6 Flash|low,high", - "gemini-3.6-flash-tiered|Gemini 3.6 Flash (Tiered)|low,high", - "gemini-9-flash-tiered|gemini-9-flash-tiered|", - "mystery-model|mystery-model|", - ]) -}) - -test.each([ - ["gemini-3.7-flash", "low", "gemini-3.7-flash-low", "low"], - ["gemini-3.7-flash", "medium", "gemini-3.7-flash-medium", "medium"], - ["gemini-3.7-flash", "xhigh", "gemini-3.7-flash-high", "high"], - ["gemini-3.7-flash", "", "gemini-3.7-flash-high", "high"], - ["gemini-3.7-flash-high", "", "gemini-3.7-flash-high", "high"], - ["gemini-3.7-flash-high", "low", "gemini-3.7-flash-low", "low"], - ["gemini-3.1-pro", "medium", "gemini-3.1-pro-high", "high"], - ["gemini-3-flash", "medium", "gemini-3-flash", ""], - ["gemini-pro-agent", "medium", "gemini-pro-agent", ""], -])("%s at %p goes as %s", (model, effort, want, at) => { - const levels = [ - ["gemini-3-flash", "Gemini 3 Flash"], - ["gemini-3.1-pro-high", "Gemini 3.1 Pro (High)"], - ["gemini-3.1-pro-low", "Gemini 3.1 Pro (Low)"], - ["gemini-3.7-flash-high", "Gemini 3.7 Flash (High)"], - ["gemini-3.7-flash-low", "Gemini 3.7 Flash (Low)"], - ["gemini-3.7-flash-medium", "Gemini 3.7 Flash (Medium)"], - ["gemini-pro-agent", "Gemini 3.1 Pro (High)"], - ].map(([id, name]) => ({ id, name })) - expect(sentID(levels, model, effort)).toEqual([want, at]) -}) - -test("the list as fetchAvailableModels gives it", () => { - const res = { - models: { - "gemini-3-flash": { displayName: "Gemini 3 Flash", maxTokens: 1048576, maxOutputTokens: 65536, supportsImages: true, quotaInfo: { remainingFraction: 0.5, resetTime: "2099-01-01T00:00:00Z" } }, - "claude-sonnet-4-6": { displayName: "Claude Sonnet 4.6", quotaInfo: {} }, - "gpt-oss-120b-medium": { displayName: "GPT-OSS 120B (Medium)" }, - chat_20706: { displayName: "internal" }, - "tab_x": { displayName: "tab" }, - "gemini-2.5-pro": { displayName: "Gemini 2.5 Pro" }, - "gemini-old": { displayName: "Gemini Old", disabled: true }, - // a name that is another's: the id's - "gemini-3-flash-agent": { displayName: "Gemini 3 Flash" }, - }, - agentModelSorts: [{ groups: [{ modelIds: ["claude-sonnet-4-6", "gemini-3-flash"] }] }], - } - const infos = listed(res) - expect(infos.map((m) => m.id)).toEqual(["claude-sonnet-4-6", "gemini-3-flash", "gemini-3-flash-agent", "gpt-oss-120b-medium"]) - expect(infos[0].remaining).toBe(0) // the fraction left out once none is left - expect(infos[1]).toMatchObject({ remaining: 0.5, resets: "2099-01-01T00:00:00Z", context: 1048576, output: 65536 }) - expect(infos[2].name).toBe("") - expect(infos[3].remaining).toBe(-1) - const cat = catalogOf(infos) - expect(cat.find((m) => m.id === "gpt-oss-120b-medium").images).toBe(false) - expect(cat.find((m) => m.id === "claude-sonnet-4-6").images).toBe(true) - // nothing listed: the fallback - expect(catalogOf([]).length).toBeGreaterThan(3) -}) diff --git a/packages/antigravity/package.json b/packages/antigravity/package.json index 70562b4..fad44cb 100644 --- a/packages/antigravity/package.json +++ b/packages/antigravity/package.json @@ -1,7 +1,7 @@ { "name": "@magpie-community/opencode-antigravity-auth", - "version": "0.1.18", - "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", + "version": "0.2.0", + "description": "Retired: sends no request and points to Antigravity (local agy CLI), @magpie-community/opencode-agy-cli-auth, which Google does not ban accounts for", "type": "module", "main": "./opencode.mjs", "exports": { ".": "./opencode2.mjs" }, diff --git a/packages/antigravity/requests.test.mjs b/packages/antigravity/requests.test.mjs deleted file mode 100644 index f4df78d..0000000 --- a/packages/antigravity/requests.test.mjs +++ /dev/null @@ -1,482 +0,0 @@ -// Requests as the built-in sent them (google_test.go's -// TestAntigravityProjectAndEnvelope, the tier tests in -// antigravity_tier_test.go, and codeassist.go's error rules). -import { afterEach, beforeEach, expect, test } from "bun:test" -import { AntigravityAuthPlugin, _internal } from "./index.mjs" -import { auth, fake, real, reset } from "./fake.mjs" - -beforeEach(() => { reset(); _internal.retry400.pauseMs = 0; _internal.retry400.floorMs = 3000; _internal.retry400.holdMs = 10_000 }) -afterEach(() => (globalThis.fetch = real)) - -const URL_ = (m, method = "streamGenerateContent") => `https://daily-cloudcode-pa.googleapis.com/v1beta/models/${m}:${method}?alt=sse` -const ask = (text = "hi", extra = {}) => JSON.stringify({ contents: [{ role: "user", parts: [{ text }] }], ...extra }) -const sse = (...chunks) => new Response(chunks.map((c) => "data: " + JSON.stringify({ response: c, traceId: "t" }) + "\r\n\r\n").join(""), { status: 200, headers: { "content-type": "text/event-stream" } }) -const models = { - models: { - "gemini-3.7-flash-high": { displayName: "Gemini 3.7 Flash (High)" }, - "gemini-3.7-flash-low": { displayName: "Gemini 3.7 Flash (Low)" }, - "gemini-3-flash": { displayName: "Gemini 3 Flash" }, - }, -} - -async function loaderFetch(a) { - const p = await AntigravityAuthPlugin({}) - const l = await p.auth.loader(async () => a) - return l.fetch -} - -test("a request goes in Antigravity's envelope, and its stream comes back Gemini's", async () => { - const seen = fake({ - fetchAvailableModels: models, - streamGenerateContent: () => sse({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "lo" }] }, finishReason: "STOP" }], usageMetadata: { totalTokenCount: 3 } }), - }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-3.7-flash"), { method: "POST", headers: { "content-type": "application/json", "x-magpie-effort": "low" }, body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true } } }) }) - expect(res.status).toBe(200) - const text = await res.text() - const chunks = text.split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6))) - expect(chunks.map((c) => c.candidates[0].content.parts[0].text).join("")).toBe("Hello") - 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") - // 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 - await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(seen.filter((s) => s.name === "fetchAvailableModels").length).toBe(1) -}) - -test("OpenCode's variant names the level", async () => { - const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) }) - const f = await loaderFetch(auth()) - await f(URL_("gemini-3.7-flash"), { method: "POST", body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true, thinkingLevel: "low" } } }) }) - expect(seen.find((s) => s.name === "streamGenerateContent").json.model).toBe("gemini-3.7-flash-low") -}) - -test("a level in capitals, as Gemini's own clients write it, names the level too (#1169)", async () => { - const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) }) - const f = await loaderFetch(auth()) - await f(URL_("gemini-3.7-flash"), { method: "POST", body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true, thinkingLevel: "LOW" } } }) }) - const sent = seen.find((s) => s.name === "streamGenerateContent").json - expect(sent.model).toBe("gemini-3.7-flash-low") - expect(sent.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: "low" }) -}) - -test("a Request input is read", async () => { - const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) }) - const f = await loaderFetch(auth()) - const res = await f(new Request(URL_("gemini-3-flash"), { method: "POST", body: ask("from a Request") })) - expect(res.status).toBe(200) - expect(seen.find((s) => s.name === "streamGenerateContent").json.request.contents[0].parts[0].text).toBe("from a Request") -}) - -test("generateContent is the stream read whole", async () => { - fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "lo" }, { functionCall: { name: "f", args: {} } }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "" }] }, finishReason: "STOP" }], usageMetadata: { totalTokenCount: 3 } }) }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-3-flash", "generateContent"), { method: "POST", body: ask() }) - const j = await res.json() - // the stream's last, empty text is left out - expect(j.candidates[0].content.parts).toEqual([{ text: "Hello" }, { functionCall: { name: "f", args: {} } }]) - expect(j.candidates[0].finishReason).toBe("STOP") - expect(j.usageMetadata.totalTokenCount).toBe(3) -}) - -const exhausted = () => new Response(JSON.stringify({ error: { code: 429, message: "Resource has been exhausted (e.g. check quota).", status: "RESOURCE_EXHAUSTED" } }), { status: 429 }) - -test("a 429 to a turned-away system prompt is a 400, not a quota", async () => { - fake({ fetchAvailableModels: models, streamGenerateContent: exhausted }) - const f = await loaderFetch(auth()) - for (const [sys, says] of [ - ["x-anthropic-billing-header: cc_version=2.1", "Claude Code and the Claude Agent SDK"], - ["You are Codex, a coding agent based on GPT-5.", "Codex's own system prompt"], - ["You are Hermes Agent, an intelligent AI assistant created by Nous Research.", "Hermes Agent's default persona"], - ["You are Hermes Agent, built by Nous Research.", "Hermes Agent's default persona"], - ["You are opencode, an interactive CLI tool that helps users with software engineering tasks.", "OpenCode's system prompt"], - ["You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.", "Codex's prompt for a model it has none of its own for"], - ["You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.", "pi's default system prompt"], - ["RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\n\n§ Role", "oh-my-pi (omp)'s system prompt"], - ["RFC 2119 keywords: MUST, REQUIRED,\r\nSHOULD, RECOMMENDED, MAY, OPTIONAL.\r\n\r\n§ Role", "oh-my-pi (omp)'s system prompt"], - ]) { - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask("hi", { systemInstruction: { parts: [{ text: sys }] } }) }) - expect(res.status).toBe(400) - const j = await res.json() - expect(j.error.message).toContain("answered 429 to this system prompt") - expect(j.error.message).not.toContain("unapproved channel") - expect(j.error.message).toContain(says) - } - // any other prompt's 429 is the quota it says - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask("hi", { systemInstruction: { parts: [{ text: "be brief" }] } }) }) - expect(res.status).toBe(429) - expect((await res.json()).error.status).toBe("RESOURCE_EXHAUSTED") -}) - -test("a model Antigravity doesn't have, and a sign-in that is over", async () => { - fake({ fetchAvailableModels: models, streamGenerateContent: () => new Response("{}", { status: 404 }) }) - let f = await loaderFetch(auth()) - let res = await f(URL_("gemini-9"), { method: "POST", body: ask() }) - expect(res.status).toBe(404) - expect((await res.json()).error.message).toBe("model gemini-9 not found") - - reset() - fake({ token: () => new Response(JSON.stringify({ error: "invalid_grant", error_description: "Token has been expired or revoked." }), { status: 400 }) }) - f = await loaderFetch({ ...auth(), expires: 0 }) - res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(401) - expect(res.headers.get("x-magpie-sign-in")).toBe("expired") - expect((await res.json()).error.message).toContain("sign in again") -}) - -test("an account with no project is set up for its default tier", async () => { - const seen = fake({ - loadCodeAssist: { allowedTiers: [{ id: "free-tier", name: "Antigravity", isDefault: true }] }, - onboardUser: (_, all) => (all.filter((s) => s.name === "onboardUser").length < 2 ? { done: false } : { done: true, response: { cloudaicompanionProject: { id: "ag-new" } } }), - fetchAvailableModels: models, - streamGenerateContent: () => sse({ candidates: [] }), - }) - const f = await loaderFetch(auth("")) - await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - const load = seen.find((s) => s.name === "loadCodeAssist") - 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") - // 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") -}) - -test("a paid tier is named, and a tier Google refuses is asked without, once a day", async () => { - const seen = fake({ - loadCodeAssist: { cloudaicompanionProject: "ag-proj", currentTier: { id: "standard-tier" }, paidTier: { id: "g1-pro-tier", name: "Google AI Pro" } }, - fetchAvailableModels: (s) => (s.json.entitlement ? new Response(JSON.stringify({ error: { code: 400, message: "Invalid tier" } }), { status: 400 }) : models), - }) - const p = await AntigravityAuthPlugin({}) - const a = auth() - const got = await p.provider.models({ models: {} }, { auth: a }) - expect(Object.keys(got)).toEqual(["gemini-3-flash", "gemini-3.7-flash"]) - expect(got["gemini-3.7-flash"].variants).toEqual({ low: { thinkingConfig: { thinkingLevel: "low", includeThoughts: true } }, high: { thinkingConfig: { thinkingLevel: "high", includeThoughts: true } } }) - const asks = seen.filter((s) => s.name === "fetchAvailableModels").map((s) => s.json.entitlement?.userTier ?? "") - expect(asks).toEqual(["g1-pro-tier", "standard-tier", ""]) - _internal.lists.clear() - await p.provider.models({ models: {} }, { auth: a }) - expect(seen.filter((s) => s.name === "fetchAvailableModels").length).toBe(4) - const u = await p.auth.usage(async () => a) - expect(u.plan).toBe("Google AI Pro") -}) - -test("an exported account is imported", async () => { - const { imported } = _internal - expect(imported('{"email":"a@x.com","token":{"refresh_token":"rt1","project_id":"p1"}}')).toEqual([{ rt: "rt1", project: "p1", email: "a@x.com" }]) - expect(imported('{"accounts":[{"email":"a@x.com","refreshToken":"rt1"},{"email":"b@x.com","refresh_token":"rt2","projectId":"p2"}]}').map((a) => a.rt)).toEqual(["rt1", "rt2"]) - expect(imported("# mine\n1//rt-a\n\n1//rt-b\n").map((a) => a.rt)).toEqual(["1//rt-a", "1//rt-b"]) - expect(() => imported('{"type":"kiro","refresh_token":"x"}')).toThrow("kiro") - - const seen = fake({ who: { email: "c@x.com" } }) - const p = await AntigravityAuthPlugin({}) - const m = p.auth.methods[1] - expect(m.prompts[0].key).toBe("account") - const a = await m.authorize({ account: "1//rt-c" }) - expect(a.url).toBe("") - const r = await a.callback() - expect(r).toMatchObject({ type: "success", access: "tok-new", refresh: "1//rt-c|ag-proj", accountId: "c@x.com" }) - expect(seen.find((s) => s.name === "token").body).toContain("refresh_token=1%2F%2Frt-c") - expect((await m.authorize({ account: "" })).type).toBe("failed") -}) - -// An Ultra or Pro account's quota for a model is used up: the app asks -// before it spends Google AI credits, and magpie's switch is that answer. -const withCredits = { cloudaicompanionProject: "ag-proj", currentTier: { id: "standard-tier" }, paidTier: { id: "g1-ultra-tier", name: "Google AI Ultra", availableCredits: [{ creditType: "GOOGLE_ONE_AI", creditAmount: "25000", minimumCreditAmountForUsage: "50" }] } } -const spentQuota = () => new Response(JSON.stringify({ error: { code: 429, message: "You have exhausted your capacity on this model.", status: "RESOURCE_EXHAUSTED" } }), { status: 429, headers: { "content-type": "application/json" } }) -const credited = (s) => (s.json.enabled_credit_types ? sse({ candidates: [{ content: { role: "model", parts: [{ text: "ok" }] }, finishReason: "STOP" }] }) : spentQuota()) - -async function creditsFetch(on) { - const p = await AntigravityAuthPlugin({ magpie: { option: (id, key) => (id === "antigravity" && key === "use-ai-credits" ? on : undefined) } }) - const l = await p.auth.loader(async () => auth()) - return { f: l.fetch, p } -} - -test("with Use AI credits on, a request the quota refuses is asked again with the account's credits", async () => { - const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: credited }) - const { f } = await creditsFetch(true) - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(200) - const sent = seen.filter((s) => s.name === "streamGenerateContent") - expect(sent.length).toBe(2) - expect(sent[0].json.enabled_credit_types).toBeUndefined() - expect(sent[1].json.enabled_credit_types).toEqual(["GOOGLE_ONE_AI"]) -}) - -test("when the asking with credits is refused too, the quota's 429 is what comes back, and a retry works the same", async () => { - const seen = fake({ - loadCodeAssist: withCredits, - fetchAvailableModels: models, - streamGenerateContent: (s) => (s.json.enabled_credit_types ? new Response(JSON.stringify({ error: { code: 403, message: "credits refused", status: "PERMISSION_DENIED" } }), { status: 403 }) : spentQuota()), - }) - const { f } = await creditsFetch(true) - for (let i = 0; i < 2; i++) { - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(429) - expect((await res.json()).error.message).toContain("exhausted your capacity") - } - expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(4) -}) - -test("a request the quota covers never asks for credits", async () => { - const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) }) - const { f } = await creditsFetch(true) - await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(seen.filter((s) => s.name === "streamGenerateContent").map((s) => s.json.enabled_credit_types)).toEqual([undefined]) -}) - -test("with the switch off, a refused request is not asked again, and the 429 says what would spend the credits", async () => { - const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: credited }) - const { f } = await creditsFetch(false) - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(429) - expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(1) - const j = await res.json() - expect(j.error.message).toContain("exhausted your capacity") - expect(j.error.message).toContain("Use AI credits") -}) - -// plugins#1148: a 429 came back while the model's quota wasn't used up, -// and the credits note read as if it were -const withQuota = (fraction) => ({ models: { "gemini-3-flash": { displayName: "Gemini 3 Flash", quotaInfo: fraction === undefined ? { resetTime: "2026-11-15T12:00:00Z" } : { remainingFraction: fraction, resetTime: "2026-11-15T12:00:00Z" } } } }) - -test("a 429 while the model's quota is left says so, not to spend credits (plugins#1148)", async () => { - let reads = 0 - fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.8) : withQuota(0.62)), streamGenerateContent: spentQuota }) - const { f } = await creditsFetch(false) - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(429) - const msg = (await res.json()).error.message - expect(msg).toContain("exhausted your capacity") - expect(msg).toContain("62% of its quota left") - expect(msg).not.toContain("Use AI credits") - expect(reads).toBe(2) -}) - -test("a 429 once the model's quota is used up still points at the credits switch", async () => { - let reads = 0 - fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.4) : withQuota(undefined)), streamGenerateContent: spentQuota }) - const { f } = await creditsFetch(false) - const msg = (await (await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).json()).error.message - expect(msg).toContain("Use AI credits") - expect(msg).not.toContain("quota left") -}) - -test("when the quota can't be read again, the 429 keeps the credits note", async () => { - let reads = 0 - fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.9) : new Response("boom", { status: 500 })), streamGenerateContent: spentQuota }) - const { f } = await creditsFetch(false) - const msg = (await (await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).json()).error.message - expect(msg).toContain("Use AI credits") -}) - -test("an account with no credits is not asked again, with the switch on", async () => { - const seen = fake({ loadCodeAssist: { cloudaicompanionProject: "ag-proj", paidTier: { id: "g1-pro-tier", name: "Google AI Pro" } }, fetchAvailableModels: models, streamGenerateContent: credited }) - const { f } = await creditsFetch(true) - const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() }) - expect(res.status).toBe(429) - expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(1) - expect((await res.json()).error.message).not.toContain("Use AI credits") -}) - -test("the plugin offers the switch, off unless set", async () => { - const p = await AntigravityAuthPlugin({}) - expect(p.auth.options.map((o) => o.key)).toEqual(["use-ai-credits"]) - expect(_internal.creditsOf({ paidTier: { availableCredits: [{ creditType: "GOOGLE_ONE_AI", creditAmount: "10", minimumCreditAmountForUsage: "50" }] } })).toBe(false) - expect(_internal.creditsOf({ paidTier: { availableCredits: [{ creditType: "GOOGLE_ONE_AI", minimumCreditAmountForUsage: "50" }] } })).toBe(true) -}) - -test("host session headers reach the envelope's sessionId without leaking upstream", async () => { - const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) }) - const p = await AntigravityAuthPlugin({}) - const outA = { headers: {} } - const outB = { headers: {} } - await p["chat.headers"]({ sessionID: "sess-alpha", model: { providerID: "antigravity" } }, outA) - await p["chat.headers"]({ sessionID: "sess-beta", model: { providerID: "antigravity" } }, outB) - const l = await p.auth.loader(async () => auth()) - await l.fetch(URL_("gemini-3-flash"), { method: "POST", headers: outA.headers, body: ask("# AGENTS.md instructions\nshared") }) - await l.fetch(URL_("gemini-3-flash"), { method: "POST", headers: outB.headers, body: ask("# AGENTS.md instructions\nshared") }) - const calls = seen.filter((s) => s.name === "streamGenerateContent") - expect(calls.length).toBe(2) - expect(calls[0].json.request.sessionId).not.toBe(calls[1].json.request.sessionId) - expect(calls[0].headers["x-magpie-session"]).toBeUndefined() -}) - -// ---- Gemini 4's rejected calls ---------------------------------------------------------- - -const G4 = { models: { "gemini-4-carbon": { displayName: "Gemini 4 Carbon" }, "gemini-3-flash": { displayName: "Gemini 3 Flash" } } } -const bad400 = () => new Response(JSON.stringify({ error: { code: 400, message: "Request contains an invalid argument.", status: "INVALID_ARGUMENT" } }), { status: 400, headers: { "content-type": "application/json" } }) -const think = { candidates: [{ content: { role: "model", parts: [{ text: "hmm", thought: true }] } }] } -const answer = { candidates: [{ content: { role: "model", parts: [{ functionCall: { name: "ls", args: {} } }] }, finishReason: "STOP" }] } -const raw = (...lines) => new Response(lines.join("\r\n\r\n") + "\r\n\r\n", { status: 200, headers: { "content-type": "text/event-stream" } }) -const errChunk = "data: " + JSON.stringify({ error: { code: 400, message: "Request contains an invalid argument.", status: "INVALID_ARGUMENT" } }) -const dataOf = (c) => "data: " + JSON.stringify({ response: c }) -const calls = (seen) => seen.filter((s) => s.name === "streamGenerateContent").length - -test("gemini-4's slow 400 INVALID_ARGUMENT is asked again, and the retry's reply comes back", async () => { - _internal.retry400.floorMs = 0 - let n = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? bad400() : sse(answer)) }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - expect(res.status).toBe(200) - expect(await res.text()).toContain("functionCall") - expect(calls(seen)).toBe(2) -}) - -test("a gemini-4 400 that keeps coming is asked twice more, then returned", async () => { - _internal.retry400.floorMs = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - expect(res.status).toBe(400) - expect((await res.json()).error.status).toBe("INVALID_ARGUMENT") - expect(calls(seen)).toBe(3) -}) - -test("a fast 400 is the request's own and isn't asked again; nor is another model's", async () => { - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 }) - const f = await loaderFetch(auth()) - _internal.retry400.floorMs = 3000 - expect((await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).status).toBe(400) - expect(calls(seen)).toBe(1) - _internal.retry400.floorMs = 0 - expect((await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).status).toBe(400) - expect(calls(seen)).toBe(2) -}) - -test("thinking held past holdMs goes out while the model still thinks, and nothing read is lost (#1078)", async () => { - _internal.retry400.holdMs = 50 - let ctl - const enc = new TextEncoder() - const body = new ReadableStream({ start: (c) => (ctl = c) }) - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }) }) - const f = await loaderFetch(auth()) - ctl.enqueue(enc.encode(dataOf(think) + "\r\n\r\n")) - const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - expect(res.status).toBe(200) - const rd = res.body.getReader() - const dec = new TextDecoder() - let got = "" - while (!got.includes("hmm")) { - const r = await rd.read() - if (r.done) break - got += dec.decode(r.value, { stream: true }) - } - // the answer doesn't exist yet: the thinking came out on its own - expect(got).toContain("hmm") - expect(got).not.toContain("functionCall") - ctl.enqueue(enc.encode(dataOf(answer) + "\r\n\r\n")) - ctl.close() - for (;;) { - const r = await rd.read() - if (r.done) break - got += dec.decode(r.value, { stream: true }) - } - expect(got).toContain("functionCall") - expect(calls(seen)).toBe(1) -}) - -test("an INVALID_ARGUMENT in the stream after thinking only is asked again, and no thinking is sent twice", async () => { - _internal.retry400.floorMs = 3000 - let n = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf(think), errChunk) : sse(think, answer)) }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - const text = await res.text() - expect(text).not.toContain("INVALID_ARGUMENT") - expect(text.split("hmm").length - 1).toBe(1) - expect(text).toContain("functionCall") - expect(calls(seen)).toBe(2) -}) - -test("once an answer has begun the stream is not asked again, and its error goes through", async () => { - let n = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }), errChunk) : sse(answer)) }) - const f = await loaderFetch(auth()) - const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text() - expect(text).toContain("Hel") - expect(text).toContain("INVALID_ARGUMENT") - expect(calls(seen)).toBe(1) -}) - -test("a generateContent reply is asked again the same way", async () => { - let n = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), errChunk) : sse(answer)) }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-4-carbon", "generateContent"), { method: "POST", body: ask() }) - expect(res.status).toBe(200) - expect(JSON.stringify(await res.json())).toContain("functionCall") - expect(calls(seen)).toBe(2) -}) - -// Code Assist's real late error is a bare line, no "data:" before it, after -// the thinking events (zRain's capture of gemini-4-argon-high, the bytes in -// magpie's internal/gateway/sse_bare.go) -const bareErr = '{"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}' - -test("Code Assist's bare INVALID_ARGUMENT line after thinking is asked again too (Lawson0112 on X)", async () => { - _internal.retry400.floorMs = 3000 - let n = 0 - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf(think), bareErr) : sse(think, answer)) }) - const f = await loaderFetch(auth()) - const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - const text = await res.text() - expect(text).not.toContain("INVALID_ARGUMENT") - expect(text.split("hmm").length - 1).toBe(1) - expect(text).toContain("functionCall") - expect(calls(seen)).toBe(2) -}) - -test("a bare error written over several lines is read whole", async () => { - let n = 0 - const pretty = JSON.stringify(JSON.parse(bareErr), null, 2) - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), pretty) : sse(answer)) }) - const f = await loaderFetch(auth()) - const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text() - expect(text).toContain("functionCall") - expect(calls(seen)).toBe(2) -}) - -test("gemini-4's bad call that keeps coming says what it is, not a region or account refusal", async () => { - const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => raw(dataOf(think), bareErr) }) - const f = await loaderFetch(auth()) - const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text() - expect(calls(seen)).toBe(3) - const line = text.split("\n").find((l) => l.includes("INVALID_ARGUMENT")) - const e = JSON.parse(line.replace(/^data:\s*/, "")).error - expect(e.code).toBe(400) - expect(e.status).toBe("INVALID_ARGUMENT") - expect(e.message).toContain("gemini-4-carbon turned down a call it built while thinking, asked 3 times") - expect(e.message).toContain("Request contains an invalid argument.") - expect(e.message).toContain("Not a region or account refusal") - // magpie's gateway reads "model … invalid" as a model not served - expect(e.message).not.toMatch(/model.{0,80}invalid/i) - - _internal.retry400.floorMs = 0 - fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 }) - const g = await loaderFetch(auth()) - const res = await g(URL_("gemini-4-carbon"), { method: "POST", body: ask() }) - expect(res.status).toBe(400) - expect((await res.json()).error.message).toContain("asked 3 times") -}) - -test("a fast 400 and another model's errors keep Google's words", async () => { - fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 }) - const f = await loaderFetch(auth()) - _internal.retry400.floorMs = 3000 - expect((await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).json()).error.message).toBe("Request contains an invalid argument.") - fake({ fetchAvailableModels: G4, streamGenerateContent: () => raw(dataOf(think), bareErr) }) - const g = await loaderFetch(auth()) - const text = await (await g(URL_("gemini-3-flash"), { method: "POST", body: ask() })).text() - expect(text).toContain(bareErr) -}) diff --git a/packages/antigravity/retired.test.mjs b/packages/antigravity/retired.test.mjs new file mode 100644 index 0000000..2e5eb23 --- /dev/null +++ b/packages/antigravity/retired.test.mjs @@ -0,0 +1,54 @@ +// 0.2.0 sends nothing: every way in answers with where Antigravity went. +import { afterEach, expect, test } from "bun:test" +import { AntigravityAuthPlugin, RETIRED } from "./index.mjs" + +const realFetch = globalThis.fetch +afterEach(() => { + globalThis.fetch = realFetch +}) + +function noNetwork() { + const asked = [] + globalThis.fetch = async (u) => { + asked.push(String(u)) + throw new Error("no request may leave the plugin") + } + return asked +} + +test("a request is answered 410, retired, naming agy-cli, with nothing sent", async () => { + const asked = noNetwork() + const p = await AntigravityAuthPlugin({}) + const signedIn = async () => ({ type: "oauth", refresh: "rt|proj", access: "at", expires: Date.now() + 3600e3, accountId: "a@example.com" }) + const l = await p.auth.loader(signedIn) + const res = await l.fetch("https://daily-cloudcode-pa.googleapis.com/v1beta/models/gemini-3-flash:streamGenerateContent?alt=sse", { method: "POST", body: "{}" }) + expect(res.status).toBe(410) + const j = await res.json() + expect(j.error.status).toBe("ModelDeprecated") + // magpie's modelRetired reads "model … has been retired" + expect(j.error.message).toMatch(/model.{0,80}has been retired/i) + expect(j.error.message).toContain("@magpie-community/opencode-agy-cli-auth") + expect(j.error.message).toContain("Antigravity (local agy CLI)") + expect(asked).toEqual([]) +}) + +test("signing in is turned away with the same words", async () => { + const asked = noNetwork() + const p = await AntigravityAuthPlugin({}) + expect(p.auth.methods).toHaveLength(1) + await expect(p.auth.methods[0].authorize({})).rejects.toThrow(RETIRED) + expect(asked).toEqual([]) +}) + +test("no models, usage or search, and the provider stays listed as retired", async () => { + const asked = noNetwork() + const p = await AntigravityAuthPlugin({}) + const cfg = { provider: { antigravity: { models: { "gemini-3-flash": {} } } } } + await p.config(cfg) + expect(cfg.provider.antigravity.models).toEqual({}) + expect(cfg.provider.antigravity.name).toBe("Antigravity (retired)") + expect(await p.provider.models({ models: { x: {} } }, { auth: { type: "oauth", refresh: "rt|p" } })).toEqual({}) + expect(p.auth.usage).toBeUndefined() + expect(p.search).toBeUndefined() + expect(asked).toEqual([]) +}) diff --git a/packages/antigravity/schema.test.mjs b/packages/antigravity/schema.test.mjs deleted file mode 100644 index 798e34b..0000000 --- a/packages/antigravity/schema.test.mjs +++ /dev/null @@ -1,123 +0,0 @@ -// plainSchema, held to magpie's built-in (internal/gateway/codeassist.go) -// by its tests: codeassist_test.go, antigravity_array_items_test.go, -// antigravity_enum_blank_test.go and antigravity_root_union_test.go. -import { expect, test } from "bun:test" -import { _internal } from "./index.mjs" - -const { plainSchema } = _internal -const ps = (s) => plainSchema(JSON.parse(s)) - -test("a tool's schema as the built-in sends it", () => { - const s = `{"$schema":"http://json-schema.org/draft-07/schema#","type":"object", - "properties":{"path":{"type":["string","null"],"format":"uri"},"mode":{"const":"r"},"opts":{"$ref":"#/$defs/Opts"}, - "n":{"anyOf":[{"type":"integer"},{"type":"null"}]}},"required":["path","gone"],"additionalProperties":false, - "$defs":{"Opts":{"type":"object","properties":{"deep":{"type":"boolean","default":false}}}}}` - expect(ps(s)).toEqual( - JSON.parse(`{"properties":{"mode":{"enum":["r"]},"n":{"nullable":true,"type":"integer"},"opts":{"properties":{"deep":{"type":"boolean"}},"type":"object"},"path":{"nullable":true,"type":"string"}},"required":["path"],"type":"object"}`), - ) -}) - -test("every array has items, however deep", () => { - const got = ps(`{"type":"object","$defs":{"Tags":{"type":"array","description":"tags"}}, - "properties":{ - "grid":{"type":"array","items":{"type":"array"}}, - "maybe":{"anyOf":[{"type":"null"},{"type":"array"}]}, - "one":{"oneOf":[{"type":"array","minItems":1},{"type":"string"}]}, - "both":{"allOf":[{"type":"object","properties":{"list":{"type":"array"}}}]}, - "tags":{"$ref":"#/$defs/Tags"}, - "opt":{"type":["array","null"]}, - "kept":{"type":"array","items":{"type":"string"}}, - "deep":{"type":"object","properties":{"rows":{"type":"array","items":{"type":"object","properties":{"cells":{"type":"array"}}}}}} - }}`) - expect(got).toEqual( - JSON.parse(`{"type":"object","properties":{ - "grid":{"type":"array","items":{"type":"array","items":{}}}, - "maybe":{"type":"array","items":{},"nullable":true}, - "one":{"type":"array","items":{},"minItems":1}, - "both":{"type":"object","properties":{"list":{"type":"array","items":{}}}}, - "tags":{"type":"array","items":{},"description":"tags"}, - "opt":{"type":"array","items":{},"nullable":true}, - "kept":{"type":"array","items":{"type":"string"}}, - "deep":{"type":"object","properties":{"rows":{"type":"array","items":{"type":"object","properties":{"cells":{"type":"array","items":{}}}}}}} - }}`), - ) - expect(JSON.stringify(ps(`{"type":"object","properties":{"s":{"type":"string"}}}`))).not.toContain("items") -}) - -test("blank enum values are dropped (#5235)", () => { - const out = ps( - `{"type":"object","properties":{"StatusMessage":{"type":"object","properties":{"operationStatus":{"allOf":[{"enum":["processing","warning","error",""],"type":"string","x-enum-varnames":["A","B","C","D"]}],"description":"'', 'error', 'processing'","example":"error"}}},` + - `"blank":{"type":"string","enum":[""," "]},"c":{"type":"string","const":""},"n":{"enum":["a",1,""]}}}`, - ) - const op = out.properties.StatusMessage.properties.operationStatus - expect(op.type).toBe("string") - expect(op.enum).toEqual(["processing", "warning", "error"]) - for (const k of ["blank", "c", "n"]) expect(out.properties[k].enum).toBeUndefined() - expect(JSON.stringify(out)).not.toContain('""') -}) - -const rg = `{"type":"object","properties":{"pattern":{"type":"string"},"cursor":{"type":"string"}},"oneOf":[{"required":["pattern"],"not":{"required":["cursor"]}},{"required":["cursor"],"not":{"required":["pattern"]}}]}` - -test.each([ - ["root oneOf", rg, `{"type":"object","properties":{"pattern":{"type":"string"},"cursor":{"type":"string"}}}`], - ["root anyOf", `{"type":"object","properties":{"a":{"type":"string"}},"anyOf":[{"required":["a"]},{"not":{"required":["a"]}}]}`, `{"type":"object","properties":{"a":{"type":"string"}}}`], - ["properties only, no type", `{"properties":{"a":{"type":"string"}},"oneOf":[{"required":["a"]}]}`, `{"type":"object","properties":{"a":{"type":"string"}},"required":["a"]}`], - [ - "nested oneOf", - `{"type":"object","properties":{"q":{"type":"object","description":"query","properties":{"pattern":{"type":"string"},"cursor":{"type":"string"}},"oneOf":[{"required":["pattern"],"not":{"required":["cursor"]}},{"required":["cursor"],"not":{"required":["pattern"]}}]}},"required":["q"]}`, - `{"type":"object","properties":{"q":{"type":"object","description":"query","properties":{"pattern":{"type":"string"},"cursor":{"type":"string"}}}},"required":["q"]}`, - ], - [ - "nested anyOf", - `{"type":"object","properties":{"q":{"type":"object","properties":{"a":{"type":"integer"}},"anyOf":[{"required":["a"]},{"type":"null"}]}}}`, - `{"type":"object","properties":{"q":{"type":"object","properties":{"a":{"type":"integer"}},"required":["a"],"nullable":true}}}`, - ], - [ - "branches add fields", - `{"type":"object","properties":{"kind":{"type":"string"}},"required":["kind"],"oneOf":[{"properties":{"kind":{"const":"a"},"x":{"type":"string"}},"required":["kind","x"]},{"properties":{"kind":{"const":"b"},"y":{"type":"number"}},"required":["kind","y"]}]}`, - `{"type":"object","properties":{"kind":{"type":"string"},"x":{"type":"string"},"y":{"type":"number"}},"required":["kind"]}`, - ], - [ - "every branch requires it", - `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}},"anyOf":[{"required":["a","b"]},{"required":["a"]}]}`, - `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}},"required":["a"]}`, - ], - [ - "root allOf", - `{"type":"object","properties":{"a":{"type":"string"}},"required":["a"],"allOf":[{"properties":{"b":{"type":"string"}},"required":["b"]},{"not":{"required":["c"]}}]}`, - `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}},"required":["a","b"]}`, - ], - [ - "nested allOf", - `{"type":"object","properties":{"q":{"type":"object","properties":{"a":{"type":"string"}},"allOf":[{"required":["a"]}]}}}`, - `{"type":"object","properties":{"q":{"type":"object","properties":{"a":{"type":"string"}},"required":["a"]}}}`, - ], - [ - "allOf beside oneOf", - `{"type":"object","properties":{"a":{"type":"string"}},"allOf":[{"properties":{"b":{"type":"string"}}}],"oneOf":[{"required":["a"]},{"required":["b"]}]}`, - `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}}}`, - ], - ["typed scalar", `{"type":"string","description":"d","anyOf":[{"format":"date"},{"format":"uuid"}]}`, `{"type":"string","description":"d"}`], - [ - "bare union still its first branch", - `{"type":"object","properties":{"v":{"description":"value","anyOf":[{"type":"null"},{"type":"integer"},{"type":"string"}]}}}`, - `{"type":"object","properties":{"v":{"type":"integer","description":"value","nullable":true}}}`, - ], -])("a union keeps its own shape: %s", (_, input, want) => { - expect(ps(input)).toEqual(JSON.parse(want)) -}) - -test("a reference to itself, or deeper than 32, ends", () => { - const out = ps(`{"type":"object","properties":{"node":{"$ref":"#/$defs/Node"}},"$defs":{"Node":{"type":"object","properties":{"next":{"$ref":"#/$defs/Node"},"v":{"type":"string"}}}}}`) - expect(out.properties.node.properties.next).toEqual({ type: "object" }) - expect(out.properties.node.properties.v).toEqual({ type: "string" }) - expect(ps(`{"type":"object","properties":{"me":{"$ref":"#"}}}`).properties.me).toEqual({ type: "object" }) - expect(ps(`{"type":"object","properties":{"x":{"$ref":"#/$defs/Gone"}}}`).properties.x).toEqual({ type: "object" }) -}) - -test("exclusive bounds and tuples", () => { - expect(ps(`{"type":"number","exclusiveMinimum":1,"exclusiveMaximum":9,"maximum":5}`)).toEqual({ type: "number", minimum: 1, maximum: 5 }) - expect(ps(`{"type":"array","prefixItems":[{"type":"string"},{"type":"string"}]}`)).toEqual({ type: "array", items: { type: "string" } }) - expect(ps(`{"type":"array","prefixItems":[{"type":"string"},{"type":"number"}]}`)).toEqual({ type: "array", items: {} }) - expect(ps(`{"type":"array","items":false}`)).toEqual({ type: "array", items: {}, maxItems: 0 }) -}) diff --git a/packages/antigravity/search.test.mjs b/packages/antigravity/search.test.mjs deleted file mode 100644 index c32d36b..0000000 --- a/packages/antigravity/search.test.mjs +++ /dev/null @@ -1,173 +0,0 @@ -import { afterEach, beforeEach, expect, test } from "bun:test" -import { AntigravityAuthPlugin, _internal } from "./index.mjs" -import { auth, fake, real, reset } from "./fake.mjs" - -beforeEach(() => reset()) -afterEach(() => (globalThis.fetch = real)) - -const sse = (...chunks) => - new Response(chunks.map((c) => "data: " + JSON.stringify({ response: c, traceId: "t" }) + "\r\n\r\n").join(""), { - status: 200, - headers: { "content-type": "text/event-stream" }, - }) - -const models = { - models: { - "gemini-3-flash": { displayName: "Gemini 3 Flash" }, - "gemini-2.5-flash": { displayName: "Gemini 2.5 Flash" }, - "claude-opus-4-6-thinking": { displayName: "Claude Opus 4.6 (Thinking)" }, - }, -} - -const REDIR_A = "https://vertexaisearch.cloud.google.com/grounding-api-redirect/AAA" -const REDIR_B = "https://vertexaisearch.cloud.google.com/grounding-api-redirect/BBB" - -test("plugin registers the antigravity search hook signed in as antigravity", async () => { - const p = await AntigravityAuthPlugin({}) - expect(p.search?.antigravity).toBeDefined() - expect(p.search.antigravity.auth).toBe("antigravity") - expect(typeof p.search.antigravity.execute).toBe("function") -}) - -test("search rejects an empty query and a missing sign-in", async () => { - const p = await AntigravityAuthPlugin({}) - await expect(p.search.antigravity.execute({ query: " " }, { getAuth: async () => auth() })).rejects.toThrow("query is required") - await expect(p.search.antigravity.execute({ query: "bun" }, { getAuth: async () => null })).rejects.toThrow("not signed in") -}) - -test("search calls Antigravity with googleSearch, returns URIs unchanged, deduplicates, and trims to count", async () => { - const seen = fake({ - fetchAvailableModels: models, - streamGenerateContent: () => - sse( - { candidates: [{ content: { role: "model", parts: [{ thought: true, text: "thinking" }, { text: "Bun 1.4.4 " }] } }] }, - { - candidates: [ - { - content: { role: "model", parts: [{ text: "is latest." }] }, - finishReason: "STOP", - groundingMetadata: { - webSearchQueries: ["latest bun version"], - groundingChunks: [ - { web: { uri: REDIR_A, title: "github.com" } }, - { web: { uri: REDIR_A, title: "github.com duplicate" } }, - { web: { uri: REDIR_B, title: "bun.sh" } }, - ], - groundingSupports: [ - { segment: { text: "Bun 1.4.4 was released." }, groundingChunkIndices: [0] }, - { segment: { text: "See release notes on GitHub." }, groundingChunkIndices: [1] }, - { segment: { text: "Install via bun.sh." }, groundingChunkIndices: [2] }, - ], - }, - }, - ], - }, - ), - }) - - const p = await AntigravityAuthPlugin({}) - const pages = await p.search.antigravity.execute({ query: "latest bun version", count: 5 }, { getAuth: async () => auth() }) - - expect(seen.map((s) => s.name)).toEqual(["loadCodeAssist", "fetchAvailableModels", "streamGenerateContent"]) - const req = seen.find((s) => s.name === "streamGenerateContent") - expect(req.json.model).toBe("gemini-3-flash") - expect(req.json.request.tools).toEqual([{ googleSearch: {} }]) - expect(req.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: false, thinkingLevel: "minimal" }) - expect(pages).toEqual([ - { - title: "github.com", - url: REDIR_A, - text: "Bun 1.4.4 was released.\nSee release notes on GitHub.", - }, - { - title: "bun.sh", - url: REDIR_B, - text: "Install via bun.sh.", - }, - ]) - - const one = await p.search.antigravity.execute({ query: "latest bun version", count: 1 }, { getAuth: async () => auth() }) - expect(one).toHaveLength(1) - expect(one[0].url).toBe(REDIR_A) -}) - -test("search carries numeric status and retryAfter when Antigravity refuses", async () => { - fake({ - fetchAvailableModels: models, - streamGenerateContent: () => - new Response(JSON.stringify({ error: { code: 429, message: "rate limited" } }), { - status: 429, - headers: { "retry-after": "12" }, - }), - }) - const p = await AntigravityAuthPlugin({}) - let caught - try { - await p.search.antigravity.execute({ query: "news" }, { getAuth: async () => auth() }) - } catch (e) { - caught = e - } - expect(caught).toBeDefined() - expect(caught.status).toBe(429) - expect(caught.retryAfter).toBe("12") - expect(caught.message).toContain("rate limited") -}) - -test("whole preserves groundingMetadata from an earlier SSE chunk", async () => { - const res = sse( - { - candidates: [ - { - content: { role: "model", parts: [{ text: "Answer" }] }, - groundingMetadata: { groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }] }, - }, - ], - }, - { - candidates: [ - { - content: { role: "model", parts: [{ text: "" }] }, - finishReason: "STOP", - groundingMetadata: { webSearchQueries: ["example"], groundingChunks: [] }, - }, - ], - usageMetadata: { totalTokenCount: 10 }, - }, - ) - const full = await _internal.whole(res) - expect(full.candidates[0].groundingMetadata).toEqual({ - webSearchQueries: ["example"], - groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }], - }) -}) - -test("search skips an exhausted Flash model and turns thinking off on Gemini 2.5", async () => { - const seen = fake({ - fetchAvailableModels: { - models: { - "gemini-3-flash": { displayName: "Gemini 3 Flash", quotaInfo: {} }, - "gemini-2.5-flash": { displayName: "Gemini 2.5 Flash", quotaInfo: { remainingFraction: 0.8 } }, - }, - }, - streamGenerateContent: () => - sse({ - candidates: [ - { - content: { role: "model", parts: [{ text: "Answer." }] }, - finishReason: "STOP", - groundingMetadata: { - groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }], - }, - }, - ], - }), - }) - - const p = await AntigravityAuthPlugin({}) - const pages = await p.search.antigravity.execute({ query: "example" }, { getAuth: async () => auth() }) - - const req = seen.find((s) => s.name === "streamGenerateContent") - expect(req.json.model).toBe("gemini-2.5-flash") - expect(req.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: false, thinkingBudget: 0 }) - expect(pages).toEqual([{ title: "Example", url: "https://example.com", text: "Answer." }]) -}) diff --git a/packages/antigravity/shape.test.mjs b/packages/antigravity/shape.test.mjs deleted file mode 100644 index 631719f..0000000 --- a/packages/antigravity/shape.test.mjs +++ /dev/null @@ -1,339 +0,0 @@ -// The Gemini request magpie (or the AI SDK) hands the plugin, shaped as -// the built-in shaped it for Antigravity (codeassist.go's Antigravity -// rules; codeassist_test.go's TestBuildCodeAssistForAntigravity, -// TestCodeAssistAntigravityLevels and TestCodeAssistToolImagesAfterEveryResponse). -import { expect, test } from "bun:test" -import { _internal } from "./index.mjs" - -const { shape, cloak, sessionOf, envelope } = _internal - -// what magpie's generic Code Assist build makes of codeassist_test.go's -// codeAssistRequest -const generic = () => ({ - systemInstruction: { role: "user", parts: [{ text: "be brief" }] }, - contents: [ - { role: "user", parts: [{ text: "read a" }] }, - { role: "model", parts: [{ text: "hm", thought: true }, { text: "ok" }, { functionCall: { id: "toolu_01:x", name: "read", args: { path: "a" } }, thoughtSignature: "skip_thought_signature_validator" }] }, - { role: "user", parts: [{ functionResponse: { id: "toolu_01:x", name: "read", response: { output: "A!" } } }] }, - { role: "user", parts: [{ text: "and?" }] }, - ], - tools: [{ functionDeclarations: [{ name: "read", description: "read a file", parametersJsonSchema: { type: "object", properties: { path: { type: ["string", "null"] } }, required: ["path"], additionalProperties: false } }] }], - toolConfig: { functionCallingConfig: { mode: "AUTO" } }, - generationConfig: { maxOutputTokens: 2000, thinkingConfig: { includeThoughts: true, thinkingBudget: 4000 } }, -}) - -test("Claude on Antigravity", () => { - const r = shape(generic(), "claude-sonnet-4-6", "", "") - const s = JSON.stringify(r) - expect(s).toContain(`"id":"toolu_01_x"`) - expect(s).toContain(`"response":{"result":"A!"}`) - expect(r.toolConfig.functionCallingConfig.mode).toBe("VALIDATED") - expect(r.generationConfig.maxOutputTokens).toBe(2000) - // Sonnet here doesn't think - expect(r.generationConfig.thinkingConfig).toBeUndefined() - expect(r.tools[0].functionDeclarations[0]).toEqual({ name: "read", description: "read a file", parameters: { type: "object", properties: { path: { type: "string", nullable: true } }, required: ["path"] } }) - // what the user said joins the tool's turn - expect(r.contents.length).toBe(3) - expect(r.contents[2].parts.map((p) => (p.functionResponse ? "response" : p.text))).toEqual(["response", "and?"]) - // a thinking Claude keeps its budget - const t = shape(generic(), "claude-opus-4-6-thinking", "", "") - expect(t.generationConfig.thinkingConfig.thinkingBudget).toBe(4000) -}) - -test("Gemini on Antigravity", () => { - const r = shape(generic(), "gemini-3-flash", "", "") - expect(r.generationConfig.maxOutputTokens).toBeUndefined() - expect(r.generationConfig.thinkingConfig).toEqual({ includeThoughts: true }) - expect(r.toolConfig.functionCallingConfig.mode).toBe("AUTO") - // the user's turn stays its own for Gemini - expect(r.contents.length).toBe(4) - expect(shape(generic(), "gpt-oss-120b-medium", "", "").generationConfig?.thinkingConfig).toBeUndefined() - // an empty declaration's parameters - const g = generic() - delete g.tools[0].functionDeclarations[0].parametersJsonSchema - expect(shape(g, "gemini-3-flash", "", "").tools[0].functionDeclarations[0].parameters).toEqual({ type: "object", properties: {} }) -}) - -test.each([ - // [model sent, the variant's level, the effort asked, the level sent] - ["gemini-3.7-flash-low", "low", "low", "low"], - ["gemini-3.7-flash-medium", "medium", "medium", "medium"], - ["gemini-3.7-flash-high", "high", "xhigh", "high"], - // a variant at xhigh thinks at xhigh, asked or by default (#1169) - ["gemini-4-hydrogen-xhigh", "xhigh", "xhigh", "xhigh"], - ["gemini-4-hydrogen-xhigh", "xhigh", "", "xhigh"], - ["gemini-4-hydrogen-high", "high", "xhigh", "high"], - ["gemini-3.1-pro-high", "high", "medium", "high"], - ["gemini-3-flash", "", "medium", "medium"], - ["gemini-pro-agent", "", "medium", "high"], - ["gemini-pro-agent", "", "low", "low"], - // reasoning off goes at low, the least every one takes (#250) - ["gemini-3.1-flash-lite", "", "minimal", "low"], - ["gemini-3.1-flash-lite", "", "none", "low"], - // a variant at minimal is asked at minimal; a Pro, at low - ["gemini-3.5-flash-extra-low", "minimal", "", "minimal"], - ["gemini-3.1-pro-low", "minimal", "", "low"], - // a model that draws, asked off, goes at high - ["gemini-3.1-flash-image", "", "minimal", "high"], -])("%s (%p) asked %p thinks at %p", (sent, at, effort, level) => { - const r = shape(generic(), sent, at, effort) - expect(r.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: level }) -}) - -test("a level a variant put on a model told a budget goes", () => { - const g = generic() - g.generationConfig.thinkingConfig = { includeThoughts: true, thinkingLevel: "high" } - expect(shape(g, "gemini-2.5-flash", "", "").generationConfig?.thinkingConfig).toBeUndefined() -}) - -test("a tool's images follow every response, for Claude", () => { - const img = (d) => ({ inlineData: { mimeType: "image/png", data: d } }) - const g = { - contents: [ - { role: "user", parts: [{ text: "look" }] }, - { role: "model", parts: [{ functionCall: { id: "a", name: "shot", args: {} } }, { functionCall: { id: "b", name: "shot", args: {} } }] }, - { role: "user", parts: [{ functionResponse: { id: "a", name: "shot", response: { output: "one" } } }, img("1"), { functionResponse: { id: "b", name: "shot", response: { output: "two" } } }, img("2"), img("3")] }, - { role: "user", parts: [{ text: "what now?" }] }, - ], - } - const r = shape(g, "claude-sonnet-4-6", "", "") - const lines = r.contents[2].parts.map((p) => (p.functionResponse ? "response " + p.functionResponse.id : p.inlineData ? "image " + p.inlineData.data : p.text)) - expect(lines).toEqual(["response a", "response b", "Image returned by tool shot (call a):", "image 1", "2 images returned by tool shot (call b):", "image 2", "image 3", "what now?"]) - expect(r.contents.length).toBe(3) - // Gemini takes them where they are - expect(shape(g, "gemini-3-flash", "", "").contents[2].parts.length).toBe(5) -}) - -test("omp's RFC 2119 line goes as RFC 2119's own \"key words\", as the real account turned it away", () => { - const line = "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL." - const sys = line + " `NEVER` = `MUST NOT`; `AVOID` = `SHOULD NOT`.\n\n§ Role" - const out = cloak(sys) - // a zero-width break of this line was turned away 1 to 3 times in 10 on - // 11-14; "key words" went through 10 of 10 - expect(out).toBe(sys.replace("keywords", "key words")) - expect(out).not.toContain("\u200b") - expect(cloak("RFC 2119 keywords: MUST")).toBe("RFC 2119 keywords: MUST") -}) - -// omp 18.20.0's first line, byte for byte (src/prompts/system/system-prompt.md), -// and the copies of it a real account turned away on 11-14 although no -// space in them is a single space: wrapped after "REQUIRED," with LF or -// CRLF, wrapped after "RFC 2119", indented, a tab, two spaces, a no-break -// space. The same account answered the line without its period, with no -// space after a comma, or in another order, so those go as written. -const OMP_LINE = "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL. `NEVER` = `MUST NOT`; `AVOID` = `SHOULD NOT`." -const OMP_COPIES = [ - "RFC 2119 keywords: MUST, REQUIRED,\nSHOULD, RECOMMENDED, MAY, OPTIONAL.", - "RFC 2119 keywords: MUST, REQUIRED,\r\nSHOULD, RECOMMENDED, MAY, OPTIONAL.\r\n", - "RFC 2119\nkeywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", - "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY,\n OPTIONAL.", - "RFC 2119 keywords:\tMUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", - "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", - "RFC\u00a02119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", -] -const OMP_PASSED = [ - "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL", - "RFC 2119 keywords: MUST,REQUIRED,SHOULD,RECOMMENDED,MAY,OPTIONAL.", - "RFC 2119 keywords: MUST, SHOULD, MAY, REQUIRED, RECOMMENDED, OPTIONAL.", - "RFC 2119 applies to MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", -] - -test("omp's line is reworded wherever white space wraps or widens it", () => { - const { turnsAway, hint } = _internal - for (const line of [OMP_LINE, ...OMP_COPIES]) { - const sys = "\n" + line + "\n\n\n§ Role" - const out = cloak(sys) - expect(out).toBe(sys.replace("keywords", "key words")) - expect(turnsAway(out)).toBe(false) - expect(hint(sys)).toContain("oh-my-pi (omp)") - // every white space stays as it was - expect(shape({ systemInstruction: { parts: [{ text: sys }] }, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts[0].text).toBe(out) - } - for (const line of OMP_PASSED) expect(cloak(line)).toBe(line) - // the other lines take white space the same way (Hermes' and Codex's - // were turned away wrapped and with a tab on the same account) - expect(cloak("You are Hermes\nAgent, an intelligent\nAI assistant created by Nous Research.")).toBe("You're Hermes\nAgent, an intelligent\nAI assistant built by Nous Research.") - expect(cloak("running\tinside pi")).toBe("running\tinside pi") - expect(cloak("a coding assistant running\ninside pi")).toBe("a coding assistant running\nwithin pi") - expect(cloak("You are Codex, an agent\tbased on GPT-5.")).toBe("You are Codex, an agent\tbuilt on GPT-5.") -}) - -// Claude Desktop's Code tab, as Claude Code 2.1.316 sends it with -// CLAUDE_CODE_ENTRYPOINT=claude-desktop: the billing line and the identity -// line are blocks of their own. Its subagents begin "You are a Claude agent, -// built on Anthropic's Claude Agent SDK." Since 11-14 Google reads past a -// zero-width space: the prompt with either line broken up was turned away -// 10 of 10 on a real account (hc295971796 on X), and the reworded one -// answered 10 of 10. -const BILLING = "x-anthropic-billing-header: cc_version=2.1.316.2e4; cc_entrypoint=claude-desktop;" -const DESKTOP = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK." -const SUBAGENT = "You are a Claude agent, built on Anthropic's Claude Agent SDK." - -test("Claude Code's billing line is left out, and the Agent SDK's line is reworded", () => { - const { turnsAway, hint } = _internal - const sys = BILLING + "\n" + SUBAGENT + "\nhi" - const out = cloak(sys) - expect(out).toBe("You are a Claude agent, built on the Claude Agent SDK by Anthropic.\nhi") - expect(turnsAway(out)).toBe(false) - expect(hint(sys)).toContain("Claude Agent SDK") - // twice is the same as once, and other text is left alone - expect(cloak(out)).toBe(out) - expect(cloak("be brief")).toBe("be brief") - expect(cloak(DESKTOP)).toBe(DESKTOP) - // the case and white space the agent wrote stay - expect(cloak("built on\nANTHROPIC'S claude agent sdk")).toBe("built on\nthe claude agent sdk by Anthropic") - // as the gateway hands it: each block a part; the billing line's part goes - const r = shape({ systemInstruction: { parts: [{ text: BILLING }, { text: DESKTOP }, { text: SUBAGENT }] }, contents: [] }, "gemini-3-flash", "", "") - expect(r.systemInstruction.parts.map((p) => p.text)).toEqual([DESKTOP, "You are a Claude agent, built on the Claude Agent SDK by Anthropic."]) - // a billing line alone in a string stays one (empty) part - expect(shape({ systemInstruction: BILLING, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts).toEqual([{ text: "" }]) -}) - -test("a line someone broke up with invisible characters is reworded as the line", () => { - const zw = (s, z = "\u200b") => s.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + z + w[1] + z + w.slice(2)) - const every = (s) => [...s].join("\u2060") - const lines = [ - [SUBAGENT, "You are a Claude agent, built on the Claude Agent SDK by Anthropic."], - ["You are Codex, an agent based on GPT-5.", "You are Codex, an agent built on GPT-5."], - ["You are Codex, a coding agent based on GPT-5.", "You are Codex, a coding agent built on GPT-5."], - // as "You're" alone it was turned away 3 of 3 on 11-14 - ["You are Hermes Agent, an intelligent AI assistant created by Nous Research.", "You're Hermes Agent, an intelligent AI assistant built by Nous Research."], - // 0.1.15's own rewording of it is turned away too since 11-14 - ["You are Hermes Agent, an intelligent AI assistant built by Nous Research.", "You're Hermes Agent, an intelligent AI assistant built by Nous Research."], - ["You are Hermes Agent, built by Nous Research.", "You're Hermes Agent, built by Nous Research."], - ["You are OpenCode, a coding agent that helps users with software engineering tasks.", "You're OpenCode, a coding agent that helps users with software engineering tasks."], - ["You are opencode, an interactive CLI tool that helps users with software engineering tasks.", "You're opencode, an interactive CLI tool that helps users with software engineering tasks."], - ["You are OpenCode, the best coding agent on the planet.", "You're OpenCode, the best coding agent on the planet."], - ["You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.", "You're a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful."], - ["You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.", "You are a coding assistant running within pi, a coding agent harness. Help users inspect files, run commands, and modify code."], - ["RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", "RFC 2119 key words: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL."], - ] - // the break-ups also reach words outside the turned-away part, which go as - // written: compare with the invisible characters taken out - const seen = (s) => s.replace(/[\u00ad\u200b\u2060]/g, "") - for (const [line, to] of lines) { - expect(cloak(line)).toBe(to) - for (const broken of [zw(line), every(line), zw(line, "\u00ad")]) { - const out = cloak(broken) - expect(out).not.toBe(broken) - expect(seen(out)).toBe(to) - expect(_internal.turnsAway(out)).toBe(false) - } - } - expect(cloak(zw(BILLING) + "\nhi")).toBe("hi") -}) - -test("a conversation keeps its session", () => { - const a = { contents: [{ role: "user", parts: [{ text: "hello there" }] }] } - const b = { contents: [{ role: "user", parts: [{ text: "hello there" }] }, { role: "model", parts: [{ text: "hi" }] }] } - expect(sessionOf(a)).toBe(sessionOf(b)) - expect(sessionOf(a)).toMatch(/^-\d+$/) - 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.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" }, - { text: "\n /tmp\n" }, - ] - const chatA = { contents: [{ role: "user", parts: preamble }, { role: "user", parts: [{ text: "fix login bug" }] }] } - const chatA2 = { contents: [...chatA.contents, { role: "model", parts: [{ text: "looking" }] }] } - const chatB = { contents: [{ role: "user", parts: preamble }, { role: "user", parts: [{ text: "add export csv" }] }] } - expect(sessionOf(chatA)).toBe(sessionOf(chatA2)) - expect(sessionOf(chatA)).not.toBe(sessionOf(chatB)) - - const s1 = sessionOf(chatA, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4" }) - const s2 = sessionOf(chatA, { "x-magpie-session": "01a1c9cc-0757-70e3-990f-5a818d52b0cd" }) - expect(s1).not.toBe(s2) - expect(sessionOf(chatA, { "x-magpie-session": "magpie-0123456789abcdef01234567" })).toBe(sessionOf(chatA)) - - const subA = sessionOf(chatA, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4", "x-magpie-subagent": "collab_spawn" }) - const subB = sessionOf(chatB, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4", "x-magpie-subagent": "collab_spawn" }) - expect(subA).not.toBe(s1) - expect(subA).not.toBe(subB) -}) - -test("an empty text a stream ended on isn't sent back (Claude: text Field required)", () => { - const g = { contents: [ - { role: "user", parts: [{ text: "read it" }] }, - { role: "model", parts: [{ text: "Sure." }, { functionCall: { id: "toolu_vrtx_1", name: "read", args: {} } }, { text: "" }] }, - { role: "user", parts: [{ functionResponse: { id: "toolu_vrtx_1", name: "read", response: { output: "A" } } }] }, - ] } - expect(shape(g, "claude-sonnet-4-6", "", "").contents[1].parts.map((p) => Object.keys(p)[0])).toEqual(["text", "functionCall"]) - // a signature on an empty text is kept - const s = { contents: [{ role: "model", parts: [{ text: "a" }, { text: "", thoughtSignature: "sig" }] }] } - expect(shape(s, "gemini-3-flash", "", "").contents[0].parts[1]).toEqual({ text: "", thoughtSignature: "sig" }) -}) - -test("DeepSeek Harness's @-path paragraph goes reworded, the rest as written (#1028)", () => { - // word for word as DSH desktop 0.2.2-rc.2 puts it in every system prompt - const dsh = "Tokens prefixed with @ are paths the user explicitly referenced. Relative paths resolve from the workspace root; absolute paths identify files or directories on the host. A trailing slash marks a directory: list it when its contents matter. Anything else is a file: use the read tool when its contents are needed, and do not claim to have inspected it before reading. @\"...\" quotes a path containing spaces." - const sys = "You are DeepSeek Harness.\n\n" + dsh + "\n\nBe brief." - for (const req of [{ systemInstruction: { parts: [{ text: sys }] }, contents: [] }, { systemInstruction: sys, contents: [] }]) { - const text = shape(req, "gemini-4-argon", "", "").systemInstruction.parts[0].text - expect(text).not.toContain("Tokens prefixed with @") - expect(text).toBe("You are DeepSeek Harness.\n\nWhen the user writes @ followed by a path, they are pointing at that file or folder. Relative paths start at the workspace root; absolute paths are host paths. A path ending in a slash is a folder, so list it if its contents matter; otherwise it is a file, so open it with the read tool before relying on it. Paths with spaces appear as @\"...\".\n\nBe brief.") - } - // a prompt that only mentions @ paths is left as it is - const other = "Tokens prefixed with @ are paths. Be brief." - expect(shape({ systemInstruction: { parts: [{ text: other }] }, contents: [] }, "gemini-4-argon", "", "").systemInstruction.parts[0].text).toBe(other) - // the billing line is left out and the paragraph reworded, together - const both = shape({ systemInstruction: { parts: [{ text: "x-anthropic-billing-header: cc\n" + dsh }] }, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts[0].text - expect(both).not.toContain("x-anthropic-billing-header") - expect(both).not.toMatch(/[\u200b-\u200f\u2060]/) - expect(both).toContain("When the user writes @ followed by a path") -}) - -// since 11-14 Codex's GPT-5 line in a user's turn is turned away too (3 of -// 3 on a real account): it goes reworded there, and the model's turns and -// tool results, which went through with it, as written -test("the line in a user's turn goes reworded", () => { - const line = "You are Codex, a coding agent based on GPT-5. You and the user share the same workspace." - const g = generic() - g.contents[0].parts[0].text = "Here is my AGENTS.md:\n\n" + line - g.contents[1].parts[1].text = line - g.contents[2].parts[0].functionResponse.response.output = line - const others = "x-anthropic-billing-header: cc_version=2.1.316.2e4;\nYou are a Claude agent, built on Anthropic's Claude Agent SDK.\nRFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL." - g.contents[3].parts[0].text = others - const r = shape(g, "gemini-3-flash", "", "") - expect(r.contents[3].parts[0].text).toBe(others) - expect(r.contents[0].parts[0].text).toBe("Here is my AGENTS.md:\n\nYou are Codex, a coding agent built on GPT-5. You and the user share the same workspace.") - expect(r.contents[1].parts[1].text).toBe(line) - expect(JSON.stringify(r.contents[2])).toContain("based on GPT-5") - expect(g.contents[0].parts[0].text).toContain("based on GPT-5") -}) diff --git a/packages/antigravity/usage.test.mjs b/packages/antigravity/usage.test.mjs deleted file mode 100644 index 0fbb50c..0000000 --- a/packages/antigravity/usage.test.mjs +++ /dev/null @@ -1,188 +0,0 @@ -// Usage as the built-in read it (google_test.go's TestAntigravityQuota*): -// each model's window from fetchAvailableModels, and the pools a group -// of models shares from retrieveUserQuotaSummary. -import { afterEach, beforeEach, expect, test } from "bun:test" -import { AntigravityAuthPlugin, _internal } from "./index.mjs" -import { auth, fake, real, reset } from "./fake.mjs" - -beforeEach(reset) -afterEach(() => (globalThis.fetch = real)) - -async function read(models, summary) { - _internal.lists.clear() - fake({ fetchAvailableModels: models, retrieveUserQuotaSummary: summary ?? (() => new Response("no", { status: 500 })) }) - const p = await AntigravityAuthPlugin({}) - return p.auth.usage(async () => auth()) -} -const of = (ws) => Object.fromEntries(ws.filter((w) => w.model).map((w) => [w.model, w.pool ?? ""])) -const poolWindows = (ws) => ws.filter((w) => !w.model).map((w) => `${w.pool}|${w.name}`) -const at = (ms) => new Date(Date.now() + ms).toISOString().replace(/\.\d+Z$/, "Z") -const H = 3600_000 - -test("each model's window, with its family", async () => { - const u = await read(JSON.parse(`{"models":{ - "gemini-3.1-pro-high":{"displayName":"Gemini 3.1 Pro (High)","quotaInfo":{"remainingFraction":0.4,"resetTime":"2099-01-01T00:00:00Z"}}, - "gemini-3.1-pro-low":{"displayName":"Gemini 3.1 Pro (Low)","quotaInfo":{"remainingFraction":1}}, - "gemini-3.7-flash-medium":{"displayName":"Gemini 3.7 Flash (Medium)","quotaInfo":{}}, - "claude-opus-4-6-thinking":{"displayName":"Claude Opus 4.6 (Thinking)","quotaInfo":{"remainingFraction":0.75}}, - "claude-sonnet-4-6":{"quotaInfo":{"remainingFraction":0.9}}, - "gpt-oss-120b-medium":{"displayName":"GPT-OSS 120B (Medium)","quotaInfo":{"remainingFraction":1}}, - "tab_flash_lite_preview":{"quotaInfo":{"remainingFraction":1}}}}`)) - expect(u.signIn).toBe("kept") - expect(u.windows.map((w) => `${w.model}|${w.name}|${w.family}|${Math.round(w.used)}`)).toEqual([ - "claude-opus-4-6-thinking|Claude Opus 4.6 (Thinking)|Claude|25", - "claude-sonnet-4-6|claude-sonnet-4-6|Claude|10", - "gemini-3.1-pro-high|Gemini 3.1 Pro (High)|Gemini|60", - "gemini-3.1-pro-low|Gemini 3.1 Pro (Low)|Gemini|0", - "gemini-3.7-flash-medium|Gemini 3.7 Flash (Medium)|Gemini|100", - "gpt-oss-120b-medium|GPT-OSS 120B (Medium)|GPT-OSS|0", - ]) - // a level's window names the model magpie offers too - expect(u.windows[2].models).toEqual(["gemini-3.1-pro-high", "gemini-3.1-pro"]) - expect(u.windows[0].models).toEqual(["claude-opus-4-6-thinking"]) - expect(u.windows[2].resetsAt).toBe("2099-01-01T00:00:00Z") - const { vendorOf } = _internal - expect([vendorOf("gemini-3-flash"), vendorOf("claude-x", "Other"), vendorOf("kimi-k2", "Kimi K2"), vendorOf("glm-5")]).toEqual(["Gemini", "Claude", "Kimi", "glm"]) -}) - -test("the pools a group shares, each model in its own", async () => { - const models = JSON.parse(`{"models":{ - "gemini-3.1-pro-high":{"displayName":"Gemini 3.1 Pro (High)","quotaInfo":{"remainingFraction":0.9545545,"resetTime":"2099-01-01T05:00:00Z"}}, - "gemini-3-flash":{"displayName":"Gemini 3 Flash","quotaInfo":{"remainingFraction":0.9545545,"resetTime":"2099-01-01T05:00:00Z"}}, - "claude-opus-4-6-thinking":{"displayName":"Claude Opus 4.6 (Thinking)","quotaInfo":{"remainingFraction":0.7}}, - "gpt-oss-120b-medium":{"displayName":"GPT-OSS 120B (Medium)","quotaInfo":{"remainingFraction":0.7}}}}`) - const u = await read(models, JSON.parse(`{"groups":[ - {"displayName":"Gemini Models","description":"Models within this group: Gemini Flash, Gemini Pro","buckets":[ - {"bucketId":"gemini-weekly","window":"weekly","remainingFraction":0.75,"resetTime":"2099-01-07T00:00:00Z","displayName":"Weekly Limit"}, - {"bucketId":"gemini-5h","window":"5h","remainingFraction":0.9545545,"resetTime":"2099-01-01T05:00:00Z","displayName":"Five Hour Limit"}]}, - {"displayName":"Claude and GPT models","description":"Models within this group: Claude Opus, Claude Sonnet, GPT-OSS","buckets":[ - {"bucketId":"3p-weekly","window":"weekly","resetTime":"2099-01-06T00:00:00Z"}, - {"bucketId":"3p-5h","window":"5h","remainingFraction":0.7,"resetTime":"2099-01-01T03:00:00Z"}, - {"bucketId":"3p-x","window":"5h","remainingFraction":1,"disabled":true}]}]}`)) - expect(u.windows.map((w) => `${w.model ?? ""}|${w.name}|${w.family ?? ""}|${w.pool ?? ""}|${Math.round(w.used)}|${(w.resetsAt ?? "").slice(5, 13)}|${!!w.aside}`)).toEqual([ - "claude-opus-4-6-thinking|Claude Opus 4.6 (Thinking)|Claude|Claude & GPT|30||false", - "gemini-3-flash|Gemini 3 Flash|Gemini|Gemini|5|01-01T05|false", - "gemini-3.1-pro-high|Gemini 3.1 Pro (High)|Gemini|Gemini|5|01-01T05|false", - "gpt-oss-120b-medium|GPT-OSS 120B (Medium)|GPT-OSS|Claude & GPT|30||false", - "|7 days||Gemini|25|01-07T00|true", - "|5 hours||Gemini|5|01-01T05|true", - "|7 days||Claude & GPT|100|01-06T00|true", // none left: no fraction - "|5 hours||Claude & GPT|30|01-01T03|true", - ]) - expect(u.windows[4].span).toBe(7 * 24 * 3600) - expect(u.windows[5].span).toBe(5 * 3600) - - // no summary: the models' windows alone - const none = await read(models) - expect(none.windows.length).toBe(4) - expect(none.windows.every((w) => !w.pool)).toBe(true) - - // a group's week without its 5 hours: its models stay out of it - const week = await read(models, JSON.parse(`{"groups":[ - {"displayName":"Gemini Models","description":"Models within this group: Gemini Flash, Gemini Pro","buckets":[ - {"bucketId":"gemini-weekly","window":"weekly","remainingFraction":0.75,"resetTime":"2099-01-07T00:00:00Z"}, - {"bucketId":"gemini-5h","window":"5h","remainingFraction":1,"disabled":true}]}]}`)) - expect(of(week.windows)).toEqual({ "claude-opus-4-6-thinking": "", "gemini-3-flash": "", "gemini-3.1-pro-high": "", "gpt-oss-120b-medium": "" }) - expect(poolWindows(week.windows)).toEqual(["Gemini|7 days"]) -}) - -test("a model with a group of its own is in it, and that group takes no other", async () => { - const argon = (five) => - `{"displayName":"Gemini 4 Argon","description":"For paid Pro plans, Argon quota is separate.","buckets":[{"bucketId":"gemini-argon-wtu-weekly","window":"weekly","remainingFraction":0.53,"resetTime":"2099-01-07T00:00:00Z","displayName":"Gemini 4 Argon Weekly Limit"}` + - (five ? `,{"bucketId":"gemini-argon-5h","window":"5h","remainingFraction":0.8,"resetTime":"2099-01-01T04:00:00Z"}` : "") + - `]}` - const gemini = `{"displayName":"Gemini Models","description":"Models within this group: Gemini Flash, Gemini Pro","buckets":[ - {"bucketId":"gemini-weekly","window":"weekly","remainingFraction":0.99,"resetTime":"2099-01-07T00:00:00Z"}, - {"bucketId":"gemini-5h","window":"5h","remainingFraction":1,"resetTime":"2099-01-01T05:00:00Z"}]}` - const claude = `{"displayName":"Claude and GPT models","description":"Models within this group: Claude Opus, Claude Sonnet, GPT-OSS","buckets":[ - {"bucketId":"3p-weekly","window":"weekly","remainingFraction":0.6,"resetTime":"2099-01-06T00:00:00Z"}, - {"bucketId":"3p-5h","window":"5h","remainingFraction":0.7,"resetTime":"2099-01-01T03:00:00Z"}]}` - const models = JSON.parse(`{"models":{ - "gemini-3-flash":{"displayName":"Gemini 3 Flash","quotaInfo":{"remainingFraction":1,"resetTime":"2099-01-01T05:00:00Z"}}, - "gemini-4-argon":{"displayName":"Gemini 4 Argon","quotaInfo":{"remainingFraction":0.53,"resetTime":"2099-01-07T00:00:00Z"}}, - "claude-sonnet-4-6":{"displayName":"Claude Sonnet 4.6","quotaInfo":{"remainingFraction":0.7}}}}`) - for (const [name, groups, pools] of [ - ["as agy has it", [gemini, claude, argon(false)], ["Gemini|7 days", "Gemini|5 hours", "Claude & GPT|7 days", "Claude & GPT|5 hours", "Gemini 4 Argon|7 days"]], - ["Argon first", [argon(false), gemini, claude], ["Gemini 4 Argon|7 days", "Gemini|7 days", "Gemini|5 hours", "Claude & GPT|7 days", "Claude & GPT|5 hours"]], - ["Argon first with 5 hours", [argon(true), gemini, claude], ["Gemini 4 Argon|7 days", "Gemini 4 Argon|5 hours", "Gemini|7 days", "Gemini|5 hours", "Claude & GPT|7 days", "Claude & GPT|5 hours"]], - ]) { - const u = await read(models, JSON.parse(`{"groups":[${groups.join(",")}]}`)) - expect([name, of(u.windows)]).toEqual([name, { "gemini-3-flash": "Gemini", "gemini-4-argon": "Gemini 4 Argon", "claude-sonnet-4-6": "Claude & GPT" }]) - expect([name, poolWindows(u.windows)]).toEqual([name, pools]) - } -}) - -test("a model read apart from its group is a pool of its own; one read alike folds", async () => { - const five = at(3 * H) - const week = at(6 * 24 * H) - const gemini = `{"displayName":"Gemini Models","description":"Models within this group: Gemini Flash, Gemini Pro","buckets":[ - {"bucketId":"gemini-weekly","window":"weekly","remainingFraction":0.98,"resetTime":"${week}"}, - {"bucketId":"gemini-5h","window":"5h","remainingFraction":0.92,"resetTime":"${five}"}]}` - const claude = `{"displayName":"Claude and GPT models","description":"Models within this group: Claude Opus, Claude Sonnet, GPT-OSS","buckets":[ - {"bucketId":"3p-weekly","window":"weekly","resetTime":"${week}"}, - {"bucketId":"3p-5h","window":"5h","resetTime":"${five}"}]}` - const argonGroup = `{"displayName":"Gemini 4 Argon","description":"For paid Pro plans, Argon quota is separate.","buckets":[ - {"bucketId":"gemini-argon-wtu-weekly","window":"weekly","remainingFraction":0.53,"resetTime":"${week}","displayName":"Gemini 4 Argon Weekly Limit"}]}` - const models = (argon) => - JSON.parse(`{"models":{ - "gemini-3-flash":{"displayName":"Gemini 3 Flash","quotaInfo":{"remainingFraction":0.92,"resetTime":"${five}"}}, - "gemini-3.1-pro-high":{"displayName":"Gemini 3.1 Pro (High)","quotaInfo":{"remainingFraction":0.92,"resetTime":"${five}"}}, - "gemini-4-argon-high":{"displayName":"Gemini 4 Argon (High)","quotaInfo":${argon}}, - "gemini-4-argon-low":{"displayName":"Gemini 4 Argon (Low)","quotaInfo":${argon}}, - "claude-sonnet-4-6":{"displayName":"Claude Sonnet 4.6","quotaInfo":{"resetTime":"${five}"}}}}`) - const apart = `{"remainingFraction":0.53,"resetTime":"${week}"}` - const alike = `{"remainingFraction":0.92,"resetTime":"${five}"}` - const argonPool = { "gemini-3-flash": "Gemini", "gemini-3.1-pro-high": "Gemini", "gemini-4-argon-high": "Gemini 4 Argon", "gemini-4-argon-low": "Gemini 4 Argon", "claude-sonnet-4-6": "Claude & GPT" } - const folded = { ...argonPool, "gemini-4-argon-high": "Gemini", "gemini-4-argon-low": "Gemini" } - const base = ["Gemini|7 days", "Gemini|5 hours", "Claude & GPT|7 days", "Claude & GPT|5 hours"] - for (const [name, groups, argon, pools, windows] of [ - ["no Argon group, read apart (runking)", [gemini, claude], apart, argonPool, [...base, "Gemini 4 Argon|7 days"]], - ["no Argon group, read alike", [gemini, claude], alike, folded, base], - ["the Argon group", [gemini, claude, argonGroup], apart, argonPool, [...base, "Gemini 4 Argon|7 days"]], - ]) { - const u = await read(models(argon), JSON.parse(`{"groups":[${groups.join(",")}]}`)) - expect([name, of(u.windows)]).toEqual([name, pools]) - expect([name, poolWindows(u.windows)]).toEqual([name, windows]) - for (const w of u.windows) { - if (w.pool === "Gemini 4 Argon" && !w.model) { - expect(w.used).toBeGreaterThan(46) - expect(w.used).toBeLessThan(48) - expect(w.aside).toBe(true) - } - } - } -}) - -test("models read as their group's week draw on the group", async () => { - const five = at(5 * H) - const week = at(5 * 24 * H) - const wk = `{"remainingFraction":0.01,"resetTime":"${week}"}` - const u = await read( - JSON.parse(`{"models":{ - "gemini-3-flash":{"displayName":"Gemini 3 Flash","quotaInfo":${wk}}, - "gemini-3.1-pro-high":{"displayName":"Gemini 3.1 Pro (High)","quotaInfo":${wk}}, - "gemini-3.1-pro-low":{"displayName":"Gemini 3.1 Pro (Low)","quotaInfo":${wk}}, - "gemini-3.5-flash":{"displayName":"Gemini 3.5 Flash","quotaInfo":${wk}}, - "gemini-3.1-flash-lite":{"displayName":"Gemini 3.1 Flash Lite","quotaInfo":${wk}}, - "claude-sonnet-4-6":{"displayName":"Claude Sonnet 4.6","quotaInfo":{"resetTime":"${week}"}}, - "claude-opus-4-6-thinking":{"displayName":"Claude Opus 4.6 (Thinking)","quotaInfo":{"resetTime":"${week}"}}}}`), - JSON.parse(`{"groups":[ - {"displayName":"Gemini Models","description":"Models within this group: Gemini Flash, Gemini Pro","buckets":[ - {"bucketId":"gemini-weekly","window":"weekly","remainingFraction":0.01,"resetTime":"${week}"}, - {"bucketId":"gemini-5h","window":"5h","remainingFraction":1,"resetTime":"${five}"}]}, - {"displayName":"Claude and GPT models","description":"Models within this group: Claude Opus, Claude Sonnet, GPT-OSS","buckets":[ - {"bucketId":"3p-weekly","window":"weekly","resetTime":"${week}"}, - {"bucketId":"3p-5h","window":"5h","resetTime":"${five}"}]}]}`), - ) - for (const w of u.windows.filter((w) => w.model)) expect([w.model, w.pool]).toEqual([w.model, w.family === "Claude" ? "Claude & GPT" : "Gemini"]) - expect(poolWindows(u.windows)).toEqual(["Gemini|7 days", "Gemini|5 hours", "Claude & GPT|7 days", "Claude & GPT|5 hours"]) - // a model read as the week is a week's window - expect(u.windows.find((w) => w.model === "gemini-3-flash").span).toBe(7 * 24 * 3600) -}) - -test("a refresh Google refuses is a sign-in to do again", async () => { - fake({ token: () => new Response('{"error":"invalid_grant"}', { status: 400 }) }) - const p = await AntigravityAuthPlugin({}) - const u = await p.auth.usage(async () => ({ ...auth(), expires: 0 })) - expect(u.signIn).toBe("expired") -}) diff --git a/packages/antigravity/version.test.mjs b/packages/antigravity/version.test.mjs deleted file mode 100644 index 2e7bc19..0000000 --- a/packages/antigravity/version.test.mjs +++ /dev/null @@ -1,61 +0,0 @@ -// The version the requests name is read from the update manifest (#1057). -import { afterEach, beforeEach, expect, test } from "bun:test" -import { _internal } from "./index.mjs" -import { real } from "./fake.mjs" - -const { ver, version, lists, VERSION_TTL, VERSION_RETRY, DEFAULT_VERSION } = _internal - -beforeEach(() => { - ver.v = "" - ver.at = 0 - ver.pending = null - lists.clear() -}) -afterEach(() => (globalThis.fetch = real)) - -const manifest = (v) => async () => new Response(`version: ${v}\nfiles: []\n`, { status: 200 }) -const down = async () => { throw new TypeError("fetch failed") } - -test("a manifest that can't be read is asked again after a minute, not six hours", async () => { - let asked = 0 - globalThis.fetch = async (...a) => { asked++; return down(...a) } - expect(await version()).toBe(DEFAULT_VERSION) - expect(asked).toBe(1) - expect(await version()).toBe(DEFAULT_VERSION) - expect(asked).toBe(1) - ver.at -= VERSION_RETRY + 1 - globalThis.fetch = async (...a) => { asked++; return manifest("2.40.0")(...a) } - expect(await version()).toBe("2.40.0") - expect(asked).toBe(2) - ver.at -= VERSION_RETRY + 1 - expect(await version()).toBe("2.40.0") - expect(asked).toBe(2) -}) - -test("a read manifest holds for six hours", async () => { - let asked = 0 - globalThis.fetch = async (...a) => { asked++; return manifest("2.40.0")(...a) } - await version() - ver.at -= VERSION_TTL - 1000 - await version() - expect(asked).toBe(1) -}) - -test("a new version drops the model lists read under the old one", async () => { - globalThis.fetch = down - await version() - lists.set("rt", { at: Date.now(), infos: [], project: "p" }) - ver.at -= VERSION_RETRY + 1 - globalThis.fetch = manifest(DEFAULT_VERSION) - await version() - expect(lists.size).toBe(1) - ver.at -= VERSION_TTL + 1 - globalThis.fetch = manifest("2.40.0") - await version() - expect(lists.size).toBe(0) -}) - -test("the default is a release Google serves Gemini 4 to", () => { - const [a, b] = DEFAULT_VERSION.split(".").map(Number) - expect(a > 2 || (a === 2 && b >= 20)).toBe(true) -}) diff --git a/registry.json b/registry.json index 7e1590e..c932213 100644 --- a/registry.json +++ b/registry.json @@ -37,8 +37,6 @@ "summary": { "en": "Your Qoder subscription: international (qoder.com) or Qoder CN, the China site (qoder.cn, Alibaba Cloud or phone sign-in), each its own provider. Also QwenWork (千问办公): the public cloud or the enterprise flagship with its own domain. Unofficial for QwenWork.", "zh": "用 Qoder 自己的设备登录使用 Qoder 订阅:国际版(qoder.com)与 Qoder 中国版(Qoder CN,qoder.cn,阿里云账号 / 手机号登录)各是一个订阅;也接入千问办公:公有云与企业旗舰版(输入企业自己的域名)。千问办公部分非官方。" } }, { "package": "@magpie-community/opencode-devin-auth", "name": "Devin", "icon": "devin", "providers": ["devin"], "community": true, "replaces": "devin", "summary": { "en": "Devin's models with your Devin account — a browser sign-in or the devin CLI's.", "zh": "用 Devin 账号使用 Devin 的模型:浏览器登录,或沿用 devin CLI 的登录。" } }, - { "package": "@magpie-community/opencode-antigravity-auth", "name": "Antigravity", "icon": "antigravity-color", "providers": ["antigravity"], "community": true, "replaces": "antigravity", - "summary": { "en": "Gemini, Claude and GPT-OSS in Antigravity, with your Google account (AI Pro, Ultra or free).", "zh": "用 Google 账号(AI Pro、Ultra 或免费)使用 Antigravity 里的 Gemini、Claude 和 GPT-OSS。" } }, { "package": "@magpie-community/opencode-zed-auth", "name": "Zed", "icon": "zed", "providers": ["zed"], "community": true, "replaces": "zed", "summary": { "en": "Claude, GPT, Gemini and Grok hosted by Zed, on your Zed plan.", "zh": "用 Zed 订阅使用 Zed 托管的 Claude、GPT、Gemini 和 Grok。" } }, { "package": "@magpie-community/opencode-factory-auth", "name": "Factory", "icon": "factory", "providers": ["factory"], "community": true, "replaces": "factory",