antigravity 0.2.1: serves again for whoever has it; magpie gives it to nobody new

The owner (11-15): "正在使用的继续正常,加个提示,新用户不让下载".
0.2.0 answered every request with a 410. 0.2.1 restores the plugin as
0.1.18 had it (git checkout df7d7ae0 -- packages/antigravity), so a user
who has it keeps working. It stays out of registry.json, and magpie's
plugin.Add turns it away for anyone who doesn't have it listed, with a
line on the Providers page telling its users that Google suspends accounts
it sees used this way and pointing to agy-cli. The READMEs say so.

Run on mote at this tree, HOME a temp dir: bun scripts/check.mjs all, and
bun test packages/antigravity packages/agy-cli scripts: 195 pass, 0 fail.
This commit is contained in:
yetone
2026-11-16 02:43:44 +08:00
parent 1260b2ba40
commit c0c625ac7d
13 changed files with 4006 additions and 125 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ vendor service 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` |
| [antigravity](packages/antigravity) | Withdrawn for new users: Google suspends accounts it sees used this way. Kept working for whoever has it; use agy-cli instead | `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` |
+179 -23
View File
@@ -1,30 +1,186 @@
# @magpie-community/opencode-antigravity-auth (retired)
# @magpie-community/opencode-antigravity-auth
**Retired in 0.2.0. Use [Antigravity (local agy CLI)](../agy-cli/README.md),
`@magpie-community/opencode-agy-cli-auth`, instead.**
**Withdrawn for new users (0.2.1).** Google suspends accounts it sees
calling Code Assist the way this plugin does (Antigravity's own client,
outside the Antigravity app). magpie keeps it working for whoever has it
already, tells them the risk, and installs it for nobody new. Use
[Antigravity (local agy CLI)](../agy-cli/README.md),
`@magpie-community/opencode-agy-cli-auth`, which runs the `agy` you
installed and signed in to yourself.
Up to 0.1.18 this plugin signed in to Antigravity with a Google account and
sent requests to Google's Code Assist API (`cloudcode-pa.googleapis.com`)
the way the Antigravity app does. Google bans accounts it sees used that
way. Antigravity (local agy CLI) runs the `agy` CLI you installed and signed
in to, over the Agent Client Protocol (`agy acp`), so the requests Google
sees are agy's own.
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.
From 0.2.0 this package sends no request at all:
## Sign-in
- every request is answered `410` with a message that says to install
Antigravity (local agy CLI). magpie reads it as a retired model, so a
routing group goes on to its next member;
- signing in is turned away with the same message;
- it lists no models, usage or web search.
There are two ways to sign in:
To move:
- **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.
```sh
magpie plugin add @magpie-community/opencode-agy-cli-auth
magpie plugin remove @magpie-community/opencode-antigravity-auth
```
The import signs in the first account it finds. An export of another
subscription (a `type` other than Antigravity) is refused.
Then sign in to agy once (Plugins › Antigravity (local agy CLI) › Sign in,
or `agy` in a terminal). Antigravity (local agy CLI) serves the one Google
account agy is signed in to.
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, keys in the order the app's language server
sends them (`{project, requestId, request, model, userAgent: "antigravity",
requestType: "agent"}`, captured from 2.32.1):
- The User-Agent is the language server's: `antigravity/hub/<version>
(aidev_client; os_type=<os>; arch=<arch>; cl=<changelist>)`. The version is
read from the app's update manifest every 6 hours. Google lists Gemini 4
only to new enough releases, so a manifest that can't be read is asked
again after a minute, and the model list is read again when the version
changes. The changelist is each release's own, from a table in the
plugin; a release newer than the table goes with the newest one known.
- A conversation is one cascade: `requestId` is
`agent/<cascade>/<ms>/<trajectory>/<step>`, and `request.labels` carries the
cascade and trajectory ids, the step, the model's enum from
`fetchAvailableModels` and whether it is Claude or not Gemini, as the app
labels its requests.
- `onboardUser` is asked as the language server asks it:
`{tierId, metadata: {ideType: "ANTIGRAVITY"}}`.
- The session id is a number made from the host's session header when named,
else the conversation's first real user prompt (skipping injected
`AGENTS.md` and environment preambles), so unrelated conversations that
share a preamble don't collide on one session.
- Each reply chunk (`{response: …}`) is unwrapped back into Gemini's own.
- A `generateContent` request gets the stream read whole.
The plugin also changes the request itself, as the built-in did:
- **System prompt:** lines Antigravity turns away with a 429 whatever quota
is left go reworded with the same meaning, since Google's check reads past
zero-width spaces (11-14): Claude Code's billing header is left out, the
Claude Agent SDK's "built on Anthropic's Claude Agent SDK" (Claude
Desktop's Code tab and its subagents) goes as "built on the Claude Agent
SDK by Anthropic", Codex's GPT-5 lines say "built on GPT-5", omp's line
"RFC 2119 key words: …", Hermes Agent's persona, OpenCode's prompt and
Codex's prompt for a model it has none for go as "You're …" for "You are
Hermes Agent" / "You are OpenCode" / "You are a coding agent running in
the Codex CLI", and pi's default prompt as "running within pi" for
"running inside pi" (the last four turned away since 11-14). A copy
someone broke up with invisible characters is reworded the same way.
DeepSeek Harness's paragraph on `@` paths ("Tokens prefixed with @ are
paths…") goes reworded with the same meaning: word for word, it got most
`gemini-4-argon` answers fast, without thinking and shallow (#1028).
- **Tool calls:**
- Tool call ids are reduced to `[A-Za-z0-9_-]`.
- A tool's `{output}` or `{error}` response becomes `{result}`.
- **Schemas:** a tool's schema is flattened to the subset Antigravity takes.
- Unions keep their own shape.
- Every array gets `items`.
- `null` types become `nullable`.
- `$ref` is resolved.
- Blank enum values are dropped.
- **Claude:**
- A tool's images follow every function response.
- `AUTO` function calling becomes `VALIDATED`.
- A model without "thinking" in its name loses `thinkingConfig`.
- **Gemini:**
- `maxOutputTokens` is dropped.
- Gemini 3 and later think at a `thinkingLevel`. Earlier models lose a
level a variant put on them.
## Errors
| What Antigravity answers | What the plugin answers |
|---|---|
| 429 "Resource has been exhausted" to a system prompt with a turned-away line | 400 "turned this request away as from an unapproved channel", with what to change (it isn't a quota, so nothing is rested) |
| 429 from a plan's quota, the account having Google AI credits | with the Use AI credits switch on (off by default), the request is asked again once with `enabled_credit_types: ["GOOGLE_ONE_AI"]`, as the app's Use AI Credits does; with it off, the 429 says the switch would spend them |
| Gemini 4's 400 INVALID_ARGUMENT after it ran (in the stream after thinking, or a slow 400) | asked again, up to twice. A stream's thinking is held back for up to 10 seconds, or until the answer starts, so a retry sends nothing twice; past 10 seconds the thinking streams live, and a 400 after that reaches the client. Code Assist writes the stream's error as a bare JSON line with no `data:`, read as well. A 400 that still comes says the model turned down a call it built, and how many times it was asked, since Google's words alone read as a region or account block |
| 401 | 401, sign-in kept |
| 404 | 404 "model … not found" |
| Refresh refused | 401, `x-magpie-sign-in: expired` |
## Usage
Each model has a window from its `quotaInfo`:
- The window reads 100% used when Antigravity leaves the fraction out.
- It says the model's family (Gemini, Claude, GPT-OSS).
- For a level, it also names the model magpie offers.
Then `retrieveUserQuotaSummary`'s groups give the pools that models share,
each with a 5-hour and a 7-day window (`aside`). Each model is put in the
pool it reads from:
- a group whose versioned name is the model's own (Gemini 4 Argon);
- else the group of its family, when the model reads like one of that
group's windows;
- else a pool of its own, named for the model, when it reads otherwise.
## Web Search
The plugin registers a magpie `search` hook (`antigravity:antigravity`)
backed by Antigravity's Google Search grounding (`tools: [{ googleSearch: {} }]`
on an available Flash model with minimal/zero thinking on the signed-in
Antigravity account), returning grounded pages with URLs and snippets.
## Not carried over from the built-in
- Resting an account that Antigravity turned away for 6 hours, and asking
its other accounts first. The 400 above makes magpie try the next
account at once.
- Image models (drawing) as an OpenAI images endpoint.
- `countTokens` answers 404, so magpie estimates the count.
- Sending the system prompt as written: the plugin always breaks up the
turned-away lines.
- Importing many accounts at once: an import signs in one account.
- Model names from models.dev: a model Antigravity leaves unnamed is named
for its id.
+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)
})
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@magpie-community/opencode-antigravity-auth",
"version": "0.2.0",
"description": "Retired: sends no request and points to Antigravity (local agy CLI), @magpie-community/opencode-agy-cli-auth, which Google does not ban accounts for",
"version": "0.2.1",
"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" },
+482
View File
@@ -0,0 +1,482 @@
// Requests as the built-in sent them (google_test.go's
// TestAntigravityProjectAndEnvelope, the tier tests in
// antigravity_tier_test.go, and codeassist.go's error rules).
import { afterEach, beforeEach, expect, test } from "bun:test"
import { AntigravityAuthPlugin, _internal } from "./index.mjs"
import { auth, fake, real, reset } from "./fake.mjs"
beforeEach(() => { reset(); _internal.retry400.pauseMs = 0; _internal.retry400.floorMs = 3000; _internal.retry400.holdMs = 10_000 })
afterEach(() => (globalThis.fetch = real))
const URL_ = (m, method = "streamGenerateContent") => `https://daily-cloudcode-pa.googleapis.com/v1beta/models/${m}:${method}?alt=sse`
const ask = (text = "hi", extra = {}) => JSON.stringify({ contents: [{ role: "user", parts: [{ text }] }], ...extra })
const sse = (...chunks) => new Response(chunks.map((c) => "data: " + JSON.stringify({ response: c, traceId: "t" }) + "\r\n\r\n").join(""), { status: 200, headers: { "content-type": "text/event-stream" } })
const models = {
models: {
"gemini-3.7-flash-high": { displayName: "Gemini 3.7 Flash (High)" },
"gemini-3.7-flash-low": { displayName: "Gemini 3.7 Flash (Low)" },
"gemini-3-flash": { displayName: "Gemini 3 Flash" },
},
}
async function loaderFetch(a) {
const p = await AntigravityAuthPlugin({})
const l = await p.auth.loader(async () => a)
return l.fetch
}
test("a request goes in Antigravity's envelope, and its stream comes back Gemini's", async () => {
const seen = fake({
fetchAvailableModels: models,
streamGenerateContent: () => sse({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "lo" }] }, finishReason: "STOP" }], usageMetadata: { totalTokenCount: 3 } }),
})
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-3.7-flash"), { method: "POST", headers: { "content-type": "application/json", "x-magpie-effort": "low" }, body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true } } }) })
expect(res.status).toBe(200)
const text = await res.text()
const chunks = text.split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6)))
expect(chunks.map((c) => c.candidates[0].content.parts[0].text).join("")).toBe("Hello")
const sent = seen.find((s) => s.name === "streamGenerateContent")
expect(sent.url).toBe("https://daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse")
expect(sent.headers.authorization).toBe("Bearer tok")
// as the app's language server sends it (2.32.1, captured)
expect(sent.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \(aidev_client; os_type=(darwin|linux|windows); arch=(arm64|amd64); cl=\d+\)$/)
expect(sent.headers.accept).toBeUndefined()
expect(sent.json).toMatchObject({ model: "gemini-3.7-flash-low", project: "ag-proj", userAgent: "antigravity", requestType: "agent" })
expect(Object.keys(sent.json)).toEqual(["project", "requestId", "request", "model", "userAgent", "requestType"])
expect(sent.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: "low" })
expect(sent.json.request.sessionId).toMatch(/^-\d+$/)
// models are read once
await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(seen.filter((s) => s.name === "fetchAvailableModels").length).toBe(1)
})
test("OpenCode's variant names the level", async () => {
const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) })
const f = await loaderFetch(auth())
await f(URL_("gemini-3.7-flash"), { method: "POST", body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true, thinkingLevel: "low" } } }) })
expect(seen.find((s) => s.name === "streamGenerateContent").json.model).toBe("gemini-3.7-flash-low")
})
test("a level in capitals, as Gemini's own clients write it, names the level too (#1169)", async () => {
const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) })
const f = await loaderFetch(auth())
await f(URL_("gemini-3.7-flash"), { method: "POST", body: ask("hi", { generationConfig: { thinkingConfig: { includeThoughts: true, thinkingLevel: "LOW" } } }) })
const sent = seen.find((s) => s.name === "streamGenerateContent").json
expect(sent.model).toBe("gemini-3.7-flash-low")
expect(sent.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: "low" })
})
test("a Request input is read", async () => {
const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) })
const f = await loaderFetch(auth())
const res = await f(new Request(URL_("gemini-3-flash"), { method: "POST", body: ask("from a Request") }))
expect(res.status).toBe(200)
expect(seen.find((s) => s.name === "streamGenerateContent").json.request.contents[0].parts[0].text).toBe("from a Request")
})
test("generateContent is the stream read whole", async () => {
fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "lo" }, { functionCall: { name: "f", args: {} } }] } }] }, { candidates: [{ content: { role: "model", parts: [{ text: "" }] }, finishReason: "STOP" }], usageMetadata: { totalTokenCount: 3 } }) })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-3-flash", "generateContent"), { method: "POST", body: ask() })
const j = await res.json()
// the stream's last, empty text is left out
expect(j.candidates[0].content.parts).toEqual([{ text: "Hello" }, { functionCall: { name: "f", args: {} } }])
expect(j.candidates[0].finishReason).toBe("STOP")
expect(j.usageMetadata.totalTokenCount).toBe(3)
})
const exhausted = () => new Response(JSON.stringify({ error: { code: 429, message: "Resource has been exhausted (e.g. check quota).", status: "RESOURCE_EXHAUSTED" } }), { status: 429 })
test("a 429 to a turned-away system prompt is a 400, not a quota", async () => {
fake({ fetchAvailableModels: models, streamGenerateContent: exhausted })
const f = await loaderFetch(auth())
for (const [sys, says] of [
["x-anthropic-billing-header: cc_version=2.1", "Claude Code and the Claude Agent SDK"],
["You are Codex, a coding agent based on GPT-5.", "Codex's own system prompt"],
["You are Hermes Agent, an intelligent AI assistant created by Nous Research.", "Hermes Agent's default persona"],
["You are Hermes Agent, built by Nous Research.", "Hermes Agent's default persona"],
["You are opencode, an interactive CLI tool that helps users with software engineering tasks.", "OpenCode's system prompt"],
["You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.", "Codex's prompt for a model it has none of its own for"],
["You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.", "pi's default system prompt"],
["RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.\n\n§ Role", "oh-my-pi (omp)'s system prompt"],
["RFC 2119 keywords: MUST, REQUIRED,\r\nSHOULD, RECOMMENDED, MAY, OPTIONAL.\r\n\r\n§ Role", "oh-my-pi (omp)'s system prompt"],
]) {
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask("hi", { systemInstruction: { parts: [{ text: sys }] } }) })
expect(res.status).toBe(400)
const j = await res.json()
expect(j.error.message).toContain("answered 429 to this system prompt")
expect(j.error.message).not.toContain("unapproved channel")
expect(j.error.message).toContain(says)
}
// any other prompt's 429 is the quota it says
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask("hi", { systemInstruction: { parts: [{ text: "be brief" }] } }) })
expect(res.status).toBe(429)
expect((await res.json()).error.status).toBe("RESOURCE_EXHAUSTED")
})
test("a model Antigravity doesn't have, and a sign-in that is over", async () => {
fake({ fetchAvailableModels: models, streamGenerateContent: () => new Response("{}", { status: 404 }) })
let f = await loaderFetch(auth())
let res = await f(URL_("gemini-9"), { method: "POST", body: ask() })
expect(res.status).toBe(404)
expect((await res.json()).error.message).toBe("model gemini-9 not found")
reset()
fake({ token: () => new Response(JSON.stringify({ error: "invalid_grant", error_description: "Token has been expired or revoked." }), { status: 400 }) })
f = await loaderFetch({ ...auth(), expires: 0 })
res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(401)
expect(res.headers.get("x-magpie-sign-in")).toBe("expired")
expect((await res.json()).error.message).toContain("sign in again")
})
test("an account with no project is set up for its default tier", async () => {
const seen = fake({
loadCodeAssist: { allowedTiers: [{ id: "free-tier", name: "Antigravity", isDefault: true }] },
onboardUser: (_, all) => (all.filter((s) => s.name === "onboardUser").length < 2 ? { done: false } : { done: true, response: { cloudaicompanionProject: { id: "ag-new" } } }),
fetchAvailableModels: models,
streamGenerateContent: () => sse({ candidates: [] }),
})
const f = await loaderFetch(auth(""))
await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
const load = seen.find((s) => s.name === "loadCodeAssist")
expect(load.url).toBe("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist")
expect(load.json).toEqual({ metadata: { ideType: "ANTIGRAVITY" } })
const on = seen.find((s) => s.name === "onboardUser")
// as 2.32.1's language server asks it (captured)
expect(on.json).toEqual({ tierId: "free-tier", metadata: { ideType: "ANTIGRAVITY" } })
expect(on.headers["user-agent"]).toMatch(/^antigravity\/hub\/3\.1\.4 \(aidev_client; [^)]*\)$/)
expect(on.headers["x-goog-api-client"]).toBeUndefined()
expect(seen.find((s) => s.name === "streamGenerateContent").json.project).toBe("ag-new")
})
test("a paid tier is named, and a tier Google refuses is asked without, once a day", async () => {
const seen = fake({
loadCodeAssist: { cloudaicompanionProject: "ag-proj", currentTier: { id: "standard-tier" }, paidTier: { id: "g1-pro-tier", name: "Google AI Pro" } },
fetchAvailableModels: (s) => (s.json.entitlement ? new Response(JSON.stringify({ error: { code: 400, message: "Invalid tier" } }), { status: 400 }) : models),
})
const p = await AntigravityAuthPlugin({})
const a = auth()
const got = await p.provider.models({ models: {} }, { auth: a })
expect(Object.keys(got)).toEqual(["gemini-3-flash", "gemini-3.7-flash"])
expect(got["gemini-3.7-flash"].variants).toEqual({ low: { thinkingConfig: { thinkingLevel: "low", includeThoughts: true } }, high: { thinkingConfig: { thinkingLevel: "high", includeThoughts: true } } })
const asks = seen.filter((s) => s.name === "fetchAvailableModels").map((s) => s.json.entitlement?.userTier ?? "")
expect(asks).toEqual(["g1-pro-tier", "standard-tier", ""])
_internal.lists.clear()
await p.provider.models({ models: {} }, { auth: a })
expect(seen.filter((s) => s.name === "fetchAvailableModels").length).toBe(4)
const u = await p.auth.usage(async () => a)
expect(u.plan).toBe("Google AI Pro")
})
test("an exported account is imported", async () => {
const { imported } = _internal
expect(imported('{"email":"a@x.com","token":{"refresh_token":"rt1","project_id":"p1"}}')).toEqual([{ rt: "rt1", project: "p1", email: "a@x.com" }])
expect(imported('{"accounts":[{"email":"a@x.com","refreshToken":"rt1"},{"email":"b@x.com","refresh_token":"rt2","projectId":"p2"}]}').map((a) => a.rt)).toEqual(["rt1", "rt2"])
expect(imported("# mine\n1//rt-a\n\n1//rt-b\n").map((a) => a.rt)).toEqual(["1//rt-a", "1//rt-b"])
expect(() => imported('{"type":"kiro","refresh_token":"x"}')).toThrow("kiro")
const seen = fake({ who: { email: "c@x.com" } })
const p = await AntigravityAuthPlugin({})
const m = p.auth.methods[1]
expect(m.prompts[0].key).toBe("account")
const a = await m.authorize({ account: "1//rt-c" })
expect(a.url).toBe("")
const r = await a.callback()
expect(r).toMatchObject({ type: "success", access: "tok-new", refresh: "1//rt-c|ag-proj", accountId: "c@x.com" })
expect(seen.find((s) => s.name === "token").body).toContain("refresh_token=1%2F%2Frt-c")
expect((await m.authorize({ account: "" })).type).toBe("failed")
})
// An Ultra or Pro account's quota for a model is used up: the app asks
// before it spends Google AI credits, and magpie's switch is that answer.
const withCredits = { cloudaicompanionProject: "ag-proj", currentTier: { id: "standard-tier" }, paidTier: { id: "g1-ultra-tier", name: "Google AI Ultra", availableCredits: [{ creditType: "GOOGLE_ONE_AI", creditAmount: "25000", minimumCreditAmountForUsage: "50" }] } }
const spentQuota = () => new Response(JSON.stringify({ error: { code: 429, message: "You have exhausted your capacity on this model.", status: "RESOURCE_EXHAUSTED" } }), { status: 429, headers: { "content-type": "application/json" } })
const credited = (s) => (s.json.enabled_credit_types ? sse({ candidates: [{ content: { role: "model", parts: [{ text: "ok" }] }, finishReason: "STOP" }] }) : spentQuota())
async function creditsFetch(on) {
const p = await AntigravityAuthPlugin({ magpie: { option: (id, key) => (id === "antigravity" && key === "use-ai-credits" ? on : undefined) } })
const l = await p.auth.loader(async () => auth())
return { f: l.fetch, p }
}
test("with Use AI credits on, a request the quota refuses is asked again with the account's credits", async () => {
const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: credited })
const { f } = await creditsFetch(true)
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(200)
const sent = seen.filter((s) => s.name === "streamGenerateContent")
expect(sent.length).toBe(2)
expect(sent[0].json.enabled_credit_types).toBeUndefined()
expect(sent[1].json.enabled_credit_types).toEqual(["GOOGLE_ONE_AI"])
})
test("when the asking with credits is refused too, the quota's 429 is what comes back, and a retry works the same", async () => {
const seen = fake({
loadCodeAssist: withCredits,
fetchAvailableModels: models,
streamGenerateContent: (s) => (s.json.enabled_credit_types ? new Response(JSON.stringify({ error: { code: 403, message: "credits refused", status: "PERMISSION_DENIED" } }), { status: 403 }) : spentQuota()),
})
const { f } = await creditsFetch(true)
for (let i = 0; i < 2; i++) {
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(429)
expect((await res.json()).error.message).toContain("exhausted your capacity")
}
expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(4)
})
test("a request the quota covers never asks for credits", async () => {
const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) })
const { f } = await creditsFetch(true)
await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(seen.filter((s) => s.name === "streamGenerateContent").map((s) => s.json.enabled_credit_types)).toEqual([undefined])
})
test("with the switch off, a refused request is not asked again, and the 429 says what would spend the credits", async () => {
const seen = fake({ loadCodeAssist: withCredits, fetchAvailableModels: models, streamGenerateContent: credited })
const { f } = await creditsFetch(false)
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(429)
expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(1)
const j = await res.json()
expect(j.error.message).toContain("exhausted your capacity")
expect(j.error.message).toContain("Use AI credits")
})
// plugins#1148: a 429 came back while the model's quota wasn't used up,
// and the credits note read as if it were
const withQuota = (fraction) => ({ models: { "gemini-3-flash": { displayName: "Gemini 3 Flash", quotaInfo: fraction === undefined ? { resetTime: "2026-11-15T12:00:00Z" } : { remainingFraction: fraction, resetTime: "2026-11-15T12:00:00Z" } } } })
test("a 429 while the model's quota is left says so, not to spend credits (plugins#1148)", async () => {
let reads = 0
fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.8) : withQuota(0.62)), streamGenerateContent: spentQuota })
const { f } = await creditsFetch(false)
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(429)
const msg = (await res.json()).error.message
expect(msg).toContain("exhausted your capacity")
expect(msg).toContain("62% of its quota left")
expect(msg).not.toContain("Use AI credits")
expect(reads).toBe(2)
})
test("a 429 once the model's quota is used up still points at the credits switch", async () => {
let reads = 0
fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.4) : withQuota(undefined)), streamGenerateContent: spentQuota })
const { f } = await creditsFetch(false)
const msg = (await (await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).json()).error.message
expect(msg).toContain("Use AI credits")
expect(msg).not.toContain("quota left")
})
test("when the quota can't be read again, the 429 keeps the credits note", async () => {
let reads = 0
fake({ loadCodeAssist: withCredits, fetchAvailableModels: () => (++reads === 1 ? withQuota(0.9) : new Response("boom", { status: 500 })), streamGenerateContent: spentQuota })
const { f } = await creditsFetch(false)
const msg = (await (await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).json()).error.message
expect(msg).toContain("Use AI credits")
})
test("an account with no credits is not asked again, with the switch on", async () => {
const seen = fake({ loadCodeAssist: { cloudaicompanionProject: "ag-proj", paidTier: { id: "g1-pro-tier", name: "Google AI Pro" } }, fetchAvailableModels: models, streamGenerateContent: credited })
const { f } = await creditsFetch(true)
const res = await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })
expect(res.status).toBe(429)
expect(seen.filter((s) => s.name === "streamGenerateContent").length).toBe(1)
expect((await res.json()).error.message).not.toContain("Use AI credits")
})
test("the plugin offers the switch, off unless set", async () => {
const p = await AntigravityAuthPlugin({})
expect(p.auth.options.map((o) => o.key)).toEqual(["use-ai-credits"])
expect(_internal.creditsOf({ paidTier: { availableCredits: [{ creditType: "GOOGLE_ONE_AI", creditAmount: "10", minimumCreditAmountForUsage: "50" }] } })).toBe(false)
expect(_internal.creditsOf({ paidTier: { availableCredits: [{ creditType: "GOOGLE_ONE_AI", minimumCreditAmountForUsage: "50" }] } })).toBe(true)
})
test("host session headers reach the envelope's sessionId without leaking upstream", async () => {
const seen = fake({ fetchAvailableModels: models, streamGenerateContent: () => sse({ candidates: [] }) })
const p = await AntigravityAuthPlugin({})
const outA = { headers: {} }
const outB = { headers: {} }
await p["chat.headers"]({ sessionID: "sess-alpha", model: { providerID: "antigravity" } }, outA)
await p["chat.headers"]({ sessionID: "sess-beta", model: { providerID: "antigravity" } }, outB)
const l = await p.auth.loader(async () => auth())
await l.fetch(URL_("gemini-3-flash"), { method: "POST", headers: outA.headers, body: ask("# AGENTS.md instructions\nshared") })
await l.fetch(URL_("gemini-3-flash"), { method: "POST", headers: outB.headers, body: ask("# AGENTS.md instructions\nshared") })
const calls = seen.filter((s) => s.name === "streamGenerateContent")
expect(calls.length).toBe(2)
expect(calls[0].json.request.sessionId).not.toBe(calls[1].json.request.sessionId)
expect(calls[0].headers["x-magpie-session"]).toBeUndefined()
})
// ---- Gemini 4's rejected calls ----------------------------------------------------------
const G4 = { models: { "gemini-4-carbon": { displayName: "Gemini 4 Carbon" }, "gemini-3-flash": { displayName: "Gemini 3 Flash" } } }
const bad400 = () => new Response(JSON.stringify({ error: { code: 400, message: "Request contains an invalid argument.", status: "INVALID_ARGUMENT" } }), { status: 400, headers: { "content-type": "application/json" } })
const think = { candidates: [{ content: { role: "model", parts: [{ text: "hmm", thought: true }] } }] }
const answer = { candidates: [{ content: { role: "model", parts: [{ functionCall: { name: "ls", args: {} } }] }, finishReason: "STOP" }] }
const raw = (...lines) => new Response(lines.join("\r\n\r\n") + "\r\n\r\n", { status: 200, headers: { "content-type": "text/event-stream" } })
const errChunk = "data: " + JSON.stringify({ error: { code: 400, message: "Request contains an invalid argument.", status: "INVALID_ARGUMENT" } })
const dataOf = (c) => "data: " + JSON.stringify({ response: c })
const calls = (seen) => seen.filter((s) => s.name === "streamGenerateContent").length
test("gemini-4's slow 400 INVALID_ARGUMENT is asked again, and the retry's reply comes back", async () => {
_internal.retry400.floorMs = 0
let n = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? bad400() : sse(answer)) })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
expect(res.status).toBe(200)
expect(await res.text()).toContain("functionCall")
expect(calls(seen)).toBe(2)
})
test("a gemini-4 400 that keeps coming is asked twice more, then returned", async () => {
_internal.retry400.floorMs = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
expect(res.status).toBe(400)
expect((await res.json()).error.status).toBe("INVALID_ARGUMENT")
expect(calls(seen)).toBe(3)
})
test("a fast 400 is the request's own and isn't asked again; nor is another model's", async () => {
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 })
const f = await loaderFetch(auth())
_internal.retry400.floorMs = 3000
expect((await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).status).toBe(400)
expect(calls(seen)).toBe(1)
_internal.retry400.floorMs = 0
expect((await f(URL_("gemini-3-flash"), { method: "POST", body: ask() })).status).toBe(400)
expect(calls(seen)).toBe(2)
})
test("thinking held past holdMs goes out while the model still thinks, and nothing read is lost (#1078)", async () => {
_internal.retry400.holdMs = 50
let ctl
const enc = new TextEncoder()
const body = new ReadableStream({ start: (c) => (ctl = c) })
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }) })
const f = await loaderFetch(auth())
ctl.enqueue(enc.encode(dataOf(think) + "\r\n\r\n"))
const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
expect(res.status).toBe(200)
const rd = res.body.getReader()
const dec = new TextDecoder()
let got = ""
while (!got.includes("hmm")) {
const r = await rd.read()
if (r.done) break
got += dec.decode(r.value, { stream: true })
}
// the answer doesn't exist yet: the thinking came out on its own
expect(got).toContain("hmm")
expect(got).not.toContain("functionCall")
ctl.enqueue(enc.encode(dataOf(answer) + "\r\n\r\n"))
ctl.close()
for (;;) {
const r = await rd.read()
if (r.done) break
got += dec.decode(r.value, { stream: true })
}
expect(got).toContain("functionCall")
expect(calls(seen)).toBe(1)
})
test("an INVALID_ARGUMENT in the stream after thinking only is asked again, and no thinking is sent twice", async () => {
_internal.retry400.floorMs = 3000
let n = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf(think), errChunk) : sse(think, answer)) })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
const text = await res.text()
expect(text).not.toContain("INVALID_ARGUMENT")
expect(text.split("hmm").length - 1).toBe(1)
expect(text).toContain("functionCall")
expect(calls(seen)).toBe(2)
})
test("once an answer has begun the stream is not asked again, and its error goes through", async () => {
let n = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf({ candidates: [{ content: { role: "model", parts: [{ text: "Hel" }] } }] }), errChunk) : sse(answer)) })
const f = await loaderFetch(auth())
const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text()
expect(text).toContain("Hel")
expect(text).toContain("INVALID_ARGUMENT")
expect(calls(seen)).toBe(1)
})
test("a generateContent reply is asked again the same way", async () => {
let n = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), errChunk) : sse(answer)) })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-4-carbon", "generateContent"), { method: "POST", body: ask() })
expect(res.status).toBe(200)
expect(JSON.stringify(await res.json())).toContain("functionCall")
expect(calls(seen)).toBe(2)
})
// Code Assist's real late error is a bare line, no "data:" before it, after
// the thinking events (zRain's capture of gemini-4-argon-high, the bytes in
// magpie's internal/gateway/sse_bare.go)
const bareErr = '{"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}'
test("Code Assist's bare INVALID_ARGUMENT line after thinking is asked again too (Lawson0112 on X)", async () => {
_internal.retry400.floorMs = 3000
let n = 0
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), dataOf(think), bareErr) : sse(think, answer)) })
const f = await loaderFetch(auth())
const res = await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
const text = await res.text()
expect(text).not.toContain("INVALID_ARGUMENT")
expect(text.split("hmm").length - 1).toBe(1)
expect(text).toContain("functionCall")
expect(calls(seen)).toBe(2)
})
test("a bare error written over several lines is read whole", async () => {
let n = 0
const pretty = JSON.stringify(JSON.parse(bareErr), null, 2)
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => (n++ < 1 ? raw(dataOf(think), pretty) : sse(answer)) })
const f = await loaderFetch(auth())
const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text()
expect(text).toContain("functionCall")
expect(calls(seen)).toBe(2)
})
test("gemini-4's bad call that keeps coming says what it is, not a region or account refusal", async () => {
const seen = fake({ fetchAvailableModels: G4, streamGenerateContent: () => raw(dataOf(think), bareErr) })
const f = await loaderFetch(auth())
const text = await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).text()
expect(calls(seen)).toBe(3)
const line = text.split("\n").find((l) => l.includes("INVALID_ARGUMENT"))
const e = JSON.parse(line.replace(/^data:\s*/, "")).error
expect(e.code).toBe(400)
expect(e.status).toBe("INVALID_ARGUMENT")
expect(e.message).toContain("gemini-4-carbon turned down a call it built while thinking, asked 3 times")
expect(e.message).toContain("Request contains an invalid argument.")
expect(e.message).toContain("Not a region or account refusal")
// magpie's gateway reads "model … invalid" as a model not served
expect(e.message).not.toMatch(/model.{0,80}invalid/i)
_internal.retry400.floorMs = 0
fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 })
const g = await loaderFetch(auth())
const res = await g(URL_("gemini-4-carbon"), { method: "POST", body: ask() })
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("asked 3 times")
})
test("a fast 400 and another model's errors keep Google's words", async () => {
fake({ fetchAvailableModels: G4, streamGenerateContent: bad400 })
const f = await loaderFetch(auth())
_internal.retry400.floorMs = 3000
expect((await (await f(URL_("gemini-4-carbon"), { method: "POST", body: ask() })).json()).error.message).toBe("Request contains an invalid argument.")
fake({ fetchAvailableModels: G4, streamGenerateContent: () => raw(dataOf(think), bareErr) })
const g = await loaderFetch(auth())
const text = await (await g(URL_("gemini-3-flash"), { method: "POST", body: ask() })).text()
expect(text).toContain(bareErr)
})
-54
View File
@@ -1,54 +0,0 @@
// 0.2.0 sends nothing: every way in answers with where Antigravity went.
import { afterEach, expect, test } from "bun:test"
import { AntigravityAuthPlugin, RETIRED } from "./index.mjs"
const realFetch = globalThis.fetch
afterEach(() => {
globalThis.fetch = realFetch
})
function noNetwork() {
const asked = []
globalThis.fetch = async (u) => {
asked.push(String(u))
throw new Error("no request may leave the plugin")
}
return asked
}
test("a request is answered 410, retired, naming agy-cli, with nothing sent", async () => {
const asked = noNetwork()
const p = await AntigravityAuthPlugin({})
const signedIn = async () => ({ type: "oauth", refresh: "rt|proj", access: "at", expires: Date.now() + 3600e3, accountId: "a@example.com" })
const l = await p.auth.loader(signedIn)
const res = await l.fetch("https://daily-cloudcode-pa.googleapis.com/v1beta/models/gemini-3-flash:streamGenerateContent?alt=sse", { method: "POST", body: "{}" })
expect(res.status).toBe(410)
const j = await res.json()
expect(j.error.status).toBe("ModelDeprecated")
// magpie's modelRetired reads "model … has been retired"
expect(j.error.message).toMatch(/model.{0,80}has been retired/i)
expect(j.error.message).toContain("@magpie-community/opencode-agy-cli-auth")
expect(j.error.message).toContain("Antigravity (local agy CLI)")
expect(asked).toEqual([])
})
test("signing in is turned away with the same words", async () => {
const asked = noNetwork()
const p = await AntigravityAuthPlugin({})
expect(p.auth.methods).toHaveLength(1)
await expect(p.auth.methods[0].authorize({})).rejects.toThrow(RETIRED)
expect(asked).toEqual([])
})
test("no models, usage or search, and the provider stays listed as retired", async () => {
const asked = noNetwork()
const p = await AntigravityAuthPlugin({})
const cfg = { provider: { antigravity: { models: { "gemini-3-flash": {} } } } }
await p.config(cfg)
expect(cfg.provider.antigravity.models).toEqual({})
expect(cfg.provider.antigravity.name).toBe("Antigravity (retired)")
expect(await p.provider.models({ models: { x: {} } }, { auth: { type: "oauth", refresh: "rt|p" } })).toEqual({})
expect(p.auth.usage).toBeUndefined()
expect(p.search).toBeUndefined()
expect(asked).toEqual([])
})
+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 })
})
+173
View File
@@ -0,0 +1,173 @@
import { afterEach, beforeEach, expect, test } from "bun:test"
import { AntigravityAuthPlugin, _internal } from "./index.mjs"
import { auth, fake, real, reset } from "./fake.mjs"
beforeEach(() => reset())
afterEach(() => (globalThis.fetch = real))
const sse = (...chunks) =>
new Response(chunks.map((c) => "data: " + JSON.stringify({ response: c, traceId: "t" }) + "\r\n\r\n").join(""), {
status: 200,
headers: { "content-type": "text/event-stream" },
})
const models = {
models: {
"gemini-3-flash": { displayName: "Gemini 3 Flash" },
"gemini-2.5-flash": { displayName: "Gemini 2.5 Flash" },
"claude-opus-4-6-thinking": { displayName: "Claude Opus 4.6 (Thinking)" },
},
}
const REDIR_A = "https://vertexaisearch.cloud.google.com/grounding-api-redirect/AAA"
const REDIR_B = "https://vertexaisearch.cloud.google.com/grounding-api-redirect/BBB"
test("plugin registers the antigravity search hook signed in as antigravity", async () => {
const p = await AntigravityAuthPlugin({})
expect(p.search?.antigravity).toBeDefined()
expect(p.search.antigravity.auth).toBe("antigravity")
expect(typeof p.search.antigravity.execute).toBe("function")
})
test("search rejects an empty query and a missing sign-in", async () => {
const p = await AntigravityAuthPlugin({})
await expect(p.search.antigravity.execute({ query: " " }, { getAuth: async () => auth() })).rejects.toThrow("query is required")
await expect(p.search.antigravity.execute({ query: "bun" }, { getAuth: async () => null })).rejects.toThrow("not signed in")
})
test("search calls Antigravity with googleSearch, returns URIs unchanged, deduplicates, and trims to count", async () => {
const seen = fake({
fetchAvailableModels: models,
streamGenerateContent: () =>
sse(
{ candidates: [{ content: { role: "model", parts: [{ thought: true, text: "thinking" }, { text: "Bun 1.4.4 " }] } }] },
{
candidates: [
{
content: { role: "model", parts: [{ text: "is latest." }] },
finishReason: "STOP",
groundingMetadata: {
webSearchQueries: ["latest bun version"],
groundingChunks: [
{ web: { uri: REDIR_A, title: "github.com" } },
{ web: { uri: REDIR_A, title: "github.com duplicate" } },
{ web: { uri: REDIR_B, title: "bun.sh" } },
],
groundingSupports: [
{ segment: { text: "Bun 1.4.4 was released." }, groundingChunkIndices: [0] },
{ segment: { text: "See release notes on GitHub." }, groundingChunkIndices: [1] },
{ segment: { text: "Install via bun.sh." }, groundingChunkIndices: [2] },
],
},
},
],
},
),
})
const p = await AntigravityAuthPlugin({})
const pages = await p.search.antigravity.execute({ query: "latest bun version", count: 5 }, { getAuth: async () => auth() })
expect(seen.map((s) => s.name)).toEqual(["loadCodeAssist", "fetchAvailableModels", "streamGenerateContent"])
const req = seen.find((s) => s.name === "streamGenerateContent")
expect(req.json.model).toBe("gemini-3-flash")
expect(req.json.request.tools).toEqual([{ googleSearch: {} }])
expect(req.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: false, thinkingLevel: "minimal" })
expect(pages).toEqual([
{
title: "github.com",
url: REDIR_A,
text: "Bun 1.4.4 was released.\nSee release notes on GitHub.",
},
{
title: "bun.sh",
url: REDIR_B,
text: "Install via bun.sh.",
},
])
const one = await p.search.antigravity.execute({ query: "latest bun version", count: 1 }, { getAuth: async () => auth() })
expect(one).toHaveLength(1)
expect(one[0].url).toBe(REDIR_A)
})
test("search carries numeric status and retryAfter when Antigravity refuses", async () => {
fake({
fetchAvailableModels: models,
streamGenerateContent: () =>
new Response(JSON.stringify({ error: { code: 429, message: "rate limited" } }), {
status: 429,
headers: { "retry-after": "12" },
}),
})
const p = await AntigravityAuthPlugin({})
let caught
try {
await p.search.antigravity.execute({ query: "news" }, { getAuth: async () => auth() })
} catch (e) {
caught = e
}
expect(caught).toBeDefined()
expect(caught.status).toBe(429)
expect(caught.retryAfter).toBe("12")
expect(caught.message).toContain("rate limited")
})
test("whole preserves groundingMetadata from an earlier SSE chunk", async () => {
const res = sse(
{
candidates: [
{
content: { role: "model", parts: [{ text: "Answer" }] },
groundingMetadata: { groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }] },
},
],
},
{
candidates: [
{
content: { role: "model", parts: [{ text: "" }] },
finishReason: "STOP",
groundingMetadata: { webSearchQueries: ["example"], groundingChunks: [] },
},
],
usageMetadata: { totalTokenCount: 10 },
},
)
const full = await _internal.whole(res)
expect(full.candidates[0].groundingMetadata).toEqual({
webSearchQueries: ["example"],
groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }],
})
})
test("search skips an exhausted Flash model and turns thinking off on Gemini 2.5", async () => {
const seen = fake({
fetchAvailableModels: {
models: {
"gemini-3-flash": { displayName: "Gemini 3 Flash", quotaInfo: {} },
"gemini-2.5-flash": { displayName: "Gemini 2.5 Flash", quotaInfo: { remainingFraction: 0.8 } },
},
},
streamGenerateContent: () =>
sse({
candidates: [
{
content: { role: "model", parts: [{ text: "Answer." }] },
finishReason: "STOP",
groundingMetadata: {
groundingChunks: [{ web: { uri: "https://example.com", title: "Example" } }],
},
},
],
}),
})
const p = await AntigravityAuthPlugin({})
const pages = await p.search.antigravity.execute({ query: "example" }, { getAuth: async () => auth() })
const req = seen.find((s) => s.name === "streamGenerateContent")
expect(req.json.model).toBe("gemini-2.5-flash")
expect(req.json.request.generationConfig.thinkingConfig).toEqual({ includeThoughts: false, thinkingBudget: 0 })
expect(pages).toEqual([{ title: "Example", url: "https://example.com", text: "Answer." }])
})
+339
View File
@@ -0,0 +1,339 @@
// The Gemini request magpie (or the AI SDK) hands the plugin, shaped as
// the built-in shaped it for Antigravity (codeassist.go's Antigravity
// rules; codeassist_test.go's TestBuildCodeAssistForAntigravity,
// TestCodeAssistAntigravityLevels and TestCodeAssistToolImagesAfterEveryResponse).
import { expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const { shape, cloak, sessionOf, envelope } = _internal
// what magpie's generic Code Assist build makes of codeassist_test.go's
// codeAssistRequest
const generic = () => ({
systemInstruction: { role: "user", parts: [{ text: "be brief" }] },
contents: [
{ role: "user", parts: [{ text: "read a" }] },
{ role: "model", parts: [{ text: "hm", thought: true }, { text: "ok" }, { functionCall: { id: "toolu_01:x", name: "read", args: { path: "a" } }, thoughtSignature: "skip_thought_signature_validator" }] },
{ role: "user", parts: [{ functionResponse: { id: "toolu_01:x", name: "read", response: { output: "A!" } } }] },
{ role: "user", parts: [{ text: "and?" }] },
],
tools: [{ functionDeclarations: [{ name: "read", description: "read a file", parametersJsonSchema: { type: "object", properties: { path: { type: ["string", "null"] } }, required: ["path"], additionalProperties: false } }] }],
toolConfig: { functionCallingConfig: { mode: "AUTO" } },
generationConfig: { maxOutputTokens: 2000, thinkingConfig: { includeThoughts: true, thinkingBudget: 4000 } },
})
test("Claude on Antigravity", () => {
const r = shape(generic(), "claude-sonnet-4-6", "", "")
const s = JSON.stringify(r)
expect(s).toContain(`"id":"toolu_01_x"`)
expect(s).toContain(`"response":{"result":"A!"}`)
expect(r.toolConfig.functionCallingConfig.mode).toBe("VALIDATED")
expect(r.generationConfig.maxOutputTokens).toBe(2000)
// Sonnet here doesn't think
expect(r.generationConfig.thinkingConfig).toBeUndefined()
expect(r.tools[0].functionDeclarations[0]).toEqual({ name: "read", description: "read a file", parameters: { type: "object", properties: { path: { type: "string", nullable: true } }, required: ["path"] } })
// what the user said joins the tool's turn
expect(r.contents.length).toBe(3)
expect(r.contents[2].parts.map((p) => (p.functionResponse ? "response" : p.text))).toEqual(["response", "and?"])
// a thinking Claude keeps its budget
const t = shape(generic(), "claude-opus-4-6-thinking", "", "")
expect(t.generationConfig.thinkingConfig.thinkingBudget).toBe(4000)
})
test("Gemini on Antigravity", () => {
const r = shape(generic(), "gemini-3-flash", "", "")
expect(r.generationConfig.maxOutputTokens).toBeUndefined()
expect(r.generationConfig.thinkingConfig).toEqual({ includeThoughts: true })
expect(r.toolConfig.functionCallingConfig.mode).toBe("AUTO")
// the user's turn stays its own for Gemini
expect(r.contents.length).toBe(4)
expect(shape(generic(), "gpt-oss-120b-medium", "", "").generationConfig?.thinkingConfig).toBeUndefined()
// an empty declaration's parameters
const g = generic()
delete g.tools[0].functionDeclarations[0].parametersJsonSchema
expect(shape(g, "gemini-3-flash", "", "").tools[0].functionDeclarations[0].parameters).toEqual({ type: "object", properties: {} })
})
test.each([
// [model sent, the variant's level, the effort asked, the level sent]
["gemini-3.7-flash-low", "low", "low", "low"],
["gemini-3.7-flash-medium", "medium", "medium", "medium"],
["gemini-3.7-flash-high", "high", "xhigh", "high"],
// a variant at xhigh thinks at xhigh, asked or by default (#1169)
["gemini-4-hydrogen-xhigh", "xhigh", "xhigh", "xhigh"],
["gemini-4-hydrogen-xhigh", "xhigh", "", "xhigh"],
["gemini-4-hydrogen-high", "high", "xhigh", "high"],
["gemini-3.1-pro-high", "high", "medium", "high"],
["gemini-3-flash", "", "medium", "medium"],
["gemini-pro-agent", "", "medium", "high"],
["gemini-pro-agent", "", "low", "low"],
// reasoning off goes at low, the least every one takes (#250)
["gemini-3.1-flash-lite", "", "minimal", "low"],
["gemini-3.1-flash-lite", "", "none", "low"],
// a variant at minimal is asked at minimal; a Pro, at low
["gemini-3.5-flash-extra-low", "minimal", "", "minimal"],
["gemini-3.1-pro-low", "minimal", "", "low"],
// a model that draws, asked off, goes at high
["gemini-3.1-flash-image", "", "minimal", "high"],
])("%s (%p) asked %p thinks at %p", (sent, at, effort, level) => {
const r = shape(generic(), sent, at, effort)
expect(r.generationConfig.thinkingConfig).toEqual({ includeThoughts: true, thinkingLevel: level })
})
test("a level a variant put on a model told a budget goes", () => {
const g = generic()
g.generationConfig.thinkingConfig = { includeThoughts: true, thinkingLevel: "high" }
expect(shape(g, "gemini-2.5-flash", "", "").generationConfig?.thinkingConfig).toBeUndefined()
})
test("a tool's images follow every response, for Claude", () => {
const img = (d) => ({ inlineData: { mimeType: "image/png", data: d } })
const g = {
contents: [
{ role: "user", parts: [{ text: "look" }] },
{ role: "model", parts: [{ functionCall: { id: "a", name: "shot", args: {} } }, { functionCall: { id: "b", name: "shot", args: {} } }] },
{ role: "user", parts: [{ functionResponse: { id: "a", name: "shot", response: { output: "one" } } }, img("1"), { functionResponse: { id: "b", name: "shot", response: { output: "two" } } }, img("2"), img("3")] },
{ role: "user", parts: [{ text: "what now?" }] },
],
}
const r = shape(g, "claude-sonnet-4-6", "", "")
const lines = r.contents[2].parts.map((p) => (p.functionResponse ? "response " + p.functionResponse.id : p.inlineData ? "image " + p.inlineData.data : p.text))
expect(lines).toEqual(["response a", "response b", "Image returned by tool shot (call a):", "image 1", "2 images returned by tool shot (call b):", "image 2", "image 3", "what now?"])
expect(r.contents.length).toBe(3)
// Gemini takes them where they are
expect(shape(g, "gemini-3-flash", "", "").contents[2].parts.length).toBe(5)
})
test("omp's RFC 2119 line goes as RFC 2119's own \"key words\", as the real account turned it away", () => {
const line = "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL."
const sys = line + " `NEVER` = `MUST NOT`; `AVOID` = `SHOULD NOT`.\n\n§ Role"
const out = cloak(sys)
// a zero-width break of this line was turned away 1 to 3 times in 10 on
// 11-14; "key words" went through 10 of 10
expect(out).toBe(sys.replace("keywords", "key words"))
expect(out).not.toContain("\u200b")
expect(cloak("RFC 2119 keywords: MUST")).toBe("RFC 2119 keywords: MUST")
})
// omp 18.20.0's first line, byte for byte (src/prompts/system/system-prompt.md),
// and the copies of it a real account turned away on 11-14 although no
// space in them is a single space: wrapped after "REQUIRED," with LF or
// CRLF, wrapped after "RFC 2119", indented, a tab, two spaces, a no-break
// space. The same account answered the line without its period, with no
// space after a comma, or in another order, so those go as written.
const OMP_LINE = "RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL. `NEVER` = `MUST NOT`; `AVOID` = `SHOULD NOT`."
const OMP_COPIES = [
"RFC 2119 keywords: MUST, REQUIRED,\nSHOULD, RECOMMENDED, MAY, OPTIONAL.",
"RFC 2119 keywords: MUST, REQUIRED,\r\nSHOULD, RECOMMENDED, MAY, OPTIONAL.\r\n",
"RFC 2119\nkeywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.",
"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY,\n OPTIONAL.",
"RFC 2119 keywords:\tMUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.",
"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.",
"RFC\u00a02119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.",
]
const OMP_PASSED = [
"RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL",
"RFC 2119 keywords: MUST,REQUIRED,SHOULD,RECOMMENDED,MAY,OPTIONAL.",
"RFC 2119 keywords: MUST, SHOULD, MAY, REQUIRED, RECOMMENDED, OPTIONAL.",
"RFC 2119 applies to MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.",
]
test("omp's line is reworded wherever white space wraps or widens it", () => {
const { turnsAway, hint } = _internal
for (const line of [OMP_LINE, ...OMP_COPIES]) {
const sys = "<conventions>\n" + line + "\n</conventions>\n\n§ Role"
const out = cloak(sys)
expect(out).toBe(sys.replace("keywords", "key words"))
expect(turnsAway(out)).toBe(false)
expect(hint(sys)).toContain("oh-my-pi (omp)")
// every white space stays as it was
expect(shape({ systemInstruction: { parts: [{ text: sys }] }, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts[0].text).toBe(out)
}
for (const line of OMP_PASSED) expect(cloak(line)).toBe(line)
// the other lines take white space the same way (Hermes' and Codex's
// were turned away wrapped and with a tab on the same account)
expect(cloak("You are Hermes\nAgent, an intelligent\nAI assistant created by Nous Research.")).toBe("You're Hermes\nAgent, an intelligent\nAI assistant built by Nous Research.")
expect(cloak("running\tinside pi")).toBe("running\tinside pi")
expect(cloak("a coding assistant running\ninside pi")).toBe("a coding assistant running\nwithin pi")
expect(cloak("You are Codex, an agent\tbased on GPT-5.")).toBe("You are Codex, an agent\tbuilt on GPT-5.")
})
// Claude Desktop's Code tab, as Claude Code 2.1.316 sends it with
// CLAUDE_CODE_ENTRYPOINT=claude-desktop: the billing line and the identity
// line are blocks of their own. Its subagents begin "You are a Claude agent,
// built on Anthropic's Claude Agent SDK." Since 11-14 Google reads past a
// zero-width space: the prompt with either line broken up was turned away
// 10 of 10 on a real account (hc295971796 on X), and the reworded one
// answered 10 of 10.
const BILLING = "x-anthropic-billing-header: cc_version=2.1.316.2e4; cc_entrypoint=claude-desktop;"
const DESKTOP = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK."
const SUBAGENT = "You are a Claude agent, built on Anthropic's Claude Agent SDK."
test("Claude Code's billing line is left out, and the Agent SDK's line is reworded", () => {
const { turnsAway, hint } = _internal
const sys = BILLING + "\n" + SUBAGENT + "\nhi"
const out = cloak(sys)
expect(out).toBe("You are a Claude agent, built on the Claude Agent SDK by Anthropic.\nhi")
expect(turnsAway(out)).toBe(false)
expect(hint(sys)).toContain("Claude Agent SDK")
// twice is the same as once, and other text is left alone
expect(cloak(out)).toBe(out)
expect(cloak("be brief")).toBe("be brief")
expect(cloak(DESKTOP)).toBe(DESKTOP)
// the case and white space the agent wrote stay
expect(cloak("built on\nANTHROPIC'S claude agent sdk")).toBe("built on\nthe claude agent sdk by Anthropic")
// as the gateway hands it: each block a part; the billing line's part goes
const r = shape({ systemInstruction: { parts: [{ text: BILLING }, { text: DESKTOP }, { text: SUBAGENT }] }, contents: [] }, "gemini-3-flash", "", "")
expect(r.systemInstruction.parts.map((p) => p.text)).toEqual([DESKTOP, "You are a Claude agent, built on the Claude Agent SDK by Anthropic."])
// a billing line alone in a string stays one (empty) part
expect(shape({ systemInstruction: BILLING, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts).toEqual([{ text: "" }])
})
test("a line someone broke up with invisible characters is reworded as the line", () => {
const zw = (s, z = "\u200b") => s.replace(/[A-Za-z0-9]{3,}/g, (w) => w[0] + z + w[1] + z + w.slice(2))
const every = (s) => [...s].join("\u2060")
const lines = [
[SUBAGENT, "You are a Claude agent, built on the Claude Agent SDK by Anthropic."],
["You are Codex, an agent based on GPT-5.", "You are Codex, an agent built on GPT-5."],
["You are Codex, a coding agent based on GPT-5.", "You are Codex, a coding agent built on GPT-5."],
// as "You're" alone it was turned away 3 of 3 on 11-14
["You are Hermes Agent, an intelligent AI assistant created by Nous Research.", "You're Hermes Agent, an intelligent AI assistant built by Nous Research."],
// 0.1.15's own rewording of it is turned away too since 11-14
["You are Hermes Agent, an intelligent AI assistant built by Nous Research.", "You're Hermes Agent, an intelligent AI assistant built by Nous Research."],
["You are Hermes Agent, built by Nous Research.", "You're Hermes Agent, built by Nous Research."],
["You are OpenCode, a coding agent that helps users with software engineering tasks.", "You're OpenCode, a coding agent that helps users with software engineering tasks."],
["You are opencode, an interactive CLI tool that helps users with software engineering tasks.", "You're opencode, an interactive CLI tool that helps users with software engineering tasks."],
["You are OpenCode, the best coding agent on the planet.", "You're OpenCode, the best coding agent on the planet."],
["You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.", "You're a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful."],
["You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.", "You are a coding assistant running within pi, a coding agent harness. Help users inspect files, run commands, and modify code."],
["RFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL.", "RFC 2119 key words: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL."],
]
// the break-ups also reach words outside the turned-away part, which go as
// written: compare with the invisible characters taken out
const seen = (s) => s.replace(/[\u00ad\u200b\u2060]/g, "")
for (const [line, to] of lines) {
expect(cloak(line)).toBe(to)
for (const broken of [zw(line), every(line), zw(line, "\u00ad")]) {
const out = cloak(broken)
expect(out).not.toBe(broken)
expect(seen(out)).toBe(to)
expect(_internal.turnsAway(out)).toBe(false)
}
}
expect(cloak(zw(BILLING) + "\nhi")).toBe("hi")
})
test("a conversation keeps its session", () => {
const a = { contents: [{ role: "user", parts: [{ text: "hello there" }] }] }
const b = { contents: [{ role: "user", parts: [{ text: "hello there" }] }, { role: "model", parts: [{ text: "hi" }] }] }
expect(sessionOf(a)).toBe(sessionOf(b))
expect(sessionOf(a)).toMatch(/^-\d+$/)
expect(sessionOf({ contents: [{ role: "user", parts: [{ text: "other" }] }] })).not.toBe(sessionOf(a))
const env = envelope(a, "gemini-3-flash", "ag-proj")
expect(env).toMatchObject({ model: "gemini-3-flash", project: "ag-proj", userAgent: "antigravity", requestType: "agent" })
expect(env.request.sessionId).toBe(sessionOf(a))
})
test("the envelope is the app's: key order, request id and labels", () => {
const { enums } = _internal
enums.set("gemini-3-flash", { model: "MODEL_PLACEHOLDER_M18", provider: "MODEL_PROVIDER_GOOGLE" })
enums.set("claude-sonnet-4-6", { model: "MODEL_PLACEHOLDER_M35", provider: "MODEL_PROVIDER_ANTHROPIC" })
const a = { generationConfig: { maxOutputTokens: 9 }, contents: [{ role: "user", parts: [{ text: "hello there" }] }], systemInstruction: { role: "user", parts: [{ text: "s" }] } }
const env = envelope(a, "gemini-3-flash", "ag-proj")
expect(Object.keys(env)).toEqual(["project", "requestId", "request", "model", "userAgent", "requestType"])
expect(Object.keys(env.request)).toEqual(["contents", "systemInstruction", "labels", "generationConfig", "sessionId"])
const u = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
expect(env.requestId).toMatch(new RegExp(`^agent/${u}/\\d{13}/${u}/1$`))
const l = env.request.labels
expect(Object.keys(l)).toEqual(["cascade_id", "last_step_index", "model_enum", "request_id", "root_cascade_id", "trajectory_id", "used_claude", "used_claude_conservative", "used_non_gemini_model"])
expect(l).toMatchObject({ last_step_index: "0", model_enum: "MODEL_PLACEHOLDER_M18", request_id: l.trajectory_id + "-0", root_cascade_id: l.cascade_id, used_claude: "false", used_non_gemini_model: "false" })
expect(env.requestId).toBe(`agent/${l.cascade_id}/${env.requestId.split("/")[2]}/${l.trajectory_id}/1`)
// the same conversation, further on: same ids, later step
const b = { contents: [...a.contents, { role: "model", parts: [{ text: "hi" }] }, { role: "user", parts: [{ text: "more" }] }] }
const later = envelope(b, "claude-sonnet-4-6", "ag-proj").request.labels
expect(later).toMatchObject({ cascade_id: l.cascade_id, trajectory_id: l.trajectory_id, last_step_index: "2", request_id: l.trajectory_id + "-1", model_enum: "MODEL_PLACEHOLDER_M35", used_claude: "true", used_non_gemini_model: "true" })
// a model not listed yet has no enum, and its maker is read from its id
const unknown = envelope(a, "gpt-oss-120b-medium", "ag-proj").request.labels
expect(unknown.model_enum).toBeUndefined()
expect(unknown.used_non_gemini_model).toBe("true")
})
test("the user agent is the language server's, with the release's changelist", async () => {
const { clOf, CLS } = _internal
expect(clOf("2.32.1")).toBe(CLS["2.32.1"])
// a release newer than every known one goes with the newest known changelist
const newest = Object.keys(CLS).sort((x, y) => (x < y ? 1 : -1))[0]
expect(clOf("9.0.0")).toBe(CLS[newest])
})
test("sessions with shared AGENTS.md preambles or distinct host headers don't collide", () => {
const preamble = [
{ text: "# AGENTS.md instructions\n\n<INSTRUCTIONS>global</INSTRUCTIONS>" },
{ text: "<environment_context>\n <cwd>/tmp</cwd>\n</environment_context>" },
]
const chatA = { contents: [{ role: "user", parts: preamble }, { role: "user", parts: [{ text: "fix login bug" }] }] }
const chatA2 = { contents: [...chatA.contents, { role: "model", parts: [{ text: "looking" }] }] }
const chatB = { contents: [{ role: "user", parts: preamble }, { role: "user", parts: [{ text: "add export csv" }] }] }
expect(sessionOf(chatA)).toBe(sessionOf(chatA2))
expect(sessionOf(chatA)).not.toBe(sessionOf(chatB))
const s1 = sessionOf(chatA, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4" })
const s2 = sessionOf(chatA, { "x-magpie-session": "01a1c9cc-0757-70e3-990f-5a818d52b0cd" })
expect(s1).not.toBe(s2)
expect(sessionOf(chatA, { "x-magpie-session": "magpie-0123456789abcdef01234567" })).toBe(sessionOf(chatA))
const subA = sessionOf(chatA, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4", "x-magpie-subagent": "collab_spawn" })
const subB = sessionOf(chatB, { "x-magpie-session": "01a1cb56-5f3e-74d1-b7a9-b40be82a2ba4", "x-magpie-subagent": "collab_spawn" })
expect(subA).not.toBe(s1)
expect(subA).not.toBe(subB)
})
test("an empty text a stream ended on isn't sent back (Claude: text Field required)", () => {
const g = { contents: [
{ role: "user", parts: [{ text: "read it" }] },
{ role: "model", parts: [{ text: "Sure." }, { functionCall: { id: "toolu_vrtx_1", name: "read", args: {} } }, { text: "" }] },
{ role: "user", parts: [{ functionResponse: { id: "toolu_vrtx_1", name: "read", response: { output: "A" } } }] },
] }
expect(shape(g, "claude-sonnet-4-6", "", "").contents[1].parts.map((p) => Object.keys(p)[0])).toEqual(["text", "functionCall"])
// a signature on an empty text is kept
const s = { contents: [{ role: "model", parts: [{ text: "a" }, { text: "", thoughtSignature: "sig" }] }] }
expect(shape(s, "gemini-3-flash", "", "").contents[0].parts[1]).toEqual({ text: "", thoughtSignature: "sig" })
})
test("DeepSeek Harness's @-path paragraph goes reworded, the rest as written (#1028)", () => {
// word for word as DSH desktop 0.2.2-rc.2 puts it in every system prompt
const dsh = "Tokens prefixed with @ are paths the user explicitly referenced. Relative paths resolve from the workspace root; absolute paths identify files or directories on the host. A trailing slash marks a directory: list it when its contents matter. Anything else is a file: use the read tool when its contents are needed, and do not claim to have inspected it before reading. @\"...\" quotes a path containing spaces."
const sys = "You are DeepSeek Harness.\n\n" + dsh + "\n\nBe brief."
for (const req of [{ systemInstruction: { parts: [{ text: sys }] }, contents: [] }, { systemInstruction: sys, contents: [] }]) {
const text = shape(req, "gemini-4-argon", "", "").systemInstruction.parts[0].text
expect(text).not.toContain("Tokens prefixed with @")
expect(text).toBe("You are DeepSeek Harness.\n\nWhen the user writes @ followed by a path, they are pointing at that file or folder. Relative paths start at the workspace root; absolute paths are host paths. A path ending in a slash is a folder, so list it if its contents matter; otherwise it is a file, so open it with the read tool before relying on it. Paths with spaces appear as @\"...\".\n\nBe brief.")
}
// a prompt that only mentions @ paths is left as it is
const other = "Tokens prefixed with @ are paths. Be brief."
expect(shape({ systemInstruction: { parts: [{ text: other }] }, contents: [] }, "gemini-4-argon", "", "").systemInstruction.parts[0].text).toBe(other)
// the billing line is left out and the paragraph reworded, together
const both = shape({ systemInstruction: { parts: [{ text: "x-anthropic-billing-header: cc\n" + dsh }] }, contents: [] }, "gemini-3-flash", "", "").systemInstruction.parts[0].text
expect(both).not.toContain("x-anthropic-billing-header")
expect(both).not.toMatch(/[\u200b-\u200f\u2060]/)
expect(both).toContain("When the user writes @ followed by a path")
})
// since 11-14 Codex's GPT-5 line in a user's turn is turned away too (3 of
// 3 on a real account): it goes reworded there, and the model's turns and
// tool results, which went through with it, as written
test("the line in a user's turn goes reworded", () => {
const line = "You are Codex, a coding agent based on GPT-5. You and the user share the same workspace."
const g = generic()
g.contents[0].parts[0].text = "Here is my AGENTS.md:\n\n" + line
g.contents[1].parts[1].text = line
g.contents[2].parts[0].functionResponse.response.output = line
const others = "x-anthropic-billing-header: cc_version=2.1.316.2e4;\nYou are a Claude agent, built on Anthropic's Claude Agent SDK.\nRFC 2119 keywords: MUST, REQUIRED, SHOULD, RECOMMENDED, MAY, OPTIONAL."
g.contents[3].parts[0].text = others
const r = shape(g, "gemini-3-flash", "", "")
expect(r.contents[3].parts[0].text).toBe(others)
expect(r.contents[0].parts[0].text).toBe("Here is my AGENTS.md:\n\nYou are Codex, a coding agent built on GPT-5. You and the user share the same workspace.")
expect(r.contents[1].parts[1].text).toBe(line)
expect(JSON.stringify(r.contents[2])).toContain("based on GPT-5")
expect(g.contents[0].parts[0].text).toContain("based on GPT-5")
})
+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")
})
+61
View File
@@ -0,0 +1,61 @@
// The version the requests name is read from the update manifest (#1057).
import { afterEach, beforeEach, expect, test } from "bun:test"
import { _internal } from "./index.mjs"
import { real } from "./fake.mjs"
const { ver, version, lists, VERSION_TTL, VERSION_RETRY, DEFAULT_VERSION } = _internal
beforeEach(() => {
ver.v = ""
ver.at = 0
ver.pending = null
lists.clear()
})
afterEach(() => (globalThis.fetch = real))
const manifest = (v) => async () => new Response(`version: ${v}\nfiles: []\n`, { status: 200 })
const down = async () => { throw new TypeError("fetch failed") }
test("a manifest that can't be read is asked again after a minute, not six hours", async () => {
let asked = 0
globalThis.fetch = async (...a) => { asked++; return down(...a) }
expect(await version()).toBe(DEFAULT_VERSION)
expect(asked).toBe(1)
expect(await version()).toBe(DEFAULT_VERSION)
expect(asked).toBe(1)
ver.at -= VERSION_RETRY + 1
globalThis.fetch = async (...a) => { asked++; return manifest("2.40.0")(...a) }
expect(await version()).toBe("2.40.0")
expect(asked).toBe(2)
ver.at -= VERSION_RETRY + 1
expect(await version()).toBe("2.40.0")
expect(asked).toBe(2)
})
test("a read manifest holds for six hours", async () => {
let asked = 0
globalThis.fetch = async (...a) => { asked++; return manifest("2.40.0")(...a) }
await version()
ver.at -= VERSION_TTL - 1000
await version()
expect(asked).toBe(1)
})
test("a new version drops the model lists read under the old one", async () => {
globalThis.fetch = down
await version()
lists.set("rt", { at: Date.now(), infos: [], project: "p" })
ver.at -= VERSION_RETRY + 1
globalThis.fetch = manifest(DEFAULT_VERSION)
await version()
expect(lists.size).toBe(1)
ver.at -= VERSION_TTL + 1
globalThis.fetch = manifest("2.40.0")
await version()
expect(lists.size).toBe(0)
})
test("the default is a release Google serves Gemini 4 to", () => {
const [a, b] = DEFAULT_VERSION.split(".").map(Number)
expect(a > 2 || (a === 2 && b >= 20)).toBe(true)
})