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 new file mode 100644 index 0000000000..3935a4f235 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.AllCalls.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + 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 new file mode 100644 index 0000000000..2dd3b58d33 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.Legacy.cfg @@ -0,0 +1,10 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + 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 new file mode 100644 index 0000000000..10ebca9c2a --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.MarkerAlways.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + MarkerFallback <- MarkerAlways +CONSTRAINT Bounded +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..68873b7035 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.ModelOnly.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Origin <- ModelOrigin +CONSTRAINT Bounded +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..f8f830d966 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NameOnly.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Flagged <- NoFlag +CONSTRAINT Bounded +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..7706a568e7 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NativeLeak.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + NativeUses <- NativeAny +CONSTRAINT Bounded +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..f831695f73 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + MarkerFallback <- NoMarkerFallback +CONSTRAINT Bounded +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..1b4dd26a21 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoOrigin.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + OriginMatches <- AnyOrigin +CONSTRAINT Bounded +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..90bc469a14 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NoReset.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Captured <- CapturedKept +CONSTRAINT Bounded +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..42f8c5309e --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.OldRegex.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + SignatureModelNames <- OldNames +CONSTRAINT Bounded +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..70ab147f3b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.Unlisted.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + Listed <- AnyListed +CONSTRAINT Bounded +INVARIANTS TypeOK NoRejectedCall diff --git a/docs/architecture/tla/ThoughtSignature.cfg b/docs/architecture/tla/ThoughtSignature.cfg new file mode 100644 index 0000000000..3d0f1ce293 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 +CONSTRAINT Bounded +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.tla b/docs/architecture/tla/ThoughtSignature.tla new file mode 100644 index 0000000000..2c82171d0a --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.tla @@ -0,0 +1,171 @@ +---- 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. +\* 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). +\* 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. +\* 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) | +\* | 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 | +\* | 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. +\* 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 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, 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 + +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"} + +\* 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) == NameMatch(Routed(b)) +\* The bypass condition in createMessage. listed: the catalog has the model id. +Detected(t, listed) == (listed /\ Flagged(t)) \/ NameMatch(ModelOf(t)) +\* The catalog outcomes that NoRejectedCall covers. +Listed == {TRUE} + +\* 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 : Nat \ {0}] +Message == [by : Backends, n : 1..2, marker : BOOLEAN, sig : Sigs] + +TypeOK == history \in Seq(Message) + +Init == history = <<>> + +\* 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 + 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 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) == + 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. +\* 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. + +\* 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) + +\* 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..9b43040918 --- /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) /\ minted THEN [by |-> t, step |-> k] ELSE None + +==== 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/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 e4c575c37e..7dece92c67 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -1,8 +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 { + 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" @@ -541,182 +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("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") @@ -792,6 +628,376 @@ describe("LiteLLMHandler", () => { expect(assistantMessage.tool_calls[0].provider_specific_fields.thought_signature).toBe(dummySignature) }) + describe("real thought signature round trip", () => { + const origin = thoughtSignatureOrigin("http://localhost:4000", "gemini-3-pro") + const metadata = makeCreateMessageMetadata({ + tools: [ + { + type: "function", + function: { name: "read_file", description: "Read a file", parameters: {} }, + }, + ], + }) + + function mockStream(chunks: unknown[]) { + mockCreate.mockReturnValue({ + withResponse: vi.fn().mockResolvedValue({ data: asyncStreamFrom(chunks) }), + }) + } + + 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 = [ + { choices: [{ delta: { content: "Reading the file." } }] }, + { + choices: [ + { + 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.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) + + await collectStream(handler.createMessage("system", [{ role: "user", content: "Hi" }], metadata)) + expect(handler.getThoughtSignature()).toBe(TEST_THOUGHT_SIGNATURE) + expect(handler.getThoughtSignatureOrigin()).toBe(origin) + + 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(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, bypassed], + }, + { + 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.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" } }] }]) + + 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(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, + ) + // 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) + }, + ) + }) + }) + it("should not inject thought signatures for non-Gemini models", async () => { const optionsWithGPT4: ApiHandlerOptions = { ...mockOptions, 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 6c82e61bd4..babd74f16e 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" @@ -19,6 +20,12 @@ 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 { + LITELLM_THOUGHT_SIGNATURE_ID_MARKER, + applyThoughtSignatures, + readThoughtSignature, + thoughtSignatureOrigin, +} from "./utils/thought-signature" import type { SingleCompletionHandler, @@ -41,6 +48,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 +57,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, @@ -99,75 +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) - ) - } - - /** - * 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 +120,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 @@ -285,16 +229,25 @@ 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. - const isGemini = this.isGeminiModel(modelId) - let processedMessages = enhancedMessages - if (isGemini) { - processedMessages = this.injectThoughtSignatureForGemini(enhancedMessages) - } + // 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. + // 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, + ) + const processedMessages = applyThoughtSignatures(messages, enhancedMessages, { + origin: this.thoughtSignatureOrigin, + normalizeToolCallId: sanitizeOpenAiCallId, + fallback: (toolCallId) => + isGemini || (!listed && toolCallId.includes(LITELLM_THOUGHT_SIGNATURE_ID_MARKER)) + ? GEMINI_THOUGHT_SIGNATURE_BYPASS + : undefined, + }) const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { model: modelId, @@ -373,6 +326,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 +395,14 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa } } + getThoughtSignature(): string | undefined { + return this.lastThoughtSignature + } + + getThoughtSignatureOrigin(): string | undefined { + return this.thoughtSignatureOrigin + } + 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..d05319a3a7 --- /dev/null +++ b/src/api/providers/utils/__tests__/thought-signature.spec.ts @@ -0,0 +1,156 @@ +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("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) + + 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__/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/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..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": 36 + "count": 26 } }, "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..081b9ac52d --- /dev/null +++ b/src/test-utils/thought-signature.ts @@ -0,0 +1,44 @@ +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, + 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 } : {}) }, + ] + // 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 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 +}