@librechat/agents 4.2.3 → 4.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/cjs/harness/index.cjs +123 -0
  2. package/dist/cjs/harness/index.cjs.map +1 -0
  3. package/dist/cjs/llm/google/index.cjs +27 -6
  4. package/dist/cjs/llm/google/index.cjs.map +1 -1
  5. package/dist/cjs/llm/google/utils/common.cjs +27 -14
  6. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  7. package/dist/cjs/llm/google/utils/signatures.cjs +137 -0
  8. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -0
  9. package/dist/cjs/llm/providerTextBoundary.cjs +3 -0
  10. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  11. package/dist/cjs/llm/vertexai/index.cjs +90 -7
  12. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  13. package/dist/cjs/main.cjs +8 -0
  14. package/dist/cjs/messages/content.cjs +4 -1
  15. package/dist/cjs/messages/content.cjs.map +1 -1
  16. package/dist/cjs/messages/format.cjs +11 -8
  17. package/dist/cjs/messages/format.cjs.map +1 -1
  18. package/dist/esm/harness/index.mjs +123 -0
  19. package/dist/esm/harness/index.mjs.map +1 -0
  20. package/dist/esm/llm/google/index.mjs +23 -7
  21. package/dist/esm/llm/google/index.mjs.map +1 -1
  22. package/dist/esm/llm/google/utils/common.mjs +27 -14
  23. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  24. package/dist/esm/llm/google/utils/signatures.mjs +132 -0
  25. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -0
  26. package/dist/esm/llm/providerTextBoundary.mjs +3 -0
  27. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  28. package/dist/esm/llm/vertexai/index.mjs +91 -8
  29. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  30. package/dist/esm/main.mjs +3 -1
  31. package/dist/esm/messages/content.mjs +4 -1
  32. package/dist/esm/messages/content.mjs.map +1 -1
  33. package/dist/esm/messages/format.mjs +11 -8
  34. package/dist/esm/messages/format.mjs.map +1 -1
  35. package/dist/types/harness/index.d.ts +56 -0
  36. package/dist/types/index.d.ts +4 -1
  37. package/dist/types/llm/google/index.d.ts +4 -2
  38. package/dist/types/llm/google/utils/common.d.ts +5 -1
  39. package/dist/types/llm/google/utils/signatures.d.ts +23 -0
  40. package/dist/types/llm/vertexai/index.d.ts +2 -17
  41. package/dist/types/messages/format.d.ts +3 -1
  42. package/dist/types/types/llm.d.ts +2 -2
  43. package/package.json +1 -1
  44. package/src/harness/index.ts +226 -0
  45. package/src/index.ts +16 -1
  46. package/src/llm/google/index.ts +20 -6
  47. package/src/llm/google/utils/common.ts +23 -10
  48. package/src/llm/google/utils/signatures.ts +215 -0
  49. package/src/llm/providerTextBoundary.ts +3 -0
  50. package/src/llm/vertexai/index.ts +127 -39
  51. package/src/messages/content.ts +14 -6
  52. package/src/messages/format.ts +42 -29
  53. package/src/types/llm.ts +10 -2
