diff --git a/ARCHITECTURE-MAP.md b/ARCHITECTURE-MAP.md index 3e276fd6f..22c46947b 100644 --- a/ARCHITECTURE-MAP.md +++ b/ARCHITECTURE-MAP.md @@ -3,7 +3,7 @@ # Architecture Map **Topic:** architecture / provider / streaming / routing / usage / models / thinking -**Updated:** 2026-09-23 +**Updated:** 2026-11-26 **Tags:** #architecture #provider #streaming #routing #usage #models #thinking #byok #autocomplete **Supersedes:** - **Related:** `docs/architecture/01-20260514-open-code-provider-architecture.md` · `docs/architecture/02-20260809-provider-adapter-architecture.md` @@ -214,13 +214,14 @@ flowchart TD ### Key edges & blast-radius notes -| Edge | Why it matters | -| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `OpenCodeProvider` → `transports/*` + `core/routing` | Changing a transport adapter or the registry can break the provider's request path. **Always `npm run compile` + test ≥1 model family of the touched transport.** | -| `thinking/provider` + `core/routing` → `core/registry` | The registry is the **single source of truth** for both transport AND thinking family. Never hardcode a family decision elsewhere. | -| `transports/*` → `core/transport.ts` | `StreamRequestOptions` is the shared contract — changing it touches every adapter. | -| `usage/dashboard` → `tracker` + `history` + `metadataFetcher` | The dashboard is the hub for all usage UI; it pulls from tracker (server+tracked), history (CLI SQLite), and metadata (cost). | -| `OpenCodeProvider` → `usage/*` | Every Go request records usage via `onTransportSummary` → `tracker.record()`. Breaking this silently stops usage accounting. | +| Edge | Why it matters | +| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `OpenCodeProvider` → `transports/*` + `core/routing` | Changing a transport adapter or the registry can break the provider's request path. **Always `npm run compile` + test ≥1 model family of the touched transport.** | +| `thinking/provider` + `core/routing` → `core/registry` | The registry is the **single source of truth** for both transport AND thinking family. Never hardcode a family decision elsewhere. | +| `transports/*` → `core/transport.ts` | `StreamRequestOptions` is the shared contract — changing it touches every adapter. | +| `usage/dashboard` → `tracker` + `history` + `metadataFetcher` | The dashboard is the hub for all usage UI; it pulls from tracker (server+tracked), history (CLI SQLite), and metadata (cost). | +| `OpenCodeProvider` → `usage/*` | Every Go request records usage via `onTransportSummary` → `tracker.record()`. Breaking this silently stops usage accounting. | +| `core/routing` → `transports/google` → `request/google` | Gemini 3+ thought signatures are captured by the normalizers, carried through the transcript as an internal `LanguageModelDataPart` (`chatParts.ts`), and replayed on the next turn. Never drop a signature-only event or merge adjacent assistant messages without concatenating signatures. | --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 652b3fe6d..b2b941d69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ All notable changes to the **OpenCode Go BYOK Provider** extension are documente ### Fixed +- **`[Google]` Gemini 3+ follow-up turns no longer fail with `MISSING_THOUGHT_SIGNATURE` (Gemini 4 Hydrogen on Zen).** The Google normalizers dropped the opaque `thoughtSignature` from response parts, and the request builder never sent it back. Signatures are now captured across SSE events, carried through the Copilot Chat transcript as an invisible internal data part, and replayed as trailing parts on the next `model` turn — including after tool calls. A signature-only event is no longer discarded as empty. Documented in `docs/issues/128-20261126-gemini-thought-signature-and-triage.md`, which also records the verdicts for the Haiku 5.5 context bug (upstream VS Code #336797), the `gpt-6.2-sol` skill loader (model-generated arguments), and the `globalState` growth warning (old design debt). + - **`[Google]` Gemini tool results use the valid `functionResponse` shape again (issue #283).** A July regression moved `content` to the top level; strict validators such as `gemini-4-argon` rejected every request after the first tool call. The text now lives in the required `response` object while multimodal `parts` stay at `functionResponse` level. Documented in `docs/issues/122-20261125-issue283-gemini-function-response-regression.md`. - **`[Models]` GPT Luna no longer sends a rejected `temperature` parameter (issue #285).** models.dev reports `temperature: true` for `gpt-6-luna` and `gpt-5.6-luna`, but the Go gateway rejects it. The gateway restriction now overrides live metadata, and the HTTP 400 retry classifier recognizes the `Unsupported parameter` wording. Documented in `docs/issues/123-20261125-issue285-gpt-luna-temperature.md`. diff --git a/docs/issues/128-20261126-gemini-thought-signature-and-triage.md b/docs/issues/128-20261126-gemini-thought-signature-and-triage.md new file mode 100644 index 000000000..91086d391 --- /dev/null +++ b/docs/issues/128-20261126-gemini-thought-signature-and-triage.md @@ -0,0 +1,62 @@ +**Status:** ✅ Solved + +# Gemini thoughtSignature Fix and Related Triage + +**Topic:** routing / streaming / models / provider / vscode / usage +**Updated:** 2026-11-26 +**Tags:** #gemini #routing #streaming #thought-signature #byok #vscode #usage +**Supersedes:** - +**Related:** `docs/architecture/01-20260514-open-code-provider-architecture.md` · `docs/issues/122-20261125-issue283-gemini-function-response-regression.md` + +--- + +## Overview + +Follow-up triage to PR #288 (issues #282–#287) covering five reports from the same user. Four were classified as upstream behaviour, model-generated arguments, or long-standing design debt; one was a real gap in this extension: Gemini 4 Hydrogen on Zen failed on follow-up turns because opaque `thoughtSignature` values were dropped from the response and never replayed. This document records the verdicts, the fix, and the open follow-ups. + +## Verdicts + +| Symptom | Verdict | Evidence | +| ------------------------------------------------------ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Haiku 5.5 context 1% → 0%, repeated compaction | Upstream VS Code, not our regression | [microsoft/vscode#336797](https://github.com/microsoft/vscode/issues/336797): the Agent Host BYOK bridge forwards limits as 0/0, the runtime falls back to 128K, and compaction fires near 102K (80%). The issue is still open; PR #336798 landed in 1.139 but Oct 2026 comments still confirm it. Related: #340138, #340983, #348630 (local harness removal, Feb 2027). Our extension already advertises 1M via `provider/modelInfo.ts`. | +| Gemini 4 Hydrogen on Zen does not work | **Our bug** — new-model support gap | Route and auth were probed and are valid. `core/routing.ts` dropped `thoughtSignature` from Google response parts and `request/google.ts` never sent it back. Google requires the signature on follow-up turns for Gemini 3+ when thinking is enabled; omitting it produces `MISSING_THOUGHT_SIGNATURE`. Not an old regression. | +| Skill loader with `gpt-6.2-sol` | Not our transport bug | The real model id is `gpt-6.2-sol`; it matches `/^gpt-/` → Responses API, with `temperature: false` from models.dev. `sanitizeToolSchema()` only removes `$ref`/`$defs` and keeps `description`/`required`. Empty `server`/`uri` strings are arguments generated by the model, not our payload. | +| "Models work in Copilot directly, DeepSeek BYOK works" | Supports the diagnosis above | The failure is specific to a model + Agent Host bridge combination, not BYOK API access in general. | +| `globalState` warning at 632 KB | Old design debt, not caused by PR #288 | `opencodego.usageLog.v1.` stores 2000 entries per profile with 31-day retention, plus metadata cache and transport summaries. Four profiles on the reporter's machine total ~2 MB. PR #288 added one boolean. | + +## Root cause — Gemini thought signatures + +Google's `generateContent` API has no dedicated thought blocks. Signatures are metadata attached to parts: a thought part, a `functionCall` part, or the trailing empty-text part of a response. The official `Part.thoughtSignature` field is documented as "an opaque signature for the thought so it can be reused in subsequent requests", and `Candidate.finishReason` includes `MISSING_THOUGHT_SIGNATURE` ("Request has at least one thought signature missing"). In stateless mode the client must resend thought blocks exactly as received. + +Our Google normalizers flattened parts into OpenAI-style text/reasoning/tool-call fields and discarded every other part property. A signature-only event (`{"text":"","thoughtSignature":"…"}`) was even classified as empty and returned `{ choices: [] }`. The next turn therefore went out without the signature and Gemini 4 rejected it. + +## Fix + +The signature now makes a full round-trip without ever becoming visible chat text: + +1. `core/routing.ts` — `normalizeGoogleStreamEvent()` and `normalizeGoogleFullResponse()` collect non-empty `thoughtSignature` values into `thought_signatures` on the normalized delta/message. A signature-only event is no longer treated as empty. +2. `transports/google.ts` + `transports/extractors.ts` — the Google adapter captures signatures across SSE events and emits one internal transcript part after the stream. +3. `chatParts.ts` — new `application/vnd.opencode.thought-signature+json` data part (same invisible seam as the reasoning marker), capped by `MAX_THOUGHT_SIGNATURES` in `config.ts`. +4. `provider/messages.ts` — `convertMessage()` reads the part back into `ApiMessage.thought_signatures`; `normalizeMessages()` concatenates signatures when adjacent assistant messages merge, so history trimming cannot silently drop them. +5. `request/google.ts` — replays each signature as a trailing `{ text: "", thoughtSignature }` part on the `model` turn, matching the shape the gateway returned. Tool-call turns keep their `functionCall` parts ahead of the signature parts. + +No other transport is affected: the field is only read by the Google request builder. + +## Verification + +- `npm run compile` — clean. +- `src/test/google-thought-signature.test.ts` — 11/11 pass: stream and full-response normalization, signature-only event, transcript round-trip and malformed payloads, replay on plain and tool-call turns, no extra parts when no signature was received, and history normalization retaining/merging signatures. +- Live Gemini 4 Hydrogen verification in Copilot Chat is still pending (requires the reporter's Zen key / harness). + +## Open follow-ups + +- **Haiku 5.5 compaction** — upstream VS Code #336797. Nothing to change here; the extension already advertises the correct 1M window. Recheck when the upstream issue closes. +- **`globalState` growth** — migrate `opencodego.usageLog.v1.` from `globalState` to `globalStorageUri`, keeping only a small index in `globalState`. Separate change with its own migration/compat plan; deliberately not bundled into this fix. +- **`gpt-6.2-sol` skill loader** — no extension change. If a raw tool schema from Copilot shows our payload altering `server`/`uri`, reopen with that evidence. + +## Sources + +- [Gemini thinking — thought signatures](https://aistudio.google.com/docs/thinking#signatures) +- [GenerateContent API reference — `Part.thoughtSignature`, `MISSING_THOUGHT_SIGNATURE`](https://aistudio.google.com/api-reference/generate-content) +- [Function calling with thinking models](https://aistudio.google.com/docs/function-calling#thinking) +- [microsoft/vscode#336797](https://github.com/microsoft/vscode/issues/336797) diff --git a/src/chatParts.ts b/src/chatParts.ts index 2065485f8..fbc9476b7 100644 --- a/src/chatParts.ts +++ b/src/chatParts.ts @@ -1,9 +1,11 @@ import * as vscode from "vscode"; +import { MAX_THOUGHT_SIGNATURES } from "./config"; import { hasUsageSnapshot, toProviderUsagePayload, type UsageSnapshot } from "./usage/usage"; export const OPENCODE_USAGE_DATA_MIME = "application/vnd.opencode.usage+json"; export const COPILOT_USAGE_DATA_MIME = "usage"; export const OPENCODE_REASONING_DATA_MIME = "application/vnd.opencode.reasoning+json"; +export const OPENCODE_THOUGHT_SIGNATURE_DATA_MIME = "application/vnd.opencode.thought-signature+json"; export function createUsageDataParts(usage: UsageSnapshot): vscode.LanguageModelDataPart[] { if (!hasUsageSnapshot(usage)) { @@ -26,7 +28,8 @@ export function isInternalDataPart(part: vscode.LanguageModelDataPart): boolean return ( part.mimeType === OPENCODE_USAGE_DATA_MIME || part.mimeType === COPILOT_USAGE_DATA_MIME || - part.mimeType === OPENCODE_REASONING_DATA_MIME + part.mimeType === OPENCODE_REASONING_DATA_MIME || + part.mimeType === OPENCODE_THOUGHT_SIGNATURE_DATA_MIME ); } @@ -57,3 +60,31 @@ export function readReasoningMarker(part: vscode.LanguageModelDataPart): string return undefined; } } + +/** + * Carry Gemini's opaque thought signatures through the Copilot Chat transcript. + * Google requires them on the next turn for Gemini 3+ with thinking enabled; + * VS Code history has no generic metadata field, so an internal data part is + * the only lossless round-trip seam (same pattern as the reasoning marker). + */ +export function createThoughtSignaturePart(signatures: readonly string[]): vscode.LanguageModelDataPart { + const payload = { signatures: signatures.slice(0, MAX_THOUGHT_SIGNATURES) }; + const data = new TextEncoder().encode(JSON.stringify(payload)); + return new vscode.LanguageModelDataPart(data, OPENCODE_THOUGHT_SIGNATURE_DATA_MIME); +} + +export function isThoughtSignaturePart(part: vscode.LanguageModelDataPart): boolean { + return part.mimeType === OPENCODE_THOUGHT_SIGNATURE_DATA_MIME; +} + +/** Read the signatures carried by a marker part, if any. */ +export function readThoughtSignaturePart(part: vscode.LanguageModelDataPart): string[] | undefined { + try { + const payload = JSON.parse(new TextDecoder().decode(part.data)) as { signatures?: unknown }; + return Array.isArray(payload.signatures) + ? payload.signatures.filter((value): value is string => typeof value === "string" && value.length > 0) + : undefined; + } catch { + return undefined; + } +} diff --git a/src/config.ts b/src/config.ts index 5d2a92773..ffc1be3d9 100644 --- a/src/config.ts +++ b/src/config.ts @@ -212,6 +212,8 @@ export const IMAGE_TOKEN_ESTIMATE = 1024; export const MAX_TOOL_RESULT_IMAGE_BYTES = 1_000_000; /** Max images kept in conversation history before older ones are placeholder-replaced. */ export const MAX_HISTORY_IMAGES_KEPT = 2; +/** Max opaque Gemini thought signatures replayed on one assistant turn. */ +export const MAX_THOUGHT_SIGNATURES = 8; /** * Tokens reserved below the model's input context window when trimming old * conversation history. Keeps the trimmed payload safely under the limit so the diff --git a/src/core/routing.ts b/src/core/routing.ts index f1cdaf193..7a7e00dfc 100644 --- a/src/core/routing.ts +++ b/src/core/routing.ts @@ -276,6 +276,11 @@ export function normalizeResponsesFullResponse(data: unknown): unknown { }; } +/** Opaque Gemini thought signatures must be replayed unchanged on the next turn. */ +function googleThoughtSignatures(parts: Record[]): string[] { + return parts.map((part) => part.thoughtSignature).filter((value): value is string => typeof value === "string" && value.length > 0); +} + export function normalizeGoogleStreamEvent(data: unknown): unknown { if (!isRecord(data)) { return data; @@ -312,8 +317,9 @@ export function normalizeGoogleStreamEvent(data: unknown): unknown { ]; }); const usage = normalizeGoogleUsage(data.usageMetadata); + const thoughtSignatures = googleThoughtSignatures(parts); - if (!text && !reasoning && !toolCalls.length && !candidate?.finishReason && !usage) { + if (!text && !reasoning && !toolCalls.length && !thoughtSignatures.length && !candidate?.finishReason && !usage) { return { choices: [] }; } @@ -325,6 +331,7 @@ export function normalizeGoogleStreamEvent(data: unknown): unknown { ...(text ? { content: text } : {}), ...(reasoning ? { reasoning_content: reasoning } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}), + ...(thoughtSignatures.length ? { thought_signatures: thoughtSignatures } : {}), }, finish_reason: normalizeGoogleFinishReason( typeof candidate?.finishReason === "string" ? candidate.finishReason : undefined, @@ -368,6 +375,7 @@ export function normalizeGoogleFullResponse(data: unknown): unknown { ]; }); const usage = normalizeGoogleUsage(data.usageMetadata); + const thoughtSignatures = googleThoughtSignatures(parts); return { choices: [ @@ -377,6 +385,7 @@ export function normalizeGoogleFullResponse(data: unknown): unknown { ...(text ? { content: text } : {}), ...(reasoning ? { reasoning_content: reasoning } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}), + ...(thoughtSignatures.length ? { thought_signatures: thoughtSignatures } : {}), }, finish_reason: normalizeGoogleFinishReason( typeof candidate?.finishReason === "string" ? candidate.finishReason : undefined, diff --git a/src/provider/messages.ts b/src/provider/messages.ts index 1af7c4946..8dff623c1 100644 --- a/src/provider/messages.ts +++ b/src/provider/messages.ts @@ -1,5 +1,11 @@ import * as vscode from "vscode"; -import { isInternalDataPart, isReasoningMarkerPart, readReasoningMarker } from "../chatParts"; +import { + isInternalDataPart, + isReasoningMarkerPart, + isThoughtSignaturePart, + readReasoningMarker, + readThoughtSignaturePart, +} from "../chatParts"; import { requiresStringToolContent } from "../models/modelCapabilities"; import { MAX_HISTORY_IMAGES_KEPT, MAX_TOOL_RESULT_IMAGE_BYTES } from "../config"; import { getImageDataUrlBase64Bytes, MAX_IMAGE_BASE64_BYTES, normalizeImageDataUrl } from "../imageNormalizer"; @@ -18,6 +24,7 @@ export async function convertMessage( const role = message.role === vscode.LanguageModelChatMessageRole.Assistant ? "assistant" : "user"; const textParts: string[] = []; const thinkingTextParts: string[] = []; + const thoughtSignatures: string[] = []; const imageParts: OpenAiContentPart[] = []; const toolCalls: OpenAiToolCall[] = []; const toolResults: ApiMessage[] = []; @@ -173,6 +180,14 @@ export async function convertMessage( continue; } + if (part instanceof vscode.LanguageModelDataPart && isThoughtSignaturePart(part)) { + const signatures = readThoughtSignaturePart(part); + if (signatures) { + thoughtSignatures.push(...signatures); + } + continue; + } + if (part instanceof vscode.LanguageModelDataPart && isReasoningMarkerPart(part)) { // Thinking-off responses carry their reasoning in a marker data part // (see streaming.ts / gateway bug #37635); echo it as reasoning_content @@ -262,6 +277,7 @@ export async function convertMessage( ? content || null : content, reasoning_content: shouldOmitReasoningEcho || isMiniMaxModel(rawModelId) ? undefined : toolCallReasoning, + thought_signatures: thoughtSignatures.length ? thoughtSignatures : undefined, tool_calls: toolCalls, }, ]); @@ -280,6 +296,7 @@ export async function convertMessage( role, content: plainPrefix ? plainPrefix + (textContent || "") : typeof content === "string" ? content || null : content, reasoning_content: shouldEchoThinkingHistory(rawModelId) ? thinkingText : undefined, + thought_signatures: thoughtSignatures.length ? thoughtSignatures : undefined, }, ]); } @@ -347,6 +364,9 @@ export function normalizeMessages(messages: ApiMessage[]): ApiMessage[] { if (message.reasoning_content) { previous.reasoning_content = [previous.reasoning_content, message.reasoning_content].filter(Boolean).join("\n"); } + if (message.thought_signatures?.length) { + previous.thought_signatures = [...(previous.thought_signatures ?? []), ...message.thought_signatures]; + } previous.content = `${prevContent}\n\n${msgContent}`.trim(); } else { normalized.push({ ...message }); @@ -450,6 +470,12 @@ export function hasMessagePayload(message: ApiMessage): boolean { return true; } + // A signature-only assistant turn still carries state Gemini 3+ needs on the + // next request — never drop it just because it produced no visible text. + if (message.thought_signatures?.length) { + return true; + } + if (typeof message.content === "string") { return message.content.trim().length > 0; } diff --git a/src/request/google.ts b/src/request/google.ts index a8f8afc45..7e0677be3 100644 --- a/src/request/google.ts +++ b/src/request/google.ts @@ -90,6 +90,13 @@ function googleContentsFromMessages(messages: ApiMessage[]): Record string; +const moduleResolver = Module as unknown as { _resolveFilename: ResolveFilename }; +const originalResolveFilename = moduleResolver._resolveFilename; +moduleResolver._resolveFilename = function (request: string, parent: unknown, ...args: unknown[]): string { + if (request === "vscode") { + return vscodeMockPath; + } + return originalResolveFilename.call(this, request, parent, ...args); +}; + +let normalizeGoogleStreamEvent: typeof import("../core/routing.js").normalizeGoogleStreamEvent; +let normalizeGoogleFullResponse: typeof import("../core/routing.js").normalizeGoogleFullResponse; +let buildGoogleGenerateContentBody: typeof import("../request/google.js").buildGoogleGenerateContentBody; +let createThoughtSignaturePart: typeof import("../chatParts.js").createThoughtSignaturePart; +let isThoughtSignaturePart: typeof import("../chatParts.js").isThoughtSignaturePart; +let readThoughtSignaturePart: typeof import("../chatParts.js").readThoughtSignaturePart; +let isInternalDataPart: typeof import("../chatParts.js").isInternalDataPart; +let normalizeMessages: typeof import("../provider/messages.js").normalizeMessages; + +const settings = { + temperature: 0.2, + thinking: {}, + maxOutputTokensOverride: 0, + maxInputTokensOverride: 0, + debugReasoning: false, + requestTimeoutMs: 0, + streamIdleTimeoutMs: 0, + stripThinkTags: "auto", +} as unknown as import("../request/types.js").ApiSettings; +const metadata = {} as unknown as import("../models/metadata.js").ResolvedModelMetadata; +const limits = { maxOutputTokens: 4096 } as unknown as import("../models/modelLimits.js").ModelLimits; +const options = {} as unknown as import("vscode").ProvideLanguageModelChatResponseOptions; + +interface GoogleContent { + role: string; + parts: Record[]; +} + +function contentsFor(messages: import("../request/types.js").ApiMessage[]): GoogleContent[] { + const body = buildGoogleGenerateContentBody("gemini-4-hydrogen", messages, options, settings, metadata, limits); + return body.contents as GoogleContent[]; +} + +before(async () => { + ({ normalizeGoogleStreamEvent, normalizeGoogleFullResponse } = await import("../core/routing.js")); + ({ buildGoogleGenerateContentBody } = await import("../request/google.js")); + ({ createThoughtSignaturePart, isThoughtSignaturePart, readThoughtSignaturePart, isInternalDataPart } = await import("../chatParts.js")); + ({ normalizeMessages } = await import("../provider/messages.js")); +}); + +describe("Google normalizers — thoughtSignature preservation", () => { + it("keeps signatures from thought, functionCall and trailing parts in order", () => { + const result = normalizeGoogleStreamEvent({ + candidates: [ + { + content: { + parts: [ + { text: "planning", thought: true, thoughtSignature: "sig-thought" }, + { functionCall: { name: "read_file", args: { path: "a" } }, thoughtSignature: "sig-call" }, + { text: "", thoughtSignature: "sig-final" }, + ], + }, + finishReason: "STOP", + }, + ], + }) as { choices: { delta: { thought_signatures?: string[] } }[] }; + assert.deepEqual(result.choices[0]?.delta.thought_signatures, ["sig-thought", "sig-call", "sig-final"]); + }); + + it("does not discard a signature-only event as empty", () => { + const result = normalizeGoogleStreamEvent({ + candidates: [{ content: { parts: [{ text: "", thoughtSignature: "sig-only" }] } }], + }) as { choices: unknown[] }; + assert.equal(result.choices.length, 1); + }); + + it("keeps signatures on the non-streaming full-response path", () => { + const result = normalizeGoogleFullResponse({ + candidates: [{ content: { parts: [{ text: "answer" }, { text: "", thoughtSignature: "sig-full" }] } }], + }) as { choices: { message: { thought_signatures?: string[] } }[] }; + assert.deepEqual(result.choices[0]?.message.thought_signatures, ["sig-full"]); + }); + + it("emits no signature field when the response has none", () => { + const result = normalizeGoogleStreamEvent({ + candidates: [{ content: { parts: [{ text: "answer" }] } }], + }) as { choices: { delta: { thought_signatures?: string[] } }[] }; + assert.equal(result.choices[0]?.delta.thought_signatures, undefined); + }); +}); + +describe("Thought signature transcript part", () => { + it("round-trips signatures and is classified as an internal data part", () => { + const part = createThoughtSignaturePart(["sig-a", "sig-b"]); + assert.equal(isThoughtSignaturePart(part), true); + assert.equal(isInternalDataPart(part), true); + assert.deepEqual(readThoughtSignaturePart(part), ["sig-a", "sig-b"]); + }); + + it("ignores malformed payloads and foreign parts", () => { + const malformed = { + data: new TextEncoder().encode("not json"), + mimeType: "application/vnd.opencode.thought-signature+json", + }; + assert.equal(readThoughtSignaturePart(malformed), undefined); + const foreign = createThoughtSignaturePart(["x"]); + const foreignPart = { data: foreign.data, mimeType: "application/vnd.opencode.usage+json" }; + assert.equal(isThoughtSignaturePart(foreignPart), false); + }); +}); + +describe("Gemini request builder — thoughtSignature replay", () => { + it("replays the signature as a trailing part on the model turn", () => { + const contents = contentsFor([ + { role: "user", content: "first" }, + { role: "assistant", content: "answer", thought_signatures: ["sig-1"] }, + { role: "user", content: "second" }, + ]); + assert.deepEqual(contents[1], { + role: "model", + parts: [{ text: "answer" }, { text: "", thoughtSignature: "sig-1" }], + }); + }); + + it("replays signatures after function calls on a tool turn", () => { + const contents = contentsFor([ + { role: "user", content: "first" }, + { + role: "assistant", + content: null, + thought_signatures: ["sig-2"], + tool_calls: [{ id: "call_1", type: "function", function: { name: "read_file", arguments: "{}" } }], + }, + ]); + assert.deepEqual(contents[1].parts, [{ functionCall: { name: "read_file", args: {} } }, { text: "", thoughtSignature: "sig-2" }]); + }); + + it("adds no extra parts when no signature was received", () => { + const contents = contentsFor([ + { role: "user", content: "first" }, + { role: "assistant", content: "answer" }, + ]); + assert.deepEqual(contents[1].parts, [{ text: "answer" }]); + }); +}); + +describe("History normalization — signature retention", () => { + it("keeps a signature-only assistant turn", () => { + const messages = normalizeMessages([ + { role: "user", content: "first" }, + { role: "assistant", content: null, thought_signatures: ["sig-only"] }, + ]); + assert.deepEqual(messages[1]?.thought_signatures, ["sig-only"]); + }); + + it("concatenates signatures when adjacent assistant messages merge", () => { + const messages = normalizeMessages([ + { role: "user", content: "first" }, + { role: "assistant", content: "part one", thought_signatures: ["sig-a"] }, + { role: "assistant", content: "part two", thought_signatures: ["sig-b"] }, + ]); + assert.deepEqual(messages[1]?.thought_signatures, ["sig-a", "sig-b"]); + }); +}); diff --git a/src/thinking/gemini.ts b/src/thinking/gemini.ts index 3a883843e..8521b5e77 100644 --- a/src/thinking/gemini.ts +++ b/src/thinking/gemini.ts @@ -19,6 +19,12 @@ * `thought: true` parts, `core/routing.ts` already maps them to * `reasoning_content` with no further client work. * + * SIGNATURES (2026-11-26): that opaque signature is now captured by + * `core/routing.ts`, carried through the transcript by `chatParts.ts`, and + * replayed by `request/google.ts`. Google requires it on every follow-up turn + * for Gemini 3+ with thinking enabled; omitting it yields + * `MISSING_THOUGHT_SIGNATURE`. The signature is metadata, never displayed text. + * * DISPLAY: Gemini thought parts are genuine CoT (echoed back as `thought: true` * parts on follow-up turns, see `request/google.ts`) → never visible text. * diff --git a/src/transports/extractors.ts b/src/transports/extractors.ts index 0089ae428..adf95551b 100644 --- a/src/transports/extractors.ts +++ b/src/transports/extractors.ts @@ -1,5 +1,6 @@ import * as vscode from "vscode"; -import { createReasoningMarkerPart } from "../chatParts"; +import { createReasoningMarkerPart, createThoughtSignaturePart } from "../chatParts"; +import { MAX_THOUGHT_SIGNATURES } from "../config"; import { parseToolInput, ToolCallAccumulator, type PendingToolCall } from "../toolCallAccumulator"; import { isRecord } from "../utils"; import type { ThinkTagFilter } from "./thinkTags"; @@ -241,6 +242,27 @@ class OpenAiResponseExtractor extends BaseResponseExtractor { return part; } + /** Accumulate opaque Gemini signatures seen across SSE events of one turn. */ + private readonly thoughtSignatures: string[] = []; + + captureThoughtSignatures(signatures: readonly string[]): void { + for (const signature of signatures) { + if (signature && !this.thoughtSignatures.includes(signature) && this.thoughtSignatures.length < MAX_THOUGHT_SIGNATURES) { + this.thoughtSignatures.push(signature); + } + } + } + + /** Emit an internal transcript part so the next turn can replay the signatures. */ + flushThoughtSignaturePart(): vscode.LanguageModelResponsePart2 | undefined { + if (!this.thoughtSignatures.length) { + return undefined; + } + const part = createThoughtSignaturePart(this.thoughtSignatures); + this.thoughtSignatures.length = 0; + return part; + } + /** * Accumulate reasoning for tool-call replication, and — when the thinking * part API is available — stream it live to the Copilot Chat UI. diff --git a/src/transports/google.ts b/src/transports/google.ts index ee2f22c1d..2ea7a68a4 100644 --- a/src/transports/google.ts +++ b/src/transports/google.ts @@ -4,6 +4,7 @@ import { createThinkTagFilter } from "./thinkTags"; import { createReasoningDebugger, streamOpenCodeResponse } from "./engine"; import { OpenAiResponseExtractor } from "./extractors"; import { extractChatCompletionParts } from "./extract"; +import { reportProgressPart } from "./streamParts"; /** Google Generative Language API transport (Gemini via Zen). */ export async function streamGoogleGenerateContent(options: StreamRequestOptions): Promise { @@ -21,8 +22,26 @@ export async function streamGoogleGenerateContent(options: StreamRequestOptions) ...options, usesDoneSentinel: false, url: `${options.url}:streamGenerateContent?alt=sse`, - extractStreamParts: (data) => extractor.extractStreamParts(normalizeGoogleStreamEvent(data)), - extractFullParts: (data) => extractChatCompletionParts(normalizeGoogleFullResponse(data)), + extractStreamParts: (data) => { + const normalized = normalizeGoogleStreamEvent(data) as { + choices?: { delta?: { thought_signatures?: string[] } }[]; + }; + const signatures = normalized.choices?.[0]?.delta?.thought_signatures; + if (signatures) { + extractor.captureThoughtSignatures(signatures); + } + return extractor.extractStreamParts(normalized); + }, + extractFullParts: (data) => { + const normalized = normalizeGoogleFullResponse(data) as { + choices?: { message?: { thought_signatures?: string[] } }[]; + }; + const signatures = normalized.choices?.[0]?.message?.thought_signatures; + if (signatures) { + extractor.captureThoughtSignatures(signatures); + } + return extractChatCompletionParts(normalized); + }, }); } finally { // Flush accumulated tool calls / reasoning even when the engine throws @@ -30,6 +49,12 @@ export async function streamGoogleGenerateContent(options: StreamRequestOptions) extractor.flushRemainingToolCalls(options.progress, options.requestHeaders["x-opencode-request"]); extractor.flushReasoningFallback(options.progress, options.requestHeaders["x-opencode-request"]); } + // Gemini 3+ requires the opaque signature on the next turn; carry it in the + // transcript as an internal data part (invisible in the chat UI). + const signaturePart = extractor.flushThoughtSignaturePart(); + if (signaturePart) { + reportProgressPart(options.requestHeaders["x-opencode-request"], options.progress, signaturePart); + } options.output?.appendLine( `[stream-summary model=${options.modelId}] textChars=${String(extractor.emittedText)} toolCalls=${String(extractor.emittedTools)} reasoningChars=${String(extractor.reasoningChars)}`, );