@@ -4,6 +4,7 @@ import { logApiEvent } from "./api-log.ts";
44 import {
55 getThinkingProviderOptions,
66 parseModelString,
7+ shouldDisableGeminiThinkingForTools,
78 type ThinkingEffort,
89 } from "./providers.ts";
910 import type { ToolDef, TurnEvent } from "./types.ts";
@@ -48,6 +49,105 @@ function toCoreTool(def: ToolDef): ReturnType<typeof dynamicTool> {
4849 });
4950 }
5051
52+function isRecord(value: unknown): value is Record<string, unknown> {
53+ return value !== null && typeof value === "object";
54+}
55+
56+function normalizeProviderOptions<T>(part: T): T {
57+ if (!isRecord(part)) return part;
58+ if (
59+ part.providerOptions !== undefined ||
60+ part.providerMetadata === undefined
61+ ) {
62+ return part;
63+ }
64+ return {
65+ ...part,
66+ providerOptions: part.providerMetadata,
67+ } as T;
68+}
69+
70+function normalizeMessageProviderOptions(message: CoreMessage): CoreMessage {
71+ if (!Array.isArray(message.content)) return message;
72+ return {
73+ ...message,
74+ content: message.content.map((part) =>
75+ normalizeProviderOptions(part),
76+ ) as CoreMessage["content"],
77+ } as CoreMessage;
78+}
79+
80+function getGeminiThoughtSignature(part: unknown): string | null {
81+ if (!isRecord(part)) return null;
82+ const providerOptions = isRecord(part.providerOptions)
83+ ? part.providerOptions
84+ : isRecord(part.providerMetadata)
85+ ? part.providerMetadata
86+ : null;
87+ if (!providerOptions) return null;
88+
89+ for (const provider of ["google", "vertex"] as const) {
90+ const metadata = providerOptions[provider];
91+ if (!isRecord(metadata)) continue;
92+ const signature = metadata.thoughtSignature;
93+ if (typeof signature === "string" && signature.length > 0) {
94+ return signature;
95+ }
96+ }
97+
98+ return null;
99+}
100+
101+function isToolCallPart(part: unknown): part is Record<string, unknown> {
102+ return isRecord(part) && part.type === "tool-call";
103+}
104+
105+function assistantMessageHasUnsignedGeminiToolCall(
106+ message: CoreMessage,
107+): boolean {
108+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
109+ return false;
110+ }
111+
112+ for (const part of message.content) {
113+ if (!isToolCallPart(part)) continue;
114+ if (getGeminiThoughtSignature(part) === null) return true;
115+ }
116+
117+ return false;
118+}
119+
120+export function sanitizeGeminiToolMessages(
121+ messages: CoreMessage[],
122+ modelString: string,
123+ hasTools: boolean,
124+): CoreMessage[] {
125+ if (!hasTools || !shouldDisableGeminiThinkingForTools(modelString)) {
126+ return messages;
127+ }
128+
129+ let sanitized = messages.map((message) =>
130+ normalizeMessageProviderOptions(message),
131+ );
132+
133+ while (true) {
134+ const brokenIndex = sanitized.findIndex((message) =>
135+ assistantMessageHasUnsignedGeminiToolCall(message),
136+ );
137+ if (brokenIndex === -1) return sanitized;
138+
139+ const nextUserIndex = sanitized.findIndex(
140+ (message, index) => index > brokenIndex && message.role === "user",
141+ );
142+ if (nextUserIndex !== -1) {
143+ sanitized = sanitized.slice(nextUserIndex);
144+ continue;
145+ }
146+
147+ return sanitized.slice(0, brokenIndex);
148+ }
149+}
150+
51151 // ─── Main turn function ───────────────────────────────────────────────────────
52152
53153 /**
@@ -112,8 +212,21 @@ export async function* runTurn(options: {
112212
113213 logApiEvent("turn start", { modelString, messageCount: messages.length });
114214
215+ const toolCount = Object.keys(toolSet).length;
216+ const turnMessages = sanitizeGeminiToolMessages(
217+ messages,
218+ modelString,
219+ toolCount > 0,
220+ );
221+ if (turnMessages.length !== messages.length) {
222+ logApiEvent("gemini tool history truncated", {
223+ modelString,
224+ originalMessages: messages.length,
225+ sanitizedMessages: turnMessages.length,
226+ });
227+ }
115228 const thinkingOpts = thinkingEffort
116- ? getThinkingProviderOptions(modelString, thinkingEffort)
229+ ? getThinkingProviderOptions(modelString, thinkingEffort, toolCount > 0)
117230 : null;
118231
119232 const mergedProviderOptions = {
@@ -134,7 +247,7 @@ export async function* runTurn(options: {
134247
135248 const streamOpts: StreamTextOptions = {
136249 model,
137- messages,
250+ messages: turnMessages,
138251 tools: toolSet,
139252 stopWhen: stepCountIs(MAX_STEPS),
140253 onStepFinish: (step: StepResult<ToolSet>) => {