@librechat/agents 4.2.4 → 4.2.6

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 (103) hide show
  1. package/dist/cjs/harness/identity.cjs +26 -0
  2. package/dist/cjs/harness/identity.cjs.map +1 -0
  3. package/dist/cjs/harness/index.cjs +3 -15
  4. package/dist/cjs/harness/index.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +79 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -0
  7. package/dist/cjs/llm/contextPressureMeter.cjs +1 -1
  8. package/dist/cjs/llm/contextPressureMeter.cjs.map +1 -1
  9. package/dist/cjs/llm/google/index.cjs +27 -6
  10. package/dist/cjs/llm/google/index.cjs.map +1 -1
  11. package/dist/cjs/llm/google/utils/common.cjs +27 -14
  12. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/signatures.cjs +137 -0
  14. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -0
  15. package/dist/cjs/llm/openai/index.cjs +21 -12
  16. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/streamMetadata.cjs +4 -1
  18. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  19. package/dist/cjs/llm/providerTextBoundary.cjs +3 -0
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/llm/vertexai/index.cjs +90 -7
  22. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  23. package/dist/cjs/main.cjs +11 -0
  24. package/dist/cjs/messages/content.cjs +4 -1
  25. package/dist/cjs/messages/content.cjs.map +1 -1
  26. package/dist/cjs/messages/format.cjs +11 -8
  27. package/dist/cjs/messages/format.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +4 -1
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/BashExecutor.cjs +2 -1
  31. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  32. package/dist/cjs/tools/ToolNode.cjs +141 -94
  33. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  34. package/dist/cjs/tools/toolOutputReferences.cjs +39 -17
  35. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  36. package/dist/esm/harness/identity.mjs +24 -0
  37. package/dist/esm/harness/identity.mjs.map +1 -0
  38. package/dist/esm/harness/index.mjs +3 -15
  39. package/dist/esm/harness/index.mjs.map +1 -1
  40. package/dist/esm/harness/providerText.mjs +78 -0
  41. package/dist/esm/harness/providerText.mjs.map +1 -0
  42. package/dist/esm/llm/contextPressureMeter.mjs +1 -1
  43. package/dist/esm/llm/contextPressureMeter.mjs.map +1 -1
  44. package/dist/esm/llm/google/index.mjs +23 -7
  45. package/dist/esm/llm/google/index.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/common.mjs +27 -14
  47. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  48. package/dist/esm/llm/google/utils/signatures.mjs +132 -0
  49. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -0
  50. package/dist/esm/llm/openai/index.mjs +21 -12
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/streamMetadata.mjs +4 -1
  53. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  54. package/dist/esm/llm/providerTextBoundary.mjs +3 -0
  55. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  56. package/dist/esm/llm/vertexai/index.mjs +91 -8
  57. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  58. package/dist/esm/main.mjs +4 -1
  59. package/dist/esm/messages/content.mjs +4 -1
  60. package/dist/esm/messages/content.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +11 -8
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/stream.mjs +4 -1
  64. package/dist/esm/stream.mjs.map +1 -1
  65. package/dist/esm/tools/BashExecutor.mjs +2 -1
  66. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/ToolNode.mjs +142 -95
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/toolOutputReferences.mjs +39 -18
  70. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  71. package/dist/types/harness/identity.d.ts +14 -0
  72. package/dist/types/harness/index.d.ts +5 -9
  73. package/dist/types/harness/providerText.d.ts +32 -0
  74. package/dist/types/index.d.ts +2 -0
  75. package/dist/types/llm/google/index.d.ts +4 -2
  76. package/dist/types/llm/google/utils/common.d.ts +5 -1
  77. package/dist/types/llm/google/utils/signatures.d.ts +23 -0
  78. package/dist/types/llm/openai/streamMetadata.d.ts +3 -3
  79. package/dist/types/llm/vertexai/index.d.ts +2 -17
  80. package/dist/types/messages/format.d.ts +3 -1
  81. package/dist/types/tools/ToolNode.d.ts +7 -7
  82. package/dist/types/tools/toolOutputReferences.d.ts +16 -4
  83. package/dist/types/types/llm.d.ts +2 -2
  84. package/package.json +1 -1
  85. package/src/harness/identity.ts +34 -0
  86. package/src/harness/index.ts +15 -23
  87. package/src/harness/providerText.ts +128 -0
  88. package/src/index.ts +9 -0
  89. package/src/llm/contextPressureMeter.ts +2 -4
  90. package/src/llm/google/index.ts +20 -6
  91. package/src/llm/google/utils/common.ts +23 -10
  92. package/src/llm/google/utils/signatures.ts +215 -0
  93. package/src/llm/openai/index.ts +60 -20
  94. package/src/llm/openai/streamMetadata.ts +14 -3
  95. package/src/llm/providerTextBoundary.ts +3 -0
  96. package/src/llm/vertexai/index.ts +127 -39
  97. package/src/messages/content.ts +14 -6
  98. package/src/messages/format.ts +42 -29
  99. package/src/stream.ts +10 -1
  100. package/src/tools/BashExecutor.ts +2 -1
  101. package/src/tools/ToolNode.ts +333 -256
  102. package/src/tools/toolOutputReferences.ts +101 -32
  103. package/src/types/llm.ts +10 -2