@@ -0,0 +1,215 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AIMessageChunk, isAIMessage } from '@langchain/core/messages';
3
+ import type { BaseMessage } from '@langchain/core/messages';
4
+ import type { GeminiPart } from '@langchain/google-common';
5
+ import type { Part } from '@google/generative-ai';
6
+
7
+ export const GEMINI_PARTS = '__gemini_parts__';
8
+ export const GEMINI_REPLAY_UNSUPPORTED = '__gemini_replay_unsupported__';
9
+ export const GEMINI_SIGNATURES = '__gemini_function_call_thought_signatures__';
10
+
11
+ export type GeminiReplayPart =
12
+ | {
13
+ type: 'text';
14
+ length: number;
15
+ hash: string;
16
+ thought?: boolean;
17
+ thoughtSignature?: string;
18
+ }
19
+ | {
20
+ type: 'function_call';
21
+ id: string;
22
+ hash: string;
23
+ thoughtSignature?: string;
24
+ };
25
+
26
+ function hashText(text: string): string {
27
+ return createHash('sha256').update(text).digest('hex');
28
+ }
29
+
30
+ export function isGeminiReplayParts(
31
+ value: unknown
32
+ ): value is GeminiReplayPart[] {
33
+ return (
34
+ Array.isArray(value) &&
35
+ Array.from(value).every((value: unknown) => {
36
+ if (value == null || typeof value !== 'object') return false;
37
+ const part = value as Partial<GeminiReplayPart>;
38
+ if (
39
+ part.thoughtSignature !== undefined &&
40
+ typeof part.thoughtSignature !== 'string'
41
+ )
42
+ return false;
43
+ if (part.type === 'function_call')
44
+ return (
45
+ typeof part.id === 'string' &&
46
+ part.id !== '' &&
47
+ typeof part.hash === 'string' &&
48
+ /^[a-f0-9]{64}$/.test(part.hash) &&
49
+ Object.keys(part).every((key) =>
50
+ ['type', 'id', 'hash', 'thoughtSignature'].includes(key)
51
+ )
52
+ );
53
+ return (
54
+ part.type === 'text' &&
55
+ typeof part.length === 'number' &&
56
+ Number.isSafeInteger(part.length) &&
57
+ part.length >= 0 &&
58
+ typeof part.hash === 'string' &&
59
+ /^[a-f0-9]{64}$/.test(part.hash) &&
60
+ (part.thought === undefined || typeof part.thought === 'boolean') &&
61
+ Object.keys(part).every((key) =>
62
+ ['type', 'length', 'hash', 'thought', 'thoughtSignature'].includes(
63
+ key
64
+ )
65
+ )
66
+ );
67
+ })
68
+ );
69
+ }
70
+
71
+ /** Captures native boundaries without duplicating prose. Known Gemini 1/2 models retain their existing signature formats for cross-model compatibility. */
72
+ export function captureGeminiReplayParts(
73
+ message: BaseMessage,
74
+ parts: readonly (Part | GeminiPart)[],
75
+ model?: string
76
+ ): void {
77
+ if (!isAIMessage(message)) return;
78
+ const sourceModel = model?.toLowerCase().split('/').pop() ?? '';
79
+ if (/^gemini-(?:[12](?:[.-]|$)|pro(?:-|$))/.test(sourceModel)) return;
80
+ message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] = true;
81
+ const replay: GeminiReplayPart[] = [];
82
+ const signatures: Record<string, string> = {};
83
+ let callIndex = 0;
84
+ let reasoning = '';
85
+ for (const part of parts) {
86
+ const thoughtSignature =
87
+ 'thoughtSignature' in part && typeof part.thoughtSignature === 'string'
88
+ ? part.thoughtSignature
89
+ : undefined;
90
+ const signature = thoughtSignature != null ? { thoughtSignature } : {};
91
+ const thought =
92
+ 'thought' in part && typeof part.thought === 'boolean'
93
+ ? part.thought
94
+ : undefined;
95
+ if ('text' in part && typeof part.text === 'string') {
96
+ replay.push({
97
+ type: 'text',
98
+ length: part.text.length,
99
+ hash: hashText(part.text),
100
+ ...(thought != null ? { thought } : {}),
101
+ ...signature,
102
+ });
103
+ if (thought === true) reasoning += part.text;
104
+ continue;
105
+ }
106
+ if (!('functionCall' in part) || part.functionCall == null) continue;
107
+ const index = callIndex++;
108
+ const call = message.tool_calls?.[index];
109
+ if (call?.id == null || call.id === '') continue;
110
+ const nativeId =
111
+ 'id' in part.functionCall && typeof part.functionCall.id === 'string'
112
+ ? part.functionCall.id
113
+ : undefined;
114
+ if (nativeId != null && nativeId !== '') {
115
+ call.id = nativeId;
116
+ if (
117
+ message instanceof AIMessageChunk &&
118
+ Array.isArray(message.tool_call_chunks) &&
119
+ index < message.tool_call_chunks.length
120
+ ) {
121
+ message.tool_call_chunks[index].id = nativeId;
122
+ }
123
+ }
124
+ replay.push({
125
+ type: 'function_call',
126
+ id: call.id,
127
+ hash: hashText(JSON.stringify({ name: call.name, args: call.args })),
128
+ ...signature,
129
+ });
130
+ if (thoughtSignature != null) signatures[call.id] = thoughtSignature;
131
+ }
132
+ message.additional_kwargs[GEMINI_SIGNATURES] = signatures;
133
+ if (replay.length !== parts.length) return;
134
+ message.additional_kwargs[GEMINI_PARTS] = replay;
135
+ const hasThinkingContent =
136
+ Array.isArray(message.content) &&
137
+ message.content.some((block) => block.type === 'thinking');
138
+ if (reasoning !== '' && !hasThinkingContent)
139
+ message.additional_kwargs.reasoning = reasoning;
140
+ delete message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED];
141
+ }
142
+
143
+ /** Returns original parts only when the current message still matches every text hash and call id. */
144
+ export function restoreGeminiReplayParts(
145
+ message: BaseMessage,
146
+ replay: unknown = message.additional_kwargs[GEMINI_PARTS]
147
+ ): GeminiPart[] | undefined {
148
+ if (
149
+ message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] === true ||
150
+ !isAIMessage(message) ||
151
+ !isGeminiReplayParts(replay)
152
+ )
153
+ return undefined;
154
+ let text = '';
155
+ let contentReasoning = '';
156
+ if (typeof message.content === 'string') text = message.content;
157
+ else
158
+ for (const block of message.content) {
159
+ if (block.type === 'text' && typeof block.text === 'string')
160
+ text += block.text;
161
+ else if (block.type === 'thinking' && typeof block.thinking === 'string')
162
+ contentReasoning += block.thinking;
163
+ else if (!('functionCall' in block)) return undefined;
164
+ }
165
+ let reasoning = contentReasoning;
166
+ if (typeof message.additional_kwargs.reasoning_content === 'string')
167
+ reasoning = message.additional_kwargs.reasoning_content;
168
+ if (typeof message.additional_kwargs.reasoning === 'string')
169
+ reasoning = message.additional_kwargs.reasoning;
170
+ const calls = new Map(
171
+ (message.tool_calls ?? []).map((call) => [call.id, call])
172
+ );
173
+ const parts: GeminiPart[] = [];
174
+ let textOffset = 0;
175
+ let reasoningOffset = 0;
176
+ for (const descriptor of replay) {
177
+ const signature =
178
+ descriptor.thoughtSignature != null
179
+ ? { thoughtSignature: descriptor.thoughtSignature }
180
+ : {};
181
+ if (descriptor.type === 'function_call') {
182
+ const call = calls.get(descriptor.id);
183
+ if (
184
+ call == null ||
185
+ hashText(JSON.stringify({ name: call.name, args: call.args })) !==
186
+ descriptor.hash
187
+ )
188
+ return undefined;
189
+ const functionCall = { id: call.id, name: call.name, args: call.args };
190
+ parts.push({ functionCall, ...signature });
191
+ calls.delete(descriptor.id);
192
+ continue;
193
+ }
194
+ const offset = descriptor.thought === true ? reasoningOffset : textOffset;
195
+ const source = descriptor.thought === true ? reasoning : text;
196
+ const value = source.slice(offset, offset + descriptor.length);
197
+ if (
198
+ value.length !== descriptor.length ||
199
+ hashText(value) !== descriptor.hash
200
+ )
201
+ return undefined;
202
+ if (descriptor.thought === true) reasoningOffset += descriptor.length;
203
+ else textOffset += descriptor.length;
204
+ parts.push({
205
+ text: value,
206
+ ...(descriptor.thought != null ? { thought: descriptor.thought } : {}),
207
+ ...signature,
208
+ });
209
+ }
210
+ return textOffset === text.length &&
211
+ reasoningOffset === reasoning.length &&
212
+ calls.size === 0
213
+ ? parts
214
+ : undefined;
215
+ }
@@ -13,6 +13,7 @@ import {
13
13
  STREAMED_TOOL_CALL_SEAL_METADATA_KEY,
14
14
  } from '@/tools/streamedToolCallSeals';
