diff --git a/packages/antigravity/README.md b/packages/antigravity/README.md index fbbf517..6ee3eee 100644 --- a/packages/antigravity/README.md +++ b/packages/antigravity/README.md @@ -122,7 +122,7 @@ The plugin also changes the request itself, as the built-in did: |---|---| | 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 as it is | +| 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` | diff --git a/packages/antigravity/index.mjs b/packages/antigravity/index.mjs index 400da9a..8ce6541 100644 --- a/packages/antigravity/index.mjs +++ b/packages/antigravity/index.mjs @@ -1240,15 +1240,21 @@ function errorResponse(status, message, signIn) { } // unwrap turns Code Assist's stream, each chunk {response: }, back -// into Gemini's own -function unwrap(body) { +// into Gemini's own. With say, an INVALID_ARGUMENT error in it, as a data +// event or a bare line, is told in say's words +function unwrap(body, say) { const dec = new TextDecoder() const enc = new TextEncoder() let buf = "" const line = (l) => { - if (!l.startsWith("data:")) return l - const j = parse(l.slice(5).trim()) - if (isObj(j) && isObj(j.response)) return "data: " + JSON.stringify(j.response) + const data = l.startsWith("data:") + if (!data && !(say && l.trimStart().startsWith("{"))) return l + const j = parse(data ? l.slice(5).trim() : l) + if (say && isObj(j) && isObj(j.error) && badCall(JSON.stringify(j))) { + const e = { ...j.error, message: say(j.error.message) } + return (data ? "data: " : "") + JSON.stringify({ ...j, error: e }) + } + if (data && isObj(j) && isObj(j.response)) return "data: " + JSON.stringify(j.response) return l } return body.pipeThrough( @@ -1285,6 +1291,15 @@ const RETRY_BAD_CALL = 2 const retry400 = { floorMs: 3000, pauseMs: 300, holdMax: 512 * 1024, holdMs: 10_000 } const isGemini4 = (id) => /^gemini-4/i.test(String(id ?? "")) +// badCallSaid is what the client is told of Gemini 4's INVALID_ARGUMENT +// after the model ran, asked n times: the vendor's words alone read as a +// request magpie got wrong, or a region block (Lawson0112 on X), which +// Google refuses at once and names (FAILED_PRECONDITION "User location is +// not supported…"). The words stay clear of what magpie's gateway reads as +// another fault: "model" before "invalid" reads as a model not served +const badCallSaid = (id, n) => (message) => + `${id} turned down a call it built while thinking, asked ${n} time${n === 1 ? "" : "s"} (Google: ${String(message ?? "").trim() || "INVALID_ARGUMENT"}). Not a region or account refusal: Google names those` + // badCall is whether a reply's body is Google's INVALID_ARGUMENT function badCall(text) { const j = parse(text) @@ -1325,13 +1340,24 @@ async function holdThoughts(res, signal) { let pending let timer const late = new Promise((r) => (timer = setTimeout(r, retry400.holdMs, LATE))) + // loose is the lines of a JSON value written with no "data:" before it, + // as Code Assist writes its late error: after the thinking events, a + // line of its own, {"error":{"code":400,…,"status":"INVALID_ARGUMENT"}} + // (zRain's capture, magpie's sse_bare.go), maybe over several lines + let loose = "" const scan = (final) => { let i - while (!release && ((i = buf.indexOf("\n")) >= 0 || (final && buf))) { - const l = i >= 0 ? buf.slice(0, i) : buf + while (!release && !bad && ((i = buf.indexOf("\n")) >= 0 || (final && buf))) { + const l = (i >= 0 ? buf.slice(0, i) : buf).replace(/\r$/, "") buf = i >= 0 ? buf.slice(i + 1) : "" - if (!l.startsWith("data:")) continue - const j = parse(l.slice(5).trim()) + let j + if (l.startsWith("data:")) j = parse(l.slice(5).trim()) + else if (loose || l.trimStart().startsWith("{")) { + loose += l + "\n" + j = parse(loose) + if (j === undefined && loose.length <= retry400.holdMax) continue + loose = "" + } else continue if (!isObj(j)) continue if ((j.error || j.response?.error) && badCall(JSON.stringify(j))) bad = true else if (showsAnswer(j)) release = true @@ -1464,16 +1490,22 @@ async function complete(s, url, init, magpie) { // comes back fast is the request's own fault and is returned as it is. const again400 = isGemini4(sent) || isGemini4(model) let res, refusal + // asks is how many times the model was asked; slow, whether the last + // 400 took long enough to be the model's own (retry400.floorMs) + let asks = 0 + let slow = false for (let n = 0; ; n++) { const t0 = Date.now() ;({ res, refusal } = await attempt()) + asks = n + 1 + slow = Date.now() - t0 >= retry400.floorMs const left = again400 && n < RETRY_BAD_CALL && !init?.signal?.aborted if (!left) break if (!res.ok) { if (res.status !== 400) break const text = refusal ?? (await res.text()) refusal = text - if (!badCall(text) || Date.now() - t0 < retry400.floorMs) break + if (!badCall(text) || !slow) break await sleep(retry400.pauseMs) continue } @@ -1488,6 +1520,7 @@ async function complete(s, url, init, magpie) { if (!res.ok) { const text = refusal ?? (await res.text()) const msg = apiError(text, res.status) + if (again400 && res.status === 400 && slow && badCall(text)) return errorResponse(400, badCallSaid(sent, asks)(msg)) if (res.status === 401) return errorResponse(401, `Antigravity: ${msg}`, "kept") if (res.status === 404) return errorResponse(404, `model ${sent} not found`) if (res.status === 429 && /resource has been exhausted/i.test(text) && turnsAway(system)) { @@ -1501,7 +1534,7 @@ async function complete(s, url, init, magpie) { } return new Response(text, { status: res.status, headers: { "content-type": res.headers.get("content-type") ?? "application/json" } }) } - if (stream) return new Response(unwrap(res.body), { status: 200, headers: RESPONSE_HEADERS }) + if (stream) return new Response(unwrap(res.body, again400 ? badCallSaid(sent, asks) : undefined), { status: 200, headers: RESPONSE_HEADERS }) return new Response(JSON.stringify(await whole(res)), { status: 200, headers: { "content-type": "application/json" } }) } diff --git a/packages/antigravity/package.json b/packages/antigravity/package.json index 71eaa0a..78f712f 100644 --- a/packages/antigravity/package.json +++ b/packages/antigravity/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-antigravity-auth", - "version": "0.1.13", + "version": "0.1.14", "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/requests.test.mjs b/packages/antigravity/requests.test.mjs index af6eae7..828b5f2 100644 --- a/packages/antigravity/requests.test.mjs +++ b/packages/antigravity/requests.test.mjs @@ -367,3 +367,65 @@ test("a generateContent reply is asked again the same way", async () => { 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) +})