gcp-ai 0.2.1: Gemini's history rules before Vertex, no 400 "Requests ending with a model turn" (#734)

The loader's fetch now hardens a generateContent/streamGenerateContent
body the way magpie's gateway builds Gemini contents (codeassist.go):
- contents ending with the model's turn get a user turn after it
  ("Continue.", or the summary ask when the system prompt is an agent's
  compaction prompt);
- contents opening with the model's turn get Gemini CLI's
  "[Continuing from previous AI thoughts...]" user turn before it;
- a user turn holding a functionResponse beside the user's text is split,
  the responses (and their images) first, the text in a turn of its own.
A body that needs none of it goes byte for byte; countTokens and the
model list are not read. lib/history.mjs, test/history.test.mjs.

Note: magpie's gateway already builds a plugin's @ai-sdk/google request
through buildCodeAssistSent, so those rules reach this plugin from magpie
too (yetone/magpie test TestPluginGeminiNeverAskedEndingWithModel, red
with the gateway's guard removed). This covers a body that reaches the
plugin without them: OpenCode's own @ai-sdk/google, or a magpie path that
skips the build. The reporter's exact request body is not in the issue,
so the tests use #734's conversation shape (Codex compaction after the
model's reply) and #1533's (tool output + compaction prompt in one turn).

Run on mote (mote-run): node --test test/history.test.mjs 5/5; the
package's npm run check + node --test test/*.test.mjs 105 tests, 91 pass,
0 fail (14 skipped, Windows-only); bun scripts/check.mjs exit 0.
Broken by hand: the fetch without hardenRequest fails the end-to-end
test (Vertex fake answers 400 "ending with a model turn").
Not tried: a real Vertex account (none in a sandbox here).
This commit is contained in:
yetone
2026-11-05 01:45:46 +08:00
parent 8fcc592e8b
commit 5112465ca1
4 changed files with 245 additions and 4 deletions
+7 -2
View File
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises"
import { defaultProfile, validateProject } from "./lib/browser.mjs"
import { resolveIdentity, startLogin, tokenProvider, identityOf } from "./lib/credentials.mjs"
import { consoleAccountFor, fetchCredits, usageOf } from "./lib/credits.mjs"
import { hardenRequest } from "./lib/history.mjs"
import { testEndpoint } from "./lib/endpoint.mjs"
import { providerModels, seedModels } from "./lib/models.mjs"
@@ -215,10 +216,14 @@ export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) =>
async fetch(input, init) {
const probe = tested.get(probeKey)
if (probe?.error) throw probe.error
const request = new Request(input, init)
const url = new URL(request.url)
const asked = new Request(input, init)
const url = new URL(asked.url)
if (url.origin !== allowed.origin || !url.pathname.startsWith(allowed.pathname + "/")) throw new Error("Refusing to send a Vertex credential outside the configured Google model endpoint")
if (!geminiRoute(url.pathname, allowed.pathname)) throw new Error("Refusing to send a Vertex credential to a route the Gemini endpoint does not serve")
// Gemini's history rules: a conversation ending or opening with
// the model's turn, or a tool's response beside the user's words,
// is sent in the shape Vertex takes instead of answered 400 (#734)
const request = await hardenRequest(asked)
const headers = new Headers(request.headers)
headers.delete("x-goog-api-key")
headers.delete("x-api-key")
+101
View File
@@ -0,0 +1,101 @@
// Gemini's history rules, as Vertex AI holds a generateContent request to
// them, kept here so a conversation an agent left in another shape is sent in
// one Vertex takes (#734). These are the rules magpie's gateway applies to the
// Gemini requests it builds itself (internal/gateway/codeassist.go); a request
// that reaches this plugin some other way, OpenCode's own @ai-sdk/google
// among them, gets them here.
//
// - contents ending with the model's turn: Vertex answers 400 "Requests ending
// with a model turn are not supported" (Codex compacting on a Gemini model).
// A user turn goes after it, as Gemini CLI keeps its history ending.
// - contents opening with the model's turn (what an agent's compaction can
// leave): "function call turn comes immediately after a user turn". Gemini
// CLI's hardenHistory puts a user turn before it, and so does this.
// - a user turn holding a tool's functionResponse and the user's text: Vertex
// takes the two as separate turns and answers the same "ending with a model
// turn" 400, so the text goes in a user turn of its own after the responses.
// What the user turn put after the model's last says: the summary the
// compaction asked for, or to go on.
export const CONTINUE_TEXT = "Continue."
export const COMPACT_LAST_TEXT = "Write the summary of the conversation above that the system prompt asks for."
export const LEADING_USER_TEXT = "[Continuing from previous AI thoughts...]"
// The openings of agents' compaction system prompts, as magpie reads them
// (compactSystems in internal/gateway): within the first 2048 characters.
const COMPACT_SYSTEMS = [
"You are a helpful AI assistant tasked with summarizing conversations.",
"You are a context summarization agent.",
"You are a context summarization assistant.",
"You are a specialized system component responsible for distilling chat history into a structured XML <state_snapshot>",
"You are the component that summarizes a conversation when its context window is about to overflow.",
"You are a context compaction engine. Your summary will REPLACE the original messages in the conversation context window.",
"You are a helpful assistant that compacts conversation context.",
"You are compacting a long conversation so it can continue WITHOUT losing context.",
"You are UPDATING an existing conversation summary with new activity so the conversation can continue WITHOUT losing context.",
]
const COMPACT_LEAD = 2048
function systemText(body) {
const si = body.systemInstruction ?? body.system_instruction
const parts = Array.isArray(si?.parts) ? si.parts : []
return parts.map((p) => (typeof p?.text === "string" ? p.text : "")).join("\n")
}
function compacting(body) {
const system = systemText(body)
return COMPACT_SYSTEMS.some((p) => {
const i = system.indexOf(p)
return i >= 0 && i <= COMPACT_LEAD
})
}
const roleOf = (turn) => (turn?.role === "model" ? "model" : "user")
const isResponse = (part) => part?.functionResponse != null || part?.function_response != null
// The user's own words: a text part that isn't a thought.
const isSaid = (part) => typeof part?.text === "string" && part.thought !== true
// harden gives body's contents in the shape Vertex takes, and whether it
// changed them; body itself is never changed.
export function harden(body) {
if (!body || typeof body !== "object" || !Array.isArray(body.contents) || body.contents.length === 0) return { body, changed: false }
let changed = false
const contents = []
for (const turn of body.contents) {
const parts = Array.isArray(turn?.parts) ? turn.parts : null
if (roleOf(turn) === "user" && parts && parts.some(isResponse) && parts.some(isSaid)) {
contents.push({ ...turn, parts: parts.filter((p) => !isSaid(p)) })
contents.push({ role: "user", parts: parts.filter(isSaid) })
changed = true
continue
}
contents.push(turn)
}
if (roleOf(contents[0]) === "model") {
contents.unshift({ role: "user", parts: [{ text: LEADING_USER_TEXT }] })
changed = true
}
if (roleOf(contents.at(-1)) === "model") {
contents.push({ role: "user", parts: [{ text: compacting(body) ? COMPACT_LAST_TEXT : CONTINUE_TEXT }] })
changed = true
}
return changed ? { body: { ...body, contents }, changed } : { body, changed }
}
// A model call's body: the route a conversation goes to, and the only one
// these rules are for.
export const CONVERSATION_ROUTE = /:(?:generateContent|streamGenerateContent)$/
// hardenRequest is request with its body hardened when it is a model call
// whose contents needed it; otherwise request as it came, body untouched.
export async function hardenRequest(request) {
if (request.method !== "POST" || !CONVERSATION_ROUTE.test(new URL(request.url).pathname)) return request
const text = await request.clone().text()
let parsed
try { parsed = JSON.parse(text) } catch { return request }
const { body, changed } = harden(parsed)
if (!changed) return request
const headers = new Headers(request.headers)
headers.delete("content-length")
return new Request(request, { body: JSON.stringify(body), headers })
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-gcp-ai-auth",
"version": "0.2.0",
"version": "0.2.1",
"description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login",
"type": "module",
"main": "./opencode.mjs",
@@ -18,7 +18,7 @@
"node": ">=22"
},
"scripts": {
"check": "node --check index.mjs && node --check lib/browser.mjs && node --check lib/credentials.mjs && node --check lib/credits.mjs && node --check lib/endpoint.mjs && node --check lib/models.mjs && node --check lib/fetch_credits.mjs",
"check": "node --check index.mjs && node --check lib/browser.mjs && node --check lib/credentials.mjs && node --check lib/credits.mjs && node --check lib/endpoint.mjs && node --check lib/models.mjs && node --check lib/fetch_credits.mjs && node --check lib/history.mjs",
"models": "node lib/fetch_credits.mjs models",
"test": "node --test test/*.test.mjs",
"credits": "node lib/fetch_credits.mjs credits",
+135
View File
@@ -0,0 +1,135 @@
import "./network.mjs"
import assert from "node:assert/strict"
import test from "node:test"
import plugin from "../index.mjs"
import { fakeGcloud } from "./gcloud.mjs"
import { COMPACT_LAST_TEXT, CONTINUE_TEXT, LEADING_USER_TEXT, harden } from "../lib/history.mjs"
// Codex's compaction prompt, as it asks for the summary (#734's case: Codex
// compacting a delegate's conversation on gemini-4-argon).
const CODEX_COMPACT = "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task."
// Vertex AI's 400s, as #734 and magpie's #1533 were shown them: contents
// ending with the model's turn, or a user turn with a tool's response and the
// user's text, which Vertex takes as two turns.
function vertexRefuses(body) {
const contents = body.contents ?? []
if (contents.at(-1)?.role === "model") return "Requests ending with a model turn are not supported."
if (contents[0]?.role === "model") return "Please ensure that function call turn comes immediately after a user turn or after a function response turn."
for (const turn of contents) {
const parts = turn.parts ?? []
if (parts.some((p) => p.functionResponse) && parts.some((p) => typeof p.text === "string")) return "Requests ending with a model turn are not supported."
}
return ""
}
// The conversation of #734 in the shape @ai-sdk/google sends it: a tool call
// and its answer, then the model's reply last, which Codex's compaction hands
// on as it is.
const endsWithModel = () => ({
systemInstruction: { parts: [{ text: "You are Codex, a coding agent." }] },
contents: [
{ role: "user", parts: [{ text: "fix the bug" }] },
{ role: "model", parts: [{ functionCall: { name: "shell", args: { command: ["ls"] } }, thoughtSignature: "c2ln" }] },
{ role: "user", parts: [{ functionResponse: { name: "shell", response: { name: "shell", content: "main.go" } } }] },
{ role: "model", parts: [{ text: "Fixed it in main.go." }] },
],
generationConfig: { thinkingConfig: { thinkingLevel: "high", includeThoughts: true } },
})
test("contents ending with the model's turn get a user turn after it, the summary asked when compacting (#734)", () => {
const body = endsWithModel()
assert.match(vertexRefuses(body), /ending with a model turn/)
const before = structuredClone(body)
const { body: out, changed } = harden(body)
assert.equal(changed, true)
assert.deepEqual(body, before, "the caller's body is not changed")
assert.equal(vertexRefuses(out), "")
assert.deepEqual(out.contents.at(-1), { role: "user", parts: [{ text: CONTINUE_TEXT }] })
assert.deepEqual(out.contents.slice(0, 4), before.contents)
assert.deepEqual(out.generationConfig, before.generationConfig)
const compaction = { ...endsWithModel(), systemInstruction: { parts: [{ text: "You are a helpful AI assistant tasked with summarizing conversations." }] } }
assert.deepEqual(harden(compaction).body.contents.at(-1), { role: "user", parts: [{ text: COMPACT_LAST_TEXT }] })
})
test("contents opening with the model's turn get a user turn before it", () => {
const body = { contents: endsWithModel().contents.slice(1, 3) }
const { body: out, changed } = harden(body)
assert.equal(changed, true)
assert.deepEqual(out.contents[0], { role: "user", parts: [{ text: LEADING_USER_TEXT }] })
assert.equal(vertexRefuses(out), "")
})
test("a tool's response and the compaction prompt in one user turn go as two turns, the responses first (#1533's shape)", () => {
const body = {
contents: [
{ role: "user", parts: [{ text: "Read a sample file." }] },
{ role: "model", parts: [{ functionCall: { id: "call_1", name: "read_sample", args: { path: "sample.txt" } } }, { functionCall: { id: "call_2", name: "read_sample", args: { path: "other.txt" } } }] },
{ role: "user", parts: [
{ functionResponse: { id: "call_1", name: "read_sample", response: { output: "Sample file content: hello." } } },
{ inlineData: { mimeType: "image/png", data: "iVBORw0KGgo=" } },
{ functionResponse: { id: "call_2", name: "read_sample", response: { output: "other" } } },
{ text: CODEX_COMPACT },
] },
],
}
assert.match(vertexRefuses(body), /ending with a model turn/)
const { body: out } = harden(body)
assert.equal(vertexRefuses(out), "")
assert.equal(out.contents.length, 4)
const [tools, said] = out.contents.slice(2)
assert.equal(tools.role, "user")
assert.deepEqual(tools.parts.map((p) => Object.keys(p)[0]), ["functionResponse", "inlineData", "functionResponse"])
assert.deepEqual(said, { role: "user", parts: [{ text: CODEX_COMPACT }] })
})
test("contents Vertex already takes are left as they are", () => {
const body = { contents: [...endsWithModel().contents, { role: "user", parts: [{ text: "and the test?" }] }] }
const { body: out, changed } = harden(body)
assert.equal(changed, false)
assert.equal(out, body)
for (const odd of [undefined, null, {}, { contents: [] }, { contents: "x" }]) assert.equal(harden(odd).changed, false)
})
// End to end through the loader's fetch, as magpie and OpenCode call it: the
// body Vertex is sent is the hardened one, the call's other fields as they came;
// a body that needs nothing goes byte for byte, and a non-conversation route is
// not read at all.
test("the loader's fetch sends Vertex the hardened conversation (#734)", { timeout: 30000 }, async () => {
const fixture = await fakeGcloud()
const original = globalThis.fetch
const sent = []
globalThis.fetch = async (input, init) => {
const url = String(input?.url ?? input)
if (url === "https://oauth2.googleapis.com/token") return Response.json({ access_token: "token", expires_in: 3600 })
if (url.includes("/v1/projects/")) return Response.json({}, { status: 200 })
const text = input instanceof Request ? await input.text() : String(init?.body ?? "")
sent.push({ url, text })
const refusal = text && !url.includes(":countTokens") ? vertexRefuses(JSON.parse(text)) : ""
if (refusal) return Response.json({ error: { code: 400, message: refusal, status: "INVALID_ARGUMENT" } }, { status: 400 })
return Response.json({ candidates: [{ content: { role: "model", parts: [{ text: "summary" }] }, finishReason: "STOP" }] })
}
try {
await fixture.setAdc()
const hooks = await plugin()
const auth = { project: "history-project", accountId: "history@example.com", authMode: "adc", cloudsdkConfig: fixture.sdk }
const loaded = await hooks.auth.loader(async () => auth)
const call = (route, body) => loaded.fetch(`${loaded.baseURL}/models/gemini-4-argon:${route}`, { method: "POST", body, headers: { "content-type": "application/json" } })
const asked = JSON.stringify(endsWithModel())
const response = await call("streamGenerateContent?alt=sse", asked)
assert.equal(response.status, 200, await response.clone().text())
const got = JSON.parse(sent.at(-1).text)
assert.match(sent.at(-1).url, /:streamGenerateContent\?alt=sse$/)
assert.deepEqual(got.contents.at(-1), { role: "user", parts: [{ text: CONTINUE_TEXT }] })
assert.deepEqual(got.systemInstruction, endsWithModel().systemInstruction)
const fine = JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hi" }] }] })
assert.equal((await call("generateContent", fine)).status, 200)
assert.equal(sent.at(-1).text, fine)
// countTokens counts what it is given
assert.equal((await call("countTokens", JSON.stringify({ contents: endsWithModel().contents }))).status, 200)
assert.equal(JSON.parse(sent.at(-1).text).contents.at(-1).role, "model")
} finally { globalThis.fetch = original; await fixture.close() }
})