diff --git a/packages/opencode/src/id/id.ts b/packages/opencode/src/id/id.ts index 847a5c0329245..2bcf26f31e7e0 100644 --- a/packages/opencode/src/id/id.ts +++ b/packages/opencode/src/id/id.ts @@ -18,6 +18,10 @@ const LENGTH = 26 // State for monotonic ID generation let lastTimestamp = 0 let counter = 0 +// The wall clock is not monotonic (NTP corrections, VM or WSL2 resume). Parts and messages are +// replayed in ID order, so an ID minted after a backward step must still sort after every ID +// this process handed out before it. `last` is the highest value minted so far. +let last = BigInt(0) export function ascending(prefix: keyof typeof prefixes, given?: string) { return generateID(prefix, "ascending", given) @@ -59,6 +63,11 @@ export function create(prefix: string, direction: "descending" | "ascending", ti let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter) + // Keep wall-clock IDs strictly ascending through a backward clock step + if (timestamp === undefined) { + if (now <= last) now = last + BigInt(1) + last = now + } now = direction === "descending" ? ~now : now const timeBytes = Buffer.alloc(6) diff --git a/packages/opencode/src/provider/transform.ts b/packages/opencode/src/provider/transform.ts index 8ae8b4d9f16b7..2234202ce5e7f 100644 --- a/packages/opencode/src/provider/transform.ts +++ b/packages/opencode/src/provider/transform.ts @@ -514,9 +514,31 @@ export function message(msgs: ModelMessage[], model: Provider.Model, options: Re }) } + // Gemini rejects contents that end with a model turn + if (model.api.npm === "@ai-sdk/google" || model.api.npm === "@ai-sdk/google-vertex") { + msgs = geminiTail(msgs) + } + return msgs } +// Gemini rejects any request whose contents end with a model turn (400 INVALID_ARGUMENT +// "Requests ending with a model turn are not supported."). The replayed transcript can end with an +// assistant message: parts minted across a backward clock step sort a tool call ahead of its own +// step-start, which strands that step's reasoning as a trailing assistant block, and a continued +// turn can replay a finished assistant message with no user input behind it. Thought text carries +// nothing to continue from (thought signatures travel with the tool call), so a reasoning-only tail +// is dropped; any other assistant tail gets a primed user turn, mirroring the synthetic "Done." +// assistant turn normalizeMessages inserts for tool -> user. Outbound only: the stored transcript +// is never changed. +function geminiTail(msgs: ModelMessage[]): ModelMessage[] { + const last = msgs.at(-1) + if (last?.role !== "assistant") return msgs + const parts = typeof last.content === "string" ? undefined : last.content + if (parts?.every((part) => part.type === "reasoning")) return geminiTail(msgs.slice(0, -1)) + return [...msgs, { role: "user", content: "Continue." }] +} + const GEMINI_2_5_RE = /gemini-2[.-]5(?:[.-]|$)/i const GEMINI_LEGACY_RE = /gemini-(?:(?:flash|pro)-)?[12](?:[.-]|$)/i diff --git a/packages/opencode/test/id/id.test.ts b/packages/opencode/test/id/id.test.ts new file mode 100644 index 0000000000000..ee331baf9fc59 --- /dev/null +++ b/packages/opencode/test/id/id.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, setSystemTime, test } from "bun:test" +import { Identifier } from "@/id/id" + +// Parts and messages are stored and replayed in ID order, so IDs minted by one +// process must keep their order even when the wall clock steps backward +// (NTP corrections, VM or WSL2 resume). +describe("Identifier - wall clock steps backward", () => { + test("ascending ids keep ascending across a backward step", () => { + const base = Date.now() + setSystemTime(new Date(base)) + const ids = [Identifier.ascending("part")] + setSystemTime(new Date(base - 5_000)) + ids.push(Identifier.ascending("part"), Identifier.ascending("part")) + setSystemTime(new Date(base + 1)) + ids.push(Identifier.ascending("part")) + setSystemTime() + + expect([...ids].sort()).toEqual(ids) + expect(new Set(ids).size).toBe(ids.length) + }) + + test("descending ids keep descending across a backward step", () => { + const base = Date.now() + setSystemTime(new Date(base)) + const ids = [Identifier.descending("session")] + setSystemTime(new Date(base - 5_000)) + ids.push(Identifier.descending("session")) + setSystemTime(new Date(base + 1)) + ids.push(Identifier.descending("session")) + setSystemTime() + + expect([...ids].sort().reverse()).toEqual(ids) + }) + + test("ids minted in the same millisecond still ascend", () => { + const base = Date.now() + setSystemTime(new Date(base)) + const ids = [Identifier.ascending("part"), Identifier.ascending("part"), Identifier.ascending("part")] + setSystemTime() + + expect([...ids].sort()).toEqual(ids) + }) + + test("explicit timestamps do not move the wall-clock floor", () => { + const base = Date.now() + setSystemTime(new Date(base)) + const before = Identifier.ascending("part") + const given = Identifier.create("prt", "ascending", base + 10_000) + const after = Identifier.ascending("part") + setSystemTime() + + expect(before < given).toBe(true) + expect(after < given).toBe(true) + expect(Identifier.timestamp(after) - Identifier.timestamp(before)).toBeLessThan(1_000) + }) +}) diff --git a/packages/opencode/test/provider/transform.test.ts b/packages/opencode/test/provider/transform.test.ts index cf42346716eab..ea1d3cfe1c1d6 100644 --- a/packages/opencode/test/provider/transform.test.ts +++ b/packages/opencode/test/provider/transform.test.ts @@ -6315,3 +6315,82 @@ describe("ProviderTransform.options - kimi family adaptive thinking", () => { expect(result.thinking).toBeUndefined() }) }) + +// Gemini rejects any request whose contents end with a model turn: +// 400 INVALID_ARGUMENT "Requests ending with a model turn are not supported." +describe("ProviderTransform.message - gemini trailing model turn", () => { + const model = (npm: string, providerID: string) => + ({ + id: `${providerID}/gemini-3.8-flash`, + providerID, + api: { + id: "gemini-3.8-flash", + url: "https://generativelanguage.googleapis.com", + npm, + }, + name: "Gemini 3.8 Flash", + capabilities: { + temperature: true, + reasoning: true, + attachment: true, + toolcall: true, + input: { text: true, audio: false, image: true, video: false, pdf: true }, + output: { text: true, audio: false, image: false, video: false, pdf: false }, + interleaved: false, + }, + cost: { input: 0.001, output: 0.002, cache: { read: 0.0001, write: 0.0002 } }, + limit: { context: 1_000_000, output: 8192 }, + status: "active", + options: {}, + headers: {}, + }) as any + + const gemini = model("@ai-sdk/google", "google") + const user: ModelMessage = { role: "user", content: "Check the merge queue" } + const call: ModelMessage = { + role: "assistant", + content: [{ type: "tool-call", toolCallId: "call_1", toolName: "bash", input: { command: "gh run list" } }], + } + const result: ModelMessage = { + role: "tool", + content: [{ type: "tool-result", toolCallId: "call_1", toolName: "bash", output: { type: "text", value: "ok" } }], + } + const thought: ModelMessage = { + role: "assistant", + content: [{ type: "reasoning", text: "**Reviewing Merge Queue Status**\n\nAll checks are green so far." }], + } + const answer: ModelMessage = { role: "assistant", content: [{ type: "text", text: "All checks passed." }] } + const primed: ModelMessage = { role: "user", content: "Continue." } + + test("drops a reasoning-only assistant tail", () => { + expect(ProviderTransform.message([user, call, result, thought], gemini, {})).toEqual([user, call, result]) + }) + + test("primes a user turn behind a text assistant tail", () => { + expect(ProviderTransform.message([user, answer], gemini, {})).toEqual([user, answer, primed]) + }) + + test("drops a reasoning-only tail and still primes behind the text tail underneath", () => { + expect(ProviderTransform.message([user, answer, thought], gemini, {})).toEqual([user, answer, primed]) + }) + + test("leaves requests that end with a user or tool turn alone", () => { + expect(ProviderTransform.message([user, call, result], gemini, {})).toEqual([user, call, result]) + expect(ProviderTransform.message([user], gemini, {})).toEqual([user]) + }) + + test("applies to gemini on vertex", () => { + const vertex = model("@ai-sdk/google-vertex", "google-vertex") + expect(ProviderTransform.message([user, call, result, thought], vertex, {})).toEqual([user, call, result]) + }) + + test("keeps assistant prefill for other providers", () => { + const anthropic = { + ...model("@ai-sdk/anthropic", "anthropic"), + id: "anthropic/claude-sonnet-4-5", + api: { id: "claude-sonnet-4-5", url: "https://api.anthropic.com", npm: "@ai-sdk/anthropic" }, + } + const out = ProviderTransform.message([user, answer, thought], anthropic, {}) + expect(out.map((msg) => msg.role)).toEqual(["user", "assistant", "assistant"]) + }) +})