15
15
  import { GEMINI_SIGNATURES, RESPONSES_POSITIONS, stringMap, safetyRatings, replayPositions, ResponsesTextProjection, keys } from '@/llm/providerTextControls';
16
+ import { GEMINI_PARTS, GEMINI_REPLAY_UNSUPPORTED, isGeminiReplayParts } from '@/llm/google/utils/signatures';
16
17
  import {
17
18
  ProviderTextAttempt,
18
19
  ProviderTextProtectionError,
@@ -48,6 +49,8 @@ const additionalControls: Readonly<Partial<Record<string, (value: unknown) => bo
48
49
 
49
50
  const geminiControls: Readonly<Partial<Record<string, (value: unknown) => boolean>>> = {
50
51
  [GEMINI_SIGNATURES]: stringMap,
52
+ [GEMINI_PARTS]: isGeminiReplayParts,
53
+ [GEMINI_REPLAY_UNSUPPORTED]: (value) => value === true,
51
54
  finishReason: (value) => ['STOP', 'MAX_TOKENS', 'SAFETY', 'RECITATION', 'OTHER', 'MALFORMED_FUNCTION_CALL', 'FINISH_REASON_UNSPECIFIED'].includes(String(value)),
52
55
  safetyRatings,
53
56
  avgLogprobs: (value) => typeof value === 'number' && Number.isFinite(value),
@@ -1,21 +1,32 @@
1
1
  import { ChatGoogle } from '@langchain/google-gauth';
2
2
  import { ChatConnection } from '@langchain/google-common';
3
- import { AIMessageChunk, isAIMessage } from '@langchain/core/messages';
3
+ import { AIMessageChunk, isAIMessage, isToolMessage } from '@langchain/core/messages';
4
4
  import type {
5
5
  GeminiContent,
6
+ GoogleAIAPI,
7
+ GenerateContentResponseData,
8
+ GeminiResponseCandidate,
6
9
  GeminiRequest,
7
10
  GoogleAIModelRequestParams,
8
11
  GoogleAbstractedClient,
9
12
  } from '@langchain/google-common';
10
13
  import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
14
+ import type { ChatResult, ChatGenerationChunk } from '@langchain/core/outputs';
11
15
  import type { BaseMessage, UsageMetadata } from '@langchain/core/messages';
12
- import type { ChatGenerationChunk } from '@langchain/core/outputs';
13
16
  import type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';
14
17
  import {
15
18
  STREAMED_TOOL_CALL_SEAL_METADATA_KEY,
16
19
  STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY,
17
20
  GOOGLE_STREAMED_TOOL_CALL_ADAPTER,
18
21
  } from '@/tools/streamedToolCallSeals';
22
+ import {
23
+ GEMINI_PARTS,
24
+ GEMINI_REPLAY_UNSUPPORTED,
25
+ GEMINI_SIGNATURES,
26
+ captureGeminiReplayParts,
27
+ restoreGeminiReplayParts,
28
+ } from '@/llm/google/utils/signatures';
29
+ import { dropUnsupportedModelTurnPrefill } from '@/llm/google/utils/common';
19
30
  import { smoothGenerationChunks } from '@/llm/stream/chunkAdapters';
20
31
  import { resolveStreamDelay } from '@/llm/stream/smoother';
21
32
 
@@ -86,64 +97,119 @@ type AdditionalKwargs =
86
97
  signatures?: Array<string | undefined>;
87
98
  });
