@librechat/agents 3.3.7 → 3.3.9

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 (168) hide show
  1. package/dist/cjs/graphs/Graph.cjs +47 -13
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +56 -6
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/hitl/askUserQuestion.cjs +3 -2
  6. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  7. package/dist/cjs/instrumentation.cjs +18 -48
  8. package/dist/cjs/instrumentation.cjs.map +1 -1
  9. package/dist/cjs/langfuse.cjs +174 -29
  10. package/dist/cjs/langfuse.cjs.map +1 -1
  11. package/dist/cjs/langfuseConfig.cjs +12 -0
  12. package/dist/cjs/langfuseConfig.cjs.map +1 -1
  13. package/dist/cjs/langfuseRuntimeContext.cjs +23 -2
  14. package/dist/cjs/langfuseRuntimeContext.cjs.map +1 -1
  15. package/dist/cjs/langfuseRuntimeScope.cjs +39 -8
  16. package/dist/cjs/langfuseRuntimeScope.cjs.map +1 -1
  17. package/dist/cjs/langfuseSpanRegistry.cjs +95 -0
  18. package/dist/cjs/langfuseSpanRegistry.cjs.map +1 -0
  19. package/dist/cjs/langfuseTraceShaping.cjs +121 -4
  20. package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
  21. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +39 -15
  22. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  23. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +25 -5
  24. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  25. package/dist/cjs/llm/init.cjs +3 -3
  26. package/dist/cjs/llm/invoke.cjs +5 -5
  27. package/dist/cjs/llm/openai/index.cjs +1 -1
  28. package/dist/cjs/main.cjs +10 -10
  29. package/dist/cjs/messages/format.cjs +124 -15
  30. package/dist/cjs/messages/format.cjs.map +1 -1
  31. package/dist/cjs/messages/injected.cjs +10 -1
  32. package/dist/cjs/messages/injected.cjs.map +1 -1
  33. package/dist/cjs/messages/prune.cjs +13 -1
  34. package/dist/cjs/messages/prune.cjs.map +1 -1
  35. package/dist/cjs/prompts/activityLabel.cjs +51 -11
  36. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  37. package/dist/cjs/run.cjs +54 -24
  38. package/dist/cjs/run.cjs.map +1 -1
  39. package/dist/cjs/session/messageSerialization.cjs +6 -0
  40. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  41. package/dist/cjs/stream.cjs +21 -10
  42. package/dist/cjs/stream.cjs.map +1 -1
  43. package/dist/cjs/summarization/node.cjs +60 -0
  44. package/dist/cjs/summarization/node.cjs.map +1 -1
  45. package/dist/cjs/tools/ToolNode.cjs +253 -24
  46. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  47. package/dist/cjs/tools/handlers.cjs +1 -1
  48. package/dist/cjs/tools/search/tool.cjs +1 -1
  49. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -1
  50. package/dist/cjs/utils/index.cjs +2 -2
  51. package/dist/esm/graphs/Graph.mjs +48 -14
  52. package/dist/esm/graphs/Graph.mjs.map +1 -1
  53. package/dist/esm/graphs/MultiAgentGraph.mjs +56 -6
  54. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  55. package/dist/esm/hitl/askUserQuestion.mjs +3 -2
  56. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  57. package/dist/esm/instrumentation.mjs +18 -48
  58. package/dist/esm/instrumentation.mjs.map +1 -1
  59. package/dist/esm/langfuse.mjs +176 -28
  60. package/dist/esm/langfuse.mjs.map +1 -1
  61. package/dist/esm/langfuseConfig.mjs +10 -1
  62. package/dist/esm/langfuseConfig.mjs.map +1 -1
  63. package/dist/esm/langfuseRuntimeContext.mjs +21 -3
  64. package/dist/esm/langfuseRuntimeContext.mjs.map +1 -1
  65. package/dist/esm/langfuseRuntimeScope.mjs +39 -10
  66. package/dist/esm/langfuseRuntimeScope.mjs.map +1 -1
  67. package/dist/esm/langfuseSpanRegistry.mjs +91 -0
  68. package/dist/esm/langfuseSpanRegistry.mjs.map +1 -0
  69. package/dist/esm/langfuseTraceShaping.mjs +121 -4
  70. package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
  71. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +39 -15
  72. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  73. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +25 -5
  74. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  75. package/dist/esm/llm/init.mjs +2 -2
  76. package/dist/esm/llm/invoke.mjs +5 -5
  77. package/dist/esm/llm/openai/index.mjs +1 -1
  78. package/dist/esm/main.mjs +8 -8
  79. package/dist/esm/messages/format.mjs +124 -15
  80. package/dist/esm/messages/format.mjs.map +1 -1
  81. package/dist/esm/messages/injected.mjs +10 -1
  82. package/dist/esm/messages/injected.mjs.map +1 -1
  83. package/dist/esm/messages/prune.mjs +13 -1
  84. package/dist/esm/messages/prune.mjs.map +1 -1
  85. package/dist/esm/prompts/activityLabel.mjs +51 -11
  86. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  87. package/dist/esm/run.mjs +54 -24
  88. package/dist/esm/run.mjs.map +1 -1
  89. package/dist/esm/session/messageSerialization.mjs +6 -0
  90. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  91. package/dist/esm/stream.mjs +21 -10
  92. package/dist/esm/stream.mjs.map +1 -1
  93. package/dist/esm/summarization/node.mjs +60 -0
  94. package/dist/esm/summarization/node.mjs.map +1 -1
  95. package/dist/esm/tools/ToolNode.mjs +254 -25
  96. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  97. package/dist/esm/tools/handlers.mjs +1 -1
  98. package/dist/esm/tools/search/tool.mjs +1 -1
  99. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -1
  100. package/dist/esm/utils/index.mjs +2 -2
  101. package/dist/types/graphs/Graph.d.ts +19 -0
  102. package/dist/types/hitl/askUserQuestion.d.ts +11 -1
  103. package/dist/types/langfuse.d.ts +16 -8
  104. package/dist/types/langfuseConfig.d.ts +6 -0
  105. package/dist/types/langfuseRuntimeContext.d.ts +27 -1
  106. package/dist/types/langfuseRuntimeScope.d.ts +17 -2
  107. package/dist/types/langfuseSpanRegistry.d.ts +17 -0
  108. package/dist/types/langfuseTraceShaping.d.ts +2 -1
  109. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  110. package/dist/types/messages/format.d.ts +9 -8
  111. package/dist/types/prompts/activityLabel.d.ts +8 -1
  112. package/dist/types/run.d.ts +1 -1
  113. package/dist/types/session/types.d.ts +1 -0
  114. package/dist/types/tools/ToolNode.d.ts +7 -1
  115. package/dist/types/types/activityLabel.d.ts +8 -0
  116. package/dist/types/types/hitl.d.ts +8 -0
  117. package/dist/types/types/stream.d.ts +19 -0
  118. package/dist/types/types/tools.d.ts +30 -0
  119. package/package.json +7 -4
  120. package/src/__tests__/stream.eagerArgsDivergence.test.ts +753 -0
  121. package/src/graphs/Graph.ts +69 -20
  122. package/src/graphs/MultiAgentGraph.ts +74 -6
  123. package/src/graphs/__tests__/composition.smoke.test.ts +4 -0
  124. package/src/hitl/askUserQuestion.ts +14 -1
  125. package/src/instrumentation.ts +35 -77
  126. package/src/langfuse.ts +320 -43
  127. package/src/langfuseConfig.ts +24 -0
  128. package/src/langfuseRuntimeContext.ts +43 -1
  129. package/src/langfuseRuntimeScope.ts +94 -21
  130. package/src/langfuseSpanRegistry.ts +131 -0
  131. package/src/langfuseTraceShaping.ts +194 -7
  132. package/src/llm/anthropic/utils/message_inputs.ts +70 -19
  133. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +186 -11
  134. package/src/llm/bedrock/utils/message_inputs.test.ts +120 -4
  135. package/src/llm/bedrock/utils/message_inputs.ts +32 -7
  136. package/src/messages/format.ts +222 -50
  137. package/src/messages/formatAgentMessages.test.ts +308 -6
  138. package/src/messages/injected.test.ts +18 -1
  139. package/src/messages/injected.ts +8 -1
  140. package/src/messages/prune.ts +12 -1
  141. package/src/prompts/activityLabel.ts +67 -2
  142. package/src/run.ts +86 -46
  143. package/src/scripts/activity-labels/captured.json +56 -0
  144. package/src/scripts/activity-labels/checks.cjs +205 -0
  145. package/src/scripts/activity-labels/corpus.cjs +473 -0
  146. package/src/scripts/activity-labels/report.cjs +203 -0
  147. package/src/scripts/activity-labels/rescore.cjs +102 -0
  148. package/src/scripts/activity-labels/run.ts +705 -0
  149. package/src/scripts/activity-labels/variants.ts +71 -0
  150. package/src/session/messageSerialization.ts +12 -1
  151. package/src/session/types.ts +1 -0
  152. package/src/specs/activity-label-prompt.test.ts +109 -0
  153. package/src/specs/agent-handoffs.test.ts +306 -0
  154. package/src/specs/langfuse-callbacks.test.ts +456 -0
  155. package/src/specs/langfuse-routing.integration.test.ts +138 -1
  156. package/src/specs/langfuse-span-registry.test.ts +70 -0
  157. package/src/specs/langfuse-trace-shaping.test.ts +294 -0
  158. package/src/specs/prune.test.ts +38 -1
  159. package/src/stream.ts +70 -6
  160. package/src/summarization/__tests__/node.test.ts +188 -0
  161. package/src/summarization/node.ts +72 -0
  162. package/src/tools/ToolNode.ts +400 -9
  163. package/src/tools/__tests__/ToolNode.invalidToolCalls.test.ts +757 -0
  164. package/src/tools/__tests__/hitl.test.ts +58 -0
  165. package/src/types/activityLabel.ts +8 -0
  166. package/src/types/hitl.ts +8 -0
  167. package/src/types/stream.ts +20 -0
  168. package/src/types/tools.ts +35 -1
