Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions ARCHITECTURE-MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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. |

---

Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
62 changes: 62 additions & 0 deletions docs/issues/128-20261126-gemini-thought-signature-and-triage.md
Original file line number Diff line number Diff line change
@@ -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.<key>` 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.<key>` 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)
33 changes: 32 additions & 1 deletion src/chatParts.ts
Original file line number Diff line number Diff line change
@@ -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)) {
Expand All @@ -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
);
}

Expand Down Expand Up @@ -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;
}
}
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading