diff --git a/README.md b/README.md index 12389df..e8f22a2 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [agnes](packages/agnes) | Agnes AI international (agnes-ai.com), with Chrome browser sign-in, live text models, plan usage and USD balance | `agnes` | | [agnes-code](packages/agnes-code) | Agnes AI's Agnes Code desktop, with the desktop's saved session (Windows) or a pasted access token: live models, daily credit check-in and points balance (unofficial) | `agnes-code` | | [agy-cli](packages/agy-cli) | Antigravity on your installed agy CLI through ACP (`agy acp`), with agy's own Google sign-in: only the models agy offers this client, a process pool, MCP tool bridge and session resume (unofficial) | `agy-cli` | +| [antigravity](packages/antigravity) | Antigravity with a Google account (AI Pro, Ultra, free): Gemini, and the Claude and GPT-OSS models Google hosts for it, with Google sign-in or an imported refresh token | `antigravity` | | [astudio](packages/astudio) | iFlytek's AStudio (科大讯飞 Astron Studio desktop), with the desktop's saved credentials or a pasted model token: live model catalog, daily login-points check-in and points balance (unofficial) | `astudio` | | [atomcode](packages/atomcode) | AtomGit CodingPlan, with browser OAuth or the local AtomCode CLI's sign-in, signed requests, live models, quota windows and a read-only diagnostics page (unofficial) | `atomcode` | | [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` | diff --git a/packages/antigravity/README.md b/packages/antigravity/README.md new file mode 100644 index 0000000..d188b5d --- /dev/null +++ b/packages/antigravity/README.md @@ -0,0 +1,142 @@ +# @magpie-community/opencode-antigravity-auth + +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. + +## Sign-in + +There are two ways to sign in: + +- **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. + + The import signs in the first account it finds. An export of another + subscription (a `type` other than Antigravity) is refused. + +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. + +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 (`{model, project, userAgent: "antigravity", +requestType: "agent", requestId, request}`): + +- The User-Agent is `antigravity/hub/ /`. The version is + read from the app's update manifest every 6 hours. +- The session id is a number made from the conversation's first user + message, so every turn of one conversation is 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 (Claude Code's billing + header, Codex's and Hermes Agent's own prompts) are broken up with a + zero-width space. +- **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) | +| 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. + +## 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. +- Google Search grounding, and image models (drawing). +- `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. diff --git a/packages/antigravity/fake.mjs b/packages/antigravity/fake.mjs new file mode 100644 index 0000000..92f1662 --- /dev/null +++ b/packages/antigravity/fake.mjs @@ -0,0 +1,44 @@ +// 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 new file mode 100644 index 0000000..3084cb8 --- /dev/null +++ b/packages/antigravity/index.mjs @@ -0,0 +1,1647 @@ +// 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): +// +// - 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: }. +// +// 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" + +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", +] +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" +const DEFAULT_VERSION = "2.9.1" + +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 + +// the header magpie names a request's effort in +const EFFORT = "x-magpie-effort" + +// ---- 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 platform = () => `${GOOS[process.platform] ?? process.platform}/${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 +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 () => { + try { + const res = await fetch(VERSION_URL, { headers: { "User-Agent": "electron-builder" }, signal: AbortSignal.timeout(5000) }) + 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)) ver.v = v + break + } + } + } catch {} + ver.pending = null + return ver.v + })() + return ver.pending +} + +const userAgent = async () => `antigravity/hub/${await version()} ${platform()}` + +// ---- 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 ?? "" } +} + +// 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 } = tiersOf(load) + if (s.project) { + if (err) return { id: s.project, plan: "", tier: "", paid: "", at: Date.now() } + return { id: s.project, plan: planOf(load), tier, paid, at: Date.now() } + } + if (err) throw err + const own = companion(load.cloudaicompanionProject) + if (own) return { id: own, plan: planOf(load), tier, paid, at: Date.now() } + const t = { ...defaultTier(load) } + if (!t.id || t.id === "legacy-tier") t.id = "free-tier" + const ua = await userAgent() + const id = await onboard( + s, + { tier_id: t.id, metadata: { ide_type: "ANTIGRAVITY", ide_version: await version(), ide_name: "antigravity" } }, + { "User-Agent": ua + " google-api-nodejs-client/10.3.0", "X-Goog-Api-Client": "gl-node/22.21.1" }, + ) + 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, 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 } = tiersOf(load) + if (tier || paid) { + p = { ...p, tier, paid } + 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 (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 is broken up before it goes by a zero-width +// space after its first letter, which Google lets through. +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", + "hermes agent, an intelligent ai assistant created by nous research", +] + +const ZW = "​" + +const turnsAway = (system) => { + const low = system.toLowerCase() + return TURNED_AWAY.some((l) => low.includes(l)) +} + +const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase()) + +function cloak(system) { + if (!turnsAway(system)) return system + const low = asciiLower(system) + const at = new Set() + for (const line of TURNED_AWAY) { + for (let i = 0; ; ) { + const j = low.indexOf(line, i) + if (j < 0) break + at.add(j + 1) + i = j + line.length + } + } + let out = "" + let prev = 0 + for (const i of [...at].sort((a, b) => a - b)) { + out += system.slice(prev, i) + ZW + prev = i + } + 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 earlier default persona (its SOUL.md) whatever quota is left, so it is not a quota and waiting won't help; Hermes' current default persona goes through, so put it in SOUL.md, or use another provider for these chats" + +function hint(system) { + const low = system.toLowerCase() + if (low.includes("you are codex, an agent based on gpt-5") || low.includes("you are codex, a coding agent based on gpt-5")) return CODEX_HINT + if (low.includes("hermes agent, an intelligent ai assistant created by nous research")) return HERMES_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 +} + +// 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 = cloak(p.text) + } else if (typeof req.systemInstruction === "string") { + req.systemInstruction = { role: "user", parts: [{ text: cloak(req.systemInstruction) }] } + } + if (Array.isArray(req.contents)) { + for (const c of req.contents) { + // 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" + 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 +} + +// sessionOf is the session id the app gives a conversation: a number +// made of its first thing said +function sessionOf(req) { + let text = "" + for (const c of req.contents ?? []) { + if (c?.role !== "user") continue + for (const p of c.parts ?? []) { + if (typeof p?.text === "string" && p.text !== "") { + text = p.text + break + } + } + break + } + 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() +} + +function envelope(req, sent, projectID) { + return { + model: sent, + project: projectID, + userAgent: "antigravity", + requestType: "agent", + requestId: "agent-" + crypto.randomBytes(6).toString("hex"), + request: { ...req, sessionId: sessionOf(req) }, + } +} + +// ---- 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 +function unwrap(body) { + const dec = new TextDecoder() + const enc = new TextEncoder() + let buf = "" + const line = (l) => { + if (!l.startsWith("data:")) return l + const j = parse(l.slice(5).trim()) + if (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" } + +// complete sends a Gemini request at url (…/models/:) to +// Antigravity for the account s +async function complete(s, url, init) { + 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 + if (!effort && typeof tl === "string" && LEVELS.includes(tl)) effort = tl + 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 res = await fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "text/event-stream", Authorization: "Bearer " + tok, "User-Agent": await userAgent() }, + body: JSON.stringify(envelope(req, sent, l.project.id)), + signal: init?.signal, + }) + if (!res.ok) { + const text = await res.text() + const msg = apiError(text, res.status) + 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 + return errorResponse(400, `Antigravity turned this request away as from an unapproved channel: ${msg} — ${hint(system)}`) + } + 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), { status: 200, headers: RESPONSE_HEADERS }) + return new Response(JSON.stringify(await whole(res)), { status: 200, headers: { "content-type": "application/json" } }) +} + +// 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 + 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 + for (const p of j.candidates?.[0]?.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, 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() + } + }, + } +} + +// 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] + 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) } + } + }, + } +} + +// ---- the plugin --------------------------------------------------------------------------- + +export async function AntigravityAuthPlugin({ client } = {}) { + return { + 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 ?? {}) }, + } + }, + 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)])) + }, + }, + auth: { + provider: PROVIDER, + 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, + }, + ], + async loader(getAuth) { + if (!stateOf(await getAuth())) return {} + 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) + }, + } + }, + async usage(getAuth) { + return usage(await getAuth()) + }, + }, + } +} + +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, + entitlements, + complete, + usage, + tokens, + projects, + lists, + refused, + ver, +} diff --git a/packages/antigravity/models.test.mjs b/packages/antigravity/models.test.mjs new file mode 100644 index 0000000..7d4537e --- /dev/null +++ b/packages/antigravity/models.test.mjs @@ -0,0 +1,111 @@ +// 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/opencode.mjs b/packages/antigravity/opencode.mjs new file mode 100644 index 0000000..4916f5e --- /dev/null +++ b/packages/antigravity/opencode.mjs @@ -0,0 +1,5 @@ +// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host +// load them: its plugin functions and nothing else (1.x refuses a +// package whose exports include anything but plugins). OpenCode 2.x +// loads opencode2.mjs, which runs these. +export { AntigravityAuthPlugin } from "./index.mjs" diff --git a/packages/antigravity/opencode2.mjs b/packages/antigravity/opencode2.mjs new file mode 100644 index 0000000..364ea8a --- /dev/null +++ b/packages/antigravity/opencode2.mjs @@ -0,0 +1,596 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + void refresh() +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/antigravity/package.json b/packages/antigravity/package.json new file mode 100644 index 0000000..61f1205 --- /dev/null +++ b/packages/antigravity/package.json @@ -0,0 +1,12 @@ +{ + "name": "@magpie-community/opencode-antigravity-auth", + "version": "0.1.0", + "description": "Sign in to Antigravity with a Google account from OpenCode or magpie: Gemini, and the Claude and GPT-OSS models Google hosts for it", + "type": "module", + "main": "./opencode.mjs", + "exports": { ".": "./opencode2.mjs" }, + "files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "README.md"], + "keywords": ["opencode", "opencode-plugin", "magpie", "antigravity", "gemini"], + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/antigravity" } +} diff --git a/packages/antigravity/requests.test.mjs b/packages/antigravity/requests.test.mjs new file mode 100644 index 0000000..6356647 --- /dev/null +++ b/packages/antigravity/requests.test.mjs @@ -0,0 +1,170 @@ +// 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) +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") + expect(sent.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \w+\/\w+$/) + expect(sent.json).toMatchObject({ model: "gemini-3.7-flash-low", project: "ag-proj", userAgent: "antigravity", requestType: "agent" }) + 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 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 earlier default persona"], + ]) { + 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("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") + expect(on.json).toEqual({ tier_id: "free-tier", metadata: { ide_type: "ANTIGRAVITY", ide_version: "3.1.4", ide_name: "antigravity" } }) + expect(on.headers["user-agent"]).toEndWith(" google-api-nodejs-client/10.3.0") + expect(on.headers["x-goog-api-client"]).toBe("gl-node/22.21.1") + 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") +}) diff --git a/packages/antigravity/schema.test.mjs b/packages/antigravity/schema.test.mjs new file mode 100644 index 0000000..798e34b --- /dev/null +++ b/packages/antigravity/schema.test.mjs @@ -0,0 +1,123 @@ +// 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/shape.test.mjs b/packages/antigravity/shape.test.mjs new file mode 100644 index 0000000..91894ee --- /dev/null +++ b/packages/antigravity/shape.test.mjs @@ -0,0 +1,139 @@ +// 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"], + ["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("the lines Antigravity turns away are broken up", () => { + const sys = "x-anthropic-billing-header: cc_version=2\nYou are Claude Code, built on Anthropic's Claude Agent SDK.\nhi" + const out = cloak(sys) + expect(out).not.toBe(sys) + expect(out.replaceAll("​", "")).toBe(sys) + expect(out).toContain("x​-anthropic-billing-header:") + expect(out).toContain("b​uilt on Anthropic's") + // twice is the same as once, and other text is left alone + expect(cloak(out)).toBe(out) + expect(cloak("be brief")).toBe("be brief") + const r = shape({ systemInstruction: { parts: [{ text: sys }] }, contents: [] }, "gemini-3-flash", "", "") + expect(r.systemInstruction.parts[0].text).toBe(out) +}) + +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.requestId).toMatch(/^agent-[0-9a-f]{12}$/) + expect(env.request.sessionId).toBe(sessionOf(a)) +}) + +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" }) +}) diff --git a/packages/antigravity/usage.test.mjs b/packages/antigravity/usage.test.mjs new file mode 100644 index 0000000..0fbb50c --- /dev/null +++ b/packages/antigravity/usage.test.mjs @@ -0,0 +1,188 @@ +// 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/registry.json b/registry.json index 629ba82..dbe561a 100644 --- a/registry.json +++ b/registry.json @@ -35,6 +35,8 @@ "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",