@@ -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/stream.ts CHANGED
@@ -176,6 +176,12 @@ function hasToolOutputReference(value: unknown): boolean {
176
176
  return false;
177
177
  }
178
178
 
179
+ function hasAnthropicServerToolId(toolCall: ToolCall): boolean {
180
+ return (
181
+ toolCall.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false
182
+ );
183
+ }
184
+
179
185
  function isEagerExecutionExcludedTool(
180
186
  name: string,
181
187
  graph: StandardGraph,
@@ -728,9 +734,12 @@ function createEagerToolExecutionPlan(args: {
728
734
  // Drop host-excluded tools only AFTER the batch-level guards above have run
729
735
  // against the full batch, so excluding a call never hides a sibling direct
730
736
  // tool from `hasDirectToolCallInBatch`. Excluded calls fall through to normal
731
- // ToolNode execution; siblings may still eager-execute.
737
+ // ToolNode execution; siblings may still eager-execute. Provider-executed
738
+ // server tool calls (`srvtoolu_`, e.g. Anthropic web_search) already ran on
739
+ // the provider side, so they are never dispatched to the host.
732
740
  const candidateToolCalls = unstartedToolCalls.filter(
733
741
  (toolCall) =>
742
+ !hasAnthropicServerToolId(toolCall) &&
734
743
  !isEagerExecutionExcludedTool(toolCall.name, graph, agentContext)
735
744
  );
736
745
  if (candidateToolCalls.length === 0) {
@@ -128,7 +128,8 @@ Referencing previous tool outputs:
128
128
  - Example (simple ASCII output): \`echo '{{tool0turn0}}' | jq '.foo'\` takes the full output of the first tool from the first turn and pipes it into jq.
129
129
  - For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \`echo '…'\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.
130
130
  - Heredoc example: \`wc -c << 'EOF'\\n{{tool0turn0}}\\nEOF\` (the quotes around \`'EOF'\` disable interpolation inside the body).
131
- - Unknown reference keys are left in place and surfaced as \`[unresolved refs: …]\` after the output.
131
+ - A call that uses an unknown reference key is rejected before anything runs. The error names the unknown keys and lists the most recent available ones; correct the key or fetch the output again.
132
+ - To pass a placeholder as literal text, prefix it with a backslash: \`\\{{tool0turn0}}\` reaches the tool as \`{{tool0turn0}}\` with no substitution. For a real backslash directly before a reference (for example a Windows path), double it: \`C:\\out\\\\{{tool0turn0}}\`.
132
133
  `.trim();
133
134
 
134
135
  /**