xonecas.io
64875
Mc

mini-coder / commit fe79440

refactor: split history transforms and terminal width utilities

xonecas2026-03-14 fe79440b5218c15531766cf5ba5fe002e35354f9 parent 90c67e1

4 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

src/cli/stream-render.ts+1−121
@@ -13,6 +13,7 @@ import {
1313 normalizeReasoningText,
1414 } from "./reasoning.ts";
1515 import type { Spinner } from "./spinner.ts";
16+import { visibleLength } from "./terminal-width.ts";
1617 import { renderToolCall, renderToolResult } from "./tool-render.ts";
1718
1819 export async function renderTurn(
@@ -83,127 +84,6 @@ export async function renderTurn(
8384 return rendered.output;
8485 }
8586
86- const emojiLikeRegex = /\p{Extended_Pictographic}/u;
87- const ansiEscapeChar = String.fromCharCode(0x1b);
88- const graphemeSegmenter =
89- typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
90- ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
91- : null;
92-
93- function stripSgrAnsi(s: string): string {
94- if (!s) return "";
95- let out = "";
96- for (let i = 0; i < s.length; i++) {
97- if (s[i] !== ansiEscapeChar || s[i + 1] !== "[") {
98- out += s[i] ?? "";
99- continue;
100- }
101-
102- let j = i + 2;
103- while (j < s.length) {
104- const ch = s[j] ?? "";
105- if ((ch >= "0" && ch <= "9") || ch === ";") {
106- j++;
107- continue;
108- }
109- break;
110- }
111-
112- if (s[j] === "m") {
113- i = j;
114- continue;
115- }
116-
117- out += s[i] ?? "";
118- }
119- return out;
120- }
121-
122- function isControlCodePoint(cp: number): boolean {
123- return (cp >= 0 && cp <= 0x1f) || (cp >= 0x7f && cp <= 0x9f);
124- }
125-
126- function isCombiningCodePoint(cp: number): boolean {
127- return (
128- (cp >= 0x0300 && cp <= 0x036f) ||
129- (cp >= 0x1ab0 && cp <= 0x1aff) ||
130- (cp >= 0x1dc0 && cp <= 0x1dff) ||
131- (cp >= 0x20d0 && cp <= 0x20ff) ||
132- (cp >= 0xfe20 && cp <= 0xfe2f)
133- );
134- }
135-
136- function isVariationSelector(cp: number): boolean {
137- return (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xe0100 && cp <= 0xe01ef);
138- }
139-
140- function isWideCodePoint(cp: number): boolean {
141- return (
142- cp >= 0x1100 &&
143- (cp <= 0x115f ||
144- cp === 0x2329 ||
145- cp === 0x232a ||
146- (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
147- (cp >= 0xac00 && cp <= 0xd7a3) ||
148- (cp >= 0xf900 && cp <= 0xfaff) ||
149- (cp >= 0xfe10 && cp <= 0xfe19) ||
150- (cp >= 0xfe30 && cp <= 0xfe6f) ||
151- (cp >= 0xff00 && cp <= 0xff60) ||
152- (cp >= 0xffe0 && cp <= 0xffe6) ||
153- (cp >= 0x1f300 && cp <= 0x1f64f) ||
154- (cp >= 0x1f900 && cp <= 0x1f9ff) ||
155- (cp >= 0x20000 && cp <= 0x3fffd))
156- );
157- }
158-
159- function graphemeWidth(grapheme: string): number {
160- if (!grapheme) return 0;
161- if (emojiLikeRegex.test(grapheme)) return 2;
162-
163- let width = 0;
164- let hasRegionalIndicator = false;
165- for (const ch of grapheme) {
166- const cp = ch.codePointAt(0);
167- if (cp === undefined) continue;
168- if (cp >= 0x1f1e6 && cp <= 0x1f1ff) hasRegionalIndicator = true;
169- if (
170- isControlCodePoint(cp) ||
171- isCombiningCodePoint(cp) ||
172- isVariationSelector(cp) ||
173- cp === 0x200d ||
174- (cp >= 0x1f3fb && cp <= 0x1f3ff)
175- ) {
176- continue;
177- }
178- width += isWideCodePoint(cp) ? 2 : 1;
179- }
180-
181- if (hasRegionalIndicator) return 2;
182- return width;
183- }
184-
185- function visibleLength(s: string): number {
186- if (!s) return 0;
187- const plain = stripSgrAnsi(s);
188- if (!plain) return 0;
189-
190- if (!graphemeSegmenter) {
191- let width = 0;
192- for (const ch of plain) {
193- const cp = ch.codePointAt(0);
194- if (cp === undefined || isControlCodePoint(cp)) continue;
195- width += isWideCodePoint(cp) ? 2 : 1;
196- }
197- return width;
198- }
199-
200- let width = 0;
201- for (const { segment } of graphemeSegmenter.segment(plain)) {
202- width += graphemeWidth(segment);
203- }
204- return width;
205- }
206-
20787 function estimateWrappedRows(visibleChars: number): number {
20888 if (visibleChars <= 0) return 1;
20989 const cols = process.stdout.columns ?? 0;
src/cli/terminal-width.ts+120−0
@@ -0,0 +1,120 @@
1+const emojiLikeRegex = /\p{Extended_Pictographic}/u;
2+const ansiEscapeChar = String.fromCharCode(0x1b);
3+const graphemeSegmenter =
4+ typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
5+ ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
6+ : null;
7+
8+function stripSgrAnsi(s: string): string {
9+ if (!s) return "";
10+ let out = "";
11+ for (let i = 0; i < s.length; i++) {
12+ if (s[i] !== ansiEscapeChar || s[i + 1] !== "[") {
13+ out += s[i] ?? "";
14+ continue;
15+ }
16+
17+ let j = i + 2;
18+ while (j < s.length) {
19+ const ch = s[j] ?? "";
20+ if ((ch >= "0" && ch <= "9") || ch === ";") {
21+ j++;
22+ continue;
23+ }
24+ break;
25+ }
26+
27+ if (s[j] === "m") {
28+ i = j;
29+ continue;
30+ }
31+
32+ out += s[i] ?? "";
33+ }
34+ return out;
35+}
36+
37+function isControlCodePoint(cp: number): boolean {
38+ return (cp >= 0 && cp <= 0x1f) || (cp >= 0x7f && cp <= 0x9f);
39+}
40+
41+function isCombiningCodePoint(cp: number): boolean {
42+ return (
43+ (cp >= 0x0300 && cp <= 0x036f) ||
44+ (cp >= 0x1ab0 && cp <= 0x1aff) ||
45+ (cp >= 0x1dc0 && cp <= 0x1dff) ||
46+ (cp >= 0x20d0 && cp <= 0x20ff) ||
47+ (cp >= 0xfe20 && cp <= 0xfe2f)
48+ );
49+}
50+
51+function isVariationSelector(cp: number): boolean {
52+ return (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0xe0100 && cp <= 0xe01ef);
53+}
54+
55+function isWideCodePoint(cp: number): boolean {
56+ return (
57+ cp >= 0x1100 &&
58+ (cp <= 0x115f ||
59+ cp === 0x2329 ||
60+ cp === 0x232a ||
61+ (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
62+ (cp >= 0xac00 && cp <= 0xd7a3) ||
63+ (cp >= 0xf900 && cp <= 0xfaff) ||
64+ (cp >= 0xfe10 && cp <= 0xfe19) ||
65+ (cp >= 0xfe30 && cp <= 0xfe6f) ||
66+ (cp >= 0xff00 && cp <= 0xff60) ||
67+ (cp >= 0xffe0 && cp <= 0xffe6) ||
68+ (cp >= 0x1f300 && cp <= 0x1f64f) ||
69+ (cp >= 0x1f900 && cp <= 0x1f9ff) ||
70+ (cp >= 0x20000 && cp <= 0x3fffd))
71+ );
72+}
73+
74+function graphemeWidth(grapheme: string): number {
75+ if (!grapheme) return 0;
76+ if (emojiLikeRegex.test(grapheme)) return 2;
77+
78+ let width = 0;
79+ let hasRegionalIndicator = false;
80+ for (const ch of grapheme) {
81+ const cp = ch.codePointAt(0);
82+ if (cp === undefined) continue;
83+ if (cp >= 0x1f1e6 && cp <= 0x1f1ff) hasRegionalIndicator = true;
84+ if (
85+ isControlCodePoint(cp) ||
86+ isCombiningCodePoint(cp) ||
87+ isVariationSelector(cp) ||
88+ cp === 0x200d ||
89+ (cp >= 0x1f3fb && cp <= 0x1f3ff)
90+ ) {
91+ continue;
92+ }
93+ width += isWideCodePoint(cp) ? 2 : 1;
94+ }
95+
96+ if (hasRegionalIndicator) return 2;
97+ return width;
98+}
99+
100+export function visibleLength(s: string): number {
101+ if (!s) return 0;
102+ const plain = stripSgrAnsi(s);
103+ if (!plain) return 0;
104+
105+ if (!graphemeSegmenter) {
106+ let width = 0;
107+ for (const ch of plain) {
108+ const cp = ch.codePointAt(0);
109+ if (cp === undefined || isControlCodePoint(cp)) continue;
110+ width += isWideCodePoint(cp) ? 2 : 1;
111+ }
112+ return width;
113+ }
114+
115+ let width = 0;
116+ for (const { segment } of graphemeSegmenter.segment(plain)) {
117+ width += graphemeWidth(segment);
118+ }
119+ return width;
120+}
src/llm-api/history-transforms.ts+428−0
@@ -0,0 +1,428 @@
1+import { parseModelString } from "./providers.ts";
2+import type { CoreMessage } from "./turn.ts";
3+
4+type StreamChunk = { type?: string; [key: string]: unknown };
5+
6+type GeminiToolHistoryRepairReason = "missing-signature-anchor";
7+
8+function isRecord(value: unknown): value is Record<string, unknown> {
9+ return value !== null && typeof value === "object";
10+}
11+
12+function normalizeProviderOptions<T>(part: T): T {
13+ if (!isRecord(part)) return part;
14+ if (
15+ part.providerOptions !== undefined ||
16+ part.providerMetadata === undefined
17+ ) {
18+ return part;
19+ }
20+ return {
21+ ...part,
22+ providerOptions: part.providerMetadata,
23+ } as T;
24+}
25+
26+function normalizeMessageProviderOptions(message: CoreMessage): CoreMessage {
27+ if (!Array.isArray(message.content)) return message;
28+ return {
29+ ...message,
30+ content: message.content.map((part) =>
31+ normalizeProviderOptions(part),
32+ ) as CoreMessage["content"],
33+ } as CoreMessage;
34+}
35+
36+function stripOpenAIItemIdFromPart(part: unknown): {
37+ part: unknown;
38+ changed: boolean;
39+} {
40+ if (!isRecord(part)) return { part, changed: false };
41+
42+ let changed = false;
43+ const nextPart = { ...part };
44+
45+ const dropItemId = (field: "providerOptions" | "providerMetadata"): void => {
46+ const source = nextPart[field];
47+ if (!isRecord(source)) return;
48+ const openai = source.openai;
49+ if (!isRecord(openai) || !("itemId" in openai)) return;
50+
51+ const nextOpenAI = { ...openai };
52+ delete nextOpenAI.itemId;
53+ nextPart[field] = { ...source, openai: nextOpenAI };
54+ changed = true;
55+ };
56+
57+ dropItemId("providerOptions");
58+ dropItemId("providerMetadata");
59+
60+ return { part: changed ? nextPart : part, changed };
61+}
62+
63+function getPartProviderOptions(part: unknown): Record<string, unknown> | null {
64+ if (!isRecord(part)) return null;
65+ if (isRecord(part.providerOptions)) return part.providerOptions;
66+ if (isRecord(part.providerMetadata)) return part.providerMetadata;
67+ return null;
68+}
69+
70+function getGeminiThoughtSignature(part: unknown): string | null {
71+ const providerOptions = getPartProviderOptions(part);
72+ if (!providerOptions) return null;
73+
74+ for (const provider of ["google", "vertex"] as const) {
75+ const metadata = providerOptions[provider];
76+ if (!isRecord(metadata)) continue;
77+ const signature = metadata.thoughtSignature;
78+ if (typeof signature === "string" && signature.length > 0) {
79+ return signature;
80+ }
81+ }
82+
83+ return null;
84+}
85+
86+function isToolCallPart(part: unknown): part is Record<string, unknown> {
87+ return isRecord(part) && part.type === "tool-call";
88+}
89+
90+function isGeminiModelFamily(modelString: string): boolean {
91+ const { provider, modelId } = parseModelString(modelString);
92+ return (
93+ (provider === "google" || provider === "zen") &&
94+ modelId.startsWith("gemini-")
95+ );
96+}
97+
98+function isZenOpenAICompatibleChatModel(modelString: string): boolean {
99+ const { provider, modelId } = parseModelString(modelString);
100+ if (provider !== "zen") return false;
101+ return (
102+ !modelId.startsWith("gpt-") &&
103+ !modelId.startsWith("gemini-") &&
104+ !modelId.startsWith("claude-")
105+ );
106+}
107+
108+function validateGeminiAssistantToolCallMessage(message: CoreMessage): {
109+ valid: boolean;
110+ reason: GeminiToolHistoryRepairReason | null;
111+} {
112+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
113+ return { valid: true, reason: null };
114+ }
115+
116+ let firstToolCallPartSeen = false;
117+ for (const part of message.content) {
118+ if (!isToolCallPart(part)) continue;
119+ if (firstToolCallPartSeen) continue;
120+ firstToolCallPartSeen = true;
121+ if (getGeminiThoughtSignature(part) === null) {
122+ return { valid: false, reason: "missing-signature-anchor" };
123+ }
124+ }
125+
126+ return { valid: true, reason: null };
127+}
128+
129+function getOpenAITextPhase(part: unknown): string | null {
130+ const providerOptions = getPartProviderOptions(part);
131+ if (!providerOptions) return null;
132+ const openai = providerOptions.openai;
133+ if (!isRecord(openai)) return null;
134+ return typeof openai.phase === "string" ? openai.phase : null;
135+}
136+
137+function isCommentaryTextPart(part: unknown): boolean {
138+ if (!isRecord(part) || part.type !== "text") return false;
139+ return getOpenAITextPhase(part) === "commentary";
140+}
141+
142+export function getReasoningDeltaFromStreamChunk(
143+ chunk: StreamChunk,
144+): string | null {
145+ if (chunk.type !== "reasoning-delta" && chunk.type !== "reasoning") {
146+ return null;
147+ }
148+ if (typeof chunk.text === "string") return chunk.text;
149+ if (typeof chunk.textDelta === "string") return chunk.textDelta;
150+ if (typeof chunk.delta === "string") return chunk.delta;
151+ return "";
152+}
153+
154+export function isOpenAIGPT(modelString: string): boolean {
155+ const { provider, modelId } = parseModelString(modelString);
156+ return (
157+ (provider === "openai" || provider === "zen") && modelId.startsWith("gpt-")
158+ );
159+}
160+
161+export function stripOpenAIItemIdsFromHistory(
162+ messages: CoreMessage[],
163+ modelString: string,
164+): CoreMessage[] {
165+ if (!isOpenAIGPT(modelString)) return messages;
166+
167+ let mutated = false;
168+ const result = messages.map((message) => {
169+ if (!Array.isArray(message.content)) return message;
170+
171+ let contentMutated = false;
172+ const content = message.content.map((part) => {
173+ const cleaned = stripOpenAIItemIdFromPart(part);
174+ if (cleaned.changed) contentMutated = true;
175+ return cleaned.part;
176+ });
177+
178+ if (!contentMutated) return message;
179+ mutated = true;
180+ return {
181+ ...message,
182+ content: content as CoreMessage["content"],
183+ } as CoreMessage;
184+ });
185+
186+ return mutated ? result : messages;
187+}
188+
189+export function normalizeOpenAICompatibleToolCallInputs(
190+ messages: CoreMessage[],
191+ modelString: string,
192+): CoreMessage[] {
193+ if (!isZenOpenAICompatibleChatModel(modelString)) return messages;
194+
195+ let mutated = false;
196+ const result = messages.map((message) => {
197+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
198+ return message;
199+ }
200+
201+ let contentMutated = false;
202+ const nextContent = message.content.map((part) => {
203+ if (
204+ !isToolCallPart(part) ||
205+ !("input" in part) ||
206+ typeof part.input !== "string"
207+ ) {
208+ return part;
209+ }
210+
211+ try {
212+ const parsed = JSON.parse(part.input);
213+ if (!isRecord(parsed) || Array.isArray(parsed)) return part;
214+ contentMutated = true;
215+ return {
216+ ...part,
217+ input: parsed,
218+ };
219+ } catch {
220+ return part;
221+ }
222+ });
223+
224+ if (!contentMutated) return message;
225+ mutated = true;
226+ return {
227+ ...message,
228+ content: nextContent as CoreMessage["content"],
229+ } as CoreMessage;
230+ });
231+
232+ return mutated ? result : messages;
233+}
234+
235+export function sanitizeGeminiToolMessagesWithMetadata(
236+ messages: CoreMessage[],
237+ modelString: string,
238+ hasTools: boolean,
239+): {
240+ messages: CoreMessage[];
241+ repaired: boolean;
242+ reason: GeminiToolHistoryRepairReason | null;
243+ repairedFromIndex: number;
244+ droppedMessageCount: number;
245+ tailOnlyAffected: boolean;
246+} {
247+ if (!hasTools || !isGeminiModelFamily(modelString)) {
248+ return {
249+ messages,
250+ repaired: false,
251+ reason: null,
252+ repairedFromIndex: -1,
253+ droppedMessageCount: 0,
254+ tailOnlyAffected: true,
255+ };
256+ }
257+
258+ const normalized = messages.map((message) =>
259+ normalizeMessageProviderOptions(message),
260+ );
261+
262+ for (let index = normalized.length - 1; index >= 0; index -= 1) {
263+ const message = normalized[index];
264+ if (!message) continue;
265+ if (message.role !== "assistant" || !Array.isArray(message.content))
266+ continue;
267+ if (!message.content.some((part) => isToolCallPart(part))) continue;
268+
269+ const validation = validateGeminiAssistantToolCallMessage(message);
270+ if (validation.valid) {
271+ return {
272+ messages: normalized,
273+ repaired: false,
274+ reason: null,
275+ repairedFromIndex: -1,
276+ droppedMessageCount: 0,
277+ tailOnlyAffected: true,
278+ };
279+ }
280+
281+ const nextUserIndex = normalized.findIndex(
282+ (candidate, candidateIndex) =>
283+ candidateIndex > index && candidate?.role === "user",
284+ );
285+ if (nextUserIndex === -1) {
286+ return {
287+ messages: normalized.slice(0, index),
288+ repaired: true,
289+ reason: validation.reason,
290+ repairedFromIndex: index,
291+ droppedMessageCount: normalized.length - index,
292+ tailOnlyAffected: true,
293+ };
294+ }
295+
296+ return {
297+ messages: [
298+ ...normalized.slice(0, index),
299+ ...normalized.slice(nextUserIndex),
300+ ],
301+ repaired: true,
302+ reason: validation.reason,
303+ repairedFromIndex: index,
304+ droppedMessageCount: nextUserIndex - index,
305+ tailOnlyAffected: false,
306+ };
307+ }
308+
309+ return {
310+ messages: normalized,
311+ repaired: false,
312+ reason: null,
313+ repairedFromIndex: -1,
314+ droppedMessageCount: 0,
315+ tailOnlyAffected: true,
316+ };
317+}
318+
319+export function sanitizeGeminiToolMessages(
320+ messages: CoreMessage[],
321+ modelString: string,
322+ hasTools: boolean,
323+): CoreMessage[] {
324+ return sanitizeGeminiToolMessagesWithMetadata(messages, modelString, hasTools)
325+ .messages;
326+}
327+
328+export function stripGPTCommentaryFromHistory(
329+ messages: CoreMessage[],
330+ modelString: string,
331+): CoreMessage[] {
332+ if (!isOpenAIGPT(modelString)) return messages;
333+
334+ let mutated = false;
335+ const result: CoreMessage[] = [];
336+ let skipToolResults = false;
337+
338+ for (const message of messages) {
339+ if (skipToolResults) {
340+ if (message.role === "tool") {
341+ mutated = true;
342+ continue;
343+ }
344+ skipToolResults = false;
345+ }
346+
347+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
348+ result.push(message);
349+ continue;
350+ }
351+
352+ const filtered = message.content.filter(
353+ (part) => !isCommentaryTextPart(part),
354+ );
355+ if (filtered.length === message.content.length) {
356+ result.push(message);
357+ } else if (filtered.length === 0) {
358+ mutated = true;
359+ skipToolResults = true;
360+ } else {
361+ mutated = true;
362+ result.push({ ...message, content: filtered } as CoreMessage);
363+ }
364+ }
365+
366+ return mutated ? result : messages;
367+}
368+
369+export function stripOpenAIHistoryTransforms(
370+ messages: CoreMessage[],
371+ modelString: string,
372+): CoreMessage[] {
373+ if (!isOpenAIGPT(modelString)) return messages;
374+
375+ let mutated = false;
376+ const result: CoreMessage[] = [];
377+ let skipToolResults = false;
378+
379+ for (const message of messages) {
380+ if (skipToolResults) {
381+ if (message.role === "tool") {
382+ mutated = true;
383+ continue;
384+ }
385+ skipToolResults = false;
386+ }
387+
388+ let contentMutated = false;
389+ const strippedContent = Array.isArray(message.content)
390+ ? message.content.map((part) => {
391+ const cleaned = stripOpenAIItemIdFromPart(part);
392+ if (cleaned.changed) contentMutated = true;
393+ return cleaned.part;
394+ })
395+ : message.content;
396+
397+ const msgAfterIdStrip: CoreMessage = contentMutated
398+ ? ({
399+ ...message,
400+ content: strippedContent as CoreMessage["content"],
401+ } as CoreMessage)
402+ : message;
403+
404+ if (contentMutated) mutated = true;
405+
406+ if (
407+ message.role === "assistant" &&
408+ Array.isArray(msgAfterIdStrip.content)
409+ ) {
410+ const filtered = msgAfterIdStrip.content.filter(
411+ (part) => !isCommentaryTextPart(part),
412+ );
413+ if (filtered.length === msgAfterIdStrip.content.length) {
414+ result.push(msgAfterIdStrip);
415+ } else if (filtered.length === 0) {
416+ mutated = true;
417+ skipToolResults = true;
418+ } else {
419+ mutated = true;
420+ result.push({ ...msgAfterIdStrip, content: filtered } as CoreMessage);
421+ }
422+ } else {
423+ result.push(msgAfterIdStrip);
424+ }
425+ }
426+
427+ return mutated ? result : messages;
428+}
src/llm-api/turn.ts+18−473
@@ -7,11 +7,20 @@ import {
77 streamText,
88 } from "ai";
99 import { isApiLogEnabled, logApiEvent } from "./api-log.ts";
10+import {
11+ getReasoningDeltaFromStreamChunk,
12+ isOpenAIGPT,
13+ normalizeOpenAICompatibleToolCallInputs,
14+ sanitizeGeminiToolMessages,
15+ sanitizeGeminiToolMessagesWithMetadata,
16+ stripGPTCommentaryFromHistory,
17+ stripOpenAIHistoryTransforms,
18+ stripOpenAIItemIdsFromHistory,
19+} from "./history-transforms.ts";
1020 import {
1121 getCacheFamily,
1222 getCachingProviderOptions,
1323 getThinkingProviderOptions,
14- parseModelString,
1524 type ThinkingEffort,
1625 } from "./providers.ts";
1726 import type { ToolDef, TurnEvent } from "./types.ts";
@@ -263,18 +272,6 @@ export function compactToolResultPayloads(
263272 return mutated ? compacted : messages;
264273 }
265274
266-export function getReasoningDeltaFromStreamChunk(
267- chunk: StreamChunk,
268-): string | null {
269- if (chunk.type !== "reasoning-delta" && chunk.type !== "reasoning") {
270- return null;
271- }
272- if (typeof chunk.text === "string") return chunk.text;
273- if (typeof chunk.textDelta === "string") return chunk.textDelta;
274- if (typeof chunk.delta === "string") return chunk.delta;
275- return "";
276-}
277-
278275 type StreamTextResult = ReturnType<typeof streamText>;
279276 type StreamTextResultFull = StreamTextResult & {
280277 fullStream: AsyncIterable<StreamChunk>;
@@ -312,466 +309,14 @@ function isRecord(value: unknown): value is Record<string, unknown> {
312309 return value !== null && typeof value === "object";
313310 }
314311
315-function normalizeProviderOptions<T>(part: T): T {
316- if (!isRecord(part)) return part;
317- if (
318- part.providerOptions !== undefined ||
319- part.providerMetadata === undefined
320- ) {
321- return part;
322- }
323- return {
324- ...part,
325- providerOptions: part.providerMetadata,
326- } as T;
327-}
328-
329-function normalizeMessageProviderOptions(message: CoreMessage): CoreMessage {
330- if (!Array.isArray(message.content)) return message;
331- return {
332- ...message,
333- content: message.content.map((part) =>
334- normalizeProviderOptions(part),
335- ) as CoreMessage["content"],
336- } as CoreMessage;
337-}
338-
339-function stripOpenAIItemIdFromPart(part: unknown): {
340- part: unknown;
341- changed: boolean;
342-} {
343- if (!isRecord(part)) return { part, changed: false };
344-
345- let changed = false;
346- const nextPart = { ...part };
347-
348- const dropItemId = (field: "providerOptions" | "providerMetadata"): void => {
349- const source = nextPart[field];
350- if (!isRecord(source)) return;
351- const openai = source.openai;
352- if (!isRecord(openai) || !("itemId" in openai)) return;
353-
354- const nextOpenAI = { ...openai };
355- delete nextOpenAI.itemId;
356- nextPart[field] = { ...source, openai: nextOpenAI };
357- changed = true;
358- };
359-
360- dropItemId("providerOptions");
361- dropItemId("providerMetadata");
362-
363- return { part: changed ? nextPart : part, changed };
364-}
365-
366-export function stripOpenAIItemIdsFromHistory(
367- messages: CoreMessage[],
368- modelString: string,
369-): CoreMessage[] {
370- if (!isOpenAIGPT(modelString)) return messages;
371-
372- let mutated = false;
373- const result = messages.map((message) => {
374- if (!Array.isArray(message.content)) return message;
375-
376- let contentMutated = false;
377- const content = message.content.map((part) => {
378- const cleaned = stripOpenAIItemIdFromPart(part);
379- if (cleaned.changed) contentMutated = true;
380- return cleaned.part;
381- });
382-
383- if (!contentMutated) return message;
384- mutated = true;
385- return {
386- ...message,
387- content: content as CoreMessage["content"],
388- } as CoreMessage;
389- });
390-
391- return mutated ? result : messages;
392-}
393-
394-/**
395- * Reads the effective provider-options record for a content part, checking
396- * both the modern `providerOptions` field and the legacy `providerMetadata`
397- * alias (used by some older AI SDK versions and Gemini adapters).
398- */
399-function getPartProviderOptions(part: unknown): Record<string, unknown> | null {
400- if (!isRecord(part)) return null;
401- if (isRecord(part.providerOptions)) return part.providerOptions;
402- if (isRecord(part.providerMetadata)) return part.providerMetadata;
403- return null;
404-}
405-
406-function getGeminiThoughtSignature(part: unknown): string | null {
407- const providerOptions = getPartProviderOptions(part);
408- if (!providerOptions) return null;
409-
410- for (const provider of ["google", "vertex"] as const) {
411- const metadata = providerOptions[provider];
412- if (!isRecord(metadata)) continue;
413- const signature = metadata.thoughtSignature;
414- if (typeof signature === "string" && signature.length > 0) {
415- return signature;
416- }
417- }
418-
419- return null;
420-}
421-
422-function isToolCallPart(part: unknown): part is Record<string, unknown> {
423- return isRecord(part) && part.type === "tool-call";
424-}
425-
426-function isGeminiModelFamily(modelString: string): boolean {
427- const { provider, modelId } = parseModelString(modelString);
428- return (
429- (provider === "google" || provider === "zen") &&
430- modelId.startsWith("gemini-")
431- );
432-}
433-
434-function isZenOpenAICompatibleChatModel(modelString: string): boolean {
435- const { provider, modelId } = parseModelString(modelString);
436- if (provider !== "zen") return false;
437- return (
438- !modelId.startsWith("gpt-") &&
439- !modelId.startsWith("gemini-") &&
440- !modelId.startsWith("claude-")
441- );
442-}
443-
444-export function normalizeOpenAICompatibleToolCallInputs(
445- messages: CoreMessage[],
446- modelString: string,
447-): CoreMessage[] {
448- if (!isZenOpenAICompatibleChatModel(modelString)) return messages;
449-
450- let mutated = false;
451- const result = messages.map((message) => {
452- if (message.role !== "assistant" || !Array.isArray(message.content)) {
453- return message;
454- }
455-
456- let contentMutated = false;
457- const nextContent = message.content.map((part) => {
458- if (
459- !isToolCallPart(part) ||
460- !("input" in part) ||
461- typeof part.input !== "string"
462- ) {
463- return part;
464- }
465-
466- try {
467- const parsed = JSON.parse(part.input);
468- if (!isRecord(parsed) || Array.isArray(parsed)) return part;
469- contentMutated = true;
470- return {
471- ...part,
472- input: parsed,
473- };
474- } catch {
475- return part;
476- }
477- });
478-
479- if (!contentMutated) return message;
480- mutated = true;
481- return {
482- ...message,
483- content: nextContent as CoreMessage["content"],
484- } as CoreMessage;
485- });
486-
487- return mutated ? result : messages;
488-}
489-
490-type GeminiToolHistoryRepairReason = "missing-signature-anchor";
491-
492-function validateGeminiAssistantToolCallMessage(message: CoreMessage): {
493- valid: boolean;
494- reason: GeminiToolHistoryRepairReason | null;
495-} {
496- if (message.role !== "assistant" || !Array.isArray(message.content)) {
497- return { valid: true, reason: null };
498- }
499-
500- let firstToolCallPartSeen = false;
501- for (const part of message.content) {
502- if (!isToolCallPart(part)) continue;
503- if (firstToolCallPartSeen) continue;
504- firstToolCallPartSeen = true;
505- if (getGeminiThoughtSignature(part) === null) {
506- return { valid: false, reason: "missing-signature-anchor" };
507- }
508- }
509-
510- return { valid: true, reason: null };
511-}
512-
513-function sanitizeGeminiToolMessagesWithMetadata(
514- messages: CoreMessage[],
515- modelString: string,
516- hasTools: boolean,
517-): {
518- messages: CoreMessage[];
519- repaired: boolean;
520- reason: GeminiToolHistoryRepairReason | null;
521- repairedFromIndex: number;
522- droppedMessageCount: number;
523- tailOnlyAffected: boolean;
524-} {
525- if (!hasTools || !isGeminiModelFamily(modelString)) {
526- return {
527- messages,
528- repaired: false,
529- reason: null,
530- repairedFromIndex: -1,
531- droppedMessageCount: 0,
532- tailOnlyAffected: true,
533- };
534- }
535-
536- const normalized = messages.map((message) =>
537- normalizeMessageProviderOptions(message),
538- );
539-
540- for (let index = normalized.length - 1; index >= 0; index -= 1) {
541- const message = normalized[index];
542- if (!message) continue;
543- if (message.role !== "assistant" || !Array.isArray(message.content))
544- continue;
545- if (!message.content.some((part) => isToolCallPart(part))) continue;
546-
547- const validation = validateGeminiAssistantToolCallMessage(message);
548- if (validation.valid) {
549- return {
550- messages: normalized,
551- repaired: false,
552- reason: null,
553- repairedFromIndex: -1,
554- droppedMessageCount: 0,
555- tailOnlyAffected: true,
556- };
557- }
558-
559- const nextUserIndex = normalized.findIndex(
560- (candidate, candidateIndex) =>
561- candidateIndex > index && candidate?.role === "user",
562- );
563- if (nextUserIndex === -1) {
564- return {
565- messages: normalized.slice(0, index),
566- repaired: true,
567- reason: validation.reason,
568- repairedFromIndex: index,
569- droppedMessageCount: normalized.length - index,
570- tailOnlyAffected: true,
571- };
572- }
573-
574- return {
575- messages: [
576- ...normalized.slice(0, index),
577- ...normalized.slice(nextUserIndex),
578- ],
579- repaired: true,
580- reason: validation.reason,
581- repairedFromIndex: index,
582- droppedMessageCount: nextUserIndex - index,
583- tailOnlyAffected: false,
Cut short: this commit's diff is over 1000 lines.