88
99
 
89
- /**
90
- * Fixes thought signatures on functionCall parts in the formatted Gemini request.
91
- *
92
- * `@langchain/google-common` stores signatures as a flat array in
93
- * `additional_kwargs.signatures` (one per response part) and re-attaches them
94
- * by index only when `signatures.length === parts.length`. This fails when:
95
- * - The API omits a signature (length mismatch)
96
- * - Streaming chunks merge with different part counts
97
- * - The signature for a functionCall part is an empty string
98
- *
99
- * This function correlates each "model" content block in the formatted request
100
- * back to its originating AI message by *position*, then re-attaches non-empty
101
- * signatures that the library failed to apply. AI messages without signatures
102
- * still consume their slot — filtering them out shifted later messages onto
103
- * the wrong content block and dropped real signatures on the floor.
104
- */
100
+ /** Restores native part order. Legacy text with merged positional slots has lost its boundaries and requires regeneration. */
105
101
  export function fixThoughtSignatures(
106
102
  contents: GeminiContent[],
107
103
  input: BaseMessage[]
108
104
  ): void {
109
- // All AI messages, in order — non-signature ones still consume positional
105
+ // All AI messages, in order, non-signature ones still consume positional
110
106
  // slots so later messages line up with their model content blocks.
111
107
  const aiMessages = input.filter(isAIMessage);
112
108
  const modelContents = contents.filter((c) => c.role === 'model');
113
109
 
114
110
  const count = Math.min(aiMessages.length, modelContents.length);
115
111
  for (let i = 0; i < count; i++) {
112
+ const replay = restoreGeminiReplayParts(aiMessages[i]);
113
+ if (replay != null) {
114
+ modelContents[i].parts = replay;
115
+ continue;
116
+ }
117
+ if (Object.hasOwn(aiMessages[i].additional_kwargs, GEMINI_PARTS) && aiMessages[i].additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] !== true) {
118
+ for (const part of modelContents[i].parts) delete part.thoughtSignature;
119
+ continue;
120
+ }
121
+ const signatureMap = aiMessages[i].additional_kwargs[GEMINI_SIGNATURES] as Record<string, string> | undefined;
122
+ if (signatureMap != null) {
123
+ let callIndex = 0;
124
+ for (const part of modelContents[i].parts) {
125
+ if (!('functionCall' in part)) continue;
126
+ const id = aiMessages[i].tool_calls?.[callIndex++]?.id;
127
+ const signature = id != null ? signatureMap[id] : undefined;
128
+ if (typeof signature === 'string' && signature !== '') part.thoughtSignature = signature;
129
+ else delete part.thoughtSignature;
130
+ }
131
+ continue;
132
+ }
116
133
  const signatures = (aiMessages[i].additional_kwargs as AdditionalKwargs)
117
134
  ?.signatures;
118
135
  if (!Array.isArray(signatures) || signatures.length === 0) continue;
119
136
 
120
137
  const content = modelContents[i];
121
- const attachedSignatures = new Set(
122
- content.parts
123
- .map((p) => p.thoughtSignature)
124
- .filter((s): s is string => s != null && s !== '')
125
- );
126
- const availableSignatures = signatures.filter(
127
- (s): s is string => s != null && s !== '' && !attachedSignatures.has(s)
128
- );
129
-
130
- let sigIdx = 0;
131
- for (const part of content.parts) {
132
- if (
133
- 'functionCall' in part &&
134
- (part.thoughtSignature == null || part.thoughtSignature === '') &&
135
- sigIdx < availableSignatures.length
136
- ) {
137
- part.thoughtSignature = availableSignatures[sigIdx];
138
- sigIdx++;
138
+ const callCount = aiMessages[i].tool_calls?.length ?? 0;
139
+ const mismatchedSlots = signatures.length !== content.parts.length;
140
+ if (mismatchedSlots && content.parts.some((part) => 'text' in part)) continue;
141
+ if (mismatchedSlots && signatures.slice(callCount).some((signature) => signature != null && signature !== '')) continue;
142
+ for (let index = 0; index < content.parts.length; index++) {
143
+ const part = content.parts[index];
144
+ const signature = signatures[index];
145
+ if ((part.thoughtSignature == null || part.thoughtSignature === '') &&
146
+ typeof signature === 'string' && signature !== '') {
147
+ part.thoughtSignature = signature;
139
148
  }
140
149
  }
141
150
  }
142
151
  }
143
152
 
153
+ type VertexResponseData = Omit<Partial<GenerateContentResponseData>, 'candidates'> & {
154
+ candidates?: Array<Omit<Partial<GeminiResponseCandidate>, 'content'> & {
155
+ content?: GeminiResponseCandidate['content'];
156
+ }>;
157
+ };
158
+
144
159
  class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
145
160
  thinkingConfig?: GoogleThinkingConfig;
146
161
 
162
+ buildGeminiAPI(): GoogleAIAPI {
163
+ const api = super.buildGeminiAPI();
164
+ return {
165
+ ...api,
166
+ responseToChatResult: (response): ChatResult => {
167
+ const result = api.responseToChatResult(response);
168
+ const data = response.data as VertexResponseData;
169
+ const message = result.generations[0]?.message;
170
+ if (result.generations.length > 0)
171
+ captureGeminiReplayParts(
172
+ message,
173
+ data.candidates?.[0]?.content?.parts ?? [],
174
+ this.model
175
+ );
176
+ return result;
177
+ },
178
+ responseToChatGeneration: (response): ChatGenerationChunk | null => {
179
+ const data = response.data as VertexResponseData;
180
+ const candidate = data.candidates?.[0];
181
+ if (candidate?.content == null) return api.responseToChatGeneration(response);
182
+ const parts = candidate.content.parts;
183
+ if (parts.length === 0)
184
+ return api.responseToChatGeneration(response);
185
+ let combined: ChatGenerationChunk | undefined;
186
+ let generationInfo: ChatGenerationChunk['generationInfo'];
187
+ for (const part of parts) {
188
+ const chunk = api.responseToChatGeneration({
189
+ data: {
190
+ ...data,
191
+ candidates: [
192
+ {
193
+ ...candidate,
194
+ content: { ...candidate.content, parts: [part] },
195
+ },
196
+ ],
197
+ } as GenerateContentResponseData,
198
+ });
199
+ if (chunk != null) {
200
+ generationInfo ??= chunk.generationInfo;
201
+ chunk.generationInfo = undefined;
202
+ combined = combined == null ? chunk : combined.concat(chunk);
203
+ }
204
+ }
205
+ if (combined == null) return null;
206
+ combined.generationInfo = generationInfo;
207
+ captureGeminiReplayParts(combined.message, parts, this.model);
208
+ return combined;
209
+ },
210
+ };
211
+ }
212
+
147
213
  async formatData(
148
214
  input: BaseMessage[],
149
215
  parameters: GoogleAIModelRequestParams
@@ -163,7 +229,7 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
163
229
  }
164
230
  if (this.thinkingConfig?.thinkingLevel != null) {
165
231
  formattedData.generationConfig ??= {};
166
- // thinkingLevel and thinkingBudget cannot coexist — the API rejects the request.
232
+ // thinkingLevel and thinkingBudget cannot coexist, the API rejects the request.
167
233
  // Remove thinkingBudget when thinkingLevel is set.
168
234
  const { thinkingBudget: _, ...existingThinkingConfig } =
169
235
  (formattedData.generationConfig.thinkingConfig as
@@ -181,8 +247,30 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
181
247
  }
182
248
  if (formattedData.contents) {
183
249
  fixThoughtSignatures(formattedData.contents, input);
250
+ formattedData.contents = dropUnsupportedModelTurnPrefill(
251
+ formattedData.contents,
252
+ this.model
253
+ );
254
+ const functionResponseNames: Array<string | undefined> = [];
255
+ const callNames = new Map<string, string>();
256
+ for (const message of input) {
257
+ if (isAIMessage(message)) {
258
+ callNames.clear();
259
+ for (const call of message.tool_calls ?? []) {
260
+ if (call.id != null) callNames.set(call.id, call.name);
261
+ }
262
+ } else if (isToolMessage(message)) {
263
+ functionResponseNames.push(callNames.get(message.tool_call_id) ?? message.name);
264
+ }
265
+ }
266
+ let responseIndex = 0;
184
267
  // gemini-3.1+ models reject role="function"; convert to role="user"
185
- for (const content of formattedData.contents) {
268
+ for (const content of formattedData.contents ?? []) {
269
+ for (const part of content.parts) {
270
+ if (!('functionResponse' in part)) continue;
271
+ const name = functionResponseNames[responseIndex++];
272
+ if (name != null && name !== '') part.functionResponse.name = name;
273
+ }
186
274
  if (content.role === 'function') {
187
275
  (content as { role: string }).role = 'user';
188
276
  }
@@ -2,6 +2,10 @@ import type {
2
2
  BaseMessage,
3
3
  MessageContentComplex,
4
4
  } from '@langchain/core/messages';
5
+ import {
6
+ GEMINI_PARTS,
7
+ isGeminiReplayParts,
8
+ } from '@/llm/google/utils/signatures';
5
9
  import { ContentTypes } from '@/common';
6
10
  import { cloneMessage } from './cache';
7
11
 
@@ -53,12 +57,16 @@ export const formatContentStrings = (
53
57
  continue;
54
58
  }
55
59
 
56
- result.push(
57
- cloneMessage(
58
- message,
59
- flattenLegacyContent(message.content as MessageContentComplex[])
60
- )
61
- );
60
+ const blocks = message.content as MessageContentComplex[];
61
+ const preserveNativeText =
62
+ message.getType() === 'ai' &&
63
+ isGeminiReplayParts(message.additional_kwargs[GEMINI_PARTS]);
64
+ const content = preserveNativeText
65
+ ? blocks
66
+ .map((block) => ('text' in block && typeof block.text === 'string' ? block.text : ''))
67
+ .join('')
68
+ : flattenLegacyContent(blocks);
69
+ result.push(cloneMessage(message, content));
62
70
  }
63
71
 
64
72
  return result;
@@ -13,11 +13,6 @@ import type {
13
13
  } from '@langchain/core/messages';
14
14
  import type { RunnableConfig } from '@langchain/core/runnables';
15
15
  import type { ToolCall } from '@langchain/core/messages/tool';
16
- import type {
17
- OrderedToolHistoryProjection,
18
- ToolHistoryPreparation,
19
- ToolHistoryCallMirrors,
20
- } from './toolHistoryProjection';
21
16
  import type {
22
17
  BedrockReasoningContentText,
23
18
  ExtendedMessageContent,
@@ -37,6 +32,11 @@ import type {
37
32
  CompactionSemanticIndexEntry,
38
33
  CompactionSemanticIndexSnapshot,
39
34
  } from '@/types';
35
+ import type {
36
+ OrderedToolHistoryProjection,
37
+ ToolHistoryPreparation,
38
+ ToolHistoryCallMirrors,
39
+ } from './toolHistoryProjection';
40
40
  import type {
41
41
  ProviderMessageAttribution,
42
42
  ProviderMessageProvenancePart,
@@ -70,6 +70,11 @@ import {
70
70
  isAtomicToolContentBlock,
71
71
  serializeStructuredValueBounded,
72
72
  } from '@/utils/toolContent';
73
+ import {
74
+ createToolHistoryPreparation,
75
+ isToolHistoryCallMirror,
76
+ recordToolHistoryCallMirror,
77
+ } from './toolHistoryProjection';
73
78
  import {
74
79
  Providers,
75
80
  ContentTypes,
@@ -78,15 +83,10 @@ import {
78
83
  } from '@/common';
79
84
  import { normalizeAnthropicToolCallId } from '@/llm/anthropic/utils/message_inputs';
80
85
  import { toLangChainContent, toLangChainMessageFields } from './langchain';
81
- import { isReasoningContentBlock } from './reasoningTypes';
82
86
  import { flattenLegacyContent, isLegacyConvertible } from './content';
83
87
  import { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';
88
+ import { isReasoningContentBlock } from './reasoningTypes';
84
89
  import { emitAgentLog } from '@/utils/events';
85
- import {
86
- createToolHistoryPreparation,
87
- isToolHistoryCallMirror,
88
- recordToolHistoryCallMirror,
89
- } from './toolHistoryProjection';
90
90
 
91
91
  interface MediaMessageParams {
92
92
  message: {
@@ -396,6 +396,7 @@ interface FormatAssistantMessageOptions {
396
396
  intentToolNames?: ReadonlySet<string>;
397
397
  preserveUnpairedServerToolUses?: boolean;
398
398
  preserveReasoningContent?: boolean;
399
+ preserveTextContent?: boolean;
399
400
  provider?: ProviderName;
400
401
  retainedSourceContentEnd?: number;
401
402
  sourceMessageId?: string;
@@ -418,6 +419,8 @@ export interface FormatAgentMessagesOptions {
418
419
  * tool-call messages. Explicit opt-in for OpenAI-compatible endpoints that
419
420
  * replay reasoning across turns; defaults to on for DeepSeek thinking-mode. */
420
421
  preserveReasoningContent?: boolean;
422
+ /** Preserve exact assistant text bytes for provider signature replay. */
423
+ preserveTextContent?: boolean;
421
424
  /** Skill names already primed fresh this turn (manual/always-apply). Their
422
425
  * historical `skill` tool_calls are not reconstructed into a HumanMessage,
423
426
  * so the same SKILL.md body is not injected twice in one request. */
@@ -1612,6 +1615,7 @@ function formatAssistantMessage(
1612
1615
  sourceContentPartIndices: SourceContentPartIndices;
1613
1616
  }
1614
1617
  >();
1618
+ const preserveTextContent = options?.preserveTextContent === true;
1615
1619
  const shouldPreserveReasoningContent =
1616
1620
  options?.preserveReasoningContent === true;
1617
1621
  const compactionSemanticIndex = options?.compactionSemanticIndex;
@@ -1831,13 +1835,17 @@ function formatAssistantMessage(
1831
1835
  currentContentProvenance = createProviderMessageProvenanceBuilder();
1832
1836
  continue;
1833
1837
  }
1834
- let content = currentContent.reduce((acc, curr) => {
1835
- if (curr.type === ContentTypes.TEXT) {
1836
- return `${acc}${getTextContent(curr)}\n`;
1837
- }
1838
- return acc;
1839
- }, '');
1840
- content = `${content}\n${getTextContent(part)}`.trim();
1838
+ let content = preserveTextContent
1839
+ ? currentContent.map(getTextContent).join('')
1840
+ : currentContent.reduce((acc, curr) => {
1841
+ if (curr.type === ContentTypes.TEXT) {
1842
+ return `${acc}${getTextContent(curr)}\n`;
1843
+ }
1844
+ return acc;
1845
+ }, '');
1846
+ content = preserveTextContent
1847
+ ? content + getTextContent(part)
1848
+ : `${content}\n${getTextContent(part)}`.trim();
1841
1849
  appendCurrentContentProvenance(sourcePartIndices, 'model', true);
1842
1850
  lastAIMessage = appendAIMessage(content, currentContentProvenance);
1843
1851
  currentContent = [];
@@ -2043,9 +2051,11 @@ function formatAssistantMessage(
2043
2051
  currentContentProvenance
2044
2052
  );
2045
2053
  } else {
2046
- const flushed = currentContent
2047
- .reduce((acc, curr) => `${acc}${getTextContent(curr)}\n`, '')
2048
- .trim();
2054
+ const flushed = preserveTextContent
2055
+ ? currentContent.map(getTextContent).join('')
2056
+ : currentContent
2057
+ .reduce((acc, curr) => `${acc}${getTextContent(curr)}\n`, '')
2058
+ .trim();
2049
2059
  if (flushed.length > 0) {
2050
2060
  appendAIMessage(flushed, currentContentProvenance);
2051
2061
  }
@@ -2095,7 +2105,7 @@ function formatAssistantMessage(
2095
2105
  ) {
2096
2106
  continue;
2097
2107
  } else {
2098
- if (part.type === ContentTypes.TEXT && !getTextContent(part).trim()) {
2108
+ if (part.type === ContentTypes.TEXT && !preserveTextContent && !getTextContent(part).trim()) {
2099
2109
  continue;
2100
2110
  }
2101
2111
  currentContent.push(part);
@@ -2122,18 +2132,20 @@ function formatAssistantMessage(
2122
2132
  );
2123
2133
  return finalizeFormattedMessages();
2124
2134
  }
2125
- content += `${getTextContent(part)}\n`;
2135
+ content += getTextContent(part) + (preserveTextContent ? '' : '\n');
2126
2136
  }
2127
- content = content.trim();
2137
+ if (!preserveTextContent) content = content.trim();
2128
2138
 
2129
- if (content) {
2139
+ if (content !== '' || preserveTextContent) {
2130
2140
  appendAIMessage(content, currentContentProvenance);
2131
2141
  }
2132
2142
  } else if (currentContent.length > 0) {
2133
- appendAIMessage(
2134
- toLangChainContent(currentContent),
2135
- currentContentProvenance
2136
- );
2143
+ const content = preserveTextContent && currentContent.every((part) => part.type === ContentTypes.TEXT)
2144
+ ? currentContent.map(getTextContent).join('')
2145
+ : toLangChainContent(currentContent);
2146
+ appendAIMessage(content, currentContentProvenance);
2147
+ } else if (preserveTextContent && shouldPreserveReasoningContent && pendingReasoningContent !== '') {
2148
+ appendAIMessage('', currentContentProvenance);
2137
2149
  }
2138
2150
 
2139
2151
  return finalizeFormattedMessages();
@@ -3117,6 +3129,7 @@ export const formatAgentMessages = (
3117
3129
  compactionSemanticIndex: compactionSemanticIndexCollector,
3118
3130
  intentToolNames: options?.compactionSemanticIndex?.intentToolNames,
3119
3131
  preserveUnpairedServerToolUses: i === payload.length - 1,
3132
+ preserveTextContent: options?.preserveTextContent,
3120
3133
  preserveReasoningContent:
3121
3134
  options?.preserveReasoningContent ??
3122
3135
  options?.provider === Providers.DEEPSEEK,
package/src/types/llm.ts CHANGED
@@ -74,7 +74,12 @@ export type AnthropicReasoning = {
74
74
  export type GoogleThinkingConfig = {
75
75
  thinkingBudget?: number;
76
76
  includeThoughts?: boolean;
77
- thinkingLevel?: 'THINKING_LEVEL_UNSPECIFIED' | 'LOW' | 'MEDIUM' | 'HIGH';
77
+ thinkingLevel?:
78
+ | 'THINKING_LEVEL_UNSPECIFIED'
79
+ | 'LOW'
80
+ | 'MEDIUM'
81
+ | 'HIGH'
82
+ | 'XHIGH';
78
83
  };
79
84
  /** GPT-5.6 managed-request passthrough fields, shared by the OpenAI and
80
85
  * Azure wrappers that both read them. */
@@ -153,7 +158,10 @@ export type BedrockAnthropicInput = ChatBedrockConverseInput &
153
158
  };
154
159
  export type BedrockConverseClientOptions = BedrockAnthropicInput;
155
160
  export type BedrockAnthropicClientOptions = BedrockAnthropicInput;
156
- export type GoogleClientOptions = GoogleGenerativeAIChatInput &
161
+ export type GoogleClientOptions = Omit<
162
+ GoogleGenerativeAIChatInput,
163
+ 'thinkingConfig'
164
+ > &
157
165
  StreamSmoothingOptions & {
158
166
  customHeaders?: RequestOptions['customHeaders'];
159
167
  thinkingConfig?: GoogleThinkingConfig;