From e488064e06559f011c9625fd78ff5de57312f4fc Mon Sep 17 00:00:00 2001 From: K1NG_HAER1N <54131747+Invis1ble-2@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:06:15 +0800 Subject: [PATCH] antigravity 0.1.10: Google Search grounding as a magpie web search (#1103) Adds a magpie `search` hook (`search.antigravity`, auth: antigravity) that runs a query through Google Search grounding (`tools: [{googleSearch: {}}]`) on a Flash model from the signed-in account's live catalog, with thinking off, and returns the grounded pages (title, URL, snippets), deduplicated and trimmed to `count`. A refusal carries numeric `status` and `retryAfter` so magpie rests the account for search only. Grounding redirect URLs are returned as Google sends them; no extra request is made per result. By Invis1ble-2. Run at the reviewed head f0465e41b on mote, HOME=$(mktemp -d): - bun test ./packages/antigravity/: 90 pass, 0 fail (294 expect calls) - bun scripts/check.mjs antigravity: ok Broken by hand: turning off the per-URL dedup in pagesFromGrounding turns search.test.mjs red (5 pass, 1 fail); restored. The author ran it through a real magpie with a real Antigravity account (`magpie tool web_search`, 10 pages for "latest Bun runtime release version") and checked the SEARCH_MODELS names against a real fetchAvailableModels. Not tried by the reviewer: a real Antigravity account. --- packages/antigravity/README.md | 9 +- packages/antigravity/index.mjs | 157 +++++++++++++++++++++++- packages/antigravity/package.json | 2 +- packages/antigravity/search.test.mjs | 173 +++++++++++++++++++++++++++ 4 files changed, 337 insertions(+), 4 deletions(-) create mode 100644 packages/antigravity/search.test.mjs diff --git a/packages/antigravity/README.md b/packages/antigravity/README.md index 0b331ee..3ec06cc 100644 --- a/packages/antigravity/README.md +++ b/packages/antigravity/README.md @@ -138,12 +138,19 @@ pool it reads from: 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. -- Google Search grounding, and image models (drawing). +- 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. diff --git a/packages/antigravity/index.mjs b/packages/antigravity/index.mjs index aecb037..5cf9350 100644 --- a/packages/antigravity/index.mjs +++ b/packages/antigravity/index.mjs @@ -1476,19 +1476,34 @@ function withNote(text, note) { return text } +// mergeGrounding merges SSE groundingMetadata chunks without letting a +// trailing empty array overwrite chunks/supports from an earlier chunk +function mergeGrounding(prev, next) { + if (!isObj(prev)) return { ...next } + const out = { ...prev } + for (const [k, v] of Object.entries(next)) { + if (Array.isArray(v) && v.length === 0 && Array.isArray(prev[k]) && prev[k].length > 0) continue + out[k] = v + } + return out +} + // whole is a stream read to its end, as one generateContent reply async function whole(res) { const text = await res.text() const out = { candidates: [] } const parts = [] let last + let groundingMetadata for (const l of text.split(/\r?\n/)) { if (!l.startsWith("data:")) continue let j = parse(l.slice(5).trim()) if (isObj(j?.response)) j = j.response if (!isObj(j)) continue last = j - for (const p of j.candidates?.[0]?.content?.parts ?? []) { + const c0 = j.candidates?.[0] + if (isObj(c0?.groundingMetadata)) groundingMetadata = mergeGrounding(groundingMetadata, c0.groundingMetadata) + for (const p of c0?.content?.parts ?? []) { // a stream ends on an empty text, which Claude refuses sent back if (p?.text === "" && !p.thoughtSignature && Object.keys(p).length === 1) continue const prev = parts[parts.length - 1] @@ -1500,7 +1515,7 @@ async function whole(res) { if (j.responseId) out.responseId = j.responseId } const c = last?.candidates?.[0] ?? {} - out.candidates = [{ ...c, content: { role: "model", parts } }] + out.candidates = [{ ...c, ...(groundingMetadata ? { groundingMetadata } : {}), content: { role: "model", parts } }] return out } @@ -1833,6 +1848,134 @@ async function importAccount(inputs) { } } +// ---- web search (Google Search grounding) ----------------------------------------------- + +// Preference order for search calls; falls back to any non-image Flash or Gemini model in the live catalog +const SEARCH_MODELS = ["gemini-3-flash", "gemini-2.5-flash", "gemini-3.1-flash-lite", "gemini-2.5-flash-lite"] + +function pickSearchModel(infos) { + const raw = catalogOf(infos) + const remaining = new Map((Array.isArray(infos) ? infos : []).map((m) => [m.id, m.remaining])) + const pickFrom = (pool) => { + const ids = new Set(pool.map((m) => m.id)) + for (const id of SEARCH_MODELS) if (ids.has(id)) return id + const flash = pool.find((m) => m.id.startsWith("gemini-") && !draws(m.id) && m.id.includes("flash")) + if (flash) return flash.id + const anyGemini = pool.find((m) => m.id.startsWith("gemini-") && !draws(m.id)) + return anyGemini?.id ?? "" + } + const avail = raw.filter((m) => remaining.get(m.id) !== 0) + return pickFrom(avail) || pickFrom(raw) || SEARCH_MODELS[0] +} + +function searchThinkingConfig(sent) { + const m = String(sent ?? "").toLowerCase() + if (generation(m) >= 3 || m.startsWith("gemini-pro-agent")) { + return { includeThoughts: false, thinkingLevel: m.includes("flash") ? "minimal" : "low" } + } + return { includeThoughts: false, thinkingBudget: 0 } +} + +function pagesFromGrounding(reply, count) { + const cand = reply?.candidates?.[0] + const gm = cand?.groundingMetadata + const chunks = Array.isArray(gm?.groundingChunks) ? gm.groundingChunks : [] + if (!chunks.length) return [] + const supports = Array.isArray(gm?.groundingSupports) ? gm.groundingSupports : [] + const answer = (cand?.content?.parts ?? []) + .filter((p) => !p?.thought && typeof p?.text === "string") + .map((p) => p.text) + .join("") + .trim() + const textsByIdx = chunks.map(() => []) + for (const sup of supports) { + const seg = typeof sup?.segment?.text === "string" ? sup.segment.text.trim() : "" + if (!seg || !Array.isArray(sup?.groundingChunkIndices)) continue + for (const idx of sup.groundingChunkIndices) { + if (Number.isInteger(idx) && idx >= 0 && idx < chunks.length && !textsByIdx[idx].includes(seg)) { + textsByIdx[idx].push(seg) + } + } + } + const out = [] + const byKey = new Map() + for (let i = 0; i < chunks.length; i++) { + const url = typeof chunks[i]?.web?.uri === "string" ? chunks[i].web.uri.trim() : "" + const title = (typeof chunks[i]?.web?.title === "string" ? chunks[i].web.title.trim() : "") || url + if (!url && !title) continue + const key = url || title + const existing = byKey.get(key) + if (existing) { + for (const s of textsByIdx[i]) if (!existing._snippets.includes(s)) existing._snippets.push(s) + continue + } + const entry = { title: title || url, url, _snippets: [...textsByIdx[i]] } + byKey.set(key, entry) + out.push(entry) + } + const limit = Number.isInteger(Number(count)) && Number(count) > 0 ? Number(count) : out.length + const trimmed = out.slice(0, limit).map(({ title, url, _snippets }) => ({ + title, + url, + text: _snippets.join("\n"), + })) + if (answer && trimmed.length && trimmed.every((p) => !p.text)) trimmed[0].text = answer + return trimmed +} + +async function webSearch({ query, count } = {}, ctx = {}) { + const q = typeof query === "string" ? query.trim() : "" + if (!q) throw new Error("query is required") + const s = stateOf(await ctx.getAuth?.()) + if (!s) throw new Error("not signed in to Antigravity") + let l + try { + l = await modelInfo(s) + } catch (e) { + if (e instanceof SignedOut) throw new StatusError(401, e.message) + throw e + } + const picked = pickSearchModel(l.infos) + const [sent, at] = sentID(catalogOf(l.infos), picked, "minimal") + const n = Number.isInteger(Number(count)) && Number(count) > 0 ? Math.min(Number(count), 20) : 6 + const raw = { + systemInstruction: { + role: "user", + parts: [{ text: "You are a web search retrieval assistant. Always use Google Search to look up the user's query. Write concise bullet points summarizing concrete facts, dates, versions, and numbers, and ground each bullet in the retrieved sources so every major source is cited." }], + }, + contents: [{ + role: "user", + parts: [{ text: `Search the live web for: ${q}\nProvide up to ${n} diverse, authoritative web sources, ensuring each relevant source supports at least one concrete factual bullet point.` }], + }], + tools: [{ googleSearch: {} }], + } + const req = shape(raw, sent, at, "minimal") + req.generationConfig = { thinkingConfig: searchThinkingConfig(sent) } + let tok + try { + tok = await token(s) + } catch (e) { + if (e instanceof SignedOut) throw new StatusError(401, e.message) + throw e + } + const ua = await userAgent() + const res = await fetch(`${DAILY}/v1internal:streamGenerateContent?alt=sse`, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "text/event-stream", Authorization: "Bearer " + tok, "User-Agent": ua }, + body: JSON.stringify(envelope(req, sent, l.project.id, false)), + signal: ctx.abort, + }) + if (!res.ok) { + const text = await res.text() + const err = new StatusError(res.status, `Antigravity: ${apiError(text, res.status)}`) + const ra = res.headers.get("retry-after") + if (ra) err.retryAfter = ra + throw err + } + const reply = await whole(res) + return pagesFromGrounding(reply, count) +} + // ---- the plugin --------------------------------------------------------------------------- export async function AntigravityAuthPlugin({ client, magpie } = {}) { @@ -1908,6 +2051,13 @@ export async function AntigravityAuthPlugin({ client, magpie } = {}) { return usage(await getAuth()) }, }, + search: { + antigravity: { + name: "Antigravity (Google Search)", + auth: PROVIDER, + execute: webSearch, + }, + }, } } @@ -1939,6 +2089,9 @@ export const _internal = { creditsOf, entitlements, complete, + pickSearchModel, + pagesFromGrounding, + webSearch, retry400, badCall, usage, diff --git a/packages/antigravity/package.json b/packages/antigravity/package.json index b96e8ff..0ecea42 100644 --- a/packages/antigravity/package.json +++ b/packages/antigravity/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-antigravity-auth", - "version": "0.1.9", + "version": "0.1.10", "description": "Sign in to Antigravity with a Google account from OpenCode or magpie: Gemini, and the Claude and GPT-OSS models Google hosts for it", "type": "module", "main": "./opencode.mjs", diff --git a/packages/antigravity/search.test.mjs b/packages/antigravity/search.test.mjs new file mode 100644 index 0000000..c32d36b --- /dev/null +++ b/packages/antigravity/search.test.mjs @@ -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." }]) +})