antigravity 0.1.0: Antigravity with a Google account, ported from magpie's built-in

Signs in with Google (Antigravity's client, PKCE, loopback) or imports a
refresh token / account-manager export, sets up the Code Assist project
(loadCodeAssist, onboardUser on the default tier), lists the account's
models with level variants, and sends every request through
v1internal:streamGenerateContent in the app's envelope, with the
built-in's request shaping (system-prompt cloak, tool ids and results,
schema flattening, Claude and Gemini rules), its error mapping (turned-away
429 -> 400 unapproved channel, 404 model, refused refresh -> 401 expired)
and its usage windows and pools.

A stream's last chunk is an empty text part; sent back in the next turn,
Claude refuses it ("text: Field required"). Both the whole-reply reader and
the request shaper drop it.

Run:
- bun test packages/antigravity on mote: 78 pass, 0 fail.
- bun scripts/check.mjs antigravity: registry.json ok, antigravity ok.
- Real account (the built-in's saved Google account, read only, sandbox
  HOME): model list; stream and generateContent on gemini-3.8-flash; the
  effort header picking -low; claude-sonnet-4-6, claude-opus-4-6-thinking,
  gpt-oss-120b-medium all answer; a Claude Code system prompt to Gemini
  answers 200 (cloak); an unknown model 404; usage gives plan, model
  windows and the Gemini and Claude & GPT 7-day pools; a tool call round
  trip on Claude Sonnet, Opus thinking, Gemini and GPT-OSS.
- Broken by hand: without the empty-text drop the new shape test and the
  generateContent test go red, and the real Claude round trip answered 400.

Not carried over (README): the 6h rest of a turned-away account, Google
Search grounding and image models, countTokens (404, magpie estimates),
sending the system prompt uncloaked, multi-account import, models.dev
names. Not tried: the browser sign-in end to end (the import path was).
This commit is contained in:
yetone
2026-11-10 17:30:21 +08:00
parent 34786edadb
commit e35aa928ad
13 changed files with 3180 additions and 0 deletions
+1
View File
@@ -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` |
+142
View File
@@ -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 `<refresh token>|<project>`.
- `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/<version> <os>/<arch>`. 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.
+44
View File
@@ -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",
})
File diff suppressed because it is too large Load Diff
+111
View File
@@ -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)
})
+5
View File
@@ -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"
+596
View File
@@ -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/<name>/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) }
+12
View File
@@ -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" }
}
+170
View File
@@ -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")
})
+123
View File
@@ -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 })
})
+139
View File
@@ -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" })
})
+188
View File
@@ -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")
})
+2
View File
@@ -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",