From 0dd26a1a3e3d82d7a98ad12211a4e8cd769b1bcb Mon Sep 17 00:00:00 2001 From: PierrunoYT Date: Tue, 20 Oct 2026 22:51:25 +0200 Subject: [PATCH 1/6] fix(litellm): don't truncate tool call ids that carry a thought signature LiteLLM encodes a Gemini thought signature into the tool call id after __thought__. sanitizeOpenAiCallId cut such ids to 64 characters and appended a hash, so Gemini received a corrupted signature (400 Base64 decoding failed). Only character-sanitize ids containing the marker. Fixes #2064 Co-Authored-By: Claude Sonnet 5.5 --- src/api/providers/__tests__/lite-llm.spec.ts | 42 ++++++++++++++++++++ src/api/providers/lite-llm.ts | 6 +-- src/utils/__tests__/tool-id.spec.ts | 34 +++++++++++++++- src/utils/tool-id.ts | 23 +++++++++++ 4 files changed, 101 insertions(+), 4 deletions(-) diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index e4c575c37e..1f080e7e5f 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -3,6 +3,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import { LiteLLMHandler } from "../lite-llm" import { getModels } from "../fetchers/modelCache" +import type { ApiHandlerCreateMessageMetadata } from "../../index" import { ApiHandlerOptions } from "../../../shared/api" import { type ModelInfo, type ModelRecord, litellmDefaultModelId, litellmDefaultModelInfo } from "@roo-code/types" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" @@ -792,6 +793,47 @@ describe("LiteLLMHandler", () => { expect(assistantMessage.tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) }) + it("should send tool call ids that carry a thought signature unchanged", async () => { + // LiteLLM encodes the Gemini signature into the id; truncating it breaks the signature. + const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" + const toolCallId = `call_864944__thought__${signature}` + expect(toolCallId.length).toBeGreaterThan(64) + + const messages: Anthropic.Messages.MessageParam[] = [ + { role: "user", content: "Hello" }, + { + role: "assistant", + content: [{ type: "tool_use", id: toolCallId, name: "read_file", input: { path: "test.txt" } }], + }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: toolCallId, content: "file contents" }], + }, + ] + mockCreate.mockReturnValue({ + withResponse: vi.fn().mockResolvedValue({ + data: asyncStreamFrom([{ choices: [{ delta: { content: "ok" } }] }]), + }), + }) + const metadata: ApiHandlerCreateMessageMetadata = { + taskId: "task-1", + tools: [ + { + type: "function", + function: { name: "read_file", description: "Read a file", parameters: {} }, + }, + ], + } + + await collectStream(handler.createMessage("You are a helpful assistant", messages, metadata)) + + const sent: OpenAI.Chat.ChatCompletionMessageParam[] = mockCreate.mock.calls[0][0].messages + const assistantMessage = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) + const toolMessage = sent.find((msg) => msg.role === "tool") + expect(assistantMessage?.role === "assistant" && assistantMessage.tool_calls?.[0].id).toBe(toolCallId) + expect(toolMessage?.role === "tool" && toolMessage.tool_call_id).toBe(toolCallId) + }) + it("should not inject thought signatures for non-Gemini models", async () => { const optionsWithGPT4: ApiHandlerOptions = { ...mockOptions, diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index 6c82e61bd4..716cd1e31d 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -18,7 +18,7 @@ import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" import { convertToOpenAiMessages } from "../transform/openai-format" import { convertToR1Format } from "../transform/r1-format" import { GEMINI_THOUGHT_SIGNATURE_BYPASS } from "../transform/gemini-format" -import { sanitizeOpenAiCallId } from "../../utils/tool-id" +import { sanitizeLiteLlmCallId } from "../../utils/tool-id" import type { SingleCompletionHandler, @@ -208,11 +208,11 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // never gets inserted mid-turn and causes the model to drop prior reasoning_content. const openAiMessages = info.preserveReasoning ? convertToR1Format(messages, { - normalizeToolCallId: sanitizeOpenAiCallId, + normalizeToolCallId: sanitizeLiteLlmCallId, mergeToolResultText: true, }) : convertToOpenAiMessages(messages, { - normalizeToolCallId: sanitizeOpenAiCallId, + normalizeToolCallId: sanitizeLiteLlmCallId, }) // Prepare messages with cache control if enabled and supported diff --git a/src/utils/__tests__/tool-id.spec.ts b/src/utils/__tests__/tool-id.spec.ts index 2459786cea..401c98b431 100644 --- a/src/utils/__tests__/tool-id.spec.ts +++ b/src/utils/__tests__/tool-id.spec.ts @@ -1,4 +1,10 @@ -import { sanitizeToolUseId, truncateOpenAiCallId, sanitizeOpenAiCallId, OPENAI_CALL_ID_MAX_LENGTH } from "../tool-id" +import { + sanitizeToolUseId, + truncateOpenAiCallId, + sanitizeOpenAiCallId, + sanitizeLiteLlmCallId, + OPENAI_CALL_ID_MAX_LENGTH, +} from "../tool-id" describe("sanitizeToolUseId", () => { describe("valid IDs pass through unchanged", () => { @@ -184,3 +190,29 @@ describe("OPENAI_CALL_ID_MAX_LENGTH constant", () => { expect(OPENAI_CALL_ID_MAX_LENGTH).toBe(64) }) }) + +describe("sanitizeLiteLlmCallId", () => { + const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" + + it("keeps an id that carries a thought signature intact, however long", () => { + const id = `call_864944__thought__${signature}` + + expect(id.length).toBeGreaterThan(OPENAI_CALL_ID_MAX_LENGTH) + expect(sanitizeLiteLlmCallId(id)).toBe(id) + }) + + it("sanitizes only the call id before the marker, leaving the Base64 signature intact", () => { + expect(sanitizeLiteLlmCallId("call.1:x__thought__ab+c/d=")).toBe("call_1_x__thought__ab+c/d=") + }) + + it("truncates other long ids like sanitizeOpenAiCallId", () => { + const id = "call_" + "x".repeat(100) + + expect(sanitizeLiteLlmCallId(id)).toBe(sanitizeOpenAiCallId(id)) + expect(sanitizeLiteLlmCallId(id).length).toBe(OPENAI_CALL_ID_MAX_LENGTH) + }) + + it("leaves short ids unchanged", () => { + expect(sanitizeLiteLlmCallId("toolu_123")).toBe("toolu_123") + }) +}) diff --git a/src/utils/tool-id.ts b/src/utils/tool-id.ts index feba6598f6..c7f5c862fa 100644 --- a/src/utils/tool-id.ts +++ b/src/utils/tool-id.ts @@ -54,3 +54,26 @@ export function sanitizeOpenAiCallId(id: string, maxLength: number = OPENAI_CALL const sanitized = sanitizeToolUseId(id) return truncateOpenAiCallId(sanitized, maxLength) } + +/** + * LiteLLM carries a Gemini thought signature inside the tool call id, as + * `__thought__`. Truncating such an id corrupts the signature. + */ +export const LITELLM_THOUGHT_SIGNATURE_MARKER = "__thought__" + +/** + * Normalize a tool call id for LiteLLM. For ids that carry a thought signature only the + * call id before the marker is character-sanitized; the marker and the Base64 signature + * (which may contain `+`, `/` and `=`) pass through unchanged, because Gemini must receive + * the signature intact. Every other id gets the usual OpenAI 64-character treatment. + * + * @param id - The original call_id + * @returns The id to send to LiteLLM + */ +export function sanitizeLiteLlmCallId(id: string): string { + const markerIndex = id.indexOf(LITELLM_THOUGHT_SIGNATURE_MARKER) + if (markerIndex === -1) { + return sanitizeOpenAiCallId(id) + } + return sanitizeToolUseId(id.slice(0, markerIndex)) + id.slice(markerIndex) +} From adb00d5e19c1f99cf6f3fe840e0ba29d5fee1e9d Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Tue, 10 Nov 2026 16:16:22 -0500 Subject: [PATCH 2/6] fix(tool-id): keep thought signatures intact in the tool_use history --- src/api/providers/__tests__/lite-llm.spec.ts | 87 +++++++++++-------- .../__tests__/anthropic-filter.spec.ts | 34 ++++++++ src/api/transform/anthropic-filter.ts | 27 ++++-- src/utils/__tests__/tool-id.spec.ts | 52 +++++++++-- src/utils/tool-id.ts | 51 ++++++----- 5 files changed, 180 insertions(+), 71 deletions(-) diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index 1f080e7e5f..d3aff084f0 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -3,6 +3,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import { LiteLLMHandler } from "../lite-llm" import { getModels } from "../fetchers/modelCache" +import { sanitizeToolUseId } from "../../../utils/tool-id" import type { ApiHandlerCreateMessageMetadata } from "../../index" import { ApiHandlerOptions } from "../../../shared/api" import { type ModelInfo, type ModelRecord, litellmDefaultModelId, litellmDefaultModelInfo } from "@roo-code/types" @@ -793,46 +794,60 @@ describe("LiteLLMHandler", () => { expect(assistantMessage.tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) }) - it("should send tool call ids that carry a thought signature unchanged", async () => { - // LiteLLM encodes the Gemini signature into the id; truncating it breaks the signature. - const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" - const toolCallId = `call_864944__thought__${signature}` - expect(toolCallId.length).toBeGreaterThan(64) - - const messages: Anthropic.Messages.MessageParam[] = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: [{ type: "tool_use", id: toolCallId, name: "read_file", input: { path: "test.txt" } }], - }, - { - role: "user", - content: [{ type: "tool_result", tool_use_id: toolCallId, content: "file contents" }], - }, - ] - mockCreate.mockReturnValue({ - withResponse: vi.fn().mockResolvedValue({ - data: asyncStreamFrom([{ choices: [{ delta: { content: "ok" } }] }]), - }), - }) - const metadata: ApiHandlerCreateMessageMetadata = { - taskId: "task-1", - tools: [ + it.each([ + { path: "convertToOpenAiMessages", preserveReasoning: undefined }, + { path: "convertToR1Format", preserveReasoning: true }, + ])( + "should send tool call ids that carry a thought signature unchanged ($path)", + async ({ preserveReasoning }) => { + const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" + const toolCallId = `call_864944__thought__${signature}` + const historyId = sanitizeToolUseId(toolCallId) + expect(toolCallId.length).toBeGreaterThan(64) + + vi.spyOn(handler, "fetchModel").mockResolvedValue({ + id: "gemini-3-pro", + info: { ...litellmDefaultModelInfo, preserveReasoning }, + }) + const messages: Anthropic.Messages.MessageParam[] = [ + { role: "user", content: "Hello" }, { - type: "function", - function: { name: "read_file", description: "Read a file", parameters: {} }, + role: "assistant", + content: [ + { type: "tool_use", id: historyId, name: "read_file", input: { path: "test.txt" } }, + ], }, - ], - } + { + role: "user", + content: [{ type: "tool_result", tool_use_id: historyId, content: "file contents" }], + }, + ] + mockCreate.mockReturnValue({ + withResponse: vi.fn().mockResolvedValue({ + data: asyncStreamFrom([{ choices: [{ delta: { content: "ok" } }] }]), + }), + }) + const metadata: ApiHandlerCreateMessageMetadata = { + taskId: "task-1", + tools: [ + { + type: "function", + function: { name: "read_file", description: "Read a file", parameters: {} }, + }, + ], + } - await collectStream(handler.createMessage("You are a helpful assistant", messages, metadata)) + await collectStream(handler.createMessage("You are a helpful assistant", messages, metadata)) - const sent: OpenAI.Chat.ChatCompletionMessageParam[] = mockCreate.mock.calls[0][0].messages - const assistantMessage = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) - const toolMessage = sent.find((msg) => msg.role === "tool") - expect(assistantMessage?.role === "assistant" && assistantMessage.tool_calls?.[0].id).toBe(toolCallId) - expect(toolMessage?.role === "tool" && toolMessage.tool_call_id).toBe(toolCallId) - }) + const sent: OpenAI.Chat.ChatCompletionMessageParam[] = mockCreate.mock.calls[0][0].messages + const assistantMessage = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) + const toolMessage = sent.find((msg) => msg.role === "tool") + expect(assistantMessage?.role === "assistant" && assistantMessage.tool_calls?.[0].id).toBe( + toolCallId, + ) + expect(toolMessage?.role === "tool" && toolMessage.tool_call_id).toBe(toolCallId) + }, + ) it("should not inject thought signatures for non-Gemini models", async () => { const optionsWithGPT4: ApiHandlerOptions = { diff --git a/src/api/transform/__tests__/anthropic-filter.spec.ts b/src/api/transform/__tests__/anthropic-filter.spec.ts index 46ad1a1952..cab2cbc01d 100644 --- a/src/api/transform/__tests__/anthropic-filter.spec.ts +++ b/src/api/transform/__tests__/anthropic-filter.spec.ts @@ -140,5 +140,39 @@ describe("anthropic-filter", () => { expect(result).toHaveLength(1) expect(result[0].content).toEqual([{ type: "text", text: "Valid text" }]) }) + + it("makes tool ids from a thought-signature history match Anthropic's id pattern", () => { + const historyId = "call_864944__thought__ab+c/d==" + const messages: Anthropic.Messages.MessageParam[] = [ + { + role: "assistant", + content: [{ type: "tool_use", id: historyId, name: "read_file", input: {} }], + }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: historyId, content: "ok" }], + }, + ] + + const result = filterNonAnthropicBlocks(messages) + + expect(result[0].content).toEqual([ + { type: "tool_use", id: "call_864944__thought__ab_c_d__", name: "read_file", input: {} }, + ]) + expect(result[1].content).toEqual([ + { type: "tool_result", tool_use_id: "call_864944__thought__ab_c_d__", content: "ok" }, + ]) + }) + + it("leaves valid tool ids unchanged", () => { + const messages: Anthropic.Messages.MessageParam[] = [ + { + role: "assistant", + content: [{ type: "tool_use", id: "toolu_01AbC-xyz", name: "read_file", input: {} }], + }, + ] + + expect(filterNonAnthropicBlocks(messages)).toEqual(messages) + }) }) }) diff --git a/src/api/transform/anthropic-filter.ts b/src/api/transform/anthropic-filter.ts index 2bfc6dccfd..429939abd2 100644 --- a/src/api/transform/anthropic-filter.ts +++ b/src/api/transform/anthropic-filter.ts @@ -1,5 +1,7 @@ import { Anthropic } from "@anthropic-ai/sdk" +import { sanitizeToolIdForStrictProvider } from "../../utils/tool-id" + /** * Set of content block types that are valid for Anthropic API. * Only these types will be passed through to the API. @@ -22,6 +24,9 @@ export const VALID_ANTHROPIC_BLOCK_TYPES = new Set([ * - Internal "reasoning" blocks (Roo Code's internal representation) * - Gemini's "thoughtSignature" blocks (encrypted reasoning continuity tokens) * - Any other unknown block types + * + * It also makes tool ids match Anthropic's ^[a-zA-Z0-9_-]+$ pattern. The history keeps + * thought-signature ids from other providers unchanged, and those can contain `+`, `/` and `=`. */ export function filterNonAnthropicBlocks( messages: Anthropic.Messages.MessageParam[], @@ -32,11 +37,13 @@ export function filterNonAnthropicBlocks( return message } - const filteredContent = message.content.filter((block) => { - const blockType = (block as { type: string }).type - // Only keep block types that Anthropic recognizes - return VALID_ANTHROPIC_BLOCK_TYPES.has(blockType) - }) + const filteredContent = message.content + .filter((block) => { + const blockType = (block as { type: string }).type + // Only keep block types that Anthropic recognizes + return VALID_ANTHROPIC_BLOCK_TYPES.has(blockType) + }) + .map(withStrictToolId) // If all content was filtered out, return undefined to filter the message later if (filteredContent.length === 0) { @@ -50,3 +57,13 @@ export function filterNonAnthropicBlocks( }) .filter((message): message is Anthropic.Messages.MessageParam => message !== undefined) } + +function withStrictToolId(block: T): T { + if (block.type === "tool_use") { + return { ...block, id: sanitizeToolIdForStrictProvider(block.id) } + } + if (block.type === "tool_result") { + return { ...block, tool_use_id: sanitizeToolIdForStrictProvider(block.tool_use_id) } + } + return block +} diff --git a/src/utils/__tests__/tool-id.spec.ts b/src/utils/__tests__/tool-id.spec.ts index 401c98b431..ba3bb0fae7 100644 --- a/src/utils/__tests__/tool-id.spec.ts +++ b/src/utils/__tests__/tool-id.spec.ts @@ -3,9 +3,14 @@ import { truncateOpenAiCallId, sanitizeOpenAiCallId, sanitizeLiteLlmCallId, + sanitizeToolIdForStrictProvider, OPENAI_CALL_ID_MAX_LENGTH, } from "../tool-id" +const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" +const thoughtSignatureId = `call_864944__thought__${signature}` +const strictToolIdPattern = /^[a-zA-Z0-9_-]+$/ + describe("sanitizeToolUseId", () => { describe("valid IDs pass through unchanged", () => { it("should preserve alphanumeric IDs", () => { @@ -84,6 +89,36 @@ describe("sanitizeToolUseId", () => { }) }) +describe("sanitizeToolUseId with a thought signature", () => { + it("keeps the marker and the Base64 signature unchanged", () => { + expect(sanitizeToolUseId(thoughtSignatureId)).toBe(thoughtSignatureId) + }) + + it("sanitizes only the call id before the marker", () => { + expect(sanitizeToolUseId("call.1:x__thought__ab+c/d=")).toBe("call_1_x__thought__ab+c/d=") + }) + + it("still replaces + / = in ids without the marker", () => { + expect(sanitizeToolUseId("call_ab+c/d=")).toBe("call_ab_c_d_") + }) +}) + +describe("sanitizeToolIdForStrictProvider", () => { + it.each([thoughtSignatureId, "call.1:x__thought__ab+c/d=", "toolu_mcp.linear.create_issue"])( + "makes %s match ^[a-zA-Z0-9_-]+$", + (id) => { + const result = sanitizeToolIdForStrictProvider(id) + + expect(result).toMatch(strictToolIdPattern) + expect(result).toHaveLength(id.length) + }, + ) + + it("leaves a valid id unchanged", () => { + expect(sanitizeToolIdForStrictProvider("toolu_01AbC-xyz_789")).toBe("toolu_01AbC-xyz_789") + }) +}) + describe("truncateOpenAiCallId", () => { describe("IDs within limit pass through unchanged", () => { it("should preserve short IDs", () => { @@ -192,13 +227,9 @@ describe("OPENAI_CALL_ID_MAX_LENGTH constant", () => { }) describe("sanitizeLiteLlmCallId", () => { - const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" - it("keeps an id that carries a thought signature intact, however long", () => { - const id = `call_864944__thought__${signature}` - - expect(id.length).toBeGreaterThan(OPENAI_CALL_ID_MAX_LENGTH) - expect(sanitizeLiteLlmCallId(id)).toBe(id) + expect(thoughtSignatureId.length).toBeGreaterThan(OPENAI_CALL_ID_MAX_LENGTH) + expect(sanitizeLiteLlmCallId(thoughtSignatureId)).toBe(thoughtSignatureId) }) it("sanitizes only the call id before the marker, leaving the Base64 signature intact", () => { @@ -216,3 +247,12 @@ describe("sanitizeLiteLlmCallId", () => { expect(sanitizeLiteLlmCallId("toolu_123")).toBe("toolu_123") }) }) + +describe("sanitizeOpenAiCallId with a thought signature", () => { + it("returns an id that OpenAI and Bedrock accept", () => { + const result = sanitizeOpenAiCallId(thoughtSignatureId) + + expect(result).toMatch(strictToolIdPattern) + expect(result).toHaveLength(OPENAI_CALL_ID_MAX_LENGTH) + }) +}) diff --git a/src/utils/tool-id.ts b/src/utils/tool-id.ts index c7f5c862fa..91b942f1b5 100644 --- a/src/utils/tool-id.ts +++ b/src/utils/tool-id.ts @@ -7,13 +7,32 @@ import * as crypto from "crypto" export const OPENAI_CALL_ID_MAX_LENGTH = 64 /** - * Sanitize a tool_use ID to match API validation pattern: ^[a-zA-Z0-9_-]+$ - * Replaces any invalid character with underscore. + * LiteLLM carries a Gemini thought signature inside the tool call id, as + * `__thought__`. Gemini rejects the next request if the + * signature changes, so the marker and everything after it must stay byte-for-byte intact. */ -export function sanitizeToolUseId(id: string): string { +export const THOUGHT_SIGNATURE_MARKER = "__thought__" + +/** + * Replace every character outside the Anthropic/Bedrock tool id pattern ^[a-zA-Z0-9_-]+$ + * with underscore. Use this only at a request boundary that enforces the pattern. + */ +export function sanitizeToolIdForStrictProvider(id: string): string { return id.replace(/[^a-zA-Z0-9_-]/g, "_") } +/** + * Sanitize a tool_use ID for the conversation history. Ids that carry a thought signature + * keep the signature unchanged; only the call id before the marker is sanitized. + */ +export function sanitizeToolUseId(id: string): string { + const markerIndex = id.indexOf(THOUGHT_SIGNATURE_MARKER) + if (markerIndex === -1) { + return sanitizeToolIdForStrictProvider(id) + } + return sanitizeToolIdForStrictProvider(id.slice(0, markerIndex)) + id.slice(markerIndex) +} + /** * Truncate a call_id to fit within OpenAI's 64-character limit. * Uses a hash suffix to maintain uniqueness when truncation is needed. @@ -50,30 +69,14 @@ export function truncateOpenAiCallId(id: string, maxLength: number = OPENAI_CALL * @returns The sanitized and truncated ID */ export function sanitizeOpenAiCallId(id: string, maxLength: number = OPENAI_CALL_ID_MAX_LENGTH): string { - // First sanitize characters, then truncate - const sanitized = sanitizeToolUseId(id) - return truncateOpenAiCallId(sanitized, maxLength) + return truncateOpenAiCallId(sanitizeToolIdForStrictProvider(id), maxLength) } /** - * LiteLLM carries a Gemini thought signature inside the tool call id, as - * `__thought__`. Truncating such an id corrupts the signature. - */ -export const LITELLM_THOUGHT_SIGNATURE_MARKER = "__thought__" - -/** - * Normalize a tool call id for LiteLLM. For ids that carry a thought signature only the - * call id before the marker is character-sanitized; the marker and the Base64 signature - * (which may contain `+`, `/` and `=`) pass through unchanged, because Gemini must receive - * the signature intact. Every other id gets the usual OpenAI 64-character treatment. - * - * @param id - The original call_id - * @returns The id to send to LiteLLM + * Normalize a tool call id for LiteLLM. Ids that carry a thought signature are never + * truncated, because Gemini must receive the signature intact. Every other id gets the + * usual OpenAI 64-character treatment. */ export function sanitizeLiteLlmCallId(id: string): string { - const markerIndex = id.indexOf(LITELLM_THOUGHT_SIGNATURE_MARKER) - if (markerIndex === -1) { - return sanitizeOpenAiCallId(id) - } - return sanitizeToolUseId(id.slice(0, markerIndex)) + id.slice(markerIndex) + return id.includes(THOUGHT_SIGNATURE_MARKER) ? sanitizeToolUseId(id) : sanitizeOpenAiCallId(id) } From b8448b25ad4313584fc0b97210cca6b48c5e5b9d Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Tue, 10 Nov 2026 18:48:58 -0500 Subject: [PATCH 3/6] fix(litellm): carry Gemini thought signatures in provider_specific_fields --- src/api/providers/__tests__/lite-llm.spec.ts | 350 +++++++++--------- src/api/providers/lite-llm.ts | 97 ++--- .../utils/__tests__/thought-signature.spec.ts | 135 +++++++ src/api/providers/utils/thought-signature.ts | 99 +++++ .../__tests__/anthropic-filter.spec.ts | 34 -- .../transform/__tests__/gemini-format.spec.ts | 19 +- src/api/transform/anthropic-filter.ts | 27 +- src/api/transform/gemini-format.ts | 18 +- .../__tests__/apiConversationHistory.spec.ts | 24 ++ src/core/task/apiConversationHistory.ts | 3 + src/eslint-suppressions.json | 4 +- src/test-utils/thought-signature.ts | 36 ++ src/utils/__tests__/tool-id.spec.ts | 74 +--- src/utils/tool-id.ts | 38 +- 14 files changed, 565 insertions(+), 393 deletions(-) create mode 100644 src/api/providers/utils/__tests__/thought-signature.spec.ts create mode 100644 src/api/providers/utils/thought-signature.ts create mode 100644 src/test-utils/thought-signature.ts diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index d3aff084f0..75f4c19193 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -1,10 +1,20 @@ import OpenAI from "openai" import { Anthropic } from "@anthropic-ai/sdk" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + import { LiteLLMHandler } from "../lite-llm" import { getModels } from "../fetchers/modelCache" +import { prepareApiConversationMessage } from "../../../core/task/apiConversationHistory" import { sanitizeToolUseId } from "../../../utils/tool-id" -import type { ApiHandlerCreateMessageMetadata } from "../../index" +import { + SANITIZED_LITELLM_TOOL_CALL_ID, + TEST_THOUGHT_SIGNATURE, + signedAssistantMessage, + sentToolCalls, + toolResultsMessage, +} from "../../../test-utils/thought-signature" +import { thoughtSignatureOrigin } from "../utils/thought-signature" import { ApiHandlerOptions } from "../../../shared/api" import { type ModelInfo, type ModelRecord, litellmDefaultModelId, litellmDefaultModelInfo } from "@roo-code/types" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" @@ -596,129 +606,6 @@ describe("LiteLLMHandler", () => { }) }) - describe("injectThoughtSignatureForGemini", () => { - // Base64 encoded "skip_thought_signature_validator" - const dummySignature = Buffer.from("skip_thought_signature_validator").toString("base64") - - it("should inject provider_specific_fields.thought_signature for assistant messages with tool_calls", () => { - const handler = new LiteLLMHandler(mockOptions) - const injectThoughtSignature = (handler as any).injectThoughtSignatureForGemini.bind(handler) - - const messages = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: "", - tool_calls: [ - { id: "call_123", type: "function", function: { name: "test_tool", arguments: "{}" } }, - ], - }, - { role: "tool", tool_call_id: "call_123", content: "result" }, - ] - - const result = injectThoughtSignature(messages) - - // The first tool call should have provider_specific_fields.thought_signature injected - expect(result[1].tool_calls[0].provider_specific_fields).toBeDefined() - expect(result[1].tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) - }) - - it("should not inject if assistant message has no tool_calls", () => { - const handler = new LiteLLMHandler(mockOptions) - const injectThoughtSignature = (handler as any).injectThoughtSignatureForGemini.bind(handler) - - const messages = [ - { role: "user", content: "Hello" }, - { role: "assistant", content: "Hi there!" }, - ] - - const result = injectThoughtSignature(messages) - - // No changes should be made - expect(result[1].tool_calls).toBeUndefined() - }) - - it("should always overwrite existing thought_signature", () => { - const handler = new LiteLLMHandler(mockOptions) - const injectThoughtSignature = (handler as any).injectThoughtSignatureForGemini.bind(handler) - - const existingSignature = "existing_signature_base64" - - const messages = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: "", - tool_calls: [ - { - id: "call_123", - type: "function", - function: { name: "test_tool", arguments: "{}" }, - provider_specific_fields: { thought_signature: existingSignature }, - }, - ], - }, - ] - - const result = injectThoughtSignature(messages) - - // Should overwrite with dummy signature (always inject to ensure compatibility) - expect(result[1].tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) - }) - - it("should inject signature into ALL tool calls for parallel calls", () => { - const handler = new LiteLLMHandler(mockOptions) - const injectThoughtSignature = (handler as any).injectThoughtSignatureForGemini.bind(handler) - - const messages = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: "", - tool_calls: [ - { id: "call_first", type: "function", function: { name: "tool1", arguments: "{}" } }, - { id: "call_second", type: "function", function: { name: "tool2", arguments: "{}" } }, - { id: "call_third", type: "function", function: { name: "tool3", arguments: "{}" } }, - ], - }, - ] - - const result = injectThoughtSignature(messages) - - // ALL tool calls should have the signature - expect(result[1].tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) - expect(result[1].tool_calls[1].provider_specific_fields.thought_signature).toBe(dummySignature) - expect(result[1].tool_calls[2].provider_specific_fields.thought_signature).toBe(dummySignature) - }) - - it("should preserve existing provider_specific_fields when adding thought_signature", () => { - const handler = new LiteLLMHandler(mockOptions) - const injectThoughtSignature = (handler as any).injectThoughtSignatureForGemini.bind(handler) - - const messages = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: "", - tool_calls: [ - { - id: "call_123", - type: "function", - function: { name: "test_tool", arguments: "{}" }, - provider_specific_fields: { other_field: "value" }, - }, - ], - }, - ] - - const result = injectThoughtSignature(messages) - - // Should have both existing field and new thought_signature - expect(result[1].tool_calls[0].provider_specific_fields.other_field).toBe("value") - expect(result[1].tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) - }) - }) - describe("createMessage integration with Gemini models", () => { // Base64 encoded "skip_thought_signature_validator" const dummySignature = Buffer.from("skip_thought_signature_validator").toString("base64") @@ -794,60 +681,187 @@ describe("LiteLLMHandler", () => { expect(assistantMessage.tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) }) - it.each([ - { path: "convertToOpenAiMessages", preserveReasoning: undefined }, - { path: "convertToR1Format", preserveReasoning: true }, - ])( - "should send tool call ids that carry a thought signature unchanged ($path)", - async ({ preserveReasoning }) => { - const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" - const toolCallId = `call_864944__thought__${signature}` - const historyId = sanitizeToolUseId(toolCallId) - expect(toolCallId.length).toBeGreaterThan(64) - - vi.spyOn(handler, "fetchModel").mockResolvedValue({ - id: "gemini-3-pro", - info: { ...litellmDefaultModelInfo, preserveReasoning }, - }) - const messages: Anthropic.Messages.MessageParam[] = [ - { role: "user", content: "Hello" }, - { - role: "assistant", - content: [ - { type: "tool_use", id: historyId, name: "read_file", input: { path: "test.txt" } }, - ], - }, + describe("real thought signature round trip", () => { + const origin = thoughtSignatureOrigin("http://localhost:4000", "gemini-3-pro") + const metadata = makeCreateMessageMetadata({ + tools: [ { - role: "user", - content: [{ type: "tool_result", tool_use_id: historyId, content: "file contents" }], + type: "function", + function: { name: "read_file", description: "Read a file", parameters: {} }, }, - ] + ], + }) + + function mockStream(chunks: unknown[]) { mockCreate.mockReturnValue({ - withResponse: vi.fn().mockResolvedValue({ - data: asyncStreamFrom([{ choices: [{ delta: { content: "ok" } }] }]), - }), + withResponse: vi.fn().mockResolvedValue({ data: asyncStreamFrom(chunks) }), + }) + } + + function useModel(id: string, preserveReasoning?: boolean) { + vi.spyOn(handler, "fetchModel").mockResolvedValue({ + id, + info: { ...litellmDefaultModelInfo, preserveReasoning }, }) - const metadata: ApiHandlerCreateMessageMetadata = { - taskId: "task-1", - tools: [ + } + + const signedToolCallStream = [ + { choices: [{ delta: { content: "Reading the file." } }] }, + { + choices: [ { - type: "function", - function: { name: "read_file", description: "Read a file", parameters: {} }, + delta: { + tool_calls: [ + { + index: 0, + id: `call_1__thought__${TEST_THOUGHT_SIGNATURE}`, + function: { name: "read_file", arguments: "" }, + provider_specific_fields: { thought_signature: TEST_THOUGHT_SIGNATURE }, + }, + ], + }, }, ], - } + }, + { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '{"path":' } }] } }] }, + { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '"a.ts"}' } }] } }] }, + { choices: [{ delta: {} }], usage: { prompt_tokens: 1, completion_tokens: 1 } }, + ] + + it("captures the signature from a streamed tool call and resets it per request", async () => { + useModel("gemini-3-pro") + mockStream(signedToolCallStream) - await collectStream(handler.createMessage("You are a helpful assistant", messages, metadata)) + await collectStream(handler.createMessage("system", [{ role: "user", content: "Hi" }], metadata)) + expect(handler.getThoughtSignature()).toBe(TEST_THOUGHT_SIGNATURE) + expect(handler.getThoughtSignatureOrigin()).toBe(origin) - const sent: OpenAI.Chat.ChatCompletionMessageParam[] = mockCreate.mock.calls[0][0].messages - const assistantMessage = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) - const toolMessage = sent.find((msg) => msg.role === "tool") - expect(assistantMessage?.role === "assistant" && assistantMessage.tool_calls?.[0].id).toBe( - toolCallId, + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + await collectStream(handler.createMessage("system", [{ role: "user", content: "Hi" }], metadata)) + expect(handler.getThoughtSignature()).toBeUndefined() + }) + + it("stores the streamed signature in the history and sends it on the next request", async () => { + useModel("gemini-4-pro") + mockStream(signedToolCallStream) + await collectStream(handler.createMessage("system", [{ role: "user", content: "Hi" }], metadata)) + + const historyId = sanitizeToolUseId(`call_1__thought__${TEST_THOUGHT_SIGNATURE}`) + const assistantMessage = prepareApiConversationMessage({ + message: { + role: "assistant", + content: [{ type: "tool_use", id: historyId, name: "read_file", input: { path: "a.ts" } }], + }, + api: handler, + apiConfiguration: { apiProvider: providerIdentifiers.litellm, litellmModelId: "gemini-4-pro" }, + apiConversationHistory: [], + }) + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + await collectStream( + handler.createMessage( + "system", + [{ role: "user", content: "Hi" }, assistantMessage, toolResultsMessage([historyId])], + metadata, + ), ) - expect(toolMessage?.role === "tool" && toolMessage.tool_call_id).toBe(toolCallId) - }, - ) + + expect(sentToolCalls(mockCreate)).toEqual([ + expect.objectContaining({ + provider_specific_fields: { thought_signature: TEST_THOUGHT_SIGNATURE }, + }), + ]) + }) + + const bypassed = expect.objectContaining({ + provider_specific_fields: { thought_signature: dummySignature }, + }) + const untouched = expect.not.objectContaining({ provider_specific_fields: expect.anything() }) + const real = expect.objectContaining({ + provider_specific_fields: { thought_signature: TEST_THOUGHT_SIGNATURE }, + }) + + it.each([ + { + modelId: "gemini-3-pro", + preserveReasoning: undefined, + storedBy: "this backend", + storedOrigin: origin, + expected: [real, bypassed], + }, + { + modelId: "gemini-3-pro", + preserveReasoning: true, + storedBy: "this backend", + storedOrigin: origin, + expected: [real, bypassed], + }, + { + modelId: "gemini-4-pro", + preserveReasoning: undefined, + storedBy: "this backend", + storedOrigin: thoughtSignatureOrigin("http://localhost:4000/", "gemini-4-pro"), + expected: [real, untouched], + }, + { + modelId: "gemini-3-pro", + preserveReasoning: undefined, + storedBy: "another backend", + storedOrigin: "another-backend", + expected: [bypassed, bypassed], + }, + { + modelId: "gpt-4", + preserveReasoning: undefined, + storedBy: "another backend", + storedOrigin: "another-backend", + expected: [untouched, untouched], + }, + ])( + "writes signatures for $modelId with a signature from $storedBy (preserveReasoning=$preserveReasoning)", + async ({ modelId, preserveReasoning, storedOrigin, expected }) => { + useModel(modelId, preserveReasoning) + const historyIds = ["call_1", "call_2"] + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + + await collectStream( + handler.createMessage( + "system", + [ + { role: "user", content: "Hello" }, + signedAssistantMessage(historyIds, { origin: storedOrigin }), + toolResultsMessage(historyIds), + ], + metadata, + ), + ) + + expect(sentToolCalls(mockCreate)).toEqual(expected) + }, + ) + + it("sends the bypass for a sanitized __thought__ id on an alias that isGeminiModel does not match", async () => { + useModel("my-gateway-model") + const historyId = SANITIZED_LITELLM_TOOL_CALL_ID + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + + await collectStream( + handler.createMessage( + "system", + [ + { role: "user", content: "Hello" }, + { + role: "assistant", + content: [{ type: "tool_use", id: historyId, name: "read_file", input: {} }], + }, + toolResultsMessage([historyId]), + ], + metadata, + ), + ) + + expect(sentToolCalls(mockCreate)).toEqual([bypassed]) + }) + }) it("should not inject thought signatures for non-Gemini models", async () => { const optionsWithGPT4: ApiHandlerOptions = { diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index 716cd1e31d..17c6e84bfc 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -18,7 +18,13 @@ import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" import { convertToOpenAiMessages } from "../transform/openai-format" import { convertToR1Format } from "../transform/r1-format" import { GEMINI_THOUGHT_SIGNATURE_BYPASS } from "../transform/gemini-format" -import { sanitizeLiteLlmCallId } from "../../utils/tool-id" +import { sanitizeOpenAiCallId } from "../../utils/tool-id" +import { + LITELLM_THOUGHT_SIGNATURE_ID_MARKER, + applyThoughtSignatures, + readThoughtSignature, + thoughtSignatureOrigin, +} from "./utils/thought-signature" import type { SingleCompletionHandler, @@ -41,6 +47,8 @@ import { import { RequestConfigBuilder } from "./config-builder/request-config-builder" import { createTimeoutError, getRequestTimeoutMs } from "./utils/request-timeout" +const LITELLM_DEFAULT_BASE_URL = "http://localhost:4000" + /** * LiteLLM provider handler * @@ -48,11 +56,14 @@ import { createTimeoutError, getRequestTimeoutMs } from "./utils/request-timeout * It follows the OpenAI API format for compatibility. */ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHandler { + private lastThoughtSignature: string | undefined + private thoughtSignatureOrigin: string | undefined + constructor(options: ApiHandlerOptions) { super({ options, name: providerIdentifiers.litellm, - baseURL: `${options.litellmBaseUrl || "http://localhost:4000"}`, + baseURL: options.litellmBaseUrl || LITELLM_DEFAULT_BASE_URL, apiKey: options.litellmApiKey || "dummy-key", modelId: options.litellmModelId, defaultModelId: litellmDefaultModelId, @@ -124,50 +135,6 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa ) } - /** - * Inject thought signatures for Gemini models via provider_specific_fields. - * This is required when switching from other models to Gemini to satisfy API validation - * for function calls that weren't generated by Gemini (and thus lack thought signatures). - * - * Per LiteLLM documentation: - * - Thought signatures are stored in provider_specific_fields.thought_signature of tool calls - * - The bypass token (GEMINI_THOUGHT_SIGNATURE_BYPASS) skips signature validation - * - * We inject the dummy signature on EVERY tool call unconditionally to ensure Gemini - * doesn't complain about missing/corrupted signatures when conversation history - * contains tool calls from other models (like Claude). - */ - private injectThoughtSignatureForGemini( - openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[], - ): OpenAI.Chat.ChatCompletionMessageParam[] { - const dummySignature = GEMINI_THOUGHT_SIGNATURE_BYPASS - - return openAiMessages.map((msg) => { - if (msg.role === "assistant") { - const toolCalls = (msg as any).tool_calls as any[] | undefined - - // Only process if there are tool calls - if (toolCalls && toolCalls.length > 0) { - // Inject dummy signature into ALL tool calls' provider_specific_fields - // This ensures Gemini doesn't reject tool calls from other models - const updatedToolCalls = toolCalls.map((tc) => ({ - ...tc, - provider_specific_fields: { - ...(tc.provider_specific_fields || {}), - thought_signature: dummySignature, - }, - })) - - return { - ...msg, - tool_calls: updatedToolCalls, - } - } - } - return msg - }) - } - override async *createMessage( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], @@ -177,6 +144,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // already-aborted request fails with AbortError before provider model // discovery (getModels/refreshModels) begins. throwIfAborted(metadata?.abortSignal) + this.lastThoughtSignature = undefined // Model discovery is shared single-flight (RouterProvider.fetchModel): // concurrent callers join one in-flight fetch, so the fetch itself @@ -208,11 +176,11 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // never gets inserted mid-turn and causes the model to drop prior reasoning_content. const openAiMessages = info.preserveReasoning ? convertToR1Format(messages, { - normalizeToolCallId: sanitizeLiteLlmCallId, + normalizeToolCallId: sanitizeOpenAiCallId, mergeToolResultText: true, }) : convertToOpenAiMessages(messages, { - normalizeToolCallId: sanitizeLiteLlmCallId, + normalizeToolCallId: sanitizeOpenAiCallId, }) // Prepare messages with cache control if enabled and supported @@ -285,16 +253,22 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa const usesMaxCompletionTokens = this.isGpt5(modelId) || info.requiresResponsesApi const reasoningEffort = this.getReasoningEffort(info) - // For Gemini models with native protocol: inject fake reasoning.encrypted block for tool calls - // This is required when switching from other models to Gemini to satisfy API validation. - // Gemini 3 models validate thought signatures for function calls, and when conversation - // history contains tool calls from other models (like Claude), they lack the required - // signatures. The "skip_thought_signature_validator" value bypasses this validation. + // Gemini validates thought signatures on function calls. A tool call without a signature + // from this backend gets the bypass token: calls from other models (like Claude) for + // Gemini models, and `__thought__` ids whose embedded signature the history sanitized. const isGemini = this.isGeminiModel(modelId) - let processedMessages = enhancedMessages - if (isGemini) { - processedMessages = this.injectThoughtSignatureForGemini(enhancedMessages) - } + this.thoughtSignatureOrigin = thoughtSignatureOrigin( + this.options.litellmBaseUrl || LITELLM_DEFAULT_BASE_URL, + modelId, + ) + const processedMessages = applyThoughtSignatures(messages, enhancedMessages, { + origin: this.thoughtSignatureOrigin, + normalizeToolCallId: sanitizeOpenAiCallId, + fallback: (toolCallId) => + isGemini || toolCallId.includes(LITELLM_THOUGHT_SIGNATURE_ID_MARKER) + ? GEMINI_THOUGHT_SIGNATURE_BYPASS + : undefined, + }) const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { model: modelId, @@ -373,6 +347,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // Handle tool calls in stream - emit partial chunks for NativeToolCallParser if (delta?.tool_calls) { + this.lastThoughtSignature ??= readThoughtSignature(delta.tool_calls) for (const toolCall of delta.tool_calls) { throwIfAborted(requestSignal) yield { @@ -441,6 +416,14 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa } } + getThoughtSignature(): string | undefined { + return this.lastThoughtSignature + } + + getThoughtSignatureOrigin(): string | undefined { + return this.lastThoughtSignature ? this.thoughtSignatureOrigin : undefined + } + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { // Fast-fail if the request was already aborted before building, so an // already-aborted request fails with AbortError before provider model diff --git a/src/api/providers/utils/__tests__/thought-signature.spec.ts b/src/api/providers/utils/__tests__/thought-signature.spec.ts new file mode 100644 index 0000000000..f6ec6f89cf --- /dev/null +++ b/src/api/providers/utils/__tests__/thought-signature.spec.ts @@ -0,0 +1,135 @@ +import OpenAI from "openai" + +import { sanitizeOpenAiCallId } from "../../../../utils/tool-id" +import { signedAssistantMessage, TEST_THOUGHT_SIGNATURE as signature } from "../../../../test-utils/thought-signature" +import { applyThoughtSignatures, readThoughtSignature, thoughtSignatureOrigin } from "../thought-signature" + +const origin = "litellm|http://localhost:4000|gemini-3-pro" +const bypass = "bypass" + +function toolCall(id: string): OpenAI.Chat.ChatCompletionMessageFunctionToolCall { + return { id, type: "function", function: { name: "read_file", arguments: "{}" } } +} + +function signed(id: string, value: string) { + return { ...toolCall(id), provider_specific_fields: { thought_signature: value } } +} + +function assistantWith(...ids: string[]): OpenAI.Chat.ChatCompletionMessageParam { + return { role: "assistant", content: null, tool_calls: ids.map(toolCall) } +} + +describe("readThoughtSignature", () => { + it("returns the first signature in provider_specific_fields", () => { + const toolCalls = [ + { index: 0, provider_specific_fields: {} }, + { index: 1, provider_specific_fields: { thought_signature: signature } }, + { index: 2, provider_specific_fields: { thought_signature: "later" } }, + ] + + expect(readThoughtSignature(toolCalls)).toBe(signature) + }) + + it.each([ + ["no tool calls", undefined], + ["null tool calls", null], + ["no provider_specific_fields", [{ index: 0 }]], + ["an empty signature", [{ index: 0, provider_specific_fields: { thought_signature: "" } }]], + ["a non-string signature", [{ index: 0, provider_specific_fields: { thought_signature: 42 } }]], + ])("returns undefined for %s", (_case, toolCalls) => { + expect(readThoughtSignature(toolCalls)).toBeUndefined() + }) +}) + +describe("thoughtSignatureOrigin", () => { + const origin = thoughtSignatureOrigin("http://localhost:4000", "gemini-3-pro") + + it("ignores a trailing slash on the base URL", () => { + expect(thoughtSignatureOrigin("http://localhost:4000/", "gemini-3-pro")).toBe(origin) + }) + + it.each([ + ["model", "http://localhost:4000", "gemini-3-pro-preview"], + ["base URL", "http://other:4000", "gemini-3-pro"], + ])("differs for another %s", (_case, baseUrl, modelId) => { + expect(thoughtSignatureOrigin(baseUrl, modelId)).not.toBe(origin) + }) + + it("does not contain the base URL", () => { + expect(origin).toMatch(/^[0-9a-f]{16}$/) + }) +}) + +describe("applyThoughtSignatures", () => { + it("puts a stored signature with the same origin on the first tool call of its message", () => { + const history = [signedAssistantMessage(["call_1", "call_2"], { origin })] + + const result = applyThoughtSignatures(history, [assistantWith("call_1", "call_2")], { origin }) + + expect(result).toEqual([ + { role: "assistant", content: null, tool_calls: [signed("call_1", signature), toolCall("call_2")] }, + ]) + }) + + it("sends each signed turn its own signature", () => { + const history = [ + signedAssistantMessage(["call_1"], { origin, signature: "first" }), + signedAssistantMessage(["call_2"], { origin, signature: "second" }), + ] + + const result = applyThoughtSignatures(history, [assistantWith("call_1"), assistantWith("call_2")], { origin }) + + expect(result).toEqual([ + { role: "assistant", content: null, tool_calls: [signed("call_1", "first")] }, + { role: "assistant", content: null, tool_calls: [signed("call_2", "second")] }, + ]) + }) + + it.each([ + ["another backend", "litellm|http://other:4000|gemini-3-pro"], + ["native Gemini (no origin)", undefined], + ["an origin that is a prefix of this one", "litellm|http://localhost:4000|gemini-3"], + ["an origin that extends this one", "litellm|http://localhost:4000|gemini-3-pro-preview"], + ])("does not send a signature minted by %s", (_case, storedOrigin) => { + const history = [signedAssistantMessage(["call_1"], { origin: storedOrigin })] + const fallback = vi.fn(() => bypass) + + const result = applyThoughtSignatures(history, [assistantWith("call_1")], { origin, fallback }) + + expect(result).toEqual([{ role: "assistant", content: null, tool_calls: [signed("call_1", bypass)] }]) + expect(fallback).toHaveBeenCalledWith("call_1") + }) + + it("matches tool calls by the normalized id", () => { + const longId = "call_" + "x".repeat(100) + const history = [signedAssistantMessage([longId], { origin })] + + const result = applyThoughtSignatures(history, [assistantWith(sanitizeOpenAiCallId(longId))], { + origin, + normalizeToolCallId: sanitizeOpenAiCallId, + }) + + expect(result).toEqual([ + { role: "assistant", content: null, tool_calls: [signed(sanitizeOpenAiCallId(longId), signature)] }, + ]) + }) + + it("uses the fallback for every tool call without a stored signature", () => { + const fallback = (id: string) => (id === "call_2" ? bypass : undefined) + + const result = applyThoughtSignatures([], [assistantWith("call_1", "call_2")], { origin, fallback }) + + expect(result).toEqual([ + { role: "assistant", content: null, tool_calls: [toolCall("call_1"), signed("call_2", bypass)] }, + ]) + }) + + it("leaves messages without tool calls unchanged", () => { + const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + ] + + expect(applyThoughtSignatures([], messages, { origin, fallback: () => bypass })).toEqual(messages) + }) +}) diff --git a/src/api/providers/utils/thought-signature.ts b/src/api/providers/utils/thought-signature.ts new file mode 100644 index 0000000000..3b84ab0a84 --- /dev/null +++ b/src/api/providers/utils/thought-signature.ts @@ -0,0 +1,99 @@ +import { createHash } from "crypto" + +import type { Anthropic } from "@anthropic-ai/sdk" +import type OpenAI from "openai" + +import { type ExtendedContentBlockParam, isThoughtSignatureContentBlock } from "../../transform/gemini-format" + +/** LiteLLM embeds a Gemini thought signature in the tool call id after this marker. */ +export const LITELLM_THOUGHT_SIGNATURE_ID_MARKER = "__thought__" + +/** + * Name the backend that minted a signature, so it is sent back only to that backend. The hash + * keeps the endpoint URL out of the task history and the diagnostics export. + */ +export function thoughtSignatureOrigin(baseUrl: string, modelId: string): string { + const endpoint = baseUrl.replace(/\/+$/, "") + return createHash("sha256").update(`${endpoint}|${modelId}`).digest("hex").slice(0, 16) +} + +function signatureOf(toolCall: unknown): string | undefined { + const fields = (toolCall as { provider_specific_fields?: { thought_signature?: unknown } } | undefined) + ?.provider_specific_fields + return typeof fields?.thought_signature === "string" && fields.thought_signature.length > 0 + ? fields.thought_signature + : undefined +} + +/** + * Read the thought signature from `provider_specific_fields` of tool calls, the slot that + * LiteLLM fills for Gemini. LiteLLM also embeds it in the tool call id, but the history + * sanitizes ids, so the id copy does not survive. + */ +export function readThoughtSignature(toolCalls: readonly unknown[] | null | undefined): string | undefined { + return toolCalls?.map(signatureOf).find((signature) => signature !== undefined) +} + +function collectThoughtSignatures( + history: Anthropic.Messages.MessageParam[], + origin: string, + normalizeToolCallId: (id: string) => string, +): Map { + const signatureByToolCallId = new Map() + for (const message of history) { + if (message.role !== "assistant" || !Array.isArray(message.content)) { + continue + } + let signature: string | undefined + let firstToolUseId: string | undefined + const blocks: readonly ExtendedContentBlockParam[] = message.content + for (const block of blocks) { + if (isThoughtSignatureContentBlock(block)) { + signature = block.origin === origin ? block.thoughtSignature : undefined + } else if (block.type === "tool_use") { + firstToolUseId ??= block.id + } + } + if (signature && firstToolUseId) { + signatureByToolCallId.set(normalizeToolCallId(firstToolUseId), signature) + } + } + return signatureByToolCallId +} + +interface ApplyThoughtSignaturesOptions { + /** Only signatures stored with this origin are sent back. */ + origin: string + /** The same id normalizer the caller used to build the OpenAI messages. */ + normalizeToolCallId?: (id: string) => string + /** Signature for a tool call without a stored one, for example the Gemini bypass token. */ + fallback?: (toolCallId: string) => string | undefined +} + +/** + * Write `provider_specific_fields.thought_signature` on assistant tool calls, where LiteLLM + * reads it before the id. A stored signature goes on the first tool call of its message, + * because Gemini signs only the first call of a parallel set. + */ +export function applyThoughtSignatures( + history: Anthropic.Messages.MessageParam[], + openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[], + { origin, normalizeToolCallId = (id) => id, fallback }: ApplyThoughtSignaturesOptions, +): OpenAI.Chat.ChatCompletionMessageParam[] { + const storedSignatures = collectThoughtSignatures(history, origin, normalizeToolCallId) + + return openAiMessages.map((message) => { + if (message.role !== "assistant" || !message.tool_calls?.length) { + return message + } + return { + ...message, + tool_calls: message.tool_calls.map((toolCall) => { + const signature = storedSignatures.get(toolCall.id) ?? fallback?.(toolCall.id) + return signature + ? { ...toolCall, provider_specific_fields: { thought_signature: signature } } + : toolCall + }), + } + }) +} diff --git a/src/api/transform/__tests__/anthropic-filter.spec.ts b/src/api/transform/__tests__/anthropic-filter.spec.ts index cab2cbc01d..46ad1a1952 100644 --- a/src/api/transform/__tests__/anthropic-filter.spec.ts +++ b/src/api/transform/__tests__/anthropic-filter.spec.ts @@ -140,39 +140,5 @@ describe("anthropic-filter", () => { expect(result).toHaveLength(1) expect(result[0].content).toEqual([{ type: "text", text: "Valid text" }]) }) - - it("makes tool ids from a thought-signature history match Anthropic's id pattern", () => { - const historyId = "call_864944__thought__ab+c/d==" - const messages: Anthropic.Messages.MessageParam[] = [ - { - role: "assistant", - content: [{ type: "tool_use", id: historyId, name: "read_file", input: {} }], - }, - { - role: "user", - content: [{ type: "tool_result", tool_use_id: historyId, content: "ok" }], - }, - ] - - const result = filterNonAnthropicBlocks(messages) - - expect(result[0].content).toEqual([ - { type: "tool_use", id: "call_864944__thought__ab_c_d__", name: "read_file", input: {} }, - ]) - expect(result[1].content).toEqual([ - { type: "tool_result", tool_use_id: "call_864944__thought__ab_c_d__", content: "ok" }, - ]) - }) - - it("leaves valid tool ids unchanged", () => { - const messages: Anthropic.Messages.MessageParam[] = [ - { - role: "assistant", - content: [{ type: "tool_use", id: "toolu_01AbC-xyz", name: "read_file", input: {} }], - }, - ] - - expect(filterNonAnthropicBlocks(messages)).toEqual(messages) - }) }) }) diff --git a/src/api/transform/__tests__/gemini-format.spec.ts b/src/api/transform/__tests__/gemini-format.spec.ts index 407984956a..a15287e815 100644 --- a/src/api/transform/__tests__/gemini-format.spec.ts +++ b/src/api/transform/__tests__/gemini-format.spec.ts @@ -2,7 +2,8 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { convertAnthropicMessageToGemini } from "../gemini-format" +import { signedAssistantMessage } from "../../../test-utils/thought-signature" +import { GEMINI_THOUGHT_SIGNATURE_BYPASS, convertAnthropicMessageToGemini } from "../gemini-format" describe("convertAnthropicMessageToGemini", () => { it("should convert a simple text message", () => { @@ -166,6 +167,22 @@ describe("convertAnthropicMessageToGemini", () => { expect(functionCallParts[1].thoughtSignature).toBeUndefined() }) + it("should send the bypass instead of a signature that another backend minted", () => { + const result = convertAnthropicMessageToGemini( + signedAssistantMessage(["call-1"], { + signature: "sig-123", + origin: "litellm|http://localhost:4000|gemini-3-pro", + }), + ) + + expect(result[0]?.parts).toEqual([ + expect.objectContaining({ + functionCall: expect.anything(), + thoughtSignature: GEMINI_THOUGHT_SIGNATURE_BYPASS, + }), + ]) + }) + it("should convert a message with tool result as string", () => { const toolIdToName = new Map() toolIdToName.set("calculator-123", "calculator") diff --git a/src/api/transform/anthropic-filter.ts b/src/api/transform/anthropic-filter.ts index 429939abd2..2bfc6dccfd 100644 --- a/src/api/transform/anthropic-filter.ts +++ b/src/api/transform/anthropic-filter.ts @@ -1,7 +1,5 @@ import { Anthropic } from "@anthropic-ai/sdk" -import { sanitizeToolIdForStrictProvider } from "../../utils/tool-id" - /** * Set of content block types that are valid for Anthropic API. * Only these types will be passed through to the API. @@ -24,9 +22,6 @@ export const VALID_ANTHROPIC_BLOCK_TYPES = new Set([ * - Internal "reasoning" blocks (Roo Code's internal representation) * - Gemini's "thoughtSignature" blocks (encrypted reasoning continuity tokens) * - Any other unknown block types - * - * It also makes tool ids match Anthropic's ^[a-zA-Z0-9_-]+$ pattern. The history keeps - * thought-signature ids from other providers unchanged, and those can contain `+`, `/` and `=`. */ export function filterNonAnthropicBlocks( messages: Anthropic.Messages.MessageParam[], @@ -37,13 +32,11 @@ export function filterNonAnthropicBlocks( return message } - const filteredContent = message.content - .filter((block) => { - const blockType = (block as { type: string }).type - // Only keep block types that Anthropic recognizes - return VALID_ANTHROPIC_BLOCK_TYPES.has(blockType) - }) - .map(withStrictToolId) + const filteredContent = message.content.filter((block) => { + const blockType = (block as { type: string }).type + // Only keep block types that Anthropic recognizes + return VALID_ANTHROPIC_BLOCK_TYPES.has(blockType) + }) // If all content was filtered out, return undefined to filter the message later if (filteredContent.length === 0) { @@ -57,13 +50,3 @@ export function filterNonAnthropicBlocks( }) .filter((message): message is Anthropic.Messages.MessageParam => message !== undefined) } - -function withStrictToolId(block: T): T { - if (block.type === "tool_use") { - return { ...block, id: sanitizeToolIdForStrictProvider(block.id) } - } - if (block.type === "tool_result") { - return { ...block, tool_use_id: sanitizeToolIdForStrictProvider(block.tool_use_id) } - } - return block -} diff --git a/src/api/transform/gemini-format.ts b/src/api/transform/gemini-format.ts index d45e9f27ec..7d88d26aa3 100644 --- a/src/api/transform/gemini-format.ts +++ b/src/api/transform/gemini-format.ts @@ -6,9 +6,14 @@ import { Content, Part } from "@google/genai" // This bypass token tells Gemini to skip signature validation for cross-model history entries. export const GEMINI_THOUGHT_SIGNATURE_BYPASS = Buffer.from("skip_thought_signature_validator").toString("base64") -type ThoughtSignatureContentBlock = { +export type ThoughtSignatureContentBlock = { type: "thoughtSignature" thoughtSignature?: string + /** + * Backend that minted the signature, set by handlers that are not native Gemini. + * A signature validates only on the backend that minted it. + */ + origin?: string } type ReasoningContentBlock = { @@ -16,7 +21,8 @@ type ReasoningContentBlock = { text: string } -type ExtendedContentBlockParam = Anthropic.ContentBlockParam | ThoughtSignatureContentBlock | ReasoningContentBlock +export type ExtendedContentBlockParam = + Anthropic.ContentBlockParam | ThoughtSignatureContentBlock | ReasoningContentBlock type ExtendedAnthropicContent = string | ExtendedContentBlockParam[] // Extension type to safely add thoughtSignature to Part @@ -24,7 +30,9 @@ type PartWithThoughtSignature = Part & { thoughtSignature?: string } -function isThoughtSignatureContentBlock(block: ExtendedContentBlockParam): block is ThoughtSignatureContentBlock { +export function isThoughtSignatureContentBlock( + block: ExtendedContentBlockParam, +): block is ThoughtSignatureContentBlock { return block.type === "thoughtSignature" } @@ -38,7 +46,9 @@ export function convertAnthropicContentToGemini( // First pass: find thoughtSignature if it exists in the content blocks let activeThoughtSignature: string | undefined if (Array.isArray(content)) { - const sigBlock = content.find((block) => isThoughtSignatureContentBlock(block)) as ThoughtSignatureContentBlock + const sigBlock = content.find( + (block) => isThoughtSignatureContentBlock(block) && block.origin === undefined, + ) as ThoughtSignatureContentBlock if (sigBlock?.thoughtSignature) { activeThoughtSignature = sigBlock.thoughtSignature } diff --git a/src/core/task/__tests__/apiConversationHistory.spec.ts b/src/core/task/__tests__/apiConversationHistory.spec.ts index 7a1ef2adeb..5e737c4ef1 100644 --- a/src/core/task/__tests__/apiConversationHistory.spec.ts +++ b/src/core/task/__tests__/apiConversationHistory.spec.ts @@ -137,6 +137,30 @@ describe("prepareApiConversationMessage", () => { ]) }) + it("stores the origin of a thought signature when the handler reports one", () => { + const api = { + getThoughtSignature: () => "signature-1", + getThoughtSignatureOrigin: () => "litellm|http://localhost:4000|gemini-3-pro", + } + + const result = prepareApiConversationMessage({ + message: { role: "assistant", content: "answer" }, + // prepareApiConversationMessage reads only the thought signature hooks of the handler. + api: api as unknown as ApiHandler, + apiConfiguration: { apiProvider: providerIdentifiers.litellm, litellmModelId: "gemini-3-pro" }, + apiConversationHistory: [], + }) + + expect(result.content).toEqual([ + { type: "text", text: "answer" }, + { + type: "thoughtSignature", + thoughtSignature: "signature-1", + origin: "litellm|http://localhost:4000|gemini-3-pro", + }, + ]) + }) + it("validates user tool_result blocks against the last effective assistant message", () => { const result = prepareApiConversationMessage({ message: { diff --git a/src/core/task/apiConversationHistory.ts b/src/core/task/apiConversationHistory.ts index c75fb4f1c5..cb358949f5 100644 --- a/src/core/task/apiConversationHistory.ts +++ b/src/core/task/apiConversationHistory.ts @@ -12,6 +12,7 @@ type ApiHistoryHandler = ApiHandler & { getResponseId?: () => string | undefined getEncryptedContent?: () => { encrypted_content: string; id?: string } | undefined getThoughtSignature?: () => string | undefined + getThoughtSignatureOrigin?: () => string | undefined getReasoningDetails?: () => any[] | undefined } @@ -46,6 +47,7 @@ function prepareAssistantMessage( const responseId = handler.getResponseId?.() const reasoningData = handler.getEncryptedContent?.() const thoughtSignature = handler.getThoughtSignature?.() + const thoughtSignatureOrigin = handler.getThoughtSignatureOrigin?.() const reasoningDetails = handler.getReasoningDetails?.() const modelId = getModelId(apiConfiguration) @@ -107,6 +109,7 @@ function prepareAssistantMessage( const thoughtSignatureBlock = { type: "thoughtSignature", thoughtSignature, + ...(thoughtSignatureOrigin ? { origin: thoughtSignatureOrigin } : {}), } appendContentBlock(messageWithTs, thoughtSignatureBlock) diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index 4e010d814f..3cab377fcb 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -81,7 +81,7 @@ }, "api/providers/__tests__/lite-llm.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 36 + "count": 31 } }, "api/providers/__tests__/mimo.spec.ts": { @@ -276,7 +276,7 @@ }, "api/providers/lite-llm.ts": { "@typescript-eslint/no-explicit-any": { - "count": 8 + "count": 6 } }, "api/providers/mimo.ts": { diff --git a/src/test-utils/thought-signature.ts b/src/test-utils/thought-signature.ts new file mode 100644 index 0000000000..9eb048fa1d --- /dev/null +++ b/src/test-utils/thought-signature.ts @@ -0,0 +1,36 @@ +import type { Anthropic } from "@anthropic-ai/sdk" +import type OpenAI from "openai" +import type { Mock } from "vitest" + +import type { ExtendedContentBlockParam } from "../api/transform/gemini-format" + +export const TEST_THOUGHT_SIGNATURE = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" + +/** A LiteLLM `__thought__` id after the history sanitizer changed `+`, `/` and `=` to `_`. */ +export const SANITIZED_LITELLM_TOOL_CALL_ID = + "call_1__thought__AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i_aDwY5o_0" + +export function signedAssistantMessage( + toolUseIds: string[], + { signature = TEST_THOUGHT_SIGNATURE, origin }: { signature?: string; origin?: string } = {}, +): Anthropic.Messages.MessageParam { + const content: ExtendedContentBlockParam[] = [ + ...toolUseIds.map((id) => ({ type: "tool_use" as const, id, name: "read_file", input: {} })), + { type: "thoughtSignature", thoughtSignature: signature, ...(origin ? { origin } : {}) }, + ] + // The history stores the non-Anthropic thoughtSignature block next to the tool_use blocks. + return { role: "assistant", content: content as Anthropic.Messages.ContentBlockParam[] } +} + +export function toolResultsMessage(toolUseIds: string[]): Anthropic.Messages.MessageParam { + return { + role: "user", + content: toolUseIds.map((id) => ({ type: "tool_result", tool_use_id: id, content: "ok" })), + } +} + +export function sentToolCalls(create: Mock): OpenAI.Chat.ChatCompletionMessageToolCall[] | undefined { + const sent: OpenAI.Chat.ChatCompletionMessageParam[] = create.mock.calls.at(-1)?.[0].messages + const assistant = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) + return assistant?.role === "assistant" ? assistant.tool_calls : undefined +} diff --git a/src/utils/__tests__/tool-id.spec.ts b/src/utils/__tests__/tool-id.spec.ts index ba3bb0fae7..2459786cea 100644 --- a/src/utils/__tests__/tool-id.spec.ts +++ b/src/utils/__tests__/tool-id.spec.ts @@ -1,15 +1,4 @@ -import { - sanitizeToolUseId, - truncateOpenAiCallId, - sanitizeOpenAiCallId, - sanitizeLiteLlmCallId, - sanitizeToolIdForStrictProvider, - OPENAI_CALL_ID_MAX_LENGTH, -} from "../tool-id" - -const signature = "AY89a18ErUKBAfkTYnDbzq6mGnRG5QS8VFogncpDzYVXzC0i+aDwY5o/0123456789abcdef==" -const thoughtSignatureId = `call_864944__thought__${signature}` -const strictToolIdPattern = /^[a-zA-Z0-9_-]+$/ +import { sanitizeToolUseId, truncateOpenAiCallId, sanitizeOpenAiCallId, OPENAI_CALL_ID_MAX_LENGTH } from "../tool-id" describe("sanitizeToolUseId", () => { describe("valid IDs pass through unchanged", () => { @@ -89,36 +78,6 @@ describe("sanitizeToolUseId", () => { }) }) -describe("sanitizeToolUseId with a thought signature", () => { - it("keeps the marker and the Base64 signature unchanged", () => { - expect(sanitizeToolUseId(thoughtSignatureId)).toBe(thoughtSignatureId) - }) - - it("sanitizes only the call id before the marker", () => { - expect(sanitizeToolUseId("call.1:x__thought__ab+c/d=")).toBe("call_1_x__thought__ab+c/d=") - }) - - it("still replaces + / = in ids without the marker", () => { - expect(sanitizeToolUseId("call_ab+c/d=")).toBe("call_ab_c_d_") - }) -}) - -describe("sanitizeToolIdForStrictProvider", () => { - it.each([thoughtSignatureId, "call.1:x__thought__ab+c/d=", "toolu_mcp.linear.create_issue"])( - "makes %s match ^[a-zA-Z0-9_-]+$", - (id) => { - const result = sanitizeToolIdForStrictProvider(id) - - expect(result).toMatch(strictToolIdPattern) - expect(result).toHaveLength(id.length) - }, - ) - - it("leaves a valid id unchanged", () => { - expect(sanitizeToolIdForStrictProvider("toolu_01AbC-xyz_789")).toBe("toolu_01AbC-xyz_789") - }) -}) - describe("truncateOpenAiCallId", () => { describe("IDs within limit pass through unchanged", () => { it("should preserve short IDs", () => { @@ -225,34 +184,3 @@ describe("OPENAI_CALL_ID_MAX_LENGTH constant", () => { expect(OPENAI_CALL_ID_MAX_LENGTH).toBe(64) }) }) - -describe("sanitizeLiteLlmCallId", () => { - it("keeps an id that carries a thought signature intact, however long", () => { - expect(thoughtSignatureId.length).toBeGreaterThan(OPENAI_CALL_ID_MAX_LENGTH) - expect(sanitizeLiteLlmCallId(thoughtSignatureId)).toBe(thoughtSignatureId) - }) - - it("sanitizes only the call id before the marker, leaving the Base64 signature intact", () => { - expect(sanitizeLiteLlmCallId("call.1:x__thought__ab+c/d=")).toBe("call_1_x__thought__ab+c/d=") - }) - - it("truncates other long ids like sanitizeOpenAiCallId", () => { - const id = "call_" + "x".repeat(100) - - expect(sanitizeLiteLlmCallId(id)).toBe(sanitizeOpenAiCallId(id)) - expect(sanitizeLiteLlmCallId(id).length).toBe(OPENAI_CALL_ID_MAX_LENGTH) - }) - - it("leaves short ids unchanged", () => { - expect(sanitizeLiteLlmCallId("toolu_123")).toBe("toolu_123") - }) -}) - -describe("sanitizeOpenAiCallId with a thought signature", () => { - it("returns an id that OpenAI and Bedrock accept", () => { - const result = sanitizeOpenAiCallId(thoughtSignatureId) - - expect(result).toMatch(strictToolIdPattern) - expect(result).toHaveLength(OPENAI_CALL_ID_MAX_LENGTH) - }) -}) diff --git a/src/utils/tool-id.ts b/src/utils/tool-id.ts index 91b942f1b5..feba6598f6 100644 --- a/src/utils/tool-id.ts +++ b/src/utils/tool-id.ts @@ -7,30 +7,11 @@ import * as crypto from "crypto" export const OPENAI_CALL_ID_MAX_LENGTH = 64 /** - * LiteLLM carries a Gemini thought signature inside the tool call id, as - * `__thought__`. Gemini rejects the next request if the - * signature changes, so the marker and everything after it must stay byte-for-byte intact. - */ -export const THOUGHT_SIGNATURE_MARKER = "__thought__" - -/** - * Replace every character outside the Anthropic/Bedrock tool id pattern ^[a-zA-Z0-9_-]+$ - * with underscore. Use this only at a request boundary that enforces the pattern. - */ -export function sanitizeToolIdForStrictProvider(id: string): string { - return id.replace(/[^a-zA-Z0-9_-]/g, "_") -} - -/** - * Sanitize a tool_use ID for the conversation history. Ids that carry a thought signature - * keep the signature unchanged; only the call id before the marker is sanitized. + * Sanitize a tool_use ID to match API validation pattern: ^[a-zA-Z0-9_-]+$ + * Replaces any invalid character with underscore. */ export function sanitizeToolUseId(id: string): string { - const markerIndex = id.indexOf(THOUGHT_SIGNATURE_MARKER) - if (markerIndex === -1) { - return sanitizeToolIdForStrictProvider(id) - } - return sanitizeToolIdForStrictProvider(id.slice(0, markerIndex)) + id.slice(markerIndex) + return id.replace(/[^a-zA-Z0-9_-]/g, "_") } /** @@ -69,14 +50,7 @@ export function truncateOpenAiCallId(id: string, maxLength: number = OPENAI_CALL * @returns The sanitized and truncated ID */ export function sanitizeOpenAiCallId(id: string, maxLength: number = OPENAI_CALL_ID_MAX_LENGTH): string { - return truncateOpenAiCallId(sanitizeToolIdForStrictProvider(id), maxLength) -} - -/** - * Normalize a tool call id for LiteLLM. Ids that carry a thought signature are never - * truncated, because Gemini must receive the signature intact. Every other id gets the - * usual OpenAI 64-character treatment. - */ -export function sanitizeLiteLlmCallId(id: string): string { - return id.includes(THOUGHT_SIGNATURE_MARKER) ? sanitizeToolUseId(id) : sanitizeOpenAiCallId(id) + // First sanitize characters, then truncate + const sanitized = sanitizeToolUseId(id) + return truncateOpenAiCallId(sanitized, maxLength) } From e75f89d6e07475034a08cba06604d2f2eec2fb61 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 19 Nov 2026 14:13:03 -0500 Subject: [PATCH 4/6] fix(litellm): flag Gemini aliases from the catalog and model the signature round trip --- .../tla/ThoughtSignature.AllCalls.cfg | 6 + .../tla/ThoughtSignature.Legacy.cfg | 6 + .../tla/ThoughtSignature.MarkerAlways.cfg | 6 + .../tla/ThoughtSignature.ModelOnly.cfg | 6 + .../tla/ThoughtSignature.NameOnly.cfg | 6 + .../tla/ThoughtSignature.NativeLeak.cfg | 6 + .../tla/ThoughtSignature.NoMarker.cfg | 6 + .../tla/ThoughtSignature.NoOrigin.cfg | 6 + .../tla/ThoughtSignature.NoReset.cfg | 6 + .../tla/ThoughtSignature.OldRegex.cfg | 6 + .../tla/ThoughtSignature.Unlisted.cfg | 6 + docs/architecture/tla/ThoughtSignature.cfg | 6 + docs/architecture/tla/ThoughtSignature.tla | 159 +++++++++++ packages/types/src/__tests__/lite-llm.test.ts | 31 ++- packages/types/src/model.ts | 2 + packages/types/src/providers/lite-llm.ts | 9 + src/api/providers/__tests__/lite-llm.spec.ts | 258 +++++++++++++----- .../fetchers/__tests__/litellm.spec.ts | 24 ++ src/api/providers/fetchers/litellm.ts | 4 +- src/api/providers/lite-llm.ts | 33 +-- .../utils/__tests__/thought-signature.spec.ts | 21 ++ src/eslint-suppressions.json | 2 +- src/test-utils/thought-signature.ts | 14 +- 23 files changed, 533 insertions(+), 96 deletions(-) create mode 100644 docs/architecture/tla/ThoughtSignature.AllCalls.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.Legacy.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.ModelOnly.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.NameOnly.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.NativeLeak.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.NoMarker.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.NoOrigin.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.NoReset.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.OldRegex.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.Unlisted.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.cfg create mode 100644 docs/architecture/tla/ThoughtSignature.tla diff --git a/docs/architecture/tla/ThoughtSignature.AllCalls.cfg b/docs/architecture/tla/ThoughtSignature.AllCalls.cfg new file mode 100644 index 0000000000..41fb03187b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.AllCalls.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "AllCalls" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.Legacy.cfg b/docs/architecture/tla/ThoughtSignature.Legacy.cfg new file mode 100644 index 0000000000..e5e2955175 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.Legacy.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "Legacy" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg b/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg new file mode 100644 index 0000000000..ab7ef0e28a --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "MarkerAlways" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg b/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg new file mode 100644 index 0000000000..359e39b6e0 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "ModelOnly" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NameOnly.cfg b/docs/architecture/tla/ThoughtSignature.NameOnly.cfg new file mode 100644 index 0000000000..a67a92ca25 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NameOnly.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "NameOnly" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg b/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg new file mode 100644 index 0000000000..ab781e87d2 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "NativeLeak" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoMarker.cfg b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg new file mode 100644 index 0000000000..cd491e5029 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "NoMarker" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg b/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg new file mode 100644 index 0000000000..cea6d9b259 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "NoOrigin" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoReset.cfg b/docs/architecture/tla/ThoughtSignature.NoReset.cfg new file mode 100644 index 0000000000..7bfa46a00b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoReset.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "NoReset" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.OldRegex.cfg b/docs/architecture/tla/ThoughtSignature.OldRegex.cfg new file mode 100644 index 0000000000..ca77263edb --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.OldRegex.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "OldRegex" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.Unlisted.cfg b/docs/architecture/tla/ThoughtSignature.Unlisted.cfg new file mode 100644 index 0000000000..9e47ab71ab --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.Unlisted.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "Unlisted" +INVARIANTS TypeOK NoRejectedCall diff --git a/docs/architecture/tla/ThoughtSignature.cfg b/docs/architecture/tla/ThoughtSignature.cfg new file mode 100644 index 0000000000..04a2846a89 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Variant = "Fixed" +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.tla b/docs/architecture/tla/ThoughtSignature.tla new file mode 100644 index 0000000000..540e53b9f1 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.tla @@ -0,0 +1,159 @@ +---- MODULE ThoughtSignature ---- +\* Models the Gemini thought signature round trip through the task history (PR 2119). +\* Source: LiteLLMHandler.createMessage reads provider_specific_fields (readThoughtSignature). +\* prepareAssistantMessage stores it with getThoughtSignatureOrigin. Native Gemini stores it without an origin. +\* Sink: applyThoughtSignatures (LiteLLM) and convertAnthropicContentToGemini (native) on the next request. +\* Config value: requiresThoughtSignatures. getLiteLLMModels sets it from litellm_params.model. +\* Its reader is createMessage. The default (model not in the catalog) falls back to the model id. +\* Failure: a backend rejects a tool call in the history. Invariant: NoRejectedCall. +\* Gemini rejects a signature from another backend or step, and a signature on a later parallel call. +\* Gemini rejects a first call with no signature. LiteLLM decodes a __thought__ id when the call has no field. +\* A backend that does not run Gemini can reject the field (BerriAI/litellm#19739). +\* Failure 2: LiteLLM decodes a sanitized __thought__ id, even for a model missing from the catalog. +\* Invariant 2: NoCorruptIdDecode. Round 2 found it: with the flag, only an unlisted model needs the marker. +\* Round 1 expected: Fixed holds. Legacy fails on the alias backend. Each sabotage fails. Result: as expected. +\* Round 1 finding: an alias got no bypass for an unsigned call, for example a call from Claude. +\* Round 2 adds the catalog flag, Gemini 4 (g4) and an alias routed to Claude (other). +\* Round 2 expected: Fixed holds for a listed model. NameOnly fails on the alias. OldRegex fails on g4. +\* Unlisted fails on the alias: a model missing from the catalog has only its name. Result: as expected. +\* Round 3 adds the rejection by a non-Gemini backend. Expected: MarkerAlways (round 2 code) fails on other. +\* Fixed holds: for a listed model, the catalog flag alone decides. Result: as expected. +\* Round 3 also drops the alias name from the flag and derives the stored origin. No verdict changed. +\* TLC checks every next backend, so one turn is enough for most failures. +\* | Config | Variant | Verdict | +\* | ThoughtSignature.cfg | the PR code, listed model | holds (507 states) | +\* | ThoughtSignature.Legacy.cfg | code before the PR (bypass on name only) | fails after 1 turn | +\* | ThoughtSignature.NameOnly.cfg | round 1 code: no catalog flag | fails after 1 turn | +\* | ThoughtSignature.MarkerAlways.cfg | round 2 code: marker fallback when listed | fails after 1 turn | +\* | ThoughtSignature.OldRegex.cfg | matcher of Gemini 3 and 2.5 only | fails after 1 turn | +\* | ThoughtSignature.Unlisted.cfg | the PR code, model missing from catalog | fails after 1 turn | +\* | ThoughtSignature.ModelOnly.cfg | origin ignores litellmBaseUrl | fails after 1 turn | +\* | ThoughtSignature.NoOrigin.cfg | no origin check | fails after 1 turn | +\* | ThoughtSignature.AllCalls.cfg | signature on every parallel call | fails after 1 turn | +\* | ThoughtSignature.NoMarker.cfg | bypass on the model name only | fails after 1 turn | +\* | ThoughtSignature.NoReset.cfg | lastThoughtSignature kept across requests | fails after 2 turns | +\* | ThoughtSignature.NativeLeak.cfg | native Gemini reads a LiteLLM signature | fails after 1 turn | +\* Fixed also holds at MaxTurns 3 (11,155 states). +\* Replay of Legacy: issue 2064. The reporter used a Gemini model behind a custom gateway alias. +\* Residual (Unlisted): an alias missing from the catalog gets no bypass for a call from another model. +\* Residual (Unlisted): a non-Gemini model missing from the catalog gets the field for a __thought__ id. +\* Oracles: Gemini validity of each signature, isLiteLLMThoughtSignatureModel, the origin hash (no collisions). +\* Oracle: the routed model of a Gemini alias matches isLiteLLMThoughtSignatureModel. +\* Not modeled: R1 format, id normalization, the native position of the signature (it is on every call). +\* Property test: lite-llm.spec.ts, "never sends a call that a backend rejects" (220 cases). +\* It checks both invariants for a listed model and NoCorruptIdDecode for an unlisted model. +\* Sabotage of the code: NameOnly, MarkerAlways, NoMarker, NoOrigin, ModelOnly and AllCalls fail it. +\* NoReset passes it. NoReset needs two requests on one handler. The test "resets it per request" covers that. +\* OldRegex passes it. The test sets the catalog flag. The fetcher and matcher tests fail on OldRegex. +\* Cost: TLC runs each config in under 2 seconds. Agent time is not measured. +\* Review: 2 covered, 1 added, 5 gap, 0 on the spec files (PR 2119). See the list below Rejected. +\* The first version came after the code and the reviews. It is not an independent first pass. + +EXTENDS Naturals, Sequences + +CONSTANTS MaxTurns, Variant + +VARIABLE history \* One assistant message per turn. Each message has the fields of Message. + +\* g1 and g2: one Gemini model on two gateways. g4: a Gemini 4 model id. +\* alias: a Gemini model under a LiteLLM alias. other: an alias routed to Claude. +Backends == {"g1", "g2", "g4", "alias", "other", "native"} +Url(b) == IF b = "g2" THEN "u2" ELSE "u1" +ModelOf(b) == CASE b \in {"g1", "g2", "native"} -> "gemini-3-pro" + [] b = "g4" -> "gemini-4-pro" + [] b = "alias" -> "team-model" + [] b = "other" -> "team-claude" +Routed(b) == CASE b = "alias" -> "gemini/gemini-3-pro" \* litellm_params.model + [] b = "other" -> "anthropic/claude-sonnet" + [] OTHER -> ModelOf(b) +LiteLlm(b) == b # "native" +RunsGemini(b) == b \in {"g1", "g2", "g4", "alias", "native"} + +\* isLiteLLMThoughtSignatureModel. OldRegex and Legacy use the matcher from before the PR. +NameMatch(name) == + name \in IF Variant \in {"OldRegex", "Legacy"} THEN {"gemini-3-pro", "gemini/gemini-3-pro"} + ELSE {"gemini-3-pro", "gemini-4-pro", "gemini/gemini-3-pro"} +\* requiresThoughtSignatures from getLiteLLMModels. +Flagged(b) == Variant \notin {"NameOnly", "Legacy"} /\ NameMatch(Routed(b)) +\* The bypass condition in createMessage. listed: the catalog has the model id. +Detected(t, listed) == (listed /\ Flagged(t)) \/ NameMatch(ModelOf(t)) +Listed == IF Variant = "Unlisted" THEN BOOLEAN ELSE {TRUE} + +\* thoughtSignatureOrigin(litellmBaseUrl || default, modelId). ModelOnly drops the URL. +Origin(b) == IF Variant = "ModelOnly" THEN ModelOf(b) ELSE Url(b) \o "|" \o ModelOf(b) + +None == [by |-> "none", step |-> 0] +Bypass == [by |-> "bypass", step |-> 0] +Real(s) == s.by \in Backends +\* getThoughtSignatureOrigin of the handler that streamed the message. Native Gemini stores none. +StoredOrigin(m) == IF LiteLlm(m.by) /\ Real(m.sig) THEN Origin(m.by) ELSE "none" +Sigs == {None, Bypass} \cup [by : Backends, step : 1..MaxTurns] +Message == [by : Backends, n : 1..2, marker : BOOLEAN, sig : Sigs] + +TypeOK == history \in Seq(Message) /\ Len(history) <= MaxTurns + +Init == history = <<>> + +\* lastThoughtSignature after the stream. NoReset keeps the value from the last request on this handler. +Captured(t, k, minted) == + LET prev == history[k - 1] + kept == Variant = "NoReset" /\ k > 1 /\ prev.by = t /\ Real(prev.sig) + reads == ~(Variant = "Legacy" /\ LiteLlm(t)) \* The old LiteLLM handler did not read it. + IN IF kept THEN prev.sig ELSE IF minted /\ reads THEN [by |-> t, step |-> k] ELSE None + +\* A turn on backend t returns n tool calls. A Gemini backend can sign the first call. +\* LiteLLM then also writes the signature into the id of that call, after __thought__. +Turn(t, n, minted) == + LET k == Len(history) + 1 + sig == Captured(t, k, minted) + IN /\ k <= MaxTurns + /\ minted => RunsGemini(t) + /\ history' = Append(history, [by |-> t, n |-> n, marker |-> minted /\ LiteLlm(t), sig |-> sig]) + +Next == \E t \in Backends, n \in 1..2, minted \in BOOLEAN : Turn(t, n, minted) +Spec == Init /\ [][Next]_history + +\* The signature that a request to backend t puts on call i of history message k. +Sent(t, listed, k, i) == + LET m == history[k] + IN IF LiteLlm(t) + THEN LET matches == Real(m.sig) /\ (Variant = "NoOrigin" \/ StoredOrigin(m) = Origin(t)) + first == i = 1 \/ Variant = "AllCalls" + markerFallback == m.marker /\ i = 1 /\ Variant \notin {"NoMarker", "Legacy"} + /\ (~listed \/ Variant = "MarkerAlways") + IN IF matches /\ first /\ Variant # "Legacy" THEN m.sig + ELSE IF Detected(t, listed) \/ markerFallback THEN Bypass + ELSE None + ELSE IF Real(m.sig) /\ (StoredOrigin(m) = "none" \/ Variant = "NativeLeak") THEN m.sig ELSE Bypass + +\* LiteLLM decodes the sanitized __thought__ id of a call that has no field. +DecodesCorruptId(t, listed, k, i) == + RunsGemini(t) /\ LiteLlm(t) /\ Sent(t, listed, k, i) = None /\ history[k].marker /\ i = 1 + +\* The sink oracle. A backend that does not run Gemini rejects every call with the field. +Rejected(t, listed, k, i) == + LET s == Sent(t, listed, k, i) + IN \/ DecodesCorruptId(t, listed, k, i) + \/ ~RunsGemini(t) /\ s # None + \/ RunsGemini(t) /\ Real(s) /\ (s.by # t \/ s.step # k) + \/ RunsGemini(t) /\ Real(s) /\ LiteLlm(t) /\ i # 1 + \/ RunsGemini(t) /\ s = None /\ i = 1 +\* Review ratchet (PR 2119): +\* covered: CodeRabbit 4396808577 and edelauna on tool-id.ts. The history sanitizes the id copy (marker rule). +\* added: CodeRabbit 4532185300. Two gateways with one model id share an origin (ModelOnly). +\* gap: 4532185306 (a throw and a reasoning id), 4532185311 (test helper). The spec has no ids or exceptions. +\* gap: edelauna R1 path test, CodeRabbit on sanitizeLiteLlmCallId and its test. The PR removed that code. +\* Rounds 2 and 3 are not review findings. Round 2 fixes the round 1 finding of this spec. +\* Round 3 comes from a web search for best practice (BerriAI/litellm#19739, vercel/ai#15550). + +\* Safety: no backend rejects a tool call in the history. +NoRejectedCall == + \A t \in Backends, listed \in Listed, k \in 1..Len(history) : + \A i \in 1..history[k].n : ~Rejected(t, listed, k, i) + +\* Safety: for a model in the catalog or not, LiteLLM never decodes a sanitized __thought__ id. +NoCorruptIdDecode == + \A t \in Backends, listed \in BOOLEAN, k \in 1..Len(history) : + \A i \in 1..history[k].n : ~DecodesCorruptId(t, listed, k, i) + +==== diff --git a/packages/types/src/__tests__/lite-llm.test.ts b/packages/types/src/__tests__/lite-llm.test.ts index c76d0d84fc..8a355e4b68 100644 --- a/packages/types/src/__tests__/lite-llm.test.ts +++ b/packages/types/src/__tests__/lite-llm.test.ts @@ -1,4 +1,8 @@ -import { isLiteLLMPreserveReasoningModel, LITELLM_PRESERVE_REASONING_MODEL_IDS } from "../providers/lite-llm.js" +import { + isLiteLLMPreserveReasoningModel, + isLiteLLMThoughtSignatureModel, + LITELLM_PRESERVE_REASONING_MODEL_IDS, +} from "../providers/lite-llm.js" describe("LiteLLM preserveReasoning model detection", () => { it("matches every explicitly listed model id", () => { @@ -48,3 +52,28 @@ describe("LiteLLM preserveReasoning model detection", () => { expect(isLiteLLMPreserveReasoningModel(undefined)).toBe(false) }) }) + +describe("LiteLLM thought signature model detection", () => { + it.each([ + "gemini-3-pro", + "gemini-3-flash", + "gemini-3.1-pro-preview", + "gemini-2.5-pro", + "gemini-4-pro", + "Gemini 3 Pro", + "gemini 2.5 flash", + "google/gemini-3-pro", + "vertex_ai/gemini-2.5-pro", + "vertex_ai/gemini 2.5 pro", + "gemini/gemini-4-flash", + ])("matches %s", (modelName) => { + expect(isLiteLLMThoughtSignatureModel(modelName)).toBe(true) + }) + + it.each(["gpt-4", "claude-3-opus", "gemini-1.5-pro", "gemini-2.0-flash", "team-model", "", undefined])( + "does not match %s", + (modelName) => { + expect(isLiteLLMThoughtSignatureModel(modelName)).toBe(false) + }, + ) +}) diff --git a/packages/types/src/model.ts b/packages/types/src/model.ts index b3c2b8151d..09b37e0472 100644 --- a/packages/types/src/model.ts +++ b/packages/types/src/model.ts @@ -146,6 +146,8 @@ export const modelInfoSchema = z.object({ .optional(), requiredReasoningEffort: z.boolean().optional(), preserveReasoning: z.boolean().optional(), + // The model behind a gateway alias validates Gemini thought signatures on function calls. + requiresThoughtSignatures: z.boolean().optional(), // Some OpenAI-compatible gateways require a Responses-backed route for tool calls. requiresResponsesApi: z.boolean().optional(), supportedParameters: z.array(modelParametersSchema).optional(), diff --git a/packages/types/src/providers/lite-llm.ts b/packages/types/src/providers/lite-llm.ts index 5303772586..f5b799c169 100644 --- a/packages/types/src/providers/lite-llm.ts +++ b/packages/types/src/providers/lite-llm.ts @@ -97,3 +97,12 @@ export function isLiteLLMPreserveReasoningModel(modelName: string | undefined): return modelId !== undefined && LITELLM_PRESERVE_REASONING_MODEL_ID_SET.has(modelId) } + +/** + * Checks whether `modelName` (a LiteLLM alias or routed `litellm_params.model` + * value) names a Gemini 2.5 or later model. These models validate thought + * signatures on function calls. + */ +export function isLiteLLMThoughtSignatureModel(modelName: string | undefined): boolean { + return /gemini[-\s](?:2\.5|[3-9]|[1-9]\d)/i.test(modelName ?? "") +} diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index 75f4c19193..eec34bd19d 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -553,59 +553,6 @@ describe("LiteLLMHandler", () => { }) describe("Gemini thought signature injection", () => { - describe("isGeminiModel detection", () => { - it("should detect Gemini 3 models", () => { - const handler = new LiteLLMHandler(mockOptions) - const isGeminiModel = (handler as any).isGeminiModel.bind(handler) - - expect(isGeminiModel("gemini-3-pro")).toBe(true) - expect(isGeminiModel("gemini-3-flash")).toBe(true) - expect(isGeminiModel("gemini-3-pro-preview")).toBe(true) - }) - - it("should detect Gemini 2.5 models", () => { - const handler = new LiteLLMHandler(mockOptions) - const isGeminiModel = (handler as any).isGeminiModel.bind(handler) - - expect(isGeminiModel("gemini-2.5-pro")).toBe(true) - expect(isGeminiModel("gemini-2.5-flash")).toBe(true) - }) - - it("should detect Gemini models with spaces (LiteLLM model groups)", () => { - const handler = new LiteLLMHandler(mockOptions) - const isGeminiModel = (handler as any).isGeminiModel.bind(handler) - - // LiteLLM model groups often use space-separated names with title case - expect(isGeminiModel("Gemini 3 Pro")).toBe(true) - expect(isGeminiModel("Gemini 3 Flash")).toBe(true) - expect(isGeminiModel("gemini 3 pro")).toBe(true) - expect(isGeminiModel("Gemini 2.5 Pro")).toBe(true) - expect(isGeminiModel("gemini 2.5 flash")).toBe(true) - }) - - it("should detect provider-prefixed Gemini models", () => { - const handler = new LiteLLMHandler(mockOptions) - const isGeminiModel = (handler as any).isGeminiModel.bind(handler) - - expect(isGeminiModel("google/gemini-3-pro")).toBe(true) - expect(isGeminiModel("vertex_ai/gemini-3-pro")).toBe(true) - expect(isGeminiModel("vertex/gemini-2.5-pro")).toBe(true) - // Space-separated variants with provider prefix - expect(isGeminiModel("google/gemini 3 pro")).toBe(true) - expect(isGeminiModel("vertex_ai/gemini 2.5 pro")).toBe(true) - }) - - it("should not detect non-Gemini models", () => { - const handler = new LiteLLMHandler(mockOptions) - const isGeminiModel = (handler as any).isGeminiModel.bind(handler) - - expect(isGeminiModel("gpt-4")).toBe(false) - expect(isGeminiModel("claude-3-opus")).toBe(false) - expect(isGeminiModel("gemini-1.5-pro")).toBe(false) - expect(isGeminiModel("gemini-2.0-flash")).toBe(false) - }) - }) - describe("createMessage integration with Gemini models", () => { // Base64 encoded "skip_thought_signature_validator" const dummySignature = Buffer.from("skip_thought_signature_validator").toString("base64") @@ -698,11 +645,10 @@ describe("LiteLLMHandler", () => { }) } - function useModel(id: string, preserveReasoning?: boolean) { - vi.spyOn(handler, "fetchModel").mockResolvedValue({ - id, - info: { ...litellmDefaultModelInfo, preserveReasoning }, - }) + function useModel(id: string, info: Partial = {}, listed = true) { + const modelInfo = { ...litellmDefaultModelInfo, ...info } + vi.spyOn(handler, "fetchModel").mockResolvedValue({ id, info: modelInfo }) + handler["models"] = listed ? { [id]: modelInfo } : {} } const signedToolCallStream = [ @@ -728,6 +674,20 @@ describe("LiteLLMHandler", () => { { choices: [{ delta: {} }], usage: { prompt_tokens: 1, completion_tokens: 1 } }, ] + it.each([ + ["a configured base URL", "http://gateway:4000", "http://gateway:4000"], + ["no base URL", undefined, "http://localhost:4000"], + ])("names the origin and the client endpoint from %s", async (_case, litellmBaseUrl, endpoint) => { + handler = new LiteLLMHandler({ ...mockOptions, litellmBaseUrl }) + useModel("gemini-3-pro") + mockStream(signedToolCallStream) + + await collectStream(handler.createMessage("system", [{ role: "user", content: "Hi" }], metadata)) + + expect(vi.mocked(OpenAI)).toHaveBeenLastCalledWith(expect.objectContaining({ baseURL: endpoint })) + expect(handler.getThoughtSignatureOrigin()).toBe(thoughtSignatureOrigin(endpoint, "gemini-3-pro")) + }) + it("captures the signature from a streamed tool call and resets it per request", async () => { useModel("gemini-3-pro") mockStream(signedToolCallStream) @@ -800,7 +760,7 @@ describe("LiteLLMHandler", () => { preserveReasoning: undefined, storedBy: "this backend", storedOrigin: thoughtSignatureOrigin("http://localhost:4000/", "gemini-4-pro"), - expected: [real, untouched], + expected: [real, bypassed], }, { modelId: "gemini-3-pro", @@ -819,7 +779,7 @@ describe("LiteLLMHandler", () => { ])( "writes signatures for $modelId with a signature from $storedBy (preserveReasoning=$preserveReasoning)", async ({ modelId, preserveReasoning, storedOrigin, expected }) => { - useModel(modelId, preserveReasoning) + useModel(modelId, { preserveReasoning }) const historyIds = ["call_1", "call_2"] mockStream([{ choices: [{ delta: { content: "ok" } }] }]) @@ -839,8 +799,11 @@ describe("LiteLLMHandler", () => { }, ) - it("sends the bypass for a sanitized __thought__ id on an alias that isGeminiModel does not match", async () => { - useModel("my-gateway-model") + it.each([ + { catalog: "a model missing from the catalog", listed: false, expected: [bypassed] }, + { catalog: "an unflagged model in the catalog", listed: true, expected: [untouched] }, + ])("handles a sanitized __thought__ id on $catalog", async ({ listed, expected }) => { + useModel("my-gateway-model", {}, listed) const historyId = SANITIZED_LITELLM_TOOL_CALL_ID mockStream([{ choices: [{ delta: { content: "ok" } }] }]) @@ -859,7 +822,176 @@ describe("LiteLLMHandler", () => { ), ) - expect(sentToolCalls(mockCreate)).toEqual([bypassed]) + expect(sentToolCalls(mockCreate)).toEqual(expected) + }) + + it.each([ + { flag: true, expected: [bypassed, bypassed] }, + { flag: undefined, expected: [untouched, untouched] }, + ])( + "sends the bypass for calls from another model on an alias when requiresThoughtSignatures is $flag", + async ({ flag, expected }) => { + useModel("team-model", { requiresThoughtSignatures: flag }) + const historyIds = ["toolu_1", "toolu_2"] + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + + await collectStream( + handler.createMessage( + "system", + [ + { role: "user", content: "Hello" }, + { + role: "assistant", + content: historyIds.map((id) => ({ + type: "tool_use", + id, + name: "read_file", + input: {}, + })), + }, + toolResultsMessage(historyIds), + ], + metadata, + ), + ) + + expect(sentToolCalls(mockCreate)).toEqual(expected) + }, + ) + + // Mirrors docs/architecture/tla/ThoughtSignature.tla: no backend rejects a tool call in the history. + describe("never sends a call that a backend rejects", () => { + // flagged: the catalog sets requiresThoughtSignatures. The fetcher spec covers that mapping. + type Backend = { name: string; url?: string; model: string; flagged: boolean; runsGemini: boolean } + const g1: Backend = { + name: "g1", + url: "http://u1:4000", + model: "gemini-3-pro", + flagged: true, + runsGemini: true, + } + const g2: Backend = { ...g1, name: "g2", url: "http://u2:4000" } + const g4: Backend = { ...g1, name: "g4", model: "gemini-4-pro" } + const alias: Backend = { ...g1, name: "alias", model: "team-model" } + const other: Backend = { + ...g1, + name: "other", + model: "team-claude", + flagged: false, + runsGemini: false, + } + const native: Backend = { name: "native", model: "gemini-3-pro", flagged: true, runsGemini: true } + const targets = [g1, g2, g4, alias, other] + const cases = [...targets, native].flatMap((source) => + (source.runsGemini ? [true, false] : [false]).flatMap((minted) => + [1, 2].flatMap((n) => + targets.flatMap((target) => + [true, false].map((listed) => ({ source, minted, n, target, listed })), + ), + ), + ), + ) + + // A model missing from the catalog gets the default info, as in RouterProvider.getModel. + function useCatalog(target: LiteLLMHandler, backend: Backend, listed = true) { + const requiresThoughtSignatures = listed && backend.flagged ? true : undefined + const info = { ...litellmDefaultModelInfo, requiresThoughtSignatures } + vi.spyOn(target, "fetchModel").mockResolvedValue({ id: backend.model, info }) + target["models"] = listed ? { [backend.model]: info } : {} + } + + async function historyMessage(source: Backend, minted: boolean, n: number) { + const signature = `AY89sig${source.name}` + const mintedId = `call_0__thought__${signature}` + const viaLiteLlm = minted && source.url !== undefined + const ids = Array.from({ length: n }, (_, i) => + sanitizeToolUseId(i === 0 && viaLiteLlm ? mintedId : `call_${i}`), + ) + const toolUses: Anthropic.Messages.ToolUseBlockParam[] = ids.map((id) => ({ + type: "tool_use", + id, + name: "read_file", + input: {}, + })) + if (!minted) { + return { ids, signature, message: { role: "assistant" as const, content: toolUses } } + } + if (!viaLiteLlm) { + return { ids, signature, message: signedAssistantMessage(ids, { signature }) } + } + const sourceHandler = new LiteLLMHandler({ ...mockOptions, litellmBaseUrl: source.url }) + useCatalog(sourceHandler, source) + mockStream([ + { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: mintedId, + function: { name: "read_file", arguments: "{}" }, + provider_specific_fields: { thought_signature: signature }, + }, + ], + }, + }, + ], + }, + ]) + await collectStream( + sourceHandler.createMessage("system", [{ role: "user", content: "Hi" }], metadata), + ) + const message = prepareApiConversationMessage({ + message: { role: "assistant", content: toolUses }, + api: sourceHandler, + apiConfiguration: { + apiProvider: providerIdentifiers.litellm, + litellmModelId: source.model, + }, + apiConversationHistory: [], + }) + return { ids, signature, message } + } + + it.each(cases)( + "$source.name history (minted=$minted, $n calls) sent to $target.name (listed=$listed)", + async ({ source, minted, n, target, listed }) => { + const { ids, signature, message } = await historyMessage(source, minted, n) + handler = new LiteLLMHandler({ ...mockOptions, litellmBaseUrl: target.url }) + useCatalog(handler, target, listed) + mockStream([{ choices: [{ delta: { content: "ok" } }] }]) + + await collectStream( + handler.createMessage( + "system", + [{ role: "user", content: "Hello" }, message, toolResultsMessage(ids)], + metadata, + ), + ) + + const sent = (sentToolCalls(mockCreate) ?? []).map((call, i) => { + const fields = (call as { provider_specific_fields?: { thought_signature?: string } }) + .provider_specific_fields + return { i, id: call.id, sig: fields?.thought_signature } + }) + // NoCorruptIdDecode holds for every catalog outcome. NoRejectedCall needs a listed model. + // A non-Gemini backend can reject the field (BerriAI/litellm#19739). + const decodesCorruptId = ({ sig, id }: (typeof sent)[number]) => + sig === undefined && id.includes("__thought__") + const invalidOrMissing = ({ i, sig }: (typeof sent)[number]) => + sig === undefined + ? i === 0 + : sig !== dummySignature && !(sig === signature && source === target && i === 0) + const rejected = sent.filter((call) => + target.runsGemini + ? decodesCorruptId(call) || (listed && invalidOrMissing(call)) + : listed && call.sig !== undefined, + ) + expect(sent).toHaveLength(n) + expect(rejected).toEqual([]) + }, + ) }) }) diff --git a/src/api/providers/fetchers/__tests__/litellm.spec.ts b/src/api/providers/fetchers/__tests__/litellm.spec.ts index ce278489b5..3dd5ea5dca 100644 --- a/src/api/providers/fetchers/__tests__/litellm.spec.ts +++ b/src/api/providers/fetchers/__tests__/litellm.spec.ts @@ -913,4 +913,28 @@ describe("getLiteLLMModels", () => { expect(result["glm-5-flash"]).not.toHaveProperty("preserveReasoning") }) }) + + describe("requiresThoughtSignatures inference", () => { + it.each([ + ["a Gemini routed model", "team-model", "gemini/gemini-3-pro", true], + ["a Gemini name on another routed model", "gemini-4-pro", "openai/my-proxy-route", false], + ["a non-Gemini routed model", "team-claude", "anthropic/claude-sonnet-4", false], + ])("sets the flag from the routed model for %s", async (_case, modelName, routedModel, flagged) => { + mockedAxios.get.mockResolvedValue({ + data: { + data: [ + { + model_name: modelName, + model_info: { max_tokens: 8192, max_input_tokens: 128000 }, + litellm_params: { model: routedModel }, + }, + ], + }, + }) + + const result = await getLiteLLMModels("test-api-key", "http://localhost:4000") + + expect(result[modelName]?.requiresThoughtSignatures).toBe(flagged || undefined) + }) + }) }) diff --git a/src/api/providers/fetchers/litellm.ts b/src/api/providers/fetchers/litellm.ts index c98c36c914..e71abfab3a 100644 --- a/src/api/providers/fetchers/litellm.ts +++ b/src/api/providers/fetchers/litellm.ts @@ -1,7 +1,7 @@ import axios from "axios" import type { ModelRecord } from "@roo-code/types" -import { isLiteLLMPreserveReasoningModel } from "@roo-code/types" +import { isLiteLLMPreserveReasoningModel, isLiteLLMThoughtSignatureModel } from "@roo-code/types" import { DEFAULT_HEADERS } from "../constants" import { throwIfAborted } from "../utils/abort-signal" @@ -52,6 +52,7 @@ export async function getLiteLLMModels( // preserveReasoning from explicit model ids in either the alias or routed model name. const preservesReasoning = isLiteLLMPreserveReasoningModel(modelName) || isLiteLLMPreserveReasoningModel(litellmModelName) + const requiresThoughtSignatures = isLiteLLMThoughtSignatureModel(litellmModelName) models[modelName] = { maxTokens: modelInfo.max_output_tokens || modelInfo.max_tokens || 8192, @@ -84,6 +85,7 @@ export async function getLiteLLMModels( }, }), ...(preservesReasoning && { preserveReasoning: true }), + ...(requiresThoughtSignatures && { requiresThoughtSignatures: true }), description: `${modelName} via LiteLLM proxy`, } } diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index 17c6e84bfc..8d09c8b547 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -6,6 +6,7 @@ import { type ModelRecord, type ReasoningEffortExtended, litellmDefaultModelId, + isLiteLLMThoughtSignatureModel, litellmDefaultModelInfo, providerIdentifiers, } from "@roo-code/types" @@ -110,31 +111,6 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa return fallback && supported.includes(fallback) ? fallback : undefined } - /** - * Detect if the model is a Gemini model that requires thought signature handling. - * Gemini 3 models validate thought signatures for tool/function calling steps. - */ - private isGeminiModel(modelId: string): boolean { - // Match various Gemini model patterns: - // - gemini-3-pro, gemini-3-flash, gemini-3-* - // - gemini 3 pro, Gemini 3 Pro (space-separated, case-insensitive) - // - gemini/gemini-3-*, google/gemini-3-* - // - vertex_ai/gemini-3-*, vertex/gemini-3-* - // Also match Gemini 2.5+ models which use similar validation - const lowerModelId = modelId.toLowerCase() - return ( - // Match hyphenated versions: gemini-3, gemini-2.5 - lowerModelId.includes("gemini-3") || - lowerModelId.includes("gemini-2.5") || - // Match space-separated versions: "gemini 3", "gemini 2.5" - // This handles model names like "Gemini 3 Pro" from LiteLLM model groups - lowerModelId.includes("gemini 3") || - lowerModelId.includes("gemini 2.5") || - // Also match provider-prefixed versions - /\b(gemini|google|vertex_ai|vertex)\/gemini[-\s](3|2\.5)/i.test(modelId) - ) - } - override async *createMessage( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], @@ -256,7 +232,10 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // Gemini validates thought signatures on function calls. A tool call without a signature // from this backend gets the bypass token: calls from other models (like Claude) for // Gemini models, and `__thought__` ids whose embedded signature the history sanitized. - const isGemini = this.isGeminiModel(modelId) + // A non-Gemini backend can reject the field (BerriAI/litellm#19739), so the `__thought__` + // fallback applies only to a model missing from the catalog. + const isGemini = info.requiresThoughtSignatures || isLiteLLMThoughtSignatureModel(modelId) + const listed = Object.hasOwn(this.models, modelId) this.thoughtSignatureOrigin = thoughtSignatureOrigin( this.options.litellmBaseUrl || LITELLM_DEFAULT_BASE_URL, modelId, @@ -265,7 +244,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa origin: this.thoughtSignatureOrigin, normalizeToolCallId: sanitizeOpenAiCallId, fallback: (toolCallId) => - isGemini || toolCallId.includes(LITELLM_THOUGHT_SIGNATURE_ID_MARKER) + isGemini || (!listed && toolCallId.includes(LITELLM_THOUGHT_SIGNATURE_ID_MARKER)) ? GEMINI_THOUGHT_SIGNATURE_BYPASS : undefined, }) diff --git a/src/api/providers/utils/__tests__/thought-signature.spec.ts b/src/api/providers/utils/__tests__/thought-signature.spec.ts index f6ec6f89cf..d05319a3a7 100644 --- a/src/api/providers/utils/__tests__/thought-signature.spec.ts +++ b/src/api/providers/utils/__tests__/thought-signature.spec.ts @@ -114,6 +114,27 @@ describe("applyThoughtSignatures", () => { ]) }) + it("ignores a signed message without tool calls", () => { + const history = [signedAssistantMessage([], { origin, leadingBlocks: [{ type: "text", text: "Done." }] })] + + const result = applyThoughtSignatures(history, [assistantWith("call_1")], { + origin, + normalizeToolCallId: sanitizeOpenAiCallId, + }) + + expect(result).toEqual([assistantWith("call_1")]) + }) + + it("puts the signature on the tool call, not on a reasoning block with an id", () => { + // The history stores reasoning blocks with the Responses API item id. + const reasoning = { type: "reasoning" as const, text: "Thinking.", id: "rs_1" } + const history = [signedAssistantMessage(["call_1"], { origin, leadingBlocks: [reasoning] })] + + const result = applyThoughtSignatures(history, [assistantWith("call_1")], { origin }) + + expect(result).toEqual([{ role: "assistant", content: null, tool_calls: [signed("call_1", signature)] }]) + }) + it("uses the fallback for every tool call without a stored signature", () => { const fallback = (id: string) => (id === "call_2" ? bypass : undefined) diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index 3cab377fcb..d16effa88f 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -81,7 +81,7 @@ }, "api/providers/__tests__/lite-llm.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 31 + "count": 26 } }, "api/providers/__tests__/mimo.spec.ts": { diff --git a/src/test-utils/thought-signature.ts b/src/test-utils/thought-signature.ts index 9eb048fa1d..081b9ac52d 100644 --- a/src/test-utils/thought-signature.ts +++ b/src/test-utils/thought-signature.ts @@ -12,9 +12,14 @@ export const SANITIZED_LITELLM_TOOL_CALL_ID = export function signedAssistantMessage( toolUseIds: string[], - { signature = TEST_THOUGHT_SIGNATURE, origin }: { signature?: string; origin?: string } = {}, + { + signature = TEST_THOUGHT_SIGNATURE, + origin, + leadingBlocks = [], + }: { signature?: string; origin?: string; leadingBlocks?: ExtendedContentBlockParam[] } = {}, ): Anthropic.Messages.MessageParam { const content: ExtendedContentBlockParam[] = [ + ...leadingBlocks, ...toolUseIds.map((id) => ({ type: "tool_use" as const, id, name: "read_file", input: {} })), { type: "thoughtSignature", thoughtSignature: signature, ...(origin ? { origin } : {}) }, ] @@ -30,7 +35,10 @@ export function toolResultsMessage(toolUseIds: string[]): Anthropic.Messages.Mes } export function sentToolCalls(create: Mock): OpenAI.Chat.ChatCompletionMessageToolCall[] | undefined { - const sent: OpenAI.Chat.ChatCompletionMessageParam[] = create.mock.calls.at(-1)?.[0].messages - const assistant = sent.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) + const request: OpenAI.Chat.ChatCompletionCreateParams | undefined = create.mock.calls.at(-1)?.[0] + if (!request) { + throw new Error("sentToolCalls: the mocked create() was never called") + } + const assistant = request.messages.find((msg) => msg.role === "assistant" && msg.tool_calls?.length) return assistant?.role === "assistant" ? assistant.tool_calls : undefined } From 4c8122ecde21ca47e6841592f91c781548a83ec6 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Fri, 20 Nov 2026 23:36:57 -0500 Subject: [PATCH 5/6] docs(tla): move ThoughtSignature variants to an MC module and check delivery --- docs/architecture/tla/AGENTS.md | 2 +- .../tla/ThoughtSignature.AllCalls.cfg | 3 +- .../tla/ThoughtSignature.DropStored.cfg | 7 ++ .../tla/ThoughtSignature.Legacy.cfg | 6 +- .../tla/ThoughtSignature.MarkerAlways.cfg | 3 +- .../tla/ThoughtSignature.ModelOnly.cfg | 3 +- .../tla/ThoughtSignature.NameOnly.cfg | 3 +- .../tla/ThoughtSignature.NativeLeak.cfg | 3 +- .../tla/ThoughtSignature.NoMarker.cfg | 3 +- .../tla/ThoughtSignature.NoOrigin.cfg | 3 +- .../tla/ThoughtSignature.NoReset.cfg | 3 +- .../tla/ThoughtSignature.OldRegex.cfg | 3 +- .../tla/ThoughtSignature.Unlisted.cfg | 3 +- docs/architecture/tla/ThoughtSignature.cfg | 4 +- docs/architecture/tla/ThoughtSignature.tla | 77 +++++++++++-------- docs/architecture/tla/ThoughtSignatureMC.tla | 35 +++++++++ docs/architecture/tla/check.sh | 5 +- src/api/providers/__tests__/lite-llm.spec.ts | 3 + src/api/providers/lite-llm.ts | 2 +- 19 files changed, 122 insertions(+), 49 deletions(-) create mode 100644 docs/architecture/tla/ThoughtSignature.DropStored.cfg create mode 100644 docs/architecture/tla/ThoughtSignatureMC.tla diff --git a/docs/architecture/tla/AGENTS.md b/docs/architecture/tla/AGENTS.md index 377ab0938a..783837dba5 100644 --- a/docs/architecture/tla/AGENTS.md +++ b/docs/architecture/tla/AGENTS.md @@ -90,7 +90,7 @@ Sources: [module structure](https://learning.tlapl.us/intro/module-structure/) a ## Run TLC 1. Download `tla2tools.jar` to a folder outside the repo. Do not commit it. -2. Run: `java -XX:+UseParallelGC -cp tlc2.TLC -metadir -config Spec.Variant.cfg Spec.tla`. Without `-metadir`, TLC writes a `states` folder here. +2. Run: `java -XX:+UseParallelGC -cp tlc2.TLC -metadir -config Spec.Variant.cfg Spec.tla`. Without `-metadir`, TLC writes a `states` folder here. If `SpecMC.tla` exists, give it instead of `Spec.tla`. `check.sh` does this. 3. If the system can end, add `CHECK_DEADLOCK FALSE` to the config. Without it, TLC reports the end as a deadlock. 4. Pick the smallest constants that show the interaction. Two links are enough for interleaving. diff --git a/docs/architecture/tla/ThoughtSignature.AllCalls.cfg b/docs/architecture/tla/ThoughtSignature.AllCalls.cfg index 41fb03187b..3935a4f235 100644 --- a/docs/architecture/tla/ThoughtSignature.AllCalls.cfg +++ b/docs/architecture/tla/ThoughtSignature.AllCalls.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "AllCalls" + SignedCall <- EveryCall +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.DropStored.cfg b/docs/architecture/tla/ThoughtSignature.DropStored.cfg new file mode 100644 index 0000000000..9491e552ed --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.DropStored.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + OriginMatches <- NeverMatch +CONSTRAINT Bounded +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.Legacy.cfg b/docs/architecture/tla/ThoughtSignature.Legacy.cfg index e5e2955175..2dd3b58d33 100644 --- a/docs/architecture/tla/ThoughtSignature.Legacy.cfg +++ b/docs/architecture/tla/ThoughtSignature.Legacy.cfg @@ -2,5 +2,9 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "Legacy" + SignatureModelNames <- OldNames + Flagged <- NoFlag + MarkerFallback <- NoMarkerFallback + Captured <- CapturedNative +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg b/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg index ab7ef0e28a..10ebca9c2a 100644 --- a/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg +++ b/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "MarkerAlways" + MarkerFallback <- MarkerAlways +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg b/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg index 359e39b6e0..68873b7035 100644 --- a/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg +++ b/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "ModelOnly" + Origin <- ModelOrigin +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NameOnly.cfg b/docs/architecture/tla/ThoughtSignature.NameOnly.cfg index a67a92ca25..f8f830d966 100644 --- a/docs/architecture/tla/ThoughtSignature.NameOnly.cfg +++ b/docs/architecture/tla/ThoughtSignature.NameOnly.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "NameOnly" + Flagged <- NoFlag +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg b/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg index ab781e87d2..7706a568e7 100644 --- a/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg +++ b/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "NativeLeak" + NativeUses <- NativeAny +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoMarker.cfg b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg index cd491e5029..f831695f73 100644 --- a/docs/architecture/tla/ThoughtSignature.NoMarker.cfg +++ b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "NoMarker" + MarkerFallback <- NoMarkerFallback +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg b/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg index cea6d9b259..1b4dd26a21 100644 --- a/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg +++ b/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "NoOrigin" + OriginMatches <- AnyOrigin +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.NoReset.cfg b/docs/architecture/tla/ThoughtSignature.NoReset.cfg index 7bfa46a00b..90bc469a14 100644 --- a/docs/architecture/tla/ThoughtSignature.NoReset.cfg +++ b/docs/architecture/tla/ThoughtSignature.NoReset.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "NoReset" + Captured <- CapturedKept +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.OldRegex.cfg b/docs/architecture/tla/ThoughtSignature.OldRegex.cfg index ca77263edb..42f8c5309e 100644 --- a/docs/architecture/tla/ThoughtSignature.OldRegex.cfg +++ b/docs/architecture/tla/ThoughtSignature.OldRegex.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "OldRegex" + SignatureModelNames <- OldNames +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.Unlisted.cfg b/docs/architecture/tla/ThoughtSignature.Unlisted.cfg index 9e47ab71ab..70ab147f3b 100644 --- a/docs/architecture/tla/ThoughtSignature.Unlisted.cfg +++ b/docs/architecture/tla/ThoughtSignature.Unlisted.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "Unlisted" + Listed <- AnyListed +CONSTRAINT Bounded INVARIANTS TypeOK NoRejectedCall diff --git a/docs/architecture/tla/ThoughtSignature.cfg b/docs/architecture/tla/ThoughtSignature.cfg index 04a2846a89..3d0f1ce293 100644 --- a/docs/architecture/tla/ThoughtSignature.cfg +++ b/docs/architecture/tla/ThoughtSignature.cfg @@ -2,5 +2,5 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 - Variant = "Fixed" -INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode +CONSTRAINT Bounded +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.tla b/docs/architecture/tla/ThoughtSignature.tla index 540e53b9f1..d97aa6b776 100644 --- a/docs/architecture/tla/ThoughtSignature.tla +++ b/docs/architecture/tla/ThoughtSignature.tla @@ -11,6 +11,7 @@ \* A backend that does not run Gemini can reject the field (BerriAI/litellm#19739). \* Failure 2: LiteLLM decodes a sanitized __thought__ id, even for a model missing from the catalog. \* Invariant 2: NoCorruptIdDecode. Round 2 found it: with the flag, only an unlisted model needs the marker. +\* Failure 3: a LiteLLM backend does not get back the signature it minted. Invariant 3: SignatureDelivered. \* Round 1 expected: Fixed holds. Legacy fails on the alias backend. Each sabotage fails. Result: as expected. \* Round 1 finding: an alias got no bypass for an unsigned call, for example a call from Claude. \* Round 2 adds the catalog flag, Gemini 4 (g4) and an alias routed to Claude (other). @@ -19,6 +20,10 @@ \* Round 3 adds the rejection by a non-Gemini backend. Expected: MarkerAlways (round 2 code) fails on other. \* Fixed holds: for a listed model, the catalog flag alone decides. Result: as expected. \* Round 3 also drops the alias name from the flag and derives the stored origin. No verdict changed. +\* Round 4 adds SignatureDelivered. The bypass is always accepted, so NoRejectedCall passes a lost signature. +\* Round 4 expected: DropStored passes NoRejectedCall and NoCorruptIdDecode and fails SignatureDelivered. Result: as expected. +\* Variants are in ThoughtSignatureMC.tla. Each one replaces one or more operators of this module. +\* Run: java -cp tlc2.TLC -metadir -config ThoughtSignatureMC.tla \* TLC checks every next backend, so one turn is enough for most failures. \* | Config | Variant | Verdict | \* | ThoughtSignature.cfg | the PR code, listed model | holds (507 states) | @@ -33,6 +38,7 @@ \* | ThoughtSignature.NoMarker.cfg | bypass on the model name only | fails after 1 turn | \* | ThoughtSignature.NoReset.cfg | lastThoughtSignature kept across requests | fails after 2 turns | \* | ThoughtSignature.NativeLeak.cfg | native Gemini reads a LiteLLM signature | fails after 1 turn | +\* | ThoughtSignature.DropStored.cfg | stored signature never sent (bypass only) | fails after 1 turn | \* Fixed also holds at MaxTurns 3 (11,155 states). \* Replay of Legacy: issue 2064. The reporter used a Gemini model behind a custom gateway alias. \* Residual (Unlisted): an alias missing from the catalog gets no bypass for a call from another model. @@ -41,18 +47,16 @@ \* Oracle: the routed model of a Gemini alias matches isLiteLLMThoughtSignatureModel. \* Not modeled: R1 format, id normalization, the native position of the signature (it is on every call). \* Property test: lite-llm.spec.ts, "never sends a call that a backend rejects" (220 cases). -\* It checks both invariants for a listed model and NoCorruptIdDecode for an unlisted model. -\* Sabotage of the code: NameOnly, MarkerAlways, NoMarker, NoOrigin, ModelOnly and AllCalls fail it. +\* It checks NoRejectedCall for a listed model, and NoCorruptIdDecode and SignatureDelivered for both. +\* Sabotage of the code: NameOnly, MarkerAlways, NoMarker, NoOrigin, ModelOnly, AllCalls and DropStored fail it. \* NoReset passes it. NoReset needs two requests on one handler. The test "resets it per request" covers that. \* OldRegex passes it. The test sets the catalog flag. The fetcher and matcher tests fail on OldRegex. \* Cost: TLC runs each config in under 2 seconds. Agent time is not measured. -\* Review: 2 covered, 1 added, 5 gap, 0 on the spec files (PR 2119). See the list below Rejected. +\* Review: 2 covered, 1 added, 5 gap, 1 on the spec files (PR 2119). See the list below Rejected. \* The first version came after the code and the reviews. It is not an independent first pass. EXTENDS Naturals, Sequences -CONSTANTS MaxTurns, Variant - VARIABLE history \* One assistant message per turn. Each message has the fields of Message. \* g1 and g2: one Gemini model on two gateways. g4: a Gemini 4 model id. @@ -69,62 +73,62 @@ Routed(b) == CASE b = "alias" -> "gemini/gemini-3-pro" \* litellm_params.model LiteLlm(b) == b # "native" RunsGemini(b) == b \in {"g1", "g2", "g4", "alias", "native"} -\* isLiteLLMThoughtSignatureModel. OldRegex and Legacy use the matcher from before the PR. -NameMatch(name) == - name \in IF Variant \in {"OldRegex", "Legacy"} THEN {"gemini-3-pro", "gemini/gemini-3-pro"} - ELSE {"gemini-3-pro", "gemini-4-pro", "gemini/gemini-3-pro"} +\* The names that isLiteLLMThoughtSignatureModel matches. +SignatureModelNames == {"gemini-3-pro", "gemini-4-pro", "gemini/gemini-3-pro"} +NameMatch(name) == name \in SignatureModelNames \* requiresThoughtSignatures from getLiteLLMModels. -Flagged(b) == Variant \notin {"NameOnly", "Legacy"} /\ NameMatch(Routed(b)) +Flagged(b) == NameMatch(Routed(b)) \* The bypass condition in createMessage. listed: the catalog has the model id. Detected(t, listed) == (listed /\ Flagged(t)) \/ NameMatch(ModelOf(t)) -Listed == IF Variant = "Unlisted" THEN BOOLEAN ELSE {TRUE} +\* The catalog outcomes that NoRejectedCall covers. +Listed == {TRUE} -\* thoughtSignatureOrigin(litellmBaseUrl || default, modelId). ModelOnly drops the URL. -Origin(b) == IF Variant = "ModelOnly" THEN ModelOf(b) ELSE Url(b) \o "|" \o ModelOf(b) +\* thoughtSignatureOrigin(litellmBaseUrl || default, modelId). +Origin(b) == Url(b) \o "|" \o ModelOf(b) None == [by |-> "none", step |-> 0] Bypass == [by |-> "bypass", step |-> 0] Real(s) == s.by \in Backends \* getThoughtSignatureOrigin of the handler that streamed the message. Native Gemini stores none. StoredOrigin(m) == IF LiteLlm(m.by) /\ Real(m.sig) THEN Origin(m.by) ELSE "none" -Sigs == {None, Bypass} \cup [by : Backends, step : 1..MaxTurns] +Sigs == {None, Bypass} \cup [by : Backends, step : Nat \ {0}] Message == [by : Backends, n : 1..2, marker : BOOLEAN, sig : Sigs] -TypeOK == history \in Seq(Message) /\ Len(history) <= MaxTurns +TypeOK == history \in Seq(Message) Init == history = <<>> -\* lastThoughtSignature after the stream. NoReset keeps the value from the last request on this handler. -Captured(t, k, minted) == - LET prev == history[k - 1] - kept == Variant = "NoReset" /\ k > 1 /\ prev.by = t /\ Real(prev.sig) - reads == ~(Variant = "Legacy" /\ LiteLlm(t)) \* The old LiteLLM handler did not read it. - IN IF kept THEN prev.sig ELSE IF minted /\ reads THEN [by |-> t, step |-> k] ELSE None +\* lastThoughtSignature after the stream. createMessage resets it per request. +Captured(t, k, minted) == IF minted THEN [by |-> t, step |-> k] ELSE None \* A turn on backend t returns n tool calls. A Gemini backend can sign the first call. \* LiteLLM then also writes the signature into the id of that call, after __thought__. Turn(t, n, minted) == LET k == Len(history) + 1 - sig == Captured(t, k, minted) - IN /\ k <= MaxTurns - /\ minted => RunsGemini(t) - /\ history' = Append(history, [by |-> t, n |-> n, marker |-> minted /\ LiteLlm(t), sig |-> sig]) + IN /\ minted => RunsGemini(t) + /\ history' = Append(history, [by |-> t, n |-> n, marker |-> minted /\ LiteLlm(t), + sig |-> Captured(t, k, minted)]) Next == \E t \in Backends, n \in 1..2, minted \in BOOLEAN : Turn(t, n, minted) Spec == Init /\ [][Next]_history +\* applyThoughtSignatures sends a stored signature only to the backend that minted it. +OriginMatches(m, t) == StoredOrigin(m) = Origin(t) +\* Gemini signs only the first call of a step. +SignedCall(i) == i = 1 +\* A sanitized __thought__ id gets the bypass only for a model missing from the catalog. +MarkerFallback(m, listed, i) == m.marker /\ i = 1 /\ ~listed +\* convertAnthropicContentToGemini uses only a signature without an origin. +NativeUses(m) == StoredOrigin(m) = "none" + \* The signature that a request to backend t puts on call i of history message k. Sent(t, listed, k, i) == LET m == history[k] IN IF LiteLlm(t) - THEN LET matches == Real(m.sig) /\ (Variant = "NoOrigin" \/ StoredOrigin(m) = Origin(t)) - first == i = 1 \/ Variant = "AllCalls" - markerFallback == m.marker /\ i = 1 /\ Variant \notin {"NoMarker", "Legacy"} - /\ (~listed \/ Variant = "MarkerAlways") - IN IF matches /\ first /\ Variant # "Legacy" THEN m.sig - ELSE IF Detected(t, listed) \/ markerFallback THEN Bypass - ELSE None - ELSE IF Real(m.sig) /\ (StoredOrigin(m) = "none" \/ Variant = "NativeLeak") THEN m.sig ELSE Bypass + THEN IF Real(m.sig) /\ OriginMatches(m, t) /\ SignedCall(i) THEN m.sig + ELSE IF Detected(t, listed) \/ MarkerFallback(m, listed, i) THEN Bypass + ELSE None + ELSE IF Real(m.sig) /\ NativeUses(m) THEN m.sig ELSE Bypass \* LiteLLM decodes the sanitized __thought__ id of a call that has no field. DecodesCorruptId(t, listed, k, i) == @@ -143,8 +147,10 @@ Rejected(t, listed, k, i) == \* added: CodeRabbit 4532185300. Two gateways with one model id share an origin (ModelOnly). \* gap: 4532185306 (a throw and a reasoning id), 4532185311 (test helper). The spec has no ids or exceptions. \* gap: edelauna R1 path test, CodeRabbit on sanitizeLiteLlmCallId and its test. The PR removed that code. +\* spec file: CodeRabbit 4634073736. The variants moved to ThoughtSignatureMC.tla. No verdict or state count changed. \* Rounds 2 and 3 are not review findings. Round 2 fixes the round 1 finding of this spec. \* Round 3 comes from a web search for best practice (BerriAI/litellm#19739, vercel/ai#15550). +\* Round 4 comes from the simplify pass. A property must constrain the result, not only reject a crash. \* Safety: no backend rejects a tool call in the history. NoRejectedCall == @@ -156,4 +162,9 @@ NoCorruptIdDecode == \A t \in Backends, listed \in BOOLEAN, k \in 1..Len(history) : \A i \in 1..history[k].n : ~DecodesCorruptId(t, listed, k, i) +\* Safety: a LiteLLM backend gets back the signature it minted, on the first call of that message. +SignatureDelivered == + \A t \in Backends, listed \in BOOLEAN, k \in 1..Len(history) : + LiteLlm(t) /\ history[k].by = t /\ Real(history[k].sig) => Sent(t, listed, k, 1) = history[k].sig + ==== diff --git a/docs/architecture/tla/ThoughtSignatureMC.tla b/docs/architecture/tla/ThoughtSignatureMC.tla new file mode 100644 index 0000000000..08635942f6 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureMC.tla @@ -0,0 +1,35 @@ +---- MODULE ThoughtSignatureMC ---- +\* Model-checking settings and variants for ThoughtSignature. Each config replaces operators with these. +EXTENDS ThoughtSignature + +CONSTANT MaxTurns +Bounded == Len(history) <= MaxTurns + +\* OldRegex and Legacy: the matcher before the PR (Gemini 3 and 2.5 only). +OldNames == {"gemini-3-pro", "gemini/gemini-3-pro"} +\* NameOnly and Legacy: no catalog flag. +NoFlag(b) == FALSE +\* Unlisted: the model can be missing from the catalog. +AnyListed == BOOLEAN +\* ModelOnly: the origin ignores litellmBaseUrl. +ModelOrigin(b) == ModelOf(b) +\* NoOrigin: no origin check. +AnyOrigin(m, t) == TRUE +\* AllCalls: a signature on every parallel call. +EveryCall(i) == TRUE +\* NoMarker and Legacy: no __thought__ fallback. +NoMarkerFallback(m, listed, i) == FALSE +\* MarkerAlways: the round 2 code. The __thought__ fallback also applies to a listed model. +MarkerAlways(m, listed, i) == m.marker /\ i = 1 +\* DropStored: applyThoughtSignatures never sends a stored signature. +NeverMatch(m, t) == FALSE +\* NativeLeak: native Gemini uses a LiteLLM signature. +NativeAny(m) == TRUE +\* NoReset: lastThoughtSignature keeps the value from the last request on this handler. +CapturedKept(t, k, minted) == + IF k > 1 /\ history[k - 1].by = t /\ Real(history[k - 1].sig) THEN history[k - 1].sig + ELSE IF minted THEN [by |-> t, step |-> k] ELSE None +\* Legacy: the old LiteLLM handler did not read the signature. +CapturedNative(t, k, minted) == IF LiteLlm(t) THEN None ELSE Captured(t, k, minted) + +==== diff --git a/docs/architecture/tla/check.sh b/docs/architecture/tla/check.sh index 46cc6ee738..8f068b4de3 100755 --- a/docs/architecture/tla/check.sh +++ b/docs/architecture/tla/check.sh @@ -19,11 +19,14 @@ for spec in $specs; do if [ $all = 1 ] && ! ls "$spec".*.cfg >/dev/null 2>&1; then continue; fi echo "WRONG $spec.cfg is missing"; bad=1; continue fi + # The configs check SpecMC.tla when it exists. It holds the model-checking settings. + module=$spec.tla + [ ! -f "${spec}MC.tla" ] || module=${spec}MC.tla for cfg in "$spec".cfg "$spec".*.cfg; do [ -f "$cfg" ] || continue want=pass [ "$cfg" = "$spec.cfg" ] || want=fail - java -XX:+UseParallelGC -cp "$TLA_JAR" tlc2.TLC -metadir "$(mktemp -d -p "$meta")/s" -config "$cfg" "$spec.tla" >"$meta/out" 2>&1 + java -XX:+UseParallelGC -cp "$TLA_JAR" tlc2.TLC -metadir "$(mktemp -d -p "$meta")/s" -config "$cfg" "$module" >"$meta/out" 2>&1 got=unknown grep -q "No error has been found" "$meta/out" && got=pass grep -q "violated" "$meta/out" && got=fail diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index eec34bd19d..7dece92c67 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -988,8 +988,11 @@ describe("LiteLLMHandler", () => { ? decodesCorruptId(call) || (listed && invalidOrMissing(call)) : listed && call.sig !== undefined, ) + // SignatureDelivered: a LiteLLM backend gets back the signature it minted. + const delivered = !(minted && source === target) || sent[0]?.sig === signature expect(sent).toHaveLength(n) expect(rejected).toEqual([]) + expect(delivered).toBe(true) }, ) }) diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index 8d09c8b547..babd74f16e 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -400,7 +400,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa } getThoughtSignatureOrigin(): string | undefined { - return this.lastThoughtSignature ? this.thoughtSignatureOrigin : undefined + return this.thoughtSignatureOrigin } async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { From 0c64a154f543ed2e0db1236365369e9c3c7c2840 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 21 Nov 2026 15:07:42 -0500 Subject: [PATCH 6/6] docs(tla): stop CapturedNative from calling its own replacement --- docs/architecture/tla/ThoughtSignature.tla | 3 ++- docs/architecture/tla/ThoughtSignatureMC.tla | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/architecture/tla/ThoughtSignature.tla b/docs/architecture/tla/ThoughtSignature.tla index d97aa6b776..2c82171d0a 100644 --- a/docs/architecture/tla/ThoughtSignature.tla +++ b/docs/architecture/tla/ThoughtSignature.tla @@ -52,7 +52,7 @@ \* NoReset passes it. NoReset needs two requests on one handler. The test "resets it per request" covers that. \* OldRegex passes it. The test sets the catalog flag. The fetcher and matcher tests fail on OldRegex. \* Cost: TLC runs each config in under 2 seconds. Agent time is not measured. -\* Review: 2 covered, 1 added, 5 gap, 1 on the spec files (PR 2119). See the list below Rejected. +\* Review: 2 covered, 1 added, 5 gap, 2 on the spec files (PR 2119). See the list below Rejected. \* The first version came after the code and the reviews. It is not an independent first pass. EXTENDS Naturals, Sequences @@ -148,6 +148,7 @@ Rejected(t, listed, k, i) == \* gap: 4532185306 (a throw and a reasoning id), 4532185311 (test helper). The spec has no ids or exceptions. \* gap: edelauna R1 path test, CodeRabbit on sanitizeLiteLlmCallId and its test. The PR removed that code. \* spec file: CodeRabbit 4634073736. The variants moved to ThoughtSignatureMC.tla. No verdict or state count changed. +\* spec file: CodeRabbit 4650658263. CapturedNative called Captured, its own replacement. The Legacy violation hid it. \* Rounds 2 and 3 are not review findings. Round 2 fixes the round 1 finding of this spec. \* Round 3 comes from a web search for best practice (BerriAI/litellm#19739, vercel/ai#15550). \* Round 4 comes from the simplify pass. A property must constrain the result, not only reject a crash. diff --git a/docs/architecture/tla/ThoughtSignatureMC.tla b/docs/architecture/tla/ThoughtSignatureMC.tla index 08635942f6..9b43040918 100644 --- a/docs/architecture/tla/ThoughtSignatureMC.tla +++ b/docs/architecture/tla/ThoughtSignatureMC.tla @@ -30,6 +30,6 @@ CapturedKept(t, k, minted) == IF k > 1 /\ history[k - 1].by = t /\ Real(history[k - 1].sig) THEN history[k - 1].sig ELSE IF minted THEN [by |-> t, step |-> k] ELSE None \* Legacy: the old LiteLLM handler did not read the signature. -CapturedNative(t, k, minted) == IF LiteLlm(t) THEN None ELSE Captured(t, k, minted) +CapturedNative(t, k, minted) == IF ~LiteLlm(t) /\ minted THEN [by |-> t, step |-> k] ELSE None ====