@@ -1 +1 @@
1
- {"version":3,"file":"message_inputs.cjs","names":["serializeStructuredValueBounded","HARD_MAX_TOOL_RESULT_CHARS"],"sources":["../../../../../src/llm/bedrock/utils/message_inputs.ts"],"sourcesContent":["/**\n * Utility functions for converting LangChain messages to Bedrock Converse messages.\n * Ported from @langchain/aws common.js\n */\nimport {\n type BaseMessage,\n type ToolMessage,\n isAIMessage,\n type Data,\n parseBase64DataUrl,\n parseMimeType,\n MessageContentComplex,\n type StandardContentBlockConverter,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport type {\n AudioFormat,\n AudioSource,\n DocumentFormat,\n DocumentSource,\n VideoFormat,\n VideoSource,\n} from '@aws-sdk/client-bedrock-runtime';\nimport type {\n BedrockMessage,\n BedrockSystemContentBlock,\n BedrockContentBlock,\n MessageContentReasoningBlock,\n} from '../types';\nimport { serializeStructuredValueBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\n\n/**\n * Reasoning blocks from other providers, relative to Bedrock. Bedrock's native\n * reasoning format is `reasoning_content`; these carry provider-specific\n * signatures Bedrock cannot validate, so they are dropped on a cross-provider\n * handoff (e.g. Anthropic → Bedrock) rather than crashing the conversion.\n */\nconst FOREIGN_REASONING_TYPES = [\n 'thinking',\n 'redacted_thinking',\n 'reasoning',\n 'think',\n];\n\n/**\n * Google server-side tool blocks (`toolCall`/`toolResponse` parts from e.g.\n * URL context or Google Search). Only Google can execute these and validate\n * their thought signatures, so they are dropped on a cross-provider handoff\n * (e.g. Google → Bedrock); the assistant's answer text is kept.\n */\nconst FOREIGN_SERVER_TOOL_TYPES = ['toolCall', 'toolResponse'];\n\n/**\n * Bedrock Converse rejects assistant messages with no content blocks. When\n * filtering (e.g. dropping foreign reasoning) empties an assistant turn that\n * also has no tool calls, fall back to this placeholder text.\n */\nconst BEDROCK_EMPTY_TEXT_PLACEHOLDER = '_';\n\n/**\n * Convert a LangChain reasoning block to a Bedrock reasoning block.\n */\nexport function langchainReasoningBlockToBedrockReasoningBlock(\n content: MessageContentReasoningBlock\n): {\n reasoningText?: { text?: string; signature?: string };\n redactedContent?: Uint8Array;\n} {\n if (content.reasoningText != null) {\n return {\n reasoningText: content.reasoningText,\n };\n }\n if (content.redactedContent != null && content.redactedContent !== '') {\n return {\n redactedContent: new Uint8Array(\n Buffer.from(content.redactedContent, 'base64')\n ),\n };\n }\n throw new Error('Invalid reasoning content');\n}\n\n/**\n * Whether a reasoning block can be serialized to a valid Bedrock\n * `reasoningContent`. Bedrock Converse rejects `reasoningText` with a null/empty\n * `text` (e.g. a signature-only block that never merged with its text), so such\n * blocks must be dropped rather than sent.\n */\nfunction isSerializableBedrockReasoningBlock(\n content: MessageContentReasoningBlock\n): boolean {\n if (content.reasoningText != null) {\n const text = content.reasoningText.text;\n return text != null && text !== '';\n }\n return content.redactedContent != null && content.redactedContent !== '';\n}\n\nfunction appendSerializableBedrockTextBlock(\n contentBlocks: BedrockContentBlock[],\n text: string\n): boolean {\n if (text === '') {\n return false;\n }\n const cleanedText = text.replace(/\\n/g, '').trim();\n if (cleanedText !== '') {\n contentBlocks.push({ text });\n return true;\n }\n const lastBlock = contentBlocks[contentBlocks.length - 1] as\n | BedrockContentBlock\n | undefined;\n if (lastBlock == null || !('text' in lastBlock)) {\n return false;\n }\n const mergedTextContent = `${lastBlock.text}${text}`;\n (lastBlock as { text: string }).text = mergedTextContent;\n return true;\n}\n\n/**\n * Concatenate consecutive reasoning blocks in content array.\n */\nexport function concatenateLangchainReasoningBlocks(\n content: Array<MessageContentComplex | MessageContentReasoningBlock>\n): Array<MessageContentComplex | MessageContentReasoningBlock> {\n const result: Array<MessageContentComplex | MessageContentReasoningBlock> =\n [];\n let pendingReasoning: MessageContentReasoningBlock | undefined;\n\n const flushPendingReasoning = (): void => {\n if (pendingReasoning != null) {\n result.push(pendingReasoning);\n pendingReasoning = undefined;\n }\n };\n\n for (const block of content) {\n if (block.type !== 'reasoning_content') {\n flushPendingReasoning();\n result.push(block);\n continue;\n }\n\n const currentReasoning = block as MessageContentReasoningBlock;\n if (currentReasoning.reasoningText != null) {\n const previousText = pendingReasoning?.reasoningText?.text;\n const previousSignature = pendingReasoning?.reasoningText?.signature;\n const { text, signature } = currentReasoning.reasoningText;\n const mergedReasoningText: { text?: string; signature?: string } = {};\n if (previousText !== undefined || text !== undefined) {\n mergedReasoningText.text = (previousText ?? '') + (text ?? '');\n }\n if (previousSignature !== undefined || signature !== undefined) {\n mergedReasoningText.signature =\n (previousSignature ?? '') + (signature ?? '');\n }\n pendingReasoning = {\n type: 'reasoning_content',\n reasoningText: mergedReasoningText,\n };\n\n // A signature seals the accumulated reasoning text. Any following\n // reasoning block starts a new independently signed Bedrock block.\n if ('signature' in currentReasoning.reasoningText) {\n flushPendingReasoning();\n }\n }\n\n if (currentReasoning.redactedContent != null) {\n flushPendingReasoning();\n result.push({\n type: 'reasoning_content',\n redactedContent: currentReasoning.redactedContent,\n });\n }\n }\n\n flushPendingReasoning();\n return result;\n}\n\n/**\n * Extract image info from a base64 string or URL.\n */\nexport function extractImageInfo(base64: string): BedrockContentBlock {\n // Extract the format from the base64 string\n const formatMatch = base64.match(/^data:image\\/(\\w+);base64,/);\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (formatMatch) {\n const extractedFormat = formatMatch[1].toLowerCase();\n if (['gif', 'jpeg', 'png', 'webp'].includes(extractedFormat)) {\n format = extractedFormat as typeof format;\n }\n }\n\n // Remove the data URL prefix if present\n const base64Data = base64.replace(/^data:image\\/\\w+;base64,/, '');\n\n // Convert base64 to Uint8Array\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i += 1) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n return {\n image: {\n format,\n source: {\n bytes,\n },\n },\n };\n}\n\ntype MediaContentBlock = MessageContentComplex & {\n data?: string | Uint8Array;\n url?: string;\n fileId?: string;\n mimeType?: string;\n};\n\nconst mimeTypeToVideoFormat: Record<string, VideoFormat> = {\n 'video/flv': 'flv',\n 'video/mkv': 'mkv',\n 'video/mov': 'mov',\n 'video/mp4': 'mp4',\n 'video/mpeg': 'mpeg',\n 'video/mpg': 'mpg',\n 'video/three_gp': 'three_gp',\n 'video/webm': 'webm',\n 'video/wmv': 'wmv',\n};\n\nconst mimeTypeToAudioFormat: Record<string, AudioFormat> = {\n 'audio/aac': 'aac',\n 'audio/flac': 'flac',\n 'audio/m4a': 'm4a',\n 'audio/mka': 'mka',\n 'audio/mkv': 'mkv',\n 'audio/mp3': 'mp3',\n 'audio/mp4': 'mp4',\n 'audio/mpeg': 'mpeg',\n 'audio/mpga': 'mpga',\n 'audio/ogg': 'ogg',\n 'audio/opus': 'opus',\n 'audio/pcm': 'pcm',\n 'audio/wav': 'wav',\n 'audio/webm': 'webm',\n 'audio/x-aac': 'x-aac',\n};\n\nconst mimeTypeToDocumentFormat: Partial<Record<string, DocumentFormat>> = {\n 'text/csv': 'csv',\n 'application/msword': 'doc',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n 'docx',\n 'text/html': 'html',\n 'text/markdown': 'md',\n 'application/pdf': 'pdf',\n 'text/plain': 'txt',\n 'application/vnd.ms-excel': 'xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n};\n\nfunction base64ToBytes(data: string): Uint8Array {\n return Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nfunction getMediaFormat<T extends string>(\n mimeType: string | undefined,\n formatMap: Record<string, T>\n): T | undefined {\n if (mimeType == null || mimeType === '') {\n return undefined;\n }\n return formatMap[mimeType] ?? (parseMimeType(mimeType).subtype as T);\n}\n\nfunction resolveMediaSource(\n block: MediaContentBlock\n): AudioSource | VideoSource {\n if (typeof block.data === 'string') {\n return { bytes: base64ToBytes(block.data) };\n }\n if (block.data instanceof Uint8Array) {\n return { bytes: block.data };\n }\n if (typeof block.url === 'string') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData != null) {\n return { bytes: parsedData.data as Uint8Array };\n }\n throw new Error(\n `Only base64 data URLs are supported for ${block.type} blocks with 'url' field with ChatBedrockConverse.`\n );\n }\n if (typeof block.fileId === 'string') {\n return { s3Location: { uri: block.fileId } };\n }\n throw new Error(\n `${block.type} block must include one of: 'data' (base64 string or Uint8Array), 'url' (base64 data URL), or 'fileId' (S3 URI).`\n );\n}\n\nfunction convertMultimodalVideoBlock(\n block: MediaContentBlock\n): BedrockContentBlock {\n return {\n video: {\n format: getMediaFormat(block.mimeType, mimeTypeToVideoFormat),\n source: resolveMediaSource(block) as VideoSource,\n },\n } as BedrockContentBlock;\n}\n\nfunction convertMultimodalAudioBlock(\n block: MediaContentBlock\n): BedrockContentBlock {\n return {\n audio: {\n format: getMediaFormat(block.mimeType, mimeTypeToAudioFormat),\n source: resolveMediaSource(block) as AudioSource,\n },\n } as BedrockContentBlock;\n}\n\nfunction getDocumentName(block: Data.StandardFileBlock): string {\n return (\n (block.metadata?.name as string | undefined) ??\n (block.metadata?.filename as string | undefined) ??\n (block.metadata?.title as string | undefined) ??\n globalThis.crypto.randomUUID().replace(/-/g, '').slice(0, 12)\n );\n}\n\nfunction getDocumentFormat(\n mimeType: string | undefined\n): DocumentFormat | undefined {\n if (mimeType == null || mimeType === '') {\n return undefined;\n }\n const parsedMimeType = parseMimeType(mimeType);\n const format =\n mimeTypeToDocumentFormat[\n `${parsedMimeType.type}/${parsedMimeType.subtype}`\n ];\n if (format === undefined) {\n throw new Error(\n `Unsupported file mime type: \"${mimeType}\" ChatBedrockConverse only supports ${Object.keys(\n mimeTypeToDocumentFormat\n ).join(', ')} formats.`\n );\n }\n return format;\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: BedrockContentBlock;\n image: BedrockContentBlock;\n file: BedrockContentBlock;\n}> = {\n providerName: 'ChatBedrockConverse',\n\n fromStandardTextBlock(block: Data.StandardTextBlock): BedrockContentBlock {\n return { text: block.text };\n },\n\n fromStandardImageBlock(block: Data.StandardImageBlock): BedrockContentBlock {\n if (block.source_type === 'url') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData == null) {\n throw new Error(\n [\n 'Only base64 data URLs are supported for image blocks with source type ',\n 'url',\n ' with ChatBedrockConverse.',\n ].join(String.fromCharCode(39))\n );\n }\n return {\n image: {\n format: parseMimeType(parsedData.mime_type).subtype as\n | 'gif'\n | 'jpeg'\n | 'png'\n | 'webp',\n source: { bytes: parsedData.data as Uint8Array },\n },\n };\n }\n if (block.source_type === 'base64') {\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (block.mime_type != null && block.mime_type !== '') {\n format = parseMimeType(block.mime_type).subtype as typeof format;\n }\n if (format != null && !['gif', 'jpeg', 'png', 'webp'].includes(format)) {\n throw new Error(\n `Unsupported image mime type: \"${block.mime_type}\" ChatBedrockConverse only supports \"image/gif\", \"image/jpeg\", \"image/png\", and \"image/webp\" formats.`\n );\n }\n return {\n image: {\n format,\n source: { bytes: base64ToBytes(block.data) },\n },\n };\n }\n throw new Error(\n `Image source type '${block.source_type}' not supported with ChatBedrockConverse.`\n );\n },\n\n fromStandardFileBlock(block: Data.StandardFileBlock): BedrockContentBlock {\n const name = getDocumentName(block);\n if (block.source_type === 'text') {\n return {\n document: {\n name,\n format: 'txt',\n source: { bytes: new TextEncoder().encode(block.text) },\n },\n } as BedrockContentBlock;\n }\n if (block.source_type === 'url') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData == null) {\n throw new Error(\n [\n 'Only base64 data URLs are supported for file blocks with source type ',\n 'url',\n ' with ChatBedrockConverse.',\n ].join(String.fromCharCode(39))\n );\n }\n return {\n document: {\n name,\n format: getDocumentFormat(parsedData.mime_type),\n source: { bytes: parsedData.data as Uint8Array } as DocumentSource,\n },\n } as BedrockContentBlock;\n }\n if (block.source_type === 'base64') {\n return {\n document: {\n name,\n format: getDocumentFormat(block.mime_type),\n source: { bytes: base64ToBytes(block.data) } as DocumentSource,\n },\n } as BedrockContentBlock;\n }\n throw new Error(\n `File source type '${block.source_type}' not supported with ChatBedrockConverse.`\n );\n },\n};\n\ntype BedrockPromptCacheTtl = '5m' | '1h';\ntype NormalizedBedrockCachePoint = {\n type: 'default';\n ttl?: BedrockPromptCacheTtl;\n};\n\n/**\n * Check if a block has a default cache point and return its normalized form,\n * preserving an optional extended-TTL `ttl` (`'5m'` | `'1h'`). Returns\n * `undefined` when the block is not a default cache point.\n */\nfunction getDefaultCachePoint(\n block: unknown\n): NormalizedBedrockCachePoint | undefined {\n if (typeof block !== 'object' || block === null) {\n return undefined;\n }\n if (!('cachePoint' in block)) {\n return undefined;\n }\n const cachePoint = (block as { cachePoint?: unknown }).cachePoint;\n if (typeof cachePoint !== 'object' || cachePoint === null) {\n return undefined;\n }\n if (!('type' in cachePoint)) {\n return undefined;\n }\n if ((cachePoint as { type?: string }).type !== 'default') {\n return undefined;\n }\n const ttl = (cachePoint as { ttl?: unknown }).ttl;\n return ttl === '5m' || ttl === '1h'\n ? { type: 'default', ttl }\n : { type: 'default' };\n}\n\n/**\n * Convert a LangChain content block to a Bedrock Converse content block.\n */\nfunction convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown = 'throw',\n}: {\n block: string | MessageContentComplex;\n onUnknown?: 'throw' | 'passthrough';\n}): BedrockContentBlock {\n if (typeof block === 'string') {\n return { text: block };\n }\n\n if (isDataContentBlock(block)) {\n return convertToProviderContentBlock(block, standardContentBlockConverter);\n }\n\n if (block.type === 'text') {\n return { text: (block as { text: string }).text };\n }\n\n if (block.type === 'image_url') {\n const imageUrl =\n typeof (block as { image_url: string | { url: string } }).image_url ===\n 'string'\n ? (block as { image_url: string }).image_url\n : (block as { image_url: { url: string } }).image_url.url;\n return extractImageInfo(imageUrl);\n }\n\n if (block.type === 'image') {\n // Handle standard image block format\n const imageBlock = block as {\n source_type?: string;\n url?: string;\n data?: string;\n mime_type?: string;\n };\n if (\n imageBlock.source_type === 'url' &&\n imageBlock.url != null &&\n imageBlock.url !== ''\n ) {\n const parsedData = parseBase64DataUrl({\n dataUrl: imageBlock.url,\n asTypedArray: true,\n });\n if (parsedData != null) {\n const parsedMimeType = parseMimeType(parsedData.mime_type);\n return {\n image: {\n format: parsedMimeType.subtype as 'gif' | 'jpeg' | 'png' | 'webp',\n source: {\n bytes: parsedData.data as Uint8Array,\n },\n },\n };\n }\n } else if (\n imageBlock.source_type === 'base64' &&\n imageBlock.data != null &&\n imageBlock.data !== ''\n ) {\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (imageBlock.mime_type != null && imageBlock.mime_type !== '') {\n const parsedMimeType = parseMimeType(imageBlock.mime_type);\n format = parsedMimeType.subtype as typeof format;\n }\n return {\n image: {\n format,\n source: {\n bytes: Uint8Array.from(atob(imageBlock.data), (c) =>\n c.charCodeAt(0)\n ),\n },\n },\n };\n }\n // If it already has the Bedrock image structure, pass through\n if ((block as { image?: unknown }).image !== undefined) {\n return {\n image: (block as { image: unknown }).image,\n } as BedrockContentBlock;\n }\n }\n\n if (\n block.type === 'video' &&\n (block as { video?: unknown }).video !== undefined\n ) {\n return {\n video: (block as { video: unknown }).video,\n } as BedrockContentBlock;\n }\n\n if (block.type === 'video') {\n return convertMultimodalVideoBlock(block as MediaContentBlock);\n }\n\n if (\n block.type === 'audio' &&\n (block as { audio?: unknown }).audio !== undefined\n ) {\n return {\n audio: (block as { audio: unknown }).audio,\n } as BedrockContentBlock;\n }\n\n if (block.type === 'audio') {\n return convertMultimodalAudioBlock(block as MediaContentBlock);\n }\n\n if (\n block.type === 'document' &&\n (block as { document?: unknown }).document !== undefined\n ) {\n return {\n document: (block as { document: unknown }).document,\n } as BedrockContentBlock;\n }\n\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n return {\n cachePoint,\n } as BedrockContentBlock;\n }\n\n if (onUnknown === 'throw') {\n throw new Error(`Unsupported content block type: ${block.type}`);\n } else {\n return block as unknown as BedrockContentBlock;\n }\n}\n\n/**\n * Convert a system message to Bedrock system content blocks.\n */\nfunction convertSystemMessageToConverseMessage(\n msg: BaseMessage\n): BedrockSystemContentBlock[] {\n if (typeof msg.content === 'string') {\n return [{ text: msg.content }];\n } else if (Array.isArray(msg.content) && msg.content.length > 0) {\n const contentBlocks: BedrockSystemContentBlock[] = [];\n for (const block of msg.content) {\n if (\n typeof block === 'object' &&\n block.type === 'text' &&\n typeof (block as { text?: string }).text === 'string'\n ) {\n contentBlocks.push({\n text: (block as { text: string }).text,\n });\n } else {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint == null) {\n break;\n }\n contentBlocks.push({\n cachePoint,\n } as BedrockSystemContentBlock);\n }\n }\n if (msg.content.length === contentBlocks.length) {\n return contentBlocks;\n }\n }\n throw new Error(\n 'System message content must be either a string, or an array of text blocks, optionally including a cache point.'\n );\n}\n\n/**\n * Convert an AI message to a Bedrock message.\n */\nfunction convertAIMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n // Check for v1 format from other providers (PR #9766 fix)\n const responseMetadata = msg.response_metadata as\n | { output_version?: string }\n | undefined;\n if (responseMetadata?.output_version === 'v1') {\n return convertFromV1ToChatBedrockConverseMessage(msg);\n }\n\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: [],\n };\n\n if (typeof msg.content === 'string' && msg.content !== '') {\n assistantMsg.content?.push({ text: msg.content });\n } else if (Array.isArray(msg.content)) {\n const parsedToolCallIds = new Set(\n isAIMessage(msg)\n ? (msg.tool_calls ?? []).flatMap((toolCall) =>\n toolCall.id != null ? [toolCall.id] : []\n )\n : []\n );\n const concatenatedBlocks = concatenateLangchainReasoningBlocks(\n msg.content as Array<MessageContentComplex | MessageContentReasoningBlock>\n );\n const contentBlocks: BedrockContentBlock[] = [];\n\n concatenatedBlocks.forEach((block) => {\n if (block.type === 'text') {\n const text = (block as { text?: string }).text ?? '';\n appendSerializableBedrockTextBlock(contentBlocks, text);\n } else if (block.type === 'tool_use') {\n const toolUse = block as {\n id?: unknown;\n name?: unknown;\n input?: unknown;\n };\n if (\n typeof toolUse.id === 'string' &&\n parsedToolCallIds.has(toolUse.id)\n ) {\n return;\n }\n if (\n typeof toolUse.id !== 'string' ||\n typeof toolUse.name !== 'string' ||\n toolUse.input == null ||\n typeof toolUse.input !== 'object'\n ) {\n throw new Error('Invalid Anthropic tool_use content block');\n }\n contentBlocks.push({\n toolUse: {\n toolUseId: toolUse.id,\n name: toolUse.name,\n input: toolUse.input as Record<string, unknown>,\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning_content') {\n const reasoningBlock = block as MessageContentReasoningBlock;\n // Bedrock Converse rejects reasoningContent whose reasoningText.text is\n // null/empty (a signature-only block that never merged with its text).\n // Drop it rather than emit an invalid request; the empty-turn\n // placeholder below covers a turn left with no content.\n if (!isSerializableBedrockReasoningBlock(reasoningBlock)) {\n return;\n }\n contentBlocks.push({\n reasoningContent:\n langchainReasoningBlockToBedrockReasoningBlock(reasoningBlock),\n } as BedrockContentBlock);\n } else {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n contentBlocks.push({\n cachePoint,\n } as BedrockContentBlock);\n } else if (FOREIGN_REASONING_TYPES.some((t) => t === block.type)) {\n // Reasoning from another provider (Anthropic `thinking`/\n // `redacted_thinking`, Google `reasoning`, LibreChat `think`).\n // Bedrock's native reasoning is `reasoning_content` (handled above); a\n // foreign block carries a signature Bedrock cannot validate, so drop\n // it on a cross-provider handoff (e.g. Anthropic → Bedrock) rather\n // than crash. The Bedrock model produces its own reasoning. Anything\n // else unknown still throws below — real content must be surfaced.\n return;\n } else if (FOREIGN_SERVER_TOOL_TYPES.some((t) => t === block.type)) {\n // Google server-side tool call/response (e.g. URL context) — only\n // Google can execute it or validate its thought signature; drop it\n // on a cross-provider handoff rather than crash.\n return;\n } else {\n const blockValues = Object.fromEntries(\n Object.entries(block).filter(([key]) => key !== 'type')\n );\n throw new Error(\n `Unsupported content block type: ${block.type} with content of ${JSON.stringify(blockValues, null, 2)}`\n );\n }\n }\n });\n\n assistantMsg.content = [...(assistantMsg.content ?? []), ...contentBlocks];\n }\n\n // Important: this must be placed after any reasoning content blocks\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n const existingToolUseIds = new Set(\n (assistantMsg.content ?? [])\n .filter((content) => 'toolUse' in content)\n .map((content) => content.toolUse?.toolUseId)\n );\n const toolUseBlocks = msg.tool_calls\n .filter((toolCall) => !existingToolUseIds.has(toolCall.id))\n .map((toolCall) => ({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as Record<string, unknown>,\n },\n }));\n assistantMsg.content = [\n ...(assistantMsg.content ?? []),\n ...toolUseBlocks,\n ] as BedrockContentBlock[];\n }\n\n // Bedrock rejects an assistant message with no content blocks; if filtering\n // (e.g. dropping foreign reasoning) left it empty, emit a placeholder.\n if (assistantMsg.content == null || assistantMsg.content.length === 0) {\n assistantMsg.content = [{ text: BEDROCK_EMPTY_TEXT_PLACEHOLDER }];\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a v1 format message from other providers to Bedrock format.\n * This handles messages with standard content blocks like tool_call and reasoning.\n * (Implements PR #9766 fix for output_version v1 detection)\n */\nfunction convertFromV1ToChatBedrockConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const contentBlocks: BedrockContentBlock[] = [];\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: contentBlocks,\n };\n let droppedUnserializableContent = false;\n let unconvertedContentType: string | undefined;\n\n if (Array.isArray(msg.content)) {\n const concatenatedBlocks = concatenateLangchainReasoningBlocks(\n msg.content as Array<MessageContentComplex | MessageContentReasoningBlock>\n );\n for (const block of concatenatedBlocks) {\n if (typeof block === 'string') {\n if (!appendSerializableBedrockTextBlock(contentBlocks, block)) {\n droppedUnserializableContent = true;\n }\n } else if (block.type === 'text') {\n const text = (block as { text?: string }).text ?? '';\n if (!appendSerializableBedrockTextBlock(contentBlocks, text)) {\n droppedUnserializableContent = true;\n }\n } else if (block.type === 'tool_call') {\n const toolCall = block as {\n id: string;\n name: string;\n args: Record<string, unknown>;\n };\n contentBlocks.push({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as Record<string, unknown>,\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning') {\n const reasoning = block as { reasoning?: string };\n /** Bedrock Converse rejects `reasoningText` with a null/empty `text`\n * (`Member must not be null`), e.g. when the producing model omitted\n * reasoning text (`thinking.display: \"omitted\"`) — drop rather than send. */\n if (reasoning.reasoning == null || reasoning.reasoning === '') {\n droppedUnserializableContent = true;\n continue;\n }\n contentBlocks.push({\n reasoningContent: {\n reasoningText: { text: reasoning.reasoning },\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning_content') {\n const reasoningBlock = block as MessageContentReasoningBlock;\n if (!isSerializableBedrockReasoningBlock(reasoningBlock)) {\n droppedUnserializableContent = true;\n continue;\n }\n contentBlocks.push({\n reasoningContent:\n langchainReasoningBlockToBedrockReasoningBlock(reasoningBlock),\n } as BedrockContentBlock);\n } else {\n unconvertedContentType ??= block.type;\n }\n }\n } else if (typeof msg.content === 'string') {\n if (!appendSerializableBedrockTextBlock(contentBlocks, msg.content)) {\n droppedUnserializableContent = true;\n }\n }\n\n // Also handle tool_calls from the message\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n // Check if tool calls are already in content\n const existingToolUseIds = new Set(\n contentBlocks\n .filter((c) => 'toolUse' in c)\n .map((c) => (c as { toolUse: { toolUseId: string } }).toolUse.toolUseId)\n );\n\n for (const tc of msg.tool_calls) {\n if (!existingToolUseIds.has(tc.id ?? '')) {\n contentBlocks.push({\n toolUse: {\n toolUseId: tc.id,\n name: tc.name,\n input: tc.args as Record<string, unknown>,\n },\n } as BedrockContentBlock);\n }\n }\n }\n\n const hasNoContent = contentBlocks.length === 0;\n if (hasNoContent && unconvertedContentType != null) {\n throw new Error(\n `Unsupported v1 content block type: ${unconvertedContentType}`\n );\n }\n if (hasNoContent && droppedUnserializableContent) {\n contentBlocks.push({ text: BEDROCK_EMPTY_TEXT_PLACEHOLDER });\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a human message to a Bedrock message.\n */\nfunction convertHumanMessageToConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const userMessage: BedrockMessage = {\n role: 'user',\n content: [],\n };\n\n if (typeof msg.content === 'string') {\n userMessage.content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n userMessage.content = msg.content.map((block) =>\n convertLangChainContentBlockToConverseContentBlock({ block })\n );\n }\n\n return userMessage;\n}\n\n/**\n * Convert a tool message to a Bedrock message.\n */\nfunction convertToolMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n const toolCallId = (msg as { tool_call_id?: string }).tool_call_id;\n let isError = (msg as ToolMessage).status === 'error';\n\n let content: BedrockContentBlock[];\n if (typeof msg.content === 'string') {\n content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n content = msg.content.flatMap((block) => {\n if (typeof block === 'object' && block.type === 'tool_result') {\n if ((block as { is_error?: unknown }).is_error === true) {\n isError = true;\n }\n const toolResultContent = (block as { content?: unknown }).content;\n if (typeof toolResultContent === 'string') {\n return [{ text: toolResultContent }];\n }\n if (Array.isArray(toolResultContent)) {\n return toolResultContent.map((nestedBlock) =>\n convertLangChainContentBlockToConverseContentBlock({\n block: nestedBlock,\n onUnknown: 'passthrough',\n })\n );\n }\n return [\n {\n text: serializeStructuredValueBounded(\n toolResultContent,\n HARD_MAX_TOOL_RESULT_CHARS\n ).content,\n },\n ];\n }\n return [\n convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown: 'passthrough',\n }),\n ];\n });\n } else {\n content = [{ text: String(msg.content) }];\n }\n\n // A `cachePoint` is a message-level ContentBlock — it is NOT a valid\n // ToolResultContentBlock. A tail prompt-cache breakpoint that anchors on a\n // tool result therefore ends up nested inside `toolResult.content`, which\n // Bedrock silently ignores (no cache write, no cache read). Hoist any\n // cachePoint(s) out of the tool result body so they sit as siblings after\n // it, which is the only position Bedrock honors.\n const toolResultContent: BedrockContentBlock[] = [];\n const trailingCachePoints: BedrockContentBlock[] = [];\n for (const block of content) {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n trailingCachePoints.push({\n cachePoint,\n } as BedrockContentBlock);\n } else {\n toolResultContent.push(block);\n }\n }\n\n return {\n role: 'user',\n content: [\n {\n toolResult: {\n toolUseId: toolCallId,\n content: toolResultContent as { text: string }[],\n ...(isError ? { status: 'error' as const } : {}),\n },\n },\n ...trailingCachePoints,\n ],\n };\n}\n\n/**\n * Convert LangChain messages to Bedrock Converse messages.\n */\nexport function convertToConverseMessages(messages: BaseMessage[]): {\n converseMessages: BedrockMessage[];\n converseSystem: BedrockSystemContentBlock[];\n} {\n const converseSystem = messages\n .filter((msg) => msg._getType() === 'system')\n .flatMap((msg) => convertSystemMessageToConverseMessage(msg));\n\n const converseMessages = messages\n .filter((msg) => msg._getType() !== 'system')\n .map((msg) => {\n if (msg._getType() === 'ai') {\n return convertAIMessageToConverseMessage(msg);\n } else if (msg._getType() === 'human' || msg._getType() === 'generic') {\n return convertHumanMessageToConverseMessage(msg);\n } else if (msg._getType() === 'tool') {\n return convertToolMessageToConverseMessage(msg);\n } else {\n throw new Error(`Unsupported message type: ${msg._getType()}`);\n }\n });\n\n /**\n * Combine ALL consecutive user messages into one, not just tool-result\n * pairs. The Converse API documents strict role alternation; enforcement\n * varies by model family (Claude on Converse currently tolerates adjacent\n * user messages — verified live, 2026-07-28 — but the docs promise nothing\n * for the others), so the converter never emits the shape. The case that\n * matters: a `PostToolBatch`/`PreemptBoundary` hook injection lands a text\n * turn directly after tool results, and `ToolMessage` and `HumanMessage`\n * both convert to `role: 'user'` above. Block order is preserved\n * (toolResult blocks, then text) — verified live that Converse accepts the\n * mixed user message and answers both halves — and the toolUse/toolResult\n * pairing stays intact.\n */\n const combinedConverseMessages = converseMessages.reduce<BedrockMessage[]>(\n (acc, curr) => {\n if (acc.length === 0) {\n acc.push(curr);\n return acc;\n }\n const lastMessage = acc[acc.length - 1];\n if (lastMessage.role === 'user' && curr.role === 'user') {\n lastMessage.content = lastMessage.content?.concat(curr.content ?? []);\n } else {\n acc.push(curr);\n }\n return acc;\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,GACA,CAAC,CAG+C;EAAG;CAAe;AACtE"}
1
+ {"version":3,"file":"message_inputs.cjs","names":["serializeStructuredValueBounded","HARD_MAX_TOOL_RESULT_CHARS"],"sources":["../../../../../src/llm/bedrock/utils/message_inputs.ts"],"sourcesContent":["/**\n * Utility functions for converting LangChain messages to Bedrock Converse messages.\n * Ported from @langchain/aws common.js\n */\nimport {\n type BaseMessage,\n type ToolMessage,\n isAIMessage,\n type Data,\n parseBase64DataUrl,\n parseMimeType,\n MessageContentComplex,\n type StandardContentBlockConverter,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport type {\n AudioFormat,\n AudioSource,\n DocumentFormat,\n DocumentSource,\n VideoFormat,\n VideoSource,\n} from '@aws-sdk/client-bedrock-runtime';\nimport type {\n BedrockMessage,\n BedrockSystemContentBlock,\n BedrockContentBlock,\n MessageContentReasoningBlock,\n} from '../types';\nimport { serializeStructuredValueBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\n\n/**\n * Reasoning blocks from other providers, relative to Bedrock. Bedrock's native\n * reasoning format is `reasoning_content`; these carry provider-specific\n * signatures Bedrock cannot validate, so they are dropped on a cross-provider\n * handoff (e.g. Anthropic → Bedrock) rather than crashing the conversion.\n */\nconst FOREIGN_REASONING_TYPES = [\n 'thinking',\n 'redacted_thinking',\n 'reasoning',\n 'think',\n];\n\n/**\n * Google server-side tool blocks (`toolCall`/`toolResponse` parts from e.g.\n * URL context or Google Search). Only Google can execute these and validate\n * their thought signatures, so they are dropped on a cross-provider handoff\n * (e.g. Google → Bedrock); the assistant's answer text is kept.\n */\nconst FOREIGN_SERVER_TOOL_TYPES = ['toolCall', 'toolResponse'];\n\n/**\n * Bedrock Converse rejects assistant messages with no content blocks. When\n * filtering (e.g. dropping foreign reasoning) empties an assistant turn that\n * also has no tool calls, fall back to this placeholder text.\n */\nconst BEDROCK_EMPTY_TEXT_PLACEHOLDER = '_';\n\n/**\n * Convert a LangChain reasoning block to a Bedrock reasoning block.\n */\nexport function langchainReasoningBlockToBedrockReasoningBlock(\n content: MessageContentReasoningBlock\n): {\n reasoningText?: { text?: string; signature?: string };\n redactedContent?: Uint8Array;\n} {\n if (content.reasoningText != null) {\n return {\n reasoningText: content.reasoningText,\n };\n }\n if (content.redactedContent != null && content.redactedContent !== '') {\n return {\n redactedContent: new Uint8Array(\n Buffer.from(content.redactedContent, 'base64')\n ),\n };\n }\n throw new Error('Invalid reasoning content');\n}\n\n/**\n * Whether a reasoning block can be serialized to a valid Bedrock\n * `reasoningContent`. Bedrock Converse rejects `reasoningText` with a null/empty\n * `text` (e.g. a signature-only block that never merged with its text), so such\n * blocks must be dropped rather than sent.\n */\nfunction isSerializableBedrockReasoningBlock(\n content: MessageContentReasoningBlock\n): boolean {\n if (content.reasoningText != null) {\n const text = content.reasoningText.text;\n return text != null && text !== '';\n }\n return content.redactedContent != null && content.redactedContent !== '';\n}\n\nfunction appendSerializableBedrockTextBlock(\n contentBlocks: BedrockContentBlock[],\n text: string\n): boolean {\n if (text === '') {\n return false;\n }\n const cleanedText = text.replace(/\\n/g, '').trim();\n if (cleanedText !== '') {\n contentBlocks.push({ text });\n return true;\n }\n const lastBlock = contentBlocks[contentBlocks.length - 1] as\n | BedrockContentBlock\n | undefined;\n if (lastBlock == null || !('text' in lastBlock)) {\n return false;\n }\n const mergedTextContent = `${lastBlock.text}${text}`;\n (lastBlock as { text: string }).text = mergedTextContent;\n return true;\n}\n\n/**\n * Concatenate consecutive reasoning blocks in content array.\n */\nexport function concatenateLangchainReasoningBlocks(\n content: Array<MessageContentComplex | MessageContentReasoningBlock>\n): Array<MessageContentComplex | MessageContentReasoningBlock> {\n const result: Array<MessageContentComplex | MessageContentReasoningBlock> =\n [];\n let pendingReasoning: MessageContentReasoningBlock | undefined;\n\n const flushPendingReasoning = (): void => {\n if (pendingReasoning != null) {\n result.push(pendingReasoning);\n pendingReasoning = undefined;\n }\n };\n\n for (const block of content) {\n if (block.type !== 'reasoning_content') {\n flushPendingReasoning();\n result.push(block);\n continue;\n }\n\n const currentReasoning = block as MessageContentReasoningBlock;\n if (currentReasoning.reasoningText != null) {\n const previousText = pendingReasoning?.reasoningText?.text;\n const previousSignature = pendingReasoning?.reasoningText?.signature;\n const { text, signature } = currentReasoning.reasoningText;\n const mergedReasoningText: { text?: string; signature?: string } = {};\n if (previousText !== undefined || text !== undefined) {\n mergedReasoningText.text = (previousText ?? '') + (text ?? '');\n }\n if (previousSignature !== undefined || signature !== undefined) {\n mergedReasoningText.signature =\n (previousSignature ?? '') + (signature ?? '');\n }\n pendingReasoning = {\n type: 'reasoning_content',\n reasoningText: mergedReasoningText,\n };\n\n // A signature seals the accumulated reasoning text. Any following\n // reasoning block starts a new independently signed Bedrock block.\n if ('signature' in currentReasoning.reasoningText) {\n flushPendingReasoning();\n }\n }\n\n if (currentReasoning.redactedContent != null) {\n flushPendingReasoning();\n result.push({\n type: 'reasoning_content',\n redactedContent: currentReasoning.redactedContent,\n });\n }\n }\n\n flushPendingReasoning();\n return result;\n}\n\n/**\n * Extract image info from a base64 string or URL.\n */\nexport function extractImageInfo(base64: string): BedrockContentBlock {\n // Extract the format from the base64 string\n const formatMatch = base64.match(/^data:image\\/(\\w+);base64,/);\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (formatMatch) {\n const extractedFormat = formatMatch[1].toLowerCase();\n if (['gif', 'jpeg', 'png', 'webp'].includes(extractedFormat)) {\n format = extractedFormat as typeof format;\n }\n }\n\n // Remove the data URL prefix if present\n const base64Data = base64.replace(/^data:image\\/\\w+;base64,/, '');\n\n // Convert base64 to Uint8Array\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i += 1) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n return {\n image: {\n format,\n source: {\n bytes,\n },\n },\n };\n}\n\ntype MediaContentBlock = MessageContentComplex & {\n data?: string | Uint8Array;\n url?: string;\n fileId?: string;\n mimeType?: string;\n};\n\nconst mimeTypeToVideoFormat: Record<string, VideoFormat> = {\n 'video/flv': 'flv',\n 'video/mkv': 'mkv',\n 'video/mov': 'mov',\n 'video/mp4': 'mp4',\n 'video/mpeg': 'mpeg',\n 'video/mpg': 'mpg',\n 'video/three_gp': 'three_gp',\n 'video/webm': 'webm',\n 'video/wmv': 'wmv',\n};\n\nconst mimeTypeToAudioFormat: Record<string, AudioFormat> = {\n 'audio/aac': 'aac',\n 'audio/flac': 'flac',\n 'audio/m4a': 'm4a',\n 'audio/mka': 'mka',\n 'audio/mkv': 'mkv',\n 'audio/mp3': 'mp3',\n 'audio/mp4': 'mp4',\n 'audio/mpeg': 'mpeg',\n 'audio/mpga': 'mpga',\n 'audio/ogg': 'ogg',\n 'audio/opus': 'opus',\n 'audio/pcm': 'pcm',\n 'audio/wav': 'wav',\n 'audio/webm': 'webm',\n 'audio/x-aac': 'x-aac',\n};\n\nconst mimeTypeToDocumentFormat: Partial<Record<string, DocumentFormat>> = {\n 'text/csv': 'csv',\n 'application/msword': 'doc',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n 'docx',\n 'text/html': 'html',\n 'text/markdown': 'md',\n 'application/pdf': 'pdf',\n 'text/plain': 'txt',\n 'application/vnd.ms-excel': 'xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n};\n\nfunction base64ToBytes(data: string): Uint8Array {\n return Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nfunction getMediaFormat<T extends string>(\n mimeType: string | undefined,\n formatMap: Record<string, T>\n): T | undefined {\n if (mimeType == null || mimeType === '') {\n return undefined;\n }\n return formatMap[mimeType] ?? (parseMimeType(mimeType).subtype as T);\n}\n\nfunction resolveMediaSource(\n block: MediaContentBlock\n): AudioSource | VideoSource {\n if (typeof block.data === 'string') {\n return { bytes: base64ToBytes(block.data) };\n }\n if (block.data instanceof Uint8Array) {\n return { bytes: block.data };\n }\n if (typeof block.url === 'string') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData != null) {\n return { bytes: parsedData.data as Uint8Array };\n }\n throw new Error(\n `Only base64 data URLs are supported for ${block.type} blocks with 'url' field with ChatBedrockConverse.`\n );\n }\n if (typeof block.fileId === 'string') {\n return { s3Location: { uri: block.fileId } };\n }\n throw new Error(\n `${block.type} block must include one of: 'data' (base64 string or Uint8Array), 'url' (base64 data URL), or 'fileId' (S3 URI).`\n );\n}\n\nfunction convertMultimodalVideoBlock(\n block: MediaContentBlock\n): BedrockContentBlock {\n return {\n video: {\n format: getMediaFormat(block.mimeType, mimeTypeToVideoFormat),\n source: resolveMediaSource(block) as VideoSource,\n },\n } as BedrockContentBlock;\n}\n\nfunction convertMultimodalAudioBlock(\n block: MediaContentBlock\n): BedrockContentBlock {\n return {\n audio: {\n format: getMediaFormat(block.mimeType, mimeTypeToAudioFormat),\n source: resolveMediaSource(block) as AudioSource,\n },\n } as BedrockContentBlock;\n}\n\nfunction getDocumentName(block: Data.StandardFileBlock): string {\n return (\n (block.metadata?.name as string | undefined) ??\n (block.metadata?.filename as string | undefined) ??\n (block.metadata?.title as string | undefined) ??\n globalThis.crypto.randomUUID().replace(/-/g, '').slice(0, 12)\n );\n}\n\nfunction getDocumentFormat(\n mimeType: string | undefined\n): DocumentFormat | undefined {\n if (mimeType == null || mimeType === '') {\n return undefined;\n }\n const parsedMimeType = parseMimeType(mimeType);\n const format =\n mimeTypeToDocumentFormat[\n `${parsedMimeType.type}/${parsedMimeType.subtype}`\n ];\n if (format === undefined) {\n throw new Error(\n `Unsupported file mime type: \"${mimeType}\" ChatBedrockConverse only supports ${Object.keys(\n mimeTypeToDocumentFormat\n ).join(', ')} formats.`\n );\n }\n return format;\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: BedrockContentBlock;\n image: BedrockContentBlock;\n file: BedrockContentBlock;\n}> = {\n providerName: 'ChatBedrockConverse',\n\n fromStandardTextBlock(block: Data.StandardTextBlock): BedrockContentBlock {\n return { text: block.text };\n },\n\n fromStandardImageBlock(block: Data.StandardImageBlock): BedrockContentBlock {\n if (block.source_type === 'url') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData == null) {\n throw new Error(\n [\n 'Only base64 data URLs are supported for image blocks with source type ',\n 'url',\n ' with ChatBedrockConverse.',\n ].join(String.fromCharCode(39))\n );\n }\n return {\n image: {\n format: parseMimeType(parsedData.mime_type).subtype as\n | 'gif'\n | 'jpeg'\n | 'png'\n | 'webp',\n source: { bytes: parsedData.data as Uint8Array },\n },\n };\n }\n if (block.source_type === 'base64') {\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (block.mime_type != null && block.mime_type !== '') {\n format = parseMimeType(block.mime_type).subtype as typeof format;\n }\n if (format != null && !['gif', 'jpeg', 'png', 'webp'].includes(format)) {\n throw new Error(\n `Unsupported image mime type: \"${block.mime_type}\" ChatBedrockConverse only supports \"image/gif\", \"image/jpeg\", \"image/png\", and \"image/webp\" formats.`\n );\n }\n return {\n image: {\n format,\n source: { bytes: base64ToBytes(block.data) },\n },\n };\n }\n throw new Error(\n `Image source type '${block.source_type}' not supported with ChatBedrockConverse.`\n );\n },\n\n fromStandardFileBlock(block: Data.StandardFileBlock): BedrockContentBlock {\n const name = getDocumentName(block);\n if (block.source_type === 'text') {\n return {\n document: {\n name,\n format: 'txt',\n source: { bytes: new TextEncoder().encode(block.text) },\n },\n } as BedrockContentBlock;\n }\n if (block.source_type === 'url') {\n const parsedData = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: true,\n });\n if (parsedData == null) {\n throw new Error(\n [\n 'Only base64 data URLs are supported for file blocks with source type ',\n 'url',\n ' with ChatBedrockConverse.',\n ].join(String.fromCharCode(39))\n );\n }\n return {\n document: {\n name,\n format: getDocumentFormat(parsedData.mime_type),\n source: { bytes: parsedData.data as Uint8Array } as DocumentSource,\n },\n } as BedrockContentBlock;\n }\n if (block.source_type === 'base64') {\n return {\n document: {\n name,\n format: getDocumentFormat(block.mime_type),\n source: { bytes: base64ToBytes(block.data) } as DocumentSource,\n },\n } as BedrockContentBlock;\n }\n throw new Error(\n `File source type '${block.source_type}' not supported with ChatBedrockConverse.`\n );\n },\n};\n\ntype BedrockPromptCacheTtl = '5m' | '1h';\ntype NormalizedBedrockCachePoint = {\n type: 'default';\n ttl?: BedrockPromptCacheTtl;\n};\n\n/**\n * Check if a block has a default cache point and return its normalized form,\n * preserving an optional extended-TTL `ttl` (`'5m'` | `'1h'`). Returns\n * `undefined` when the block is not a default cache point.\n */\nfunction getDefaultCachePoint(\n block: unknown\n): NormalizedBedrockCachePoint | undefined {\n if (typeof block !== 'object' || block === null) {\n return undefined;\n }\n if (!('cachePoint' in block)) {\n return undefined;\n }\n const cachePoint = (block as { cachePoint?: unknown }).cachePoint;\n if (typeof cachePoint !== 'object' || cachePoint === null) {\n return undefined;\n }\n if (!('type' in cachePoint)) {\n return undefined;\n }\n if ((cachePoint as { type?: string }).type !== 'default') {\n return undefined;\n }\n const ttl = (cachePoint as { ttl?: unknown }).ttl;\n return ttl === '5m' || ttl === '1h'\n ? { type: 'default', ttl }\n : { type: 'default' };\n}\n\n/**\n * Convert a LangChain content block to a Bedrock Converse content block.\n */\nfunction convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown = 'throw',\n}: {\n block: string | MessageContentComplex;\n onUnknown?: 'throw' | 'passthrough';\n}): BedrockContentBlock {\n if (typeof block === 'string') {\n return { text: block };\n }\n\n if (isDataContentBlock(block)) {\n return convertToProviderContentBlock(block, standardContentBlockConverter);\n }\n\n if (block.type === 'text') {\n return { text: (block as { text: string }).text };\n }\n\n if (block.type === 'image_url') {\n const imageUrl =\n typeof (block as { image_url: string | { url: string } }).image_url ===\n 'string'\n ? (block as { image_url: string }).image_url\n : (block as { image_url: { url: string } }).image_url.url;\n return extractImageInfo(imageUrl);\n }\n\n if (block.type === 'image') {\n // Handle standard image block format\n const imageBlock = block as {\n source_type?: string;\n url?: string;\n data?: string;\n mime_type?: string;\n };\n if (\n imageBlock.source_type === 'url' &&\n imageBlock.url != null &&\n imageBlock.url !== ''\n ) {\n const parsedData = parseBase64DataUrl({\n dataUrl: imageBlock.url,\n asTypedArray: true,\n });\n if (parsedData != null) {\n const parsedMimeType = parseMimeType(parsedData.mime_type);\n return {\n image: {\n format: parsedMimeType.subtype as 'gif' | 'jpeg' | 'png' | 'webp',\n source: {\n bytes: parsedData.data as Uint8Array,\n },\n },\n };\n }\n } else if (\n imageBlock.source_type === 'base64' &&\n imageBlock.data != null &&\n imageBlock.data !== ''\n ) {\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (imageBlock.mime_type != null && imageBlock.mime_type !== '') {\n const parsedMimeType = parseMimeType(imageBlock.mime_type);\n format = parsedMimeType.subtype as typeof format;\n }\n return {\n image: {\n format,\n source: {\n bytes: Uint8Array.from(atob(imageBlock.data), (c) =>\n c.charCodeAt(0)\n ),\n },\n },\n };\n }\n // If it already has the Bedrock image structure, pass through\n if ((block as { image?: unknown }).image !== undefined) {\n return {\n image: (block as { image: unknown }).image,\n } as BedrockContentBlock;\n }\n }\n\n if (\n block.type === 'video' &&\n (block as { video?: unknown }).video !== undefined\n ) {\n return {\n video: (block as { video: unknown }).video,\n } as BedrockContentBlock;\n }\n\n if (block.type === 'video') {\n return convertMultimodalVideoBlock(block as MediaContentBlock);\n }\n\n if (\n block.type === 'audio' &&\n (block as { audio?: unknown }).audio !== undefined\n ) {\n return {\n audio: (block as { audio: unknown }).audio,\n } as BedrockContentBlock;\n }\n\n if (block.type === 'audio') {\n return convertMultimodalAudioBlock(block as MediaContentBlock);\n }\n\n if (\n block.type === 'document' &&\n (block as { document?: unknown }).document !== undefined\n ) {\n return {\n document: (block as { document: unknown }).document,\n } as BedrockContentBlock;\n }\n\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n return {\n cachePoint,\n } as BedrockContentBlock;\n }\n\n if (onUnknown === 'throw') {\n throw new Error(`Unsupported content block type: ${block.type}`);\n } else {\n return block as unknown as BedrockContentBlock;\n }\n}\n\n/**\n * Convert a system message to Bedrock system content blocks.\n */\nfunction convertSystemMessageToConverseMessage(\n msg: BaseMessage\n): BedrockSystemContentBlock[] {\n if (typeof msg.content === 'string') {\n return [{ text: msg.content }];\n } else if (Array.isArray(msg.content) && msg.content.length > 0) {\n const contentBlocks: BedrockSystemContentBlock[] = [];\n for (const block of msg.content) {\n if (\n typeof block === 'object' &&\n block.type === 'text' &&\n typeof (block as { text?: string }).text === 'string'\n ) {\n contentBlocks.push({\n text: (block as { text: string }).text,\n });\n } else {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint == null) {\n break;\n }\n contentBlocks.push({\n cachePoint,\n } as BedrockSystemContentBlock);\n }\n }\n if (msg.content.length === contentBlocks.length) {\n return contentBlocks;\n }\n }\n throw new Error(\n 'System message content must be either a string, or an array of text blocks, optionally including a cache point.'\n );\n}\n\n/**\n * Convert an AI message to a Bedrock message.\n */\n/**\n * Bedrock Converse requires `toolUse.input` to be a JSON object document.\n * History can carry non-object values: streaming leaves the raw partial-JSON\n * string on Anthropic-shaped inline blocks, and context-pressure truncation\n * (pre-3.x `createBoundedTruncationValue`) could persist `null` onto BOTH a\n * block's inline input and its `tool_calls` args. A string is parsed when it\n * forms a complete JSON object; every other shape degrades to `{}` — the call\n * already executed, so the replayed input is informational. Twin of\n * `coerceAnthropicToolUseInput` in the Anthropic fork; duplicated so each\n * fork stays self-contained against its upstream.\n */\nfunction coerceBedrockToolUseInput(input: unknown): Record<string, unknown> {\n let candidate: unknown = input;\n if (typeof candidate === 'string') {\n try {\n candidate = JSON.parse(candidate);\n } catch {\n return {};\n }\n }\n return typeof candidate === 'object' &&\n candidate !== null &&\n !Array.isArray(candidate)\n ? (candidate as Record<string, unknown>)\n : {};\n}\n\nfunction convertAIMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n // Check for v1 format from other providers (PR #9766 fix)\n const responseMetadata = msg.response_metadata as\n | { output_version?: string }\n | undefined;\n if (responseMetadata?.output_version === 'v1') {\n return convertFromV1ToChatBedrockConverseMessage(msg);\n }\n\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: [],\n };\n\n if (typeof msg.content === 'string' && msg.content !== '') {\n assistantMsg.content?.push({ text: msg.content });\n } else if (Array.isArray(msg.content)) {\n const parsedToolCallIds = new Set(\n isAIMessage(msg)\n ? (msg.tool_calls ?? []).flatMap((toolCall) =>\n toolCall.id != null ? [toolCall.id] : []\n )\n : []\n );\n const concatenatedBlocks = concatenateLangchainReasoningBlocks(\n msg.content as Array<MessageContentComplex | MessageContentReasoningBlock>\n );\n const contentBlocks: BedrockContentBlock[] = [];\n\n concatenatedBlocks.forEach((block) => {\n if (block.type === 'text') {\n const text = (block as { text?: string }).text ?? '';\n appendSerializableBedrockTextBlock(contentBlocks, text);\n } else if (block.type === 'tool_use') {\n const toolUse = block as {\n id?: unknown;\n name?: unknown;\n input?: unknown;\n };\n if (\n typeof toolUse.id === 'string' &&\n parsedToolCallIds.has(toolUse.id)\n ) {\n return;\n }\n if (\n typeof toolUse.id !== 'string' ||\n typeof toolUse.name !== 'string'\n ) {\n throw new Error('Invalid Anthropic tool_use content block');\n }\n contentBlocks.push({\n toolUse: {\n toolUseId: toolUse.id,\n name: toolUse.name,\n input: coerceBedrockToolUseInput(toolUse.input),\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning_content') {\n const reasoningBlock = block as MessageContentReasoningBlock;\n // Bedrock Converse rejects reasoningContent whose reasoningText.text is\n // null/empty (a signature-only block that never merged with its text).\n // Drop it rather than emit an invalid request; the empty-turn\n // placeholder below covers a turn left with no content.\n if (!isSerializableBedrockReasoningBlock(reasoningBlock)) {\n return;\n }\n contentBlocks.push({\n reasoningContent:\n langchainReasoningBlockToBedrockReasoningBlock(reasoningBlock),\n } as BedrockContentBlock);\n } else {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n contentBlocks.push({\n cachePoint,\n } as BedrockContentBlock);\n } else if (FOREIGN_REASONING_TYPES.some((t) => t === block.type)) {\n // Reasoning from another provider (Anthropic `thinking`/\n // `redacted_thinking`, Google `reasoning`, LibreChat `think`).\n // Bedrock's native reasoning is `reasoning_content` (handled above); a\n // foreign block carries a signature Bedrock cannot validate, so drop\n // it on a cross-provider handoff (e.g. Anthropic → Bedrock) rather\n // than crash. The Bedrock model produces its own reasoning. Anything\n // else unknown still throws below — real content must be surfaced.\n return;\n } else if (FOREIGN_SERVER_TOOL_TYPES.some((t) => t === block.type)) {\n // Google server-side tool call/response (e.g. URL context) — only\n // Google can execute it or validate its thought signature; drop it\n // on a cross-provider handoff rather than crash.\n return;\n } else {\n const blockValues = Object.fromEntries(\n Object.entries(block).filter(([key]) => key !== 'type')\n );\n throw new Error(\n `Unsupported content block type: ${block.type} with content of ${JSON.stringify(blockValues, null, 2)}`\n );\n }\n }\n });\n\n assistantMsg.content = [...(assistantMsg.content ?? []), ...contentBlocks];\n }\n\n // Important: this must be placed after any reasoning content blocks\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n const existingToolUseIds = new Set(\n (assistantMsg.content ?? [])\n .filter((content) => 'toolUse' in content)\n .map((content) => content.toolUse?.toolUseId)\n );\n const toolUseBlocks = msg.tool_calls\n .filter((toolCall) => !existingToolUseIds.has(toolCall.id))\n .map((toolCall) => ({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.name,\n input: coerceBedrockToolUseInput(toolCall.args),\n },\n }));\n assistantMsg.content = [\n ...(assistantMsg.content ?? []),\n ...toolUseBlocks,\n ] as BedrockContentBlock[];\n }\n\n // Bedrock rejects an assistant message with no content blocks; if filtering\n // (e.g. dropping foreign reasoning) left it empty, emit a placeholder.\n if (assistantMsg.content == null || assistantMsg.content.length === 0) {\n assistantMsg.content = [{ text: BEDROCK_EMPTY_TEXT_PLACEHOLDER }];\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a v1 format message from other providers to Bedrock format.\n * This handles messages with standard content blocks like tool_call and reasoning.\n * (Implements PR #9766 fix for output_version v1 detection)\n */\nfunction convertFromV1ToChatBedrockConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const contentBlocks: BedrockContentBlock[] = [];\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: contentBlocks,\n };\n let droppedUnserializableContent = false;\n let unconvertedContentType: string | undefined;\n\n if (Array.isArray(msg.content)) {\n const concatenatedBlocks = concatenateLangchainReasoningBlocks(\n msg.content as Array<MessageContentComplex | MessageContentReasoningBlock>\n );\n for (const block of concatenatedBlocks) {\n if (typeof block === 'string') {\n if (!appendSerializableBedrockTextBlock(contentBlocks, block)) {\n droppedUnserializableContent = true;\n }\n } else if (block.type === 'text') {\n const text = (block as { text?: string }).text ?? '';\n if (!appendSerializableBedrockTextBlock(contentBlocks, text)) {\n droppedUnserializableContent = true;\n }\n } else if (block.type === 'tool_call') {\n const toolCall = block as {\n id: string;\n name: string;\n args: Record<string, unknown>;\n };\n contentBlocks.push({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.name,\n input: coerceBedrockToolUseInput(toolCall.args),\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning') {\n const reasoning = block as { reasoning?: string };\n /** Bedrock Converse rejects `reasoningText` with a null/empty `text`\n * (`Member must not be null`), e.g. when the producing model omitted\n * reasoning text (`thinking.display: \"omitted\"`) — drop rather than send. */\n if (reasoning.reasoning == null || reasoning.reasoning === '') {\n droppedUnserializableContent = true;\n continue;\n }\n contentBlocks.push({\n reasoningContent: {\n reasoningText: { text: reasoning.reasoning },\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning_content') {\n const reasoningBlock = block as MessageContentReasoningBlock;\n if (!isSerializableBedrockReasoningBlock(reasoningBlock)) {\n droppedUnserializableContent = true;\n continue;\n }\n contentBlocks.push({\n reasoningContent:\n langchainReasoningBlockToBedrockReasoningBlock(reasoningBlock),\n } as BedrockContentBlock);\n } else {\n unconvertedContentType ??= block.type;\n }\n }\n } else if (typeof msg.content === 'string') {\n if (!appendSerializableBedrockTextBlock(contentBlocks, msg.content)) {\n droppedUnserializableContent = true;\n }\n }\n\n // Also handle tool_calls from the message\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n // Check if tool calls are already in content\n const existingToolUseIds = new Set(\n contentBlocks\n .filter((c) => 'toolUse' in c)\n .map((c) => (c as { toolUse: { toolUseId: string } }).toolUse.toolUseId)\n );\n\n for (const tc of msg.tool_calls) {\n if (!existingToolUseIds.has(tc.id ?? '')) {\n contentBlocks.push({\n toolUse: {\n toolUseId: tc.id,\n name: tc.name,\n input: coerceBedrockToolUseInput(tc.args),\n },\n } as BedrockContentBlock);\n }\n }\n }\n\n const hasNoContent = contentBlocks.length === 0;\n if (hasNoContent && unconvertedContentType != null) {\n throw new Error(\n `Unsupported v1 content block type: ${unconvertedContentType}`\n );\n }\n if (hasNoContent && droppedUnserializableContent) {\n contentBlocks.push({ text: BEDROCK_EMPTY_TEXT_PLACEHOLDER });\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a human message to a Bedrock message.\n */\nfunction convertHumanMessageToConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const userMessage: BedrockMessage = {\n role: 'user',\n content: [],\n };\n\n if (typeof msg.content === 'string') {\n userMessage.content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n userMessage.content = msg.content.map((block) =>\n convertLangChainContentBlockToConverseContentBlock({ block })\n );\n }\n\n return userMessage;\n}\n\n/**\n * Convert a tool message to a Bedrock message.\n */\nfunction convertToolMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n const toolCallId = (msg as { tool_call_id?: string }).tool_call_id;\n let isError = (msg as ToolMessage).status === 'error';\n\n let content: BedrockContentBlock[];\n if (typeof msg.content === 'string') {\n content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n content = msg.content.flatMap((block) => {\n if (typeof block === 'object' && block.type === 'tool_result') {\n if ((block as { is_error?: unknown }).is_error === true) {\n isError = true;\n }\n const toolResultContent = (block as { content?: unknown }).content;\n if (typeof toolResultContent === 'string') {\n return [{ text: toolResultContent }];\n }\n if (Array.isArray(toolResultContent)) {\n return toolResultContent.map((nestedBlock) =>\n convertLangChainContentBlockToConverseContentBlock({\n block: nestedBlock,\n onUnknown: 'passthrough',\n })\n );\n }\n return [\n {\n text: serializeStructuredValueBounded(\n toolResultContent,\n HARD_MAX_TOOL_RESULT_CHARS\n ).content,\n },\n ];\n }\n return [\n convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown: 'passthrough',\n }),\n ];\n });\n } else {\n content = [{ text: String(msg.content) }];\n }\n\n // A `cachePoint` is a message-level ContentBlock — it is NOT a valid\n // ToolResultContentBlock. A tail prompt-cache breakpoint that anchors on a\n // tool result therefore ends up nested inside `toolResult.content`, which\n // Bedrock silently ignores (no cache write, no cache read). Hoist any\n // cachePoint(s) out of the tool result body so they sit as siblings after\n // it, which is the only position Bedrock honors.\n const toolResultContent: BedrockContentBlock[] = [];\n const trailingCachePoints: BedrockContentBlock[] = [];\n for (const block of content) {\n const cachePoint = getDefaultCachePoint(block);\n if (cachePoint != null) {\n trailingCachePoints.push({\n cachePoint,\n } as BedrockContentBlock);\n } else {\n toolResultContent.push(block);\n }\n }\n\n return {\n role: 'user',\n content: [\n {\n toolResult: {\n toolUseId: toolCallId,\n content: toolResultContent as { text: string }[],\n ...(isError ? { status: 'error' as const } : {}),\n },\n },\n ...trailingCachePoints,\n ],\n };\n}\n\n/**\n * Convert LangChain messages to Bedrock Converse messages.\n */\nexport function convertToConverseMessages(messages: BaseMessage[]): {\n converseMessages: BedrockMessage[];\n converseSystem: BedrockSystemContentBlock[];\n} {\n const converseSystem = messages\n .filter((msg) => msg._getType() === 'system')\n .flatMap((msg) => convertSystemMessageToConverseMessage(msg));\n\n const converseMessages = messages\n .filter((msg) => msg._getType() !== 'system')\n .map((msg) => {\n if (msg._getType() === 'ai') {\n return convertAIMessageToConverseMessage(msg);\n } else if (msg._getType() === 'human' || msg._getType() === 'generic') {\n return convertHumanMessageToConverseMessage(msg);\n } else if (msg._getType() === 'tool') {\n return convertToolMessageToConverseMessage(msg);\n } else {\n throw new Error(`Unsupported message type: ${msg._getType()}`);\n }\n });\n\n /**\n * Combine ALL consecutive user messages into one, not just tool-result\n * pairs. The Converse API documents strict role alternation; enforcement\n * varies by model family (Claude on Converse currently tolerates adjacent\n * user messages — verified live, 2026-07-28 — but the docs promise nothing\n * for the others), so the converter never emits the shape. The case that\n * matters: a `PostToolBatch`/`PreemptBoundary` hook injection lands a text\n * turn directly after tool results, and `ToolMessage` and `HumanMessage`\n * both convert to `role: 'user'` above. Block order is preserved\n * (toolResult blocks, then text) — verified live that Converse accepts the\n * mixed user message and answers both halves — and the toolUse/toolResult\n * pairing stays intact.\n */\n const combinedConverseMessages = converseMessages.reduce<BedrockMessage[]>(\n (acc, curr) => {\n if (acc.length === 0) {\n acc.push(curr);\n return acc;\n }\n const lastMessage = acc[acc.length - 1];\n if (lastMessage.role === 'user' && curr.role === 'user') {\n lastMessage.content = lastMessage.content?.concat(curr.content ?? []);\n } else {\n acc.push(curr);\n }\n return acc;\n },\n []\n );\n\n return { converseMessages: combinedConverseMessages, converseSystem };\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,4BAA4B,CAAC,YAAY,cAAc;;;;;;AAO7D,MAAM,iCAAiC;;;;AAKvC,SAAgB,+CACd,SAIA;CACA,IAAI,QAAQ,iBAAiB,MAC3B,OAAO,EACL,eAAe,QAAQ,cACzB;CAEF,IAAI,QAAQ,mBAAmB,QAAQ,QAAQ,oBAAoB,IACjE,OAAO,EACL,iBAAiB,IAAI,WACnB,OAAO,KAAK,QAAQ,iBAAiB,QAAQ,CAC/C,EACF;CAEF,MAAM,IAAI,MAAM,2BAA2B;AAC7C;;;;;;;AAQA,SAAS,oC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AAoB,KAAK,EACvB,WACF,CAAwB;OAExB,kBAAkB,KAAK,KAAK;CAEhC;CAEA,OAAO;EACL,MAAM;EACN,SAAS,CACP,EACE,YAAY;GACV,WAAW;GACX,SAAS;GACT,GAAI,UAAU,EAAE,QAAQ,QAAiB,IAAI,CAAC;EAChD,EACF,GACA,GAAG,mBACL;CACF;AACF;;;;AAKA,SAAgB,0BAA0B,UAGxC;CACA,MAAM,iBAAiB,SACpB,QAAQ,QAAQ,IAAI,SAAS,MAAM,QAAQ,CAAC,CAC5C,SAAS,QAAQ,sCAAsC,GAAG,CAAC;CA8C9D,OAAO;EAAE,kBA5CgB,SACtB,QAAQ,QAAQ,IAAI,SAAS,MAAM,QAAQ,CAAC,CAC5C,KAAK,QAAQ;GACZ,IAAI,IAAI,SAAS,MAAM,MACrB,OAAO,kCAAkC,GAAG;QACvC,IAAI,IAAI,SAAS,MAAM,WAAW,IAAI,SAAS,MAAM,WAC1D,OAAO,qCAAqC,GAAG;QAC1C,IAAI,IAAI,SAAS,MAAM,QAC5B,OAAO,oCAAoC,GAAG;QAE9C,MAAM,IAAI,MAAM,6BAA6B,IAAI,SAAS,GAAG;EAEjE,CAe8C,CAAC,CAAC,QAC/C,KAAK,SAAS;GACb,IAAI,IAAI,WAAW,GAAG;IACpB,IAAI,KAAK,IAAI;IACb,OAAO;GACT;GACA,MAAM,cAAc,IAAI,IAAI,SAAS;GACrC,IAAI,YAAY,SAAS,UAAU,KAAK,SAAS,QAC/C,YAAY,UAAU,YAAY,SAAS,OAAO,KAAK,WAAW,CAAC,CAAC;QAEpE,IAAI,KAAK,IAAI;GAEf,OAAO;EACT,GACA,CAAC,CAG+C;EAAG;CAAe;AACtE"}
@@ -1,9 +1,9 @@
1
1
  require("../common/enum.cjs");
2
2
  require("../common/index.cjs");
3
+ const require_index$1 = require("./openai/index.cjs");
4
+ const require_providers = require("./providers.cjs");
3
5
  const require_llm = require("../utils/llm.cjs");
4
6
  require("../utils/index.cjs");
5
- const require_index$2 = require("./openai/index.cjs");
6
- const require_providers = require("./providers.cjs");
7
7
  let _langchain_google_vertexai = require("@langchain/google-vertexai");
8
8
  //#region src/llm/init.ts
9
9
  /**
@@ -17,7 +17,7 @@ let _langchain_google_vertexai = require("@langchain/google-vertexai");
17
17
  */
18
18
  function initializeModel({ provider, clientOptions, tools, override }) {
19
19
  const model = override ?? new (require_providers.getChatModelClass(provider))(clientOptions ?? {});
20
- if (require_llm.isOpenAILike(provider) && (model instanceof require_index$2.ChatOpenAI || model instanceof require_index$2.AzureChatOpenAI)) {
20
+ if (require_llm.isOpenAILike(provider) && (model instanceof require_index$1.ChatOpenAI || model instanceof require_index$1.AzureChatOpenAI)) {
21
21
  const opts = clientOptions;
22
22
  if (opts) {
23
23
  model.temperature = opts.temperature;
@@ -1,19 +1,19 @@
1
- const require_callbacks = require("../utils/callbacks.cjs");
2
1
  require("../common/enum.cjs");
3
2
  require("../common/index.cjs");
4
- const require_preempt = require("./preempt.cjs");
3
+ const require_callbacks = require("../utils/callbacks.cjs");
5
4
  const require_cache = require("../messages/cache.cjs");
6
5
  const require_core = require("../messages/core.cjs");
7
6
  const require_events = require("../utils/events.cjs");
8
7
  const require_alternation = require("../messages/alternation.cjs");
9
8
  const require_handoffCue = require("../messages/handoffCue.cjs");
10
9
  require("../messages/index.cjs");
11
- const require_llm = require("../utils/llm.cjs");
12
10
  const require_toolOutputReferences = require("../tools/toolOutputReferences.cjs");
13
- const require_stream = require("../stream.cjs");
14
- const require_errors = require("../utils/errors.cjs");
15
11
  const require_truncation = require("./truncation.cjs");
16
12
  const require_providers = require("./providers.cjs");
13
+ const require_errors = require("../utils/errors.cjs");
14
+ const require_preempt = require("./preempt.cjs");
15
+ const require_llm = require("../utils/llm.cjs");
16
+ const require_stream = require("../stream.cjs");
17
17
  const require_init = require("./init.cjs");
18
18
  let _langchain_core_runnables = require("@langchain/core/runnables");
19
19
  let _langchain_core_messages = require("@langchain/core/messages");
@@ -1,7 +1,7 @@
1
1
  const require_cache = require("../../messages/cache.cjs");
2
2
  const require_core = require("../../messages/core.cjs");
3
- const require_streamedToolCallSeals = require("../../tools/streamedToolCallSeals.cjs");
4
3
  const require_intentArg = require("../../tools/intentArg.cjs");
4
+ const require_streamedToolCallSeals = require("../../tools/streamedToolCallSeals.cjs");
5
5
  const require_index = require("./utils/index.cjs");
6
6
  const require_streamMetadata = require("./streamMetadata.cjs");
7
7
  let _langchain_openai = require("@langchain/openai");
package/dist/cjs/main.cjs CHANGED
@@ -5,7 +5,6 @@ const require_enum = require("./common/enum.cjs");
5
5
  require("./common/index.cjs");
6
6
  const require_truncation = require("./utils/truncation.cjs");
7
7
  const require_tokens = require("./utils/tokens.cjs");
8
- const require_preempt = require("./llm/preempt.cjs");
9
8
  const require_cache = require("./messages/cache.cjs");
10
9
  const require_core = require("./messages/core.cjs");
11
10
  const require_ids = require("./messages/ids.cjs");
@@ -23,20 +22,21 @@ const require_handoffCue = require("./messages/handoffCue.cjs");
23
22
  const require_reducer = require("./messages/reducer.cjs");
24
23
  const require_recency = require("./messages/recency.cjs");
25
24
  require("./messages/index.cjs");
26
- const require_graph = require("./utils/graph.cjs");
27
- const require_llm = require("./utils/llm.cjs");
28
- const require_handlers = require("./tools/handlers.cjs");
29
25
  const require_intentArg = require("./tools/intentArg.cjs");
26
+ const require_index$2 = require("./llm/openai/index.cjs");
27
+ const require_index$3 = require("./llm/openrouter/index.cjs");
28
+ const require_providers = require("./llm/providers.cjs");
29
+ const require_errors = require("./utils/errors.cjs");
30
+ const require_preempt = require("./llm/preempt.cjs");
31
+ const require_handlers = require("./tools/handlers.cjs");
32
+ const require_llm = require("./utils/llm.cjs");
30
33
  const require_stream = require("./stream.cjs");
34
+ const require_graph = require("./utils/graph.cjs");
31
35
  const require_events = require("./events.cjs");
32
36
  const require_handlers$1 = require("./utils/handlers.cjs");
33
37
  const require_run = require("./utils/run.cjs");
34
38
  const require_schema = require("./utils/schema.cjs");
35
- const require_errors = require("./utils/errors.cjs");
36
39
  require("./utils/index.cjs");
37
- const require_index$3 = require("./llm/openai/index.cjs");
38
- const require_index$4 = require("./llm/openrouter/index.cjs");
39
- const require_providers = require("./llm/providers.cjs");
40
40
  const require_init = require("./llm/init.cjs");
41
41
  const require_invoke = require("./llm/invoke.cjs");
42
42
  const require_bashAst = require("./tools/local/bashAst.cjs");
@@ -163,7 +163,7 @@ exports.CalculatorToolDescription = require_Calculator.CalculatorToolDescription
163
163
  exports.CalculatorToolName = require_Calculator.CalculatorToolName;
164
164
  exports.Callback = require_enum.Callback;
165
165
  exports.ChatModelStreamHandler = require_stream.ChatModelStreamHandler;
166
- exports.ChatOpenRouter = require_index$4.ChatOpenRouter;
166
+ exports.ChatOpenRouter = require_index$3.ChatOpenRouter;
167
167
  exports.CloudflareBashExecutionToolDescription = require_CloudflareSandboxTools.CloudflareBashExecutionToolDescription;
168
168
  exports.CloudflareCodeExecutionToolDescription = require_CloudflareSandboxTools.CloudflareCodeExecutionToolDescription;
169
169
  exports.CodeApiRequestError = require_CodeExecutor.CodeApiRequestError;
@@ -181,7 +181,7 @@ exports.CommonEvents = require_enum.CommonEvents;
181
181
  exports.CompileCheckToolName = require_CompileCheckTool.CompileCheckToolName;
182
182
  exports.Constants = require_enum.Constants;
183
183
  exports.ContentTypes = require_enum.ContentTypes;
184
- exports.CustomOpenAIClient = require_index$3.CustomOpenAIClient;
184
+ exports.CustomOpenAIClient = require_index$2.CustomOpenAIClient;
185
185
  exports.DATE_RANGE = require_schema$2.DATE_RANGE;
186
186
  exports.DEFAULT_CONTEXT_PRUNING_SETTINGS = require_contextPruningSettings.DEFAULT_CONTEXT_PRUNING_SETTINGS;
187
187
  exports.DEFAULT_COUNTRY_DESCRIPTION = require_schema$2.DEFAULT_COUNTRY_DESCRIPTION;
@@ -564,10 +564,23 @@ function extractToolNamesFromSearchOutput(output) {
564
564
  }
565
565
  return [];
566
566
  }
567
- function getLatestSummaryBoundary(payload) {
568
- let summaryBoundary;
567
+ function resolveCoverageIndex(coverage, indexBySourceId, summaryMessageIndex) {
568
+ /** Persisted JSON, so the declared string type is not a runtime guarantee. */
569
+ if (typeof coverage?.retainedFromMessageId !== "string") return;
570
+ const retainedFromMessageId = coverage.retainedFromMessageId.trim();
571
+ if (retainedFromMessageId === "") return;
572
+ const retainedIndex = indexBySourceId.get(retainedFromMessageId);
573
+ return retainedIndex != null && retainedIndex <= summaryMessageIndex ? retainedIndex : void 0;
574
+ }
575
+ function scanSummaryBlocks(payload) {
576
+ let boundary;
577
+ /** Filled as the scan advances, so a coverage lookup only ever resolves to a
578
+ * message already passed — no second pass over the payload. */
579
+ const indexBySourceId = /* @__PURE__ */ new Map();
569
580
  for (let i = 0; i < payload.length; i++) {
570
581
  const message = payload[i];
582
+ const sourceMessageId = getSourceMessageId(message);
583
+ if (sourceMessageId != null) indexBySourceId.set(sourceMessageId, i);
571
584
  if (!Array.isArray(message.content)) continue;
572
585
  for (let j = 0; j < message.content.length; j++) {
573
586
  const part = message.content[j];
@@ -576,18 +589,31 @@ function getLatestSummaryBoundary(payload) {
576
589
  let summaryText = (summaryPart.content ?? []).map((block) => "text" in block ? block.text : "").join("").trim();
577
590
  if (summaryText.length === 0 && typeof summaryPart.text === "string") summaryText = summaryPart.text.trim();
578
591
  if (summaryText.length === 0) continue;
579
- summaryBoundary = {
592
+ const tokenCount = typeof summaryPart.tokenCount === "number" && Number.isFinite(summaryPart.tokenCount) ? summaryPart.tokenCount : 0;
593
+ const retainedIndex = resolveCoverageIndex(summaryPart.coverage, indexBySourceId, i);
594
+ boundary = retainedIndex != null ? {
595
+ mode: "coverage",
596
+ messageIndex: retainedIndex,
597
+ text: summaryText,
598
+ tokenCount
599
+ } : {
600
+ mode: "positional",
580
601
  messageIndex: i,
581
602
  contentIndex: j,
582
603
  text: summaryText,
583
- tokenCount: typeof summaryPart.tokenCount === "number" && Number.isFinite(summaryPart.tokenCount) ? summaryPart.tokenCount : 0
604
+ tokenCount
584
605
  };
585
606
  }
586
607
  }
587
- return summaryBoundary;
608
+ return { boundary };
588
609
  }
589
610
  function applySummaryBoundary(message, messageIndex, summaryBoundary) {
590
611
  if (!summaryBoundary) return message;
612
+ /** The boundary names the first retained message, so it is exclusive: that
613
+ * message and everything after it — the recency tail included — stays
614
+ * verbatim, and only genuinely covered history is dropped. Summary parts on
615
+ * surviving messages are filtered later by `formatAssistantMessage`. */
616
+ if (summaryBoundary.mode === "coverage") return messageIndex < summaryBoundary.messageIndex ? null : message;
591
617
  if (messageIndex < summaryBoundary.messageIndex) return null;
592
618
  if (messageIndex !== summaryBoundary.messageIndex || !Array.isArray(message.content)) return message;
593
619
  return {
@@ -595,16 +621,53 @@ function applySummaryBoundary(message, messageIndex, summaryBoundary) {
595
621
  content: message.content.slice(summaryBoundary.contentIndex + 1)
596
622
  };
597
623
  }
624
+ /**
625
+ * Whether `formatAssistantMessage` filters this part out of the emitted message.
626
+ * Such a part contributes no prompt tokens, so measuring it as zero characters
627
+ * is accurate — it must not be mistaken for content the heuristic cannot see.
628
+ */
629
+ function isDroppedByFormatting(part) {
630
+ if (part == null) return true;
631
+ if (part.type === "summary" || part.type === "error" || part.type === "agent_update" || part.type === "activity_label") return true;
632
+ return part.type === "text" && getTextContent(part).trim() === "";
633
+ }
634
+ function measureValueChars(value) {
635
+ if (typeof value === "string") return value.length;
636
+ if (value == null || typeof value !== "object") return 0;
637
+ const measured = require_toolContent.serializeStructuredValueBounded(value, 0).originalChars;
638
+ return measured === Number.MAX_SAFE_INTEGER ? require_truncation.HARD_MAX_TOOL_RESULT_CHARS : Math.min(measured, require_truncation.HARD_MAX_TOOL_RESULT_CHARS);
639
+ }
640
+ /**
641
+ * Whether a retained part's whole prompt cost is the text the char heuristic
642
+ * reads, making it safe to represent in a character ratio.
643
+ *
644
+ * An allowlist, not a denylist. Media, resources, and tool calls carry cost that
645
+ * is unrelated to their serialized length — a short image URL nested in
646
+ * `tool_call.output` stands in for a fixed four-figure media charge — and
647
+ * rejecting those case by case has repeatedly missed a nesting level. Listing
648
+ * the two shapes whose characters `contentPartCharLength` actually reads makes
649
+ * every other shape, present or future, ineligible by default: the ratio is
650
+ * skipped and the entry keeps its original count, which prunes early rather than
651
+ * exceeding the window.
652
+ */
653
+ function isCharRatioEligible(part) {
654
+ if (part == null) return false;
655
+ return part.type === "text" || part.type === "thinking";
656
+ }
598
657
  function contentPartCharLength(part) {
599
658
  const record = part;
600
659
  let len = 0;
601
660
  if (typeof record.text === "string") len += record.text.length;
602
661
  if (typeof record.thinking === "string") len += record.thinking.length;
603
- const { input } = record;
604
- if (typeof input === "string") len += input.length;
605
- else if (input != null && typeof input === "object") {
606
- const measured = require_toolContent.serializeStructuredValueBounded(input, 0).originalChars;
607
- len += measured === Number.MAX_SAFE_INTEGER ? require_truncation.HARD_MAX_TOOL_RESULT_CHARS : Math.min(measured, require_truncation.HARD_MAX_TOOL_RESULT_CHARS);
662
+ len += measureValueChars(record.input);
663
+ /** Tool calls nest their payload a level down, so measuring only the
664
+ * top-level fields scores an entire tool turn as zero characters. */
665
+ const { tool_call: toolCall } = record;
666
+ if (toolCall != null && typeof toolCall === "object") {
667
+ const call = toolCall;
668
+ len += measureValueChars(call.name);
669
+ len += measureValueChars(call.args);
670
+ len += measureValueChars(call.output);
608
671
  }
609
672
  return len;
610
673
  }
@@ -654,7 +717,7 @@ const formatAgentMessages = (payload, indexTokenCountMap, tools, skills, options
654
717
  const updatedIndexTokenCountMap = {};
655
718
  let boundaryTokenAdjustment;
656
719
  const indexMapping = {};
657
- const summaryBoundary = getLatestSummaryBoundary(payload);
720
+ const { boundary: summaryBoundary } = scanSummaryBlocks(payload);
658
721
  /**
659
722
  * Create a mutable copy of the tools set that can be expanded dynamically.
660
723
  * When we encounter tool_search results, we add discovered tools to this set,
@@ -853,18 +916,64 @@ const formatAgentMessages = (payload, indexTokenCountMap, tools, skills, options
853
916
  const resultIndices = indexMapping[originalIndex] || [];
854
917
  let tokenCount = indexTokenCountMap[originalIndex];
855
918
  if (tokenCount === void 0) continue;
856
- if (summaryBoundary && originalIndex === summaryBoundary.messageIndex && Array.isArray(payload[originalIndex].content)) {
919
+ /**
920
+ * Coverage mode deliberately leaves the count alone, even though the entry
921
+ * holding the block is charged for summary text that `formatAssistantMessage`
922
+ * filters out and `summary.tokenCount` accounts separately.
923
+ *
924
+ * Discounting it needs the summary's cost in the same units as
925
+ * `indexTokenCountMap`, and that figure is not obtainable here: this
926
+ * function receives no tokenizer, and a count recorded at write time is in
927
+ * the writing run's units — `Run.create` derives its counter from the model
928
+ * in play, and a consumer may supply its own — so a conversation continued
929
+ * on a different model would subtract across encodings. Attempts to proxy
930
+ * it (character ratios, provider identity) all under-count some shape,
931
+ * which risks an over-context request; over-counting merely prunes early.
932
+ * Fixing it properly means passing the reader a tokenizer, which is a
933
+ * consumer-facing change and out of scope here.
934
+ */
935
+ if (summaryBoundary?.mode === "positional" && originalIndex === summaryBoundary.messageIndex && Array.isArray(payload[originalIndex].content)) {
857
936
  const content = payload[originalIndex].content;
858
937
  const { contentIndex } = summaryBoundary;
859
938
  if (contentIndex >= 0 && contentIndex < content.length - 1) {
860
939
  let totalCharLen = 0;
861
940
  let remainingCharLen = 0;
941
+ /**
942
+ * The ratio applies only when *every* part of the entry is one whose
943
+ * token cost tracks its character length. A single ineligible part
944
+ * cancels the discount, whichever side of the boundary it sits on.
945
+ *
946
+ * Both sides can break it, in opposite directions. A retained image has
947
+ * its fixed cost scaled away, collapsing the entry. A removed base64
948
+ * payload inflates the denominator — serializing to a huge length while
949
+ * the counter charges a fixed estimate — dragging retained text below
950
+ * its real cost. Either way the request can exceed the window.
951
+ *
952
+ * Telling a text-bearing tool payload from a media-bearing one means
953
+ * recursing into arbitrary nested output, which has already missed a
954
+ * level twice here. Cancelling instead keeps the original count: an
955
+ * over-count that prunes early rather than overflowing. Entries of
956
+ * plain text and reasoning — the common shape — still proportion.
957
+ */
958
+ let everyRetainedPartMeasurable = true;
862
959
  for (let p = 0; p < content.length; p++) {
863
- const charLen = contentPartCharLength(content[p]);
960
+ const part = content[p];
961
+ const retained = p > contentIndex;
962
+ if (isDroppedByFormatting(part)) {
963
+ /** Removed summary text is real removed content: it is read as
964
+ * plain text and belongs in the denominator. */
965
+ if (!retained && part.type === "summary") totalCharLen += contentPartCharLength(part);
966
+ continue;
967
+ }
968
+ const charLen = contentPartCharLength(part);
969
+ if (!isCharRatioEligible(part) || retained && charLen === 0) {
970
+ everyRetainedPartMeasurable = false;
971
+ break;
972
+ }
864
973
  totalCharLen += charLen;
865
- if (p > contentIndex) remainingCharLen += charLen;
974
+ if (retained) remainingCharLen += charLen;
866
975
  }
867
- if (totalCharLen > 0) {
976
+ if (totalCharLen > 0 && everyRetainedPartMeasurable) {
868
977
  const original = tokenCount;
869
978
  tokenCount = Math.max(1, Math.round(tokenCount * (remainingCharLen / totalCharLen)));
870
979
  boundaryTokenAdjustment = {