@librechat/agents 3.3.2 → 3.3.4
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.
- package/dist/cjs/agents/AgentContext.cjs +2 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +342 -109
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +6 -0
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -6
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +37 -10
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +19 -7
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +64 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +41 -5
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +25 -4
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +4 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +19 -2
- package/dist/cjs/messages/cache.cjs +54 -33
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/contextPruning.cjs +17 -43
- package/dist/cjs/messages/contextPruning.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +315 -23
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +218 -60
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/index.cjs +1 -1
- package/dist/cjs/messages/prune.cjs +503 -127
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/stream.cjs +7 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +28 -14
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +54 -41
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/toolOutputReferences.cjs +6 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/llm.cjs +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +307 -20
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/cjs/utils/toolContent.cjs +1514 -0
- package/dist/cjs/utils/toolContent.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +2 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +349 -116
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +3 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +6 -0
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -6
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +37 -10
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +19 -7
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +65 -5
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +41 -5
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +25 -4
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +4 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +7 -7
- package/dist/esm/messages/cache.mjs +55 -34
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/contextPruning.mjs +17 -43
- package/dist/esm/messages/contextPruning.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +305 -24
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +218 -61
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/index.mjs +1 -1
- package/dist/esm/messages/prune.mjs +500 -128
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/stream.mjs +7 -3
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +28 -14
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +54 -41
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/toolOutputReferences.mjs +6 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/llm.mjs +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +307 -21
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/esm/utils/toolContent.mjs +1503 -0
- package/dist/esm/utils/toolContent.mjs.map +1 -0
- package/dist/types/graphs/Graph.d.ts +1 -1
- package/dist/types/llm/invoke.d.ts +27 -1
- package/dist/types/llm/openai/index.d.ts +4 -0
- package/dist/types/llm/openai/utils/index.d.ts +2 -0
- package/dist/types/llm/openrouter/index.d.ts +5 -0
- package/dist/types/messages/contextPruning.d.ts +2 -1
- package/dist/types/messages/core.d.ts +36 -0
- package/dist/types/messages/format.d.ts +6 -0
- package/dist/types/messages/prune.d.ts +16 -12
- package/dist/types/types/stream.d.ts +1 -1
- package/dist/types/utils/tokens.d.ts +7 -0
- package/dist/types/utils/toolContent.d.ts +107 -0
- package/package.json +13 -9
- package/src/__tests__/stream.eagerEventExecution.test.ts +74 -0
- package/src/agents/AgentContext.ts +1 -0
- package/src/graphs/Graph.ts +698 -200
- package/src/graphs/MultiAgentGraph.ts +6 -1
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +1128 -4
- package/src/langfuse.ts +15 -0
- package/src/llm/anthropic/utils/message_inputs.ts +158 -12
- package/src/llm/anthropic/utils/tool-id-normalization.test.ts +109 -0
- package/src/llm/bedrock/utils/message_inputs.test.ts +49 -1
- package/src/llm/bedrock/utils/message_inputs.ts +86 -13
- package/src/llm/google/utils/common.test.ts +75 -9
- package/src/llm/google/utils/common.ts +34 -3
- package/src/llm/invoke.test.ts +488 -0
- package/src/llm/invoke.ts +196 -2
- package/src/llm/openai/index.ts +106 -6
- package/src/llm/openai/utils/index.ts +109 -53
- package/src/llm/openai/utils/messages.test.ts +330 -1
- package/src/llm/openrouter/index.ts +12 -2
- package/src/llm/openrouter/reasoning.test.ts +314 -0
- package/src/messages/__tests__/observationMasking.test.ts +93 -2
- package/src/messages/cache.tail.test.ts +193 -0
- package/src/messages/cache.test.ts +113 -0
- package/src/messages/cache.ts +92 -60
- package/src/messages/contextPruning.test.ts +184 -0
- package/src/messages/contextPruning.ts +49 -42
- package/src/messages/core.ts +653 -40
- package/src/messages/ensureThinkingBlock.test.ts +49 -1
- package/src/messages/foldToollessToolBlocks.test.ts +163 -5
- package/src/messages/format.ts +363 -91
- package/src/messages/formatAgentMessages.test.ts +604 -14
- package/src/messages/formatAgentMessages.tools.test.ts +103 -0
- package/src/messages/prune.ts +996 -183
- package/src/specs/langfuse-callbacks.test.ts +203 -1
- package/src/specs/prune.test.ts +1083 -6
- package/src/specs/summarization-unit.test.ts +105 -0
- package/src/specs/tokens.test.ts +609 -32
- package/src/stream.ts +23 -15
- package/src/summarization/__tests__/node.test.ts +77 -0
- package/src/summarization/node.ts +46 -18
- package/src/tools/ToolNode.ts +147 -68
- package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +148 -1
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +112 -3
- package/src/tools/__tests__/annotateMessagesForLLM.test.ts +32 -0
- package/src/tools/__tests__/directToolHooks.test.ts +255 -7
- package/src/tools/toolOutputReferences.ts +6 -0
- package/src/types/stream.ts +1 -1
- package/src/utils/llm.test.ts +18 -0
- package/src/utils/llm.ts +4 -1
- package/src/utils/tokens.ts +586 -31
- package/src/utils/toolContent.test.ts +1432 -0
- package/src/utils/toolContent.ts +2707 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.cjs","names":["HumanMessage","toLangChainMessageFields","AIMessage","SystemMessage","toLangChainContent","normalizeAnthropicToolCallId","ToolMessage","AIMessageChunk"],"sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type {\n MessageContent,\n MessageContentImageUrl,\n} from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n BedrockReasoningContentText,\n ExtendedMessageContent,\n GoogleReasoningContentText,\n MessageContentComplex,\n ReasoningContentText,\n SummaryContentBlock,\n ThinkingContentText,\n ToolCallContent,\n ToolResultContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { normalizeAnthropicToolCallId } from '@/llm/anthropic/utils/message_inputs';\nimport { toLangChainContent, toLangChainMessageFields } from './langchain';\nimport { Providers, ContentTypes, Constants } from '@/common';\nimport { emitAgentLog } from '@/utils/events';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\nexport type LangChainMessageRole = 'system' | 'user' | 'assistant' | 'tool';\n\nexport type RoleBearingMessage<T extends BaseMessage = BaseMessage> = T & {\n role: LangChainMessageRole;\n};\n\nexport function withMessageRole<T extends BaseMessage>(\n message: T,\n role: LangChainMessageRole\n): RoleBearingMessage<T> {\n const roleMessage = message as T & { role?: LangChainMessageRole };\n if (roleMessage.role === role) {\n return roleMessage as RoleBearingMessage<T>;\n }\n Object.defineProperty(roleMessage, 'role', {\n value: role,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n return roleMessage as RoleBearingMessage<T>;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage> => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return withMessageRole(\n new HumanMessage(toLangChainMessageFields(mediaMessage)),\n 'user'\n );\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return withMessageRole(\n new HumanMessage(toLangChainMessageFields(formattedMessage)),\n 'user'\n );\n } else if (role === 'assistant') {\n return withMessageRole(\n new AIMessage(toLangChainMessageFields(formattedMessage)),\n 'assistant'\n );\n } else {\n return withMessageRole(\n new SystemMessage(toLangChainMessageFields(formattedMessage)),\n 'system'\n );\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\ninterface FormatAssistantMessageOptions {\n preserveUnpairedServerToolUses?: boolean;\n preserveReasoningContent?: boolean;\n provider?: Providers;\n}\n\ninterface FormatAgentMessagesOptions {\n provider?: Providers;\n /** Reconstruct hidden `reasoning_content` from `THINK` parts onto prior\n * tool-call messages. Explicit opt-in for OpenAI-compatible endpoints that\n * replay reasoning across turns; defaults to on for DeepSeek thinking-mode. */\n preserveReasoningContent?: boolean;\n /** Skill names already primed fresh this turn (manual/always-apply). Their\n * historical `skill` tool_calls are not reconstructed into a HumanMessage,\n * so the same SKILL.md body is not injected twice in one request. */\n skipSkillBodyNames?: Set<string>;\n}\n\nfunction extractReasoningContent(\n part: MessageContentComplex | undefined | null\n): string {\n if (part == null || typeof part !== 'object') {\n return '';\n }\n if (part.type === ContentTypes.THINK) {\n const think = (part as ReasoningContentText).think;\n return typeof think === 'string' ? think : '';\n }\n if (part.type === ContentTypes.THINKING) {\n const thinking = (part as ThinkingContentText).thinking;\n return typeof thinking === 'string' ? thinking : '';\n }\n if (part.type === ContentTypes.REASONING) {\n const reasoning = (part as GoogleReasoningContentText).reasoning;\n return typeof reasoning === 'string' ? reasoning : '';\n }\n if (part.type === ContentTypes.REASONING_CONTENT) {\n const reasoningText = (part as BedrockReasoningContentText).reasoningText;\n return typeof reasoningText.text === 'string' ? reasoningText.text : '';\n }\n return '';\n}\n\ntype ServerToolInput = Exclude<NonNullable<ToolCallPart['args']>, string>;\n\nfunction parseServerToolInput(args: ToolCallPart['args']): ServerToolInput {\n if (typeof args === 'string') {\n try {\n const parsed = JSON.parse(args) as unknown;\n return parsed != null &&\n typeof parsed === 'object' &&\n !Array.isArray(parsed)\n ? (parsed as ServerToolInput)\n : {};\n } catch {\n return {};\n }\n }\n return args != null && typeof args === 'object' ? args : {};\n}\n\nfunction getTextContent(part: MessageContentComplex): string {\n const { text } = part as { text?: unknown };\n return typeof text === 'string' ? text : '';\n}\n\nfunction hasMeaningfulAssistantContent(part: MessageContentComplex): boolean {\n if (part.type === ContentTypes.TEXT) {\n return getTextContent(part).trim().length > 0;\n }\n if (\n part.type === ContentTypes.TOOL_CALL ||\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY ||\n part.type === ContentTypes.ACTIVITY_LABEL\n ) {\n return false;\n }\n if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n return extractReasoningContent(part).trim().length > 0;\n }\n return part.type != null && part.type !== '';\n}\n\nfunction getToolUseId(part: MessageContentComplex): string | undefined {\n if (!('tool_use_id' in part) || typeof part.tool_use_id !== 'string') {\n return undefined;\n }\n return part.tool_use_id;\n}\n\nfunction isValidServerToolResult(part: MessageContentComplex): boolean {\n const toolUseId = getToolUseId(part);\n if (\n toolUseId?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) !== true ||\n !('content' in part)\n ) {\n return false;\n }\n const { content } = part as { content?: unknown };\n return (\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as { type?: unknown }).type === 'web_search_tool_result_error')\n );\n}\n\nfunction getToolCallId(part: MessageContentComplex): string | undefined {\n if (part.type !== ContentTypes.TOOL_CALL) {\n return undefined;\n }\n const id = part.tool_call?.id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\nfunction hasToolCallOutput(part: MessageContentComplex): boolean {\n if (part.type !== ContentTypes.TOOL_CALL) {\n return false;\n }\n const output = part.tool_call?.output;\n return output != null && output !== '';\n}\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @param options Optional formatting options\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>,\n options?: FormatAssistantMessageOptions\n): Array<\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<ToolMessage>\n | RoleBearingMessage<HumanMessage>\n> {\n const formattedMessages: Array<\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<ToolMessage>\n | RoleBearingMessage<HumanMessage>\n > = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: RoleBearingMessage<AIMessage> | null = null;\n let hasReasoning = false;\n let pendingReasoningContent = '';\n const emittedServerToolUseIds = new Set<string>();\n const pendingServerToolUses = new Map<string, MessageContentComplex>();\n const shouldPreserveReasoningContent =\n options?.preserveReasoningContent === true;\n const serverToolResultIds = new Set<string>();\n const preferredToolCallParts = new Map<string, MessageContentComplex>();\n\n const takePendingReasoningContent = (): string | undefined => {\n if (!shouldPreserveReasoningContent || !pendingReasoningContent) {\n return undefined;\n }\n const reasoningContent = pendingReasoningContent;\n pendingReasoningContent = '';\n return reasoningContent;\n };\n\n const createAIMessage = (\n content: MessageContent\n ): RoleBearingMessage<AIMessage> => {\n const reasoningContent = takePendingReasoningContent();\n return withMessageRole(\n new AIMessage({\n content,\n ...(reasoningContent != null && {\n additional_kwargs: { reasoning_content: reasoningContent },\n }),\n }),\n 'assistant'\n );\n };\n\n const attachPendingReasoningContent = (aiMessage: AIMessage): void => {\n const reasoningContent = takePendingReasoningContent();\n if (reasoningContent == null) {\n return;\n }\n aiMessage.additional_kwargs.reasoning_content =\n typeof aiMessage.additional_kwargs.reasoning_content === 'string'\n ? `${aiMessage.additional_kwargs.reasoning_content}${reasoningContent}`\n : reasoningContent;\n };\n\n const flushPendingServerToolUse = (toolUseId: string): void => {\n for (const [id, content] of pendingServerToolUses) {\n pendingServerToolUses.delete(id);\n if (id === toolUseId) {\n currentContent.push(content);\n emittedServerToolUseIds.add(id);\n return;\n }\n }\n };\n\n if (Array.isArray(message.content)) {\n const contentParts = message.content as Array<\n MessageContentComplex | undefined | null\n >;\n\n for (const part of contentParts) {\n if (part == null) {\n continue;\n }\n if (isValidServerToolResult(part)) {\n serverToolResultIds.add(getToolUseId(part) ?? '');\n }\n if (options?.provider === Providers.ANTHROPIC) {\n const toolCallId = getToolCallId(part);\n if (toolCallId == null) {\n continue;\n }\n const preferredPart = preferredToolCallParts.get(toolCallId);\n if (\n preferredPart == null ||\n (!hasToolCallOutput(preferredPart) && hasToolCallOutput(part))\n ) {\n preferredToolCallParts.set(toolCallId, part);\n }\n }\n }\n\n for (const part of contentParts) {\n if (part == null) {\n continue;\n }\n const toolUseId = getToolUseId(part);\n if (toolUseId != null) {\n const isServerToolResult = isValidServerToolResult(part);\n if (\n toolUseId.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n !isServerToolResult\n ) {\n continue;\n }\n flushPendingServerToolUse(toolUseId);\n if (isServerToolResult) {\n currentContent.push(part);\n continue;\n }\n } else if (hasMeaningfulAssistantContent(part)) {\n for (const id of pendingServerToolUses.keys()) {\n if (!serverToolResultIds.has(id)) {\n pendingServerToolUses.delete(id);\n }\n }\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n if (\n currentContent.some((content) => content.type !== ContentTypes.TEXT)\n ) {\n currentContent.push(part);\n lastAIMessage = createAIMessage(toLangChainContent(currentContent));\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${getTextContent(curr)}\\n`;\n }\n return acc;\n }, '');\n content = `${content}\\n${getTextContent(part)}`.trim();\n lastAIMessage = createAIMessage(content);\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = createAIMessage(getTextContent(part));\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n const toolCallId = getToolCallId(part);\n if (\n options?.provider === Providers.ANTHROPIC &&\n toolCallId != null &&\n preferredToolCallParts.get(toolCallId) !== part\n ) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (\n options?.provider === Providers.ANTHROPIC &&\n typeof _tool_call.id === 'string' &&\n _tool_call.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n if (\n !serverToolResultIds.has(_tool_call.id) &&\n options.preserveUnpairedServerToolUses !== true\n ) {\n continue;\n }\n if (\n emittedServerToolUseIds.has(_tool_call.id) ||\n pendingServerToolUses.has(_tool_call.id)\n ) {\n continue;\n }\n pendingServerToolUses.set(_tool_call.id, {\n type: 'server_tool_use',\n id: _tool_call.id,\n name: _tool_call.name,\n input: parseServerToolInput(_args),\n } as MessageContentComplex);\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n } else {\n attachPendingReasoningContent(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (\n options?.provider === Providers.ANTHROPIC &&\n Array.isArray(lastAIMessage.content)\n ) {\n const content = lastAIMessage.content as MessageContentComplex[];\n content.push({\n type: 'tool_use',\n id: normalizeAnthropicToolCallId(tool_call.id ?? ''),\n name: tool_call.name,\n input: args,\n } as MessageContentComplex);\n lastAIMessage.content = content as MessageContent;\n } else {\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n }\n\n formattedMessages.push(\n withMessageRole(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output != null ? output : '',\n }),\n 'tool'\n )\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n pendingReasoningContent += extractReasoningContent(part);\n continue;\n } else if (part.type === ContentTypes.STEER) {\n /*\n A mid-run steer: user speech persisted inline in the assistant message\n at the tool-batch boundary it was injected. Flush accumulated\n assistant content first so ordering is preserved, then replay the\n steer as a standalone user message — multimodal when the host stamped\n a pre-encoded `media` content array (attachment refs are re-encoded\n per turn host-side, like any other user media). `lastAIMessage` is\n reset AFTER the HumanMessage: a post-steer tool_call must mint a\n FRESH assistant anchor (the heal path) so its AIMessage lands after\n the user turn — attaching it to the pre-steer anchor would emit its\n ToolMessage after the HumanMessage while the call itself sat before\n it, an invalid provider ordering.\n */\n if (currentContent.length > 0) {\n if (\n currentContent.some((content) => content.type !== ContentTypes.TEXT)\n ) {\n lastAIMessage = createAIMessage(toLangChainContent(currentContent));\n formattedMessages.push(lastAIMessage);\n } else {\n const flushed = currentContent\n .reduce((acc, curr) => `${acc}${getTextContent(curr)}\\n`, '')\n .trim();\n if (flushed.length > 0) {\n lastAIMessage = createAIMessage(flushed);\n formattedMessages.push(lastAIMessage);\n }\n }\n currentContent = [];\n } else if (shouldPreserveReasoningContent && pendingReasoningContent) {\n /**\n * Reasoning directly preceding a steer has no `currentContent`\n * flush to consume it and the anchor resets below — emit an anchor\n * AIMessage now (createAIMessage folds the pending reasoning into\n * `additional_kwargs.reasoning_content`) or the persisted\n * assistant reasoning silently vanishes on replay.\n */\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n }\n const steerPart = part as {\n steer?: string;\n media?: MessageContentComplex[];\n };\n const steerContent =\n Array.isArray(steerPart.media) && steerPart.media.length > 0\n ? toLangChainContent(steerPart.media)\n : (steerPart.steer ?? '');\n formattedMessages.push(\n withMessageRole(\n new HumanMessage({\n content: steerContent as MessageContent,\n additional_kwargs: { role: 'user', source: 'steer' },\n }),\n 'user'\n )\n );\n lastAIMessage = null;\n /** The steer splits the assistant message: the post-steer segment\n * starts with fresh reasoning state (pre-steer reasoning was either\n * flushed above or intentionally dropped when not preserving). */\n hasReasoning = false;\n pendingReasoningContent = '';\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY ||\n part.type === ContentTypes.ACTIVITY_LABEL\n ) {\n continue;\n } else {\n if (part.type === ContentTypes.TEXT && !getTextContent(part).trim()) {\n continue;\n }\n currentContent.push(part);\n }\n }\n for (const content of pendingServerToolUses.values()) {\n currentContent.push(content);\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n let content = '';\n for (const part of currentContent) {\n if (part.type !== ContentTypes.TEXT) {\n formattedMessages.push(\n createAIMessage(toLangChainContent(currentContent))\n );\n return formattedMessages;\n }\n content += `${getTextContent(part)}\\n`;\n }\n content = content.trim();\n\n if (content) {\n formattedMessages.push(createAIMessage(content));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(createAIMessage(toLangChainContent(currentContent)));\n }\n\n return formattedMessages;\n}\n\nfunction getSourceMessageId(message: Partial<TMessage>): string | undefined {\n const candidate =\n (message as { messageId?: string }).messageId ??\n (message as { id?: string }).id;\n if (typeof candidate !== 'string') {\n return undefined;\n }\n const normalized = candidate.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n /** UI-only progress headers are not agent content and must not disturb\n * agent state: a label with no `agentIdMap` entry would otherwise read\n * as an agent change and flush the buffer mid-agent, splitting one\n * agent's contiguous content into two labeled blocks. Skipped before\n * any state transition below (mirrors the transfer path). */\n if (part.type === ContentTypes.ACTIVITY_LABEL) {\n continue;\n }\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n if (part.type === ContentTypes.STEER) {\n /** User speech is never agent content — see the transfer path above. */\n flushAgentBuffer();\n result.push(part);\n continue;\n }\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n /** UI-only progress headers are not agent content and must not disturb\n * agent state: a label with no `agentIdMap` entry would otherwise look\n * like an agent change, flushing the buffer and resetting an open\n * transfer capture so the transferred agent's following chunks lose\n * their frame. Skipped before any state transition below. */\n if (part.type === ContentTypes.ACTIVITY_LABEL) {\n continue;\n }\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else if (part.type === ContentTypes.STEER) {\n /**\n * User speech is never agent content: flush the buffer in place and\n * pass the steer through verbatim so `formatAssistantMessage` replays\n * it as a user turn. Folding it into a labeled transfer summary would\n * both drop the user's words and misattribute them to the agent.\n * The steer also CLOSES any open transfer capture — `flushAgentBuffer`\n * no-ops on an empty buffer, and leaving the capture live would fold\n * post-steer agent content into the pre-steer transfer output,\n * replaying it BEFORE the user's redirect.\n */\n flushAgentBuffer();\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n currentAgentId = undefined;\n result.push(part);\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\ntype SummaryBoundary = {\n messageIndex: number;\n contentIndex: number;\n text: string;\n tokenCount: number;\n};\n\nfunction getLatestSummaryBoundary(\n payload: TPayload\n): SummaryBoundary | undefined {\n let summaryBoundary: SummaryBoundary | undefined;\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n for (let j = 0; j < message.content.length; j++) {\n const part = message.content[j] as MessageContentComplex | undefined;\n if (part == null || part.type !== ContentTypes.SUMMARY) {\n continue;\n }\n\n const summaryPart = part as Partial<SummaryContentBlock> & {\n text?: string;\n };\n\n // Try content array first (new format), then direct text (legacy format)\n let summaryText = (summaryPart.content ?? [])\n .map((block) =>\n 'text' in block ? (block as { text: string }).text : ''\n )\n .join('')\n .trim();\n\n // Fallback: legacy format where text was a direct field on the block\n if (summaryText.length === 0 && typeof summaryPart.text === 'string') {\n summaryText = summaryPart.text.trim();\n }\n\n if (summaryText.length === 0) {\n continue;\n }\n\n summaryBoundary = {\n messageIndex: i,\n contentIndex: j,\n text: summaryText,\n tokenCount:\n typeof summaryPart.tokenCount === 'number' &&\n Number.isFinite(summaryPart.tokenCount)\n ? summaryPart.tokenCount\n : 0,\n };\n }\n }\n\n return summaryBoundary;\n}\n\nfunction applySummaryBoundary(\n message: Partial<TMessage>,\n messageIndex: number,\n summaryBoundary?: SummaryBoundary\n): Partial<TMessage> | null {\n if (!summaryBoundary) {\n return message;\n }\n\n if (messageIndex < summaryBoundary.messageIndex) {\n return null;\n }\n\n if (\n messageIndex !== summaryBoundary.messageIndex ||\n !Array.isArray(message.content)\n ) {\n return message;\n }\n\n return {\n ...message,\n content: message.content.slice(summaryBoundary.contentIndex + 1),\n };\n}\n\nfunction contentPartCharLength(part: MessageContentComplex): number {\n const record = part as Record<string, unknown>;\n let len = 0;\n if (typeof record.text === 'string') {\n len += record.text.length;\n }\n if (typeof record.thinking === 'string') {\n len += record.thinking.length;\n }\n const { input } = record;\n if (typeof input === 'string') {\n len += input.length;\n } else if (input != null && typeof input === 'object') {\n len += JSON.stringify(input).length;\n }\n return len;\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * @param options - Optional formatting options (provider, skipSkillBodyNames).\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n /** Pre-resolved skill bodies keyed by skill name. When present, HumanMessages\n * are reconstructed after skill ToolMessages to restore skill instructions\n * that were only in LangGraph state during the original run. */\n skills?: Map<string, string>,\n options?: FormatAgentMessagesOptions\n): {\n messages: Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n | RoleBearingMessage<ToolMessage>\n >;\n indexTokenCountMap?: Record<number, number>;\n /** Cross-run summary extracted from the payload. Should be forwarded to the\n * agent run so it can be included in the system message via AgentContext. */\n summary?: { text: string; tokenCount: number };\n /** When a summary boundary sliced content from a message, the token count\n * was proportionally reduced. Returned so the caller can log it. */\n boundaryTokenAdjustment?: {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n };\n} => {\n const messages: Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n | RoleBearingMessage<ToolMessage>\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n let boundaryTokenAdjustment:\n | {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n }\n | undefined;\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n const summaryBoundary = getLatestSummaryBoundary(payload);\n\n // Summary metadata is returned to the caller so it can be forwarded to the\n // agent run and included in the single system message via AgentContext.\n // We intentionally do NOT create a SystemMessage here — that would conflict\n // with the agent's own system message (instructions + summary combined).\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const rawMessage = payload[i];\n const sourceMessageId = getSourceMessageId(rawMessage);\n let message = applySummaryBoundary(rawMessage, i, summaryBoundary);\n if (!message) {\n indexMapping[i] = [];\n continue;\n }\n\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message = {\n ...message,\n content: [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ],\n };\n } else if (Array.isArray(message.content) && message.content.length === 0) {\n indexMapping[i] = [];\n continue;\n }\n\n if (message.role !== 'assistant') {\n const formattedMessage = formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>;\n if (sourceMessageId != null && sourceMessageId !== '') {\n formattedMessage.id = sourceMessageId;\n }\n messages.push(formattedMessage);\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content != null && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n filteredContent.push(part);\n if (\n toolName === Constants.SKILL_TOOL &&\n skills?.size != null &&\n skills.size > 0\n ) {\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n /** When tools filtering is off, still detect skill tool_calls for body reconstruction */\n if (!discoveredTools && skills?.size != null && skills.size > 0) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n const formattedMessages = formatAssistantMessage(processedMessage, {\n preserveUnpairedServerToolUses: i === payload.length - 1,\n preserveReasoningContent:\n options?.preserveReasoningContent ??\n options?.provider === Providers.DEEPSEEK,\n provider: options?.provider,\n });\n if (sourceMessageId != null && sourceMessageId !== '') {\n for (const formattedMessage of formattedMessages) {\n formattedMessage.id = sourceMessageId;\n }\n }\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution.\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size != null && pendingSkillNames.size > 0) {\n const skipSkillBodyNames = options?.skipSkillBodyNames;\n for (const skillName of pendingSkillNames) {\n if (skipSkillBodyNames != null && skipSkillBodyNames.has(skillName)) {\n continue;\n }\n const body = skills?.get(skillName) ?? '';\n if (body) {\n messages.push(\n withMessageRole(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n }),\n 'user'\n )\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n let tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n if (\n summaryBoundary &&\n originalIndex === summaryBoundary.messageIndex &&\n Array.isArray(payload[originalIndex].content)\n ) {\n const content = payload[originalIndex]\n .content as MessageContentComplex[];\n const { contentIndex } = summaryBoundary;\n if (contentIndex >= 0 && contentIndex < content.length - 1) {\n let totalCharLen = 0;\n let remainingCharLen = 0;\n for (let p = 0; p < content.length; p++) {\n const charLen = contentPartCharLength(content[p]);\n totalCharLen += charLen;\n if (p > contentIndex) {\n remainingCharLen += charLen;\n }\n }\n if (totalCharLen > 0) {\n const original = tokenCount;\n tokenCount = Math.max(\n 1,\n Math.round(tokenCount * (remainingCharLen / totalCharLen))\n );\n boundaryTokenAdjustment = {\n original,\n adjusted: tokenCount,\n remainingChars: remainingCharLen,\n totalChars: totalCharLen,\n };\n }\n }\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n len += JSON.stringify(args).length;\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n summary: summaryBoundary\n ? { text: summaryBoundary.text, tokenCount: summaryBoundary.tokenCount }\n : undefined,\n boundaryTokenAdjustment,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Block types that contain binary image data and must be preserved structurally. */\nconst IMAGE_BLOCK_TYPES = new Set(['image_url', 'image']);\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Image blocks are shallow-copied into `parts` as-is so that\n * binary data (base64 images) never becomes text tokens. All other block\n * types are serialized to text — unrecognized types are JSON-serialized\n * rather than silently dropped.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content) {\n textChunks.push(`${role}: ${content}`);\n }\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (IMAGE_BLOCK_TYPES.has(block.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n continue;\n }\n\n if (block.type === 'tool_use') {\n hasToolUseBlock = true;\n textChunks.push(\n `${role}: [tool_use] ${String(block.name ?? '')} ${JSON.stringify(block.input ?? {})}`\n );\n continue;\n }\n\n // A `tool_call` content block appears either as the v1 standard shape\n // (`{ name, args }` at top level, which `@langchain/aws` maps to a Converse\n // toolUse) or this repo's `ToolCallContent` (`{ tool_call: { name, args,\n // output } }`, from `convertMessagesToContent` / persisted history). Handle\n // both, and emit any embedded output, so the name/args/result survive.\n if (block.type === 'tool_call') {\n hasToolUseBlock = true;\n const nested = (block as { tool_call?: ToolCallPart }).tool_call;\n const name = String(nested?.name ?? block.name ?? '');\n const rawArgs = nested?.args ?? block.args ?? {};\n const argsText =\n typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs);\n textChunks.push(`${role}: [tool_use] ${name} ${argsText}`.trimEnd());\n const output = nested?.output;\n if (output != null && output !== '') {\n textChunks.push(`Tool: ${String(output)}`);\n }\n continue;\n }\n\n // A `tool_result` content block (e.g. an AIMessage(tool_call) followed by a\n // user message carrying the result). Preserve nested image blocks as-is\n // instead of JSON-stringifying them through the generic fallback.\n if (block.type === 'tool_result') {\n hasToolUseBlock = true;\n const inner = (block as { content?: ToolResultContent['content'] })\n .content;\n if (typeof inner === 'string') {\n if (inner) {\n textChunks.push(`${role}: [tool_result] ${inner}`);\n }\n } else if (Array.isArray(inner)) {\n for (const innerBlock of inner as Array<\n string | ExtendedMessageContent\n >) {\n if (typeof innerBlock === 'string') {\n if (innerBlock) {\n textChunks.push(`${role}: [tool_result] ${innerBlock}`);\n }\n } else if (IMAGE_BLOCK_TYPES.has(innerBlock.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...innerBlock } as MessageContentComplex);\n } else {\n const innerText = innerBlock.text ?? innerBlock.input;\n textChunks.push(\n `${role}: [tool_result] ${\n typeof innerText === 'string' && innerText\n ? innerText\n : JSON.stringify(innerBlock)\n }`\n );\n }\n }\n } else if (inner != null) {\n textChunks.push(`${role}: [tool_result] ${JSON.stringify(inner)}`);\n }\n continue;\n }\n\n const text = block.text ?? block.input;\n if (typeof text === 'string' && text) {\n textChunks.push(`${role}: ${text}`);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (block.type != null && block.type !== '') {\n textChunks.push(`${role}: [${block.type}] ${JSON.stringify(block)}`);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[]\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (aiMsg.tool_calls && aiMsg.tool_calls.length > 0) {\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\n }\n return;\n }\n // Fall back to raw provider tool calls kept only in additional_kwargs.\n const rawToolCalls = aiMsg.additional_kwargs.tool_calls;\n if (!Array.isArray(rawToolCalls)) {\n return;\n }\n for (const tc of rawToolCalls) {\n const fn = (tc as { function?: { name?: string; arguments?: string } })\n .function;\n if (fn == null) {\n continue;\n }\n textChunks.push(\n `AI: [tool_call] ${String(fn.name ?? '')}(${String(fn.arguments ?? '')})`\n );\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @param config - Optional RunnableConfig for structured agent logging\n * @param runStartIndex - Index in `messages` where the CURRENT run's own\n * appended AI/Tool messages begin (i.e. anything at this index or later\n * was just produced by this run's own iterations, not historical\n * context). When provided, AI messages at or after this index are\n * never converted to `[Previous agent context]` placeholders — Claude\n * can validly skip a thinking block before a tool_use (cf. PR #116),\n * so the agent's own in-run iterations must not be misclassified as\n * foreign history. Without the signal the function falls back to its\n * prior heuristic (`chainHasThinkingBlock`), preserving backward\n * compatibility for callers that don't yet pass the boundary.\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers,\n config?: RunnableConfig,\n runStartIndex?: number\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // Find the last HumanMessage. Only the trailing sequence after it needs\n // validation — earlier messages are history already accepted by the provider.\n let lastHumanIndex = -1;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (\n m instanceof HumanMessage ||\n ('role' in m && (m as any).role === 'user')\n ) {\n lastHumanIndex = k;\n break;\n }\n }\n\n if (lastHumanIndex === messages.length - 1) {\n return messages;\n }\n\n const result: BaseMessage[] =\n lastHumanIndex >= 0 ? messages.slice(0, lastHumanIndex + 1) : [];\n let i = lastHumanIndex + 1;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n if (c.type === 'tool_use') {\n hasToolUse = true;\n } else if (\n c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Current-run boundary check: anything at or after `runStartIndex`\n // is the current run's own work — preserve it. Claude is allowed\n // to skip a thinking block before a tool_use (cf. PR #116 in the\n // agents repo), so the agent's own first-iteration AI message can\n // legitimately have tool_calls without reasoning. Converting it to\n // a `[Previous agent context]` placeholder pollutes the next\n // iteration's prompt — the LLM sees the placeholder, treats it as\n // suspicious injected content, ignores its own real prior tool\n // result, and re-runs the tool to verify (which then often fails\n // because subsequent calls land in fresh sandboxes without the\n // file). Skip the conversion when we know this is in-run.\n if (runStartIndex !== undefined && i >= runStartIndex) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous agent context]'];\n\n appendMessageContent(msg, 'AI', textChunks, parts);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n emitAgentLog(\n config,\n 'warn',\n 'format',\n 'ensureThinkingBlockInMessages: injecting [Previous agent context] HumanMessage' +\n ` (${parts.length} msgs at index ${i}, no thinking block in chain)`\n );\n result.push(\n withMessageRole(\n new HumanMessage({ content: toLangChainContent(parts) }),\n 'user'\n )\n );\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/** Whether a message carries tool content a tool-less agent cannot legally\n * send. Covers every representation a provider converter will serialize back\n * into a request: a ToolMessage, parsed `AIMessage.tool_calls`, raw\n * `additional_kwargs.tool_calls` (OpenAI keeps calls here when the parsed\n * array is empty), and `tool_use` / `tool_call` / `tool_result` content\n * blocks (`@langchain/aws` and the Anthropic converter map these to Converse\n * `toolUse` / `toolResult`). Missing the parent AI message is not just a\n * passthrough: folding its ToolMessage alone would leave an orphan\n * `assistant(tool_calls) -> user(...)` sequence. */\nfunction messageHasToolContent(msg: BaseMessage): boolean {\n if (isToolMessage(msg)) {\n return true;\n }\n const aiMsg = msg as AIMessage;\n if (aiMsg.tool_calls != null && aiMsg.tool_calls.length > 0) {\n return true;\n }\n const rawToolCalls = aiMsg.additional_kwargs.tool_calls;\n if (Array.isArray(rawToolCalls) && rawToolCalls.length > 0) {\n return true;\n }\n if (Array.isArray(msg.content)) {\n for (const block of msg.content as ExtendedMessageContent[]) {\n if (\n typeof block === 'object' &&\n (block.type === 'tool_use' ||\n block.type === 'tool_call' ||\n block.type === 'tool_result')\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** Whether a message carries a tool RESULT: a ToolMessage, or a message whose\n * content includes a `tool_result` block (the shape when a call/result pair is\n * split as `AIMessage(tool_call)` + `HumanMessage(tool_result)`). Such a result\n * belongs with the preceding tool call, so it is absorbed into the same fold\n * and labelled as tool output. */\nfunction isToolResultMessage(msg: BaseMessage): boolean {\n if (isToolMessage(msg)) {\n return true;\n }\n if (Array.isArray(msg.content)) {\n return (msg.content as ExtendedMessageContent[]).some(\n (block) => typeof block === 'object' && block.type === 'tool_result'\n );\n }\n return false;\n}\n\n/**\n * Folds tool_use / tool_result content into plain text for an agent that binds\n * no tools.\n *\n * In a multi-agent graph, a tool-less destination still inherits the prior\n * agent's conversation history, which can contain toolUse/toolResult blocks.\n * Because it binds no tools, the model is invoked with no tool schema — and\n * Bedrock's Converse API rejects any request that carries toolUse/toolResult\n * blocks without a top-level toolConfig (\"The toolConfig field must be defined\n * when using toolUse and toolResult content blocks\"). Adding a dummy toolConfig\n * is not an option: AWS requires at least one tool, and it would expose a\n * capability the destination was intentionally denied.\n *\n * Each tool-call turn plus its trailing tool results (ToolMessages or\n * `tool_result` content blocks) is collapsed into a single `[Previous tool\n * interaction]` HumanMessage that preserves the tool name, arguments and result\n * as text (image blocks are kept as-is). Runs in a single pass: non-tool\n * messages pass through, `result` is allocated lazily on the first fold, and the\n * original array is returned unchanged when it holds no tool content (the common\n * fresh-tool-less-agent case).\n */\nexport function foldToolBlocksForToollessAgent(\n messages: BaseMessage[],\n config?: RunnableConfig\n): BaseMessage[] {\n let result: BaseMessage[] | null = null;\n let foldedCount = 0;\n let i = 0;\n while (i < messages.length) {\n const msg = messages[i];\n if (!messageHasToolContent(msg)) {\n result?.push(msg);\n i++;\n continue;\n }\n\n /** First fold — copy the untouched prefix once, then append from here. */\n if (result === null) {\n result = messages.slice(0, i);\n }\n\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous tool interaction]'];\n appendMessageContent(\n msg,\n isToolResultMessage(msg) ? 'Tool' : 'AI',\n textChunks,\n parts\n );\n foldedCount++;\n\n let j = i + 1;\n while (j < messages.length && isToolResultMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n foldedCount++;\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n result.push(\n withMessageRole(\n new HumanMessage({ content: toLangChainContent(parts) }),\n 'user'\n )\n );\n i = j;\n }\n\n if (result === null) {\n return messages;\n }\n\n emitAgentLog(\n config,\n 'warn',\n 'format',\n `foldToolBlocksForToollessAgent: folded ${foldedCount} tool message(s) into text for a tool-less agent`\n );\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are part of the chain — keep walking back\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;AAmDA,MAAa,sBAAsB,EACjC,SACA,UACA,iBAMG;CAEH,MAAM,SAKF;EACF,GAAG;EACH,SAAS,CAAC;CACZ;CAEA,IAAI,aAAA,aAAkC;EACpC,OAAO,UAAU,CACf,GAAG,YACH;GAAE,MAAA;GAAyB,MAAM,QAAQ;EAAQ,CACnD;EACA,OAAO;CACT;CAEA,OAAO,UAAU,CACf;EAAE,MAAA;EAAyB,MAAM,QAAQ;CAAQ,GACjD,GAAG,UACL;CAEA,OAAO;AACT;AA8BA,SAAgB,gBACd,SACA,MACuB;CACvB,MAAM,cAAc;CACpB,IAAI,YAAY,SAAS,MACvB,OAAO;CAET,OAAO,eAAe,aAAa,QAA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":"format.cjs","names":["HumanMessage","toLangChainMessageFields","AIMessage","SystemMessage","compactToolContent","HARD_MAX_TOOL_RESULT_CHARS","toLangChainContent","normalizeAnthropicToolCallId","ToolMessage","serializeStructuredValueBounded","isAtomicToolContentBlock","getToolContentCharLength","AIMessageChunk"],"sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type {\n MessageContent,\n MessageContentImageUrl,\n} from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n BedrockReasoningContentText,\n ExtendedMessageContent,\n GoogleReasoningContentText,\n MessageContentComplex,\n ReasoningContentText,\n SummaryContentBlock,\n ThinkingContentText,\n ToolCallContent,\n ToolResultContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport {\n compactToolContent,\n getToolContentCharLength,\n isAtomicToolContentBlock,\n serializeStructuredValueBounded,\n} from '@/utils/toolContent';\nimport { normalizeAnthropicToolCallId } from '@/llm/anthropic/utils/message_inputs';\nimport { toLangChainContent, toLangChainMessageFields } from './langchain';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { Providers, ContentTypes, Constants } from '@/common';\nimport { emitAgentLog } from '@/utils/events';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\nexport type LangChainMessageRole = 'system' | 'user' | 'assistant' | 'tool';\n\nexport type RoleBearingMessage<T extends BaseMessage = BaseMessage> = T & {\n role: LangChainMessageRole;\n};\n\nexport function withMessageRole<T extends BaseMessage>(\n message: T,\n role: LangChainMessageRole\n): RoleBearingMessage<T> {\n const roleMessage = message as T & { role?: LangChainMessageRole };\n if (roleMessage.role === role) {\n return roleMessage as RoleBearingMessage<T>;\n }\n Object.defineProperty(roleMessage, 'role', {\n value: role,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n return roleMessage as RoleBearingMessage<T>;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage> => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return withMessageRole(\n new HumanMessage(toLangChainMessageFields(mediaMessage)),\n 'user'\n );\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return withMessageRole(\n new HumanMessage(toLangChainMessageFields(formattedMessage)),\n 'user'\n );\n } else if (role === 'assistant') {\n return withMessageRole(\n new AIMessage(toLangChainMessageFields(formattedMessage)),\n 'assistant'\n );\n } else {\n return withMessageRole(\n new SystemMessage(toLangChainMessageFields(formattedMessage)),\n 'system'\n );\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\ninterface FormatAssistantMessageOptions {\n preserveUnpairedServerToolUses?: boolean;\n preserveReasoningContent?: boolean;\n provider?: Providers;\n}\n\ninterface FormatAgentMessagesOptions {\n provider?: Providers;\n /** Reconstruct hidden `reasoning_content` from `THINK` parts onto prior\n * tool-call messages. Explicit opt-in for OpenAI-compatible endpoints that\n * replay reasoning across turns; defaults to on for DeepSeek thinking-mode. */\n preserveReasoningContent?: boolean;\n /** Skill names already primed fresh this turn (manual/always-apply). Their\n * historical `skill` tool_calls are not reconstructed into a HumanMessage,\n * so the same SKILL.md body is not injected twice in one request. */\n skipSkillBodyNames?: Set<string>;\n}\n\nfunction extractReasoningContent(\n part: MessageContentComplex | undefined | null\n): string {\n if (part == null || typeof part !== 'object') {\n return '';\n }\n if (part.type === ContentTypes.THINK) {\n const think = (part as ReasoningContentText).think;\n return typeof think === 'string' ? think : '';\n }\n if (part.type === ContentTypes.THINKING) {\n const thinking = (part as ThinkingContentText).thinking;\n return typeof thinking === 'string' ? thinking : '';\n }\n if (part.type === ContentTypes.REASONING) {\n const reasoning = (part as GoogleReasoningContentText).reasoning;\n return typeof reasoning === 'string' ? reasoning : '';\n }\n if (part.type === ContentTypes.REASONING_CONTENT) {\n const reasoningText = (part as BedrockReasoningContentText).reasoningText;\n return typeof reasoningText.text === 'string' ? reasoningText.text : '';\n }\n return '';\n}\n\ntype ServerToolInput = Exclude<NonNullable<ToolCallPart['args']>, string>;\n\nfunction parseServerToolInput(args: ToolCallPart['args']): ServerToolInput {\n if (typeof args === 'string') {\n try {\n const parsed = JSON.parse(args) as unknown;\n return parsed != null &&\n typeof parsed === 'object' &&\n !Array.isArray(parsed)\n ? (parsed as ServerToolInput)\n : {};\n } catch {\n return {};\n }\n }\n return args != null && typeof args === 'object' ? args : {};\n}\n\nfunction getTextContent(part: MessageContentComplex): string {\n const { text } = part as { text?: unknown };\n return typeof text === 'string' ? text : '';\n}\n\nfunction hasMeaningfulAssistantContent(part: MessageContentComplex): boolean {\n if (part.type === ContentTypes.TEXT) {\n return getTextContent(part).trim().length > 0;\n }\n if (\n part.type === ContentTypes.TOOL_CALL ||\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY ||\n part.type === ContentTypes.ACTIVITY_LABEL\n ) {\n return false;\n }\n if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n return extractReasoningContent(part).trim().length > 0;\n }\n return part.type != null && part.type !== '';\n}\n\nfunction getToolUseId(part: MessageContentComplex): string | undefined {\n if (!('tool_use_id' in part) || typeof part.tool_use_id !== 'string') {\n return undefined;\n }\n return part.tool_use_id;\n}\n\nfunction isValidServerToolResult(part: MessageContentComplex): boolean {\n const toolUseId = getToolUseId(part);\n if (\n toolUseId?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) !== true ||\n !('content' in part)\n ) {\n return false;\n }\n const { content } = part as { content?: unknown };\n return (\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as { type?: unknown }).type === 'web_search_tool_result_error')\n );\n}\n\nfunction getToolCallId(part: MessageContentComplex): string | undefined {\n if (part.type !== ContentTypes.TOOL_CALL) {\n return undefined;\n }\n const id = part.tool_call?.id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\nfunction hasToolCallOutput(part: MessageContentComplex): boolean {\n if (part.type !== ContentTypes.TOOL_CALL) {\n return false;\n }\n const output = part.tool_call?.output;\n return output != null && output !== '';\n}\n\nfunction formatToolCallOutput(\n output: ToolCallPart['output'] | undefined\n): MessageContent {\n if (output == null) {\n return '';\n }\n return compactToolContent(output, HARD_MAX_TOOL_RESULT_CHARS).content;\n}\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @param options Optional formatting options\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>,\n options?: FormatAssistantMessageOptions\n): Array<\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<ToolMessage>\n | RoleBearingMessage<HumanMessage>\n> {\n const formattedMessages: Array<\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<ToolMessage>\n | RoleBearingMessage<HumanMessage>\n > = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: RoleBearingMessage<AIMessage> | null = null;\n let hasReasoning = false;\n let pendingReasoningContent = '';\n const emittedServerToolUseIds = new Set<string>();\n const pendingServerToolUses = new Map<string, MessageContentComplex>();\n const shouldPreserveReasoningContent =\n options?.preserveReasoningContent === true;\n const serverToolResultIds = new Set<string>();\n const preferredToolCallParts = new Map<string, MessageContentComplex>();\n\n const takePendingReasoningContent = (): string | undefined => {\n if (!shouldPreserveReasoningContent || !pendingReasoningContent) {\n return undefined;\n }\n const reasoningContent = pendingReasoningContent;\n pendingReasoningContent = '';\n return reasoningContent;\n };\n\n const createAIMessage = (\n content: MessageContent\n ): RoleBearingMessage<AIMessage> => {\n const reasoningContent = takePendingReasoningContent();\n return withMessageRole(\n new AIMessage({\n content,\n ...(reasoningContent != null && {\n additional_kwargs: { reasoning_content: reasoningContent },\n }),\n }),\n 'assistant'\n );\n };\n\n const attachPendingReasoningContent = (aiMessage: AIMessage): void => {\n const reasoningContent = takePendingReasoningContent();\n if (reasoningContent == null) {\n return;\n }\n aiMessage.additional_kwargs.reasoning_content =\n typeof aiMessage.additional_kwargs.reasoning_content === 'string'\n ? `${aiMessage.additional_kwargs.reasoning_content}${reasoningContent}`\n : reasoningContent;\n };\n\n const flushPendingServerToolUse = (toolUseId: string): void => {\n for (const [id, content] of pendingServerToolUses) {\n pendingServerToolUses.delete(id);\n if (id === toolUseId) {\n currentContent.push(content);\n emittedServerToolUseIds.add(id);\n return;\n }\n }\n };\n\n if (Array.isArray(message.content)) {\n const contentParts = message.content as Array<\n MessageContentComplex | undefined | null\n >;\n\n for (const part of contentParts) {\n if (part == null) {\n continue;\n }\n if (isValidServerToolResult(part)) {\n serverToolResultIds.add(getToolUseId(part) ?? '');\n }\n if (options?.provider === Providers.ANTHROPIC) {\n const toolCallId = getToolCallId(part);\n if (toolCallId == null) {\n continue;\n }\n const preferredPart = preferredToolCallParts.get(toolCallId);\n if (\n preferredPart == null ||\n (!hasToolCallOutput(preferredPart) && hasToolCallOutput(part))\n ) {\n preferredToolCallParts.set(toolCallId, part);\n }\n }\n }\n\n for (const part of contentParts) {\n if (part == null) {\n continue;\n }\n const toolUseId = getToolUseId(part);\n if (toolUseId != null) {\n const isServerToolResult = isValidServerToolResult(part);\n if (\n toolUseId.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n !isServerToolResult\n ) {\n continue;\n }\n flushPendingServerToolUse(toolUseId);\n if (isServerToolResult) {\n currentContent.push(part);\n continue;\n }\n } else if (hasMeaningfulAssistantContent(part)) {\n for (const id of pendingServerToolUses.keys()) {\n if (!serverToolResultIds.has(id)) {\n pendingServerToolUses.delete(id);\n }\n }\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n if (\n currentContent.some((content) => content.type !== ContentTypes.TEXT)\n ) {\n currentContent.push(part);\n lastAIMessage = createAIMessage(toLangChainContent(currentContent));\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${getTextContent(curr)}\\n`;\n }\n return acc;\n }, '');\n content = `${content}\\n${getTextContent(part)}`.trim();\n lastAIMessage = createAIMessage(content);\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = createAIMessage(getTextContent(part));\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n const toolCallId = getToolCallId(part);\n if (\n options?.provider === Providers.ANTHROPIC &&\n toolCallId != null &&\n preferredToolCallParts.get(toolCallId) !== part\n ) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (\n options?.provider === Providers.ANTHROPIC &&\n typeof _tool_call.id === 'string' &&\n _tool_call.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n if (\n !serverToolResultIds.has(_tool_call.id) &&\n options.preserveUnpairedServerToolUses !== true\n ) {\n continue;\n }\n if (\n emittedServerToolUseIds.has(_tool_call.id) ||\n pendingServerToolUses.has(_tool_call.id)\n ) {\n continue;\n }\n pendingServerToolUses.set(_tool_call.id, {\n type: 'server_tool_use',\n id: _tool_call.id,\n name: _tool_call.name,\n input: parseServerToolInput(_args),\n } as MessageContentComplex);\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n } else {\n attachPendingReasoningContent(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (\n options?.provider === Providers.ANTHROPIC &&\n Array.isArray(lastAIMessage.content)\n ) {\n const content = lastAIMessage.content as MessageContentComplex[];\n content.push({\n type: 'tool_use',\n id: normalizeAnthropicToolCallId(tool_call.id ?? ''),\n name: tool_call.name,\n input: args,\n } as MessageContentComplex);\n lastAIMessage.content = content as MessageContent;\n } else {\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n }\n\n formattedMessages.push(\n withMessageRole(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: formatToolCallOutput(output),\n }),\n 'tool'\n )\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n pendingReasoningContent += extractReasoningContent(part);\n continue;\n } else if (part.type === ContentTypes.STEER) {\n /*\n A mid-run steer: user speech persisted inline in the assistant message\n at the tool-batch boundary it was injected. Flush accumulated\n assistant content first so ordering is preserved, then replay the\n steer as a standalone user message — multimodal when the host stamped\n a pre-encoded `media` content array (attachment refs are re-encoded\n per turn host-side, like any other user media). `lastAIMessage` is\n reset AFTER the HumanMessage: a post-steer tool_call must mint a\n FRESH assistant anchor (the heal path) so its AIMessage lands after\n the user turn — attaching it to the pre-steer anchor would emit its\n ToolMessage after the HumanMessage while the call itself sat before\n it, an invalid provider ordering.\n */\n if (currentContent.length > 0) {\n if (\n currentContent.some((content) => content.type !== ContentTypes.TEXT)\n ) {\n lastAIMessage = createAIMessage(toLangChainContent(currentContent));\n formattedMessages.push(lastAIMessage);\n } else {\n const flushed = currentContent\n .reduce((acc, curr) => `${acc}${getTextContent(curr)}\\n`, '')\n .trim();\n if (flushed.length > 0) {\n lastAIMessage = createAIMessage(flushed);\n formattedMessages.push(lastAIMessage);\n }\n }\n currentContent = [];\n } else if (shouldPreserveReasoningContent && pendingReasoningContent) {\n /**\n * Reasoning directly preceding a steer has no `currentContent`\n * flush to consume it and the anchor resets below — emit an anchor\n * AIMessage now (createAIMessage folds the pending reasoning into\n * `additional_kwargs.reasoning_content`) or the persisted\n * assistant reasoning silently vanishes on replay.\n */\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n }\n const steerPart = part as {\n steer?: string;\n media?: MessageContentComplex[];\n };\n const steerContent =\n Array.isArray(steerPart.media) && steerPart.media.length > 0\n ? toLangChainContent(steerPart.media)\n : (steerPart.steer ?? '');\n formattedMessages.push(\n withMessageRole(\n new HumanMessage({\n content: steerContent as MessageContent,\n additional_kwargs: { role: 'user', source: 'steer' },\n }),\n 'user'\n )\n );\n lastAIMessage = null;\n /** The steer splits the assistant message: the post-steer segment\n * starts with fresh reasoning state (pre-steer reasoning was either\n * flushed above or intentionally dropped when not preserving). */\n hasReasoning = false;\n pendingReasoningContent = '';\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY ||\n part.type === ContentTypes.ACTIVITY_LABEL\n ) {\n continue;\n } else {\n if (part.type === ContentTypes.TEXT && !getTextContent(part).trim()) {\n continue;\n }\n currentContent.push(part);\n }\n }\n for (const content of pendingServerToolUses.values()) {\n currentContent.push(content);\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n let content = '';\n for (const part of currentContent) {\n if (part.type !== ContentTypes.TEXT) {\n formattedMessages.push(\n createAIMessage(toLangChainContent(currentContent))\n );\n return formattedMessages;\n }\n content += `${getTextContent(part)}\\n`;\n }\n content = content.trim();\n\n if (content) {\n formattedMessages.push(createAIMessage(content));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(createAIMessage(toLangChainContent(currentContent)));\n }\n\n return formattedMessages;\n}\n\nfunction getSourceMessageId(message: Partial<TMessage>): string | undefined {\n const candidate =\n (message as { messageId?: string }).messageId ??\n (message as { id?: string }).id;\n if (typeof candidate !== 'string') {\n return undefined;\n }\n const normalized = candidate.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n /** UI-only progress headers are not agent content and must not disturb\n * agent state: a label with no `agentIdMap` entry would otherwise read\n * as an agent change and flush the buffer mid-agent, splitting one\n * agent's contiguous content into two labeled blocks. Skipped before\n * any state transition below (mirrors the transfer path). */\n if (part.type === ContentTypes.ACTIVITY_LABEL) {\n continue;\n }\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n if (part.type === ContentTypes.STEER) {\n /** User speech is never agent content — see the transfer path above. */\n flushAgentBuffer();\n result.push(part);\n continue;\n }\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n /** UI-only progress headers are not agent content and must not disturb\n * agent state: a label with no `agentIdMap` entry would otherwise look\n * like an agent change, flushing the buffer and resetting an open\n * transfer capture so the transferred agent's following chunks lose\n * their frame. Skipped before any state transition below. */\n if (part.type === ContentTypes.ACTIVITY_LABEL) {\n continue;\n }\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else if (part.type === ContentTypes.STEER) {\n /**\n * User speech is never agent content: flush the buffer in place and\n * pass the steer through verbatim so `formatAssistantMessage` replays\n * it as a user turn. Folding it into a labeled transfer summary would\n * both drop the user's words and misattribute them to the agent.\n * The steer also CLOSES any open transfer capture — `flushAgentBuffer`\n * no-ops on an empty buffer, and leaving the capture live would fold\n * post-steer agent content into the pre-steer transfer output,\n * replaying it BEFORE the user's redirect.\n */\n flushAgentBuffer();\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n currentAgentId = undefined;\n result.push(part);\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\ntype SummaryBoundary = {\n messageIndex: number;\n contentIndex: number;\n text: string;\n tokenCount: number;\n};\n\nfunction getLatestSummaryBoundary(\n payload: TPayload\n): SummaryBoundary | undefined {\n let summaryBoundary: SummaryBoundary | undefined;\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n for (let j = 0; j < message.content.length; j++) {\n const part = message.content[j] as MessageContentComplex | undefined;\n if (part == null || part.type !== ContentTypes.SUMMARY) {\n continue;\n }\n\n const summaryPart = part as Partial<SummaryContentBlock> & {\n text?: string;\n };\n\n // Try content array first (new format), then direct text (legacy format)\n let summaryText = (summaryPart.content ?? [])\n .map((block) =>\n 'text' in block ? (block as { text: string }).text : ''\n )\n .join('')\n .trim();\n\n // Fallback: legacy format where text was a direct field on the block\n if (summaryText.length === 0 && typeof summaryPart.text === 'string') {\n summaryText = summaryPart.text.trim();\n }\n\n if (summaryText.length === 0) {\n continue;\n }\n\n summaryBoundary = {\n messageIndex: i,\n contentIndex: j,\n text: summaryText,\n tokenCount:\n typeof summaryPart.tokenCount === 'number' &&\n Number.isFinite(summaryPart.tokenCount)\n ? summaryPart.tokenCount\n : 0,\n };\n }\n }\n\n return summaryBoundary;\n}\n\nfunction applySummaryBoundary(\n message: Partial<TMessage>,\n messageIndex: number,\n summaryBoundary?: SummaryBoundary\n): Partial<TMessage> | null {\n if (!summaryBoundary) {\n return message;\n }\n\n if (messageIndex < summaryBoundary.messageIndex) {\n return null;\n }\n\n if (\n messageIndex !== summaryBoundary.messageIndex ||\n !Array.isArray(message.content)\n ) {\n return message;\n }\n\n return {\n ...message,\n content: message.content.slice(summaryBoundary.contentIndex + 1),\n };\n}\n\nfunction contentPartCharLength(part: MessageContentComplex): number {\n const record = part as Record<string, unknown>;\n let len = 0;\n if (typeof record.text === 'string') {\n len += record.text.length;\n }\n if (typeof record.thinking === 'string') {\n len += record.thinking.length;\n }\n const { input } = record;\n if (typeof input === 'string') {\n len += input.length;\n } else if (input != null && typeof input === 'object') {\n const measured = serializeStructuredValueBounded(input, 0).originalChars;\n len +=\n measured === Number.MAX_SAFE_INTEGER\n ? HARD_MAX_TOOL_RESULT_CHARS\n : Math.min(measured, HARD_MAX_TOOL_RESULT_CHARS);\n }\n return len;\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * @param options - Optional formatting options (provider, skipSkillBodyNames).\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n /** Pre-resolved skill bodies keyed by skill name. When present, HumanMessages\n * are reconstructed after skill ToolMessages to restore skill instructions\n * that were only in LangGraph state during the original run. */\n skills?: Map<string, string>,\n options?: FormatAgentMessagesOptions\n): {\n messages: Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n | RoleBearingMessage<ToolMessage>\n >;\n indexTokenCountMap?: Record<number, number>;\n /** Cross-run summary extracted from the payload. Should be forwarded to the\n * agent run so it can be included in the system message via AgentContext. */\n summary?: { text: string; tokenCount: number };\n /** When a summary boundary sliced content from a message, the token count\n * was proportionally reduced. Returned so the caller can log it. */\n boundaryTokenAdjustment?: {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n };\n} => {\n const messages: Array<\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>\n | RoleBearingMessage<ToolMessage>\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n let boundaryTokenAdjustment:\n | {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n }\n | undefined;\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n const summaryBoundary = getLatestSummaryBoundary(payload);\n\n // Summary metadata is returned to the caller so it can be forwarded to the\n // agent run and included in the single system message via AgentContext.\n // We intentionally do NOT create a SystemMessage here — that would conflict\n // with the agent's own system message (instructions + summary combined).\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const rawMessage = payload[i];\n const sourceMessageId = getSourceMessageId(rawMessage);\n let message = applySummaryBoundary(rawMessage, i, summaryBoundary);\n if (!message) {\n indexMapping[i] = [];\n continue;\n }\n\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message = {\n ...message,\n content: [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ],\n };\n } else if (Array.isArray(message.content) && message.content.length === 0) {\n indexMapping[i] = [];\n continue;\n }\n\n if (message.role !== 'assistant') {\n const formattedMessage = formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as\n | RoleBearingMessage<HumanMessage>\n | RoleBearingMessage<AIMessage>\n | RoleBearingMessage<SystemMessage>;\n if (sourceMessageId != null && sourceMessageId !== '') {\n formattedMessage.id = sourceMessageId;\n }\n messages.push(formattedMessage);\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content != null && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n filteredContent.push(part);\n if (\n toolName === Constants.SKILL_TOOL &&\n skills?.size != null &&\n skills.size > 0\n ) {\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n /** When tools filtering is off, still detect skill tool_calls for body reconstruction */\n if (!discoveredTools && skills?.size != null && skills.size > 0) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n const formattedMessages = formatAssistantMessage(processedMessage, {\n preserveUnpairedServerToolUses: i === payload.length - 1,\n preserveReasoningContent:\n options?.preserveReasoningContent ??\n options?.provider === Providers.DEEPSEEK,\n provider: options?.provider,\n });\n if (sourceMessageId != null && sourceMessageId !== '') {\n for (const formattedMessage of formattedMessages) {\n formattedMessage.id = sourceMessageId;\n }\n }\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution.\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size != null && pendingSkillNames.size > 0) {\n const skipSkillBodyNames = options?.skipSkillBodyNames;\n for (const skillName of pendingSkillNames) {\n if (skipSkillBodyNames != null && skipSkillBodyNames.has(skillName)) {\n continue;\n }\n const body = skills?.get(skillName) ?? '';\n if (body) {\n messages.push(\n withMessageRole(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n }),\n 'user'\n )\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n let tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n if (\n summaryBoundary &&\n originalIndex === summaryBoundary.messageIndex &&\n Array.isArray(payload[originalIndex].content)\n ) {\n const content = payload[originalIndex]\n .content as MessageContentComplex[];\n const { contentIndex } = summaryBoundary;\n if (contentIndex >= 0 && contentIndex < content.length - 1) {\n let totalCharLen = 0;\n let remainingCharLen = 0;\n for (let p = 0; p < content.length; p++) {\n const charLen = contentPartCharLength(content[p]);\n totalCharLen += charLen;\n if (p > contentIndex) {\n remainingCharLen += charLen;\n }\n }\n if (totalCharLen > 0) {\n const original = tokenCount;\n tokenCount = Math.max(\n 1,\n Math.round(tokenCount * (remainingCharLen / totalCharLen))\n );\n boundaryTokenAdjustment = {\n original,\n adjusted: tokenCount,\n remainingChars: remainingCharLen,\n totalChars: totalCharLen,\n };\n }\n }\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n const measured = serializeStructuredValueBounded(\n args,\n 0\n ).originalChars;\n len +=\n measured === Number.MAX_SAFE_INTEGER\n ? HARD_MAX_TOOL_RESULT_CHARS\n : Math.min(measured, HARD_MAX_TOOL_RESULT_CHARS);\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n summary: summaryBoundary\n ? { text: summaryBoundary.text, tokenCount: summaryBoundary.tokenCount }\n : undefined,\n boundaryTokenAdjustment,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\nconst PORTABLE_FOLDED_MEDIA_TYPES = new Set(['image', 'image_url']);\nconst MAX_FOLDED_BLOCK_CHARS = 8_000;\nconst MAX_FOLDED_CONTEXT_CHARS = HARD_MAX_TOOL_RESULT_CHARS;\nconst MAX_FOLDED_CONTEXT_WORK = 100_000;\nconst FOLDED_CONTEXT_TRUNCATION_NOTICE =\n '… [additional folded context omitted]';\nconst syntheticProviderContextMessages = new WeakSet<BaseMessage>();\n\ntype FoldContextBudget = {\n remainingChars: number;\n remainingWork: number;\n truncated: boolean;\n};\n\nfunction createFoldContextBudget(): FoldContextBudget {\n return {\n remainingChars: MAX_FOLDED_CONTEXT_CHARS,\n remainingWork: MAX_FOLDED_CONTEXT_WORK,\n truncated: false,\n };\n}\n\nfunction readFoldedDataProperty(value: unknown, key: string): unknown {\n if (value == null || typeof value !== 'object') {\n return undefined;\n }\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor != null && 'value' in descriptor\n ? descriptor.value\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Adds one logical line without first concatenating caller-controlled strings.\n * The shared budget covers every synthetic message emitted by one transform,\n * so many individually bounded blocks cannot build an unbounded aggregate.\n */\nfunction appendFoldedLine(\n textChunks: string[],\n budget: FoldContextBudget,\n pieces: readonly string[]\n): boolean {\n if (budget.remainingChars <= 0) {\n budget.truncated = true;\n return false;\n }\n\n const separatorChars = textChunks.length > 0 ? 1 : 0;\n const available = budget.remainingChars - separatorChars;\n if (available <= 0) {\n budget.remainingChars = 0;\n budget.truncated = true;\n return false;\n }\n\n let totalChars = 0;\n for (const piece of pieces) {\n totalChars = Math.min(Number.MAX_SAFE_INTEGER, totalChars + piece.length);\n }\n if (totalChars <= available) {\n const line = pieces.join('');\n textChunks.push(line);\n budget.remainingChars -= separatorChars + line.length;\n return true;\n }\n\n const notice = FOLDED_CONTEXT_TRUNCATION_NOTICE.slice(0, available);\n let remainingHeadChars = Math.max(0, available - notice.length);\n const boundedPieces: string[] = [];\n for (const piece of pieces) {\n if (remainingHeadChars <= 0) {\n break;\n }\n const retained = piece.slice(0, remainingHeadChars);\n boundedPieces.push(retained);\n remainingHeadChars -= retained.length;\n }\n boundedPieces.push(notice);\n textChunks.push(boundedPieces.join(''));\n budget.remainingChars = 0;\n budget.truncated = true;\n return false;\n}\n\nfunction consumeFoldedWork(\n textChunks: string[],\n budget: FoldContextBudget\n): boolean {\n if (budget.remainingChars <= 0) {\n return false;\n }\n if (budget.remainingWork-- > 0) {\n return true;\n }\n appendFoldedLine(textChunks, budget, [FOLDED_CONTEXT_TRUNCATION_NOTICE]);\n budget.remainingChars = 0;\n budget.truncated = true;\n return false;\n}\n\nfunction serializeFoldedValue(value: unknown): string {\n const compacted = compactToolContent(value, MAX_FOLDED_BLOCK_CHARS).content;\n return typeof compacted === 'string'\n ? compacted\n : serializeStructuredValueBounded(compacted, MAX_FOLDED_BLOCK_CHARS)\n .content;\n}\n\nfunction markSyntheticProviderContext<T extends BaseMessage>(message: T): T {\n syntheticProviderContextMessages.add(message);\n return message;\n}\n\nfunction appendSyntheticProviderContextMessage(\n result: BaseMessage[],\n parts: MessageContentComplex[]\n): boolean {\n if (parts.length === 0) {\n return false;\n }\n result.push(\n markSyntheticProviderContext(\n withMessageRole(\n new HumanMessage({ content: toLangChainContent(parts) }),\n 'user'\n )\n )\n );\n return true;\n}\n\n/**\n * Identifies provider-context placeholders created by this module without\n * trusting user-controlled content prefixes or leaking marker metadata onto\n * the provider wire.\n */\nexport function isSyntheticProviderContextMessage(\n message: BaseMessage\n): boolean {\n return syntheticProviderContextMessages.has(message);\n}\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Portable image blocks are shallow-copied into `parts` so\n * binary data never becomes text tokens. Provider-specific media/resource\n * blocks are retained as bounded text so a folded cross-provider history\n * cannot contain an unsupported native block or JSON-expand without limit.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[],\n budget: FoldContextBudget\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content && consumeFoldedWork(textChunks, budget)) {\n appendFoldedLine(textChunks, budget, [`${role}: `, content]);\n }\n appendToolCalls(msg, role, textChunks, budget);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks, budget);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (!consumeFoldedWork(textChunks, budget)) {\n hasToolUseBlock = true;\n break;\n }\n const blockTypeValue = readFoldedDataProperty(block, 'type');\n const blockType =\n typeof blockTypeValue === 'string' ? blockTypeValue : undefined;\n\n if (\n blockType !== 'tool_use' &&\n blockType !== 'tool_call' &&\n blockType !== 'tool_result' &&\n isAtomicToolContentBlock(block)\n ) {\n if (PORTABLE_FOLDED_MEDIA_TYPES.has(blockType ?? '')) {\n const blockChars = getToolContentCharLength([block]);\n if (blockChars > budget.remainingChars) {\n appendFoldedLine(textChunks, budget, [\n `${role}: [${blockType ?? 'media'} omitted: folded context limit]`,\n ]);\n continue;\n }\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n budget.remainingChars -= blockChars;\n } else {\n appendFoldedLine(textChunks, budget, [\n `${role}: [${blockType ?? 'media'}] `,\n serializeFoldedValue(block),\n ]);\n }\n continue;\n }\n\n if (blockType === 'tool_use') {\n hasToolUseBlock = true;\n const name = readFoldedDataProperty(block, 'name');\n const input = readFoldedDataProperty(block, 'input');\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_use] ${typeof name === 'string' ? name : ''} `,\n serializeFoldedValue(input ?? {}),\n ]);\n continue;\n }\n\n // A `tool_call` content block appears either as the v1 standard shape\n // (`{ name, args }` at top level, which `@langchain/aws` maps to a Converse\n // toolUse) or this repo's `ToolCallContent` (`{ tool_call: { name, args,\n // output } }`, from `convertMessagesToContent` / persisted history). Handle\n // both, and emit any embedded output, so the name/args/result survive.\n if (blockType === 'tool_call') {\n hasToolUseBlock = true;\n const nested = readFoldedDataProperty(block, 'tool_call');\n const nestedName = readFoldedDataProperty(nested, 'name');\n const topLevelName = readFoldedDataProperty(block, 'name');\n let name = '';\n if (typeof nestedName === 'string') {\n name = nestedName;\n } else if (typeof topLevelName === 'string') {\n name = topLevelName;\n }\n const nestedArgs = readFoldedDataProperty(nested, 'args');\n const topLevelArgs = readFoldedDataProperty(block, 'args');\n const rawArgs = nestedArgs ?? topLevelArgs ?? {};\n const argsText =\n typeof rawArgs === 'string' ? rawArgs : serializeFoldedValue(rawArgs);\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_use] ${name}${argsText ? ' ' : ''}`,\n argsText,\n ]);\n const output = readFoldedDataProperty(nested, 'output');\n if (output != null && output !== '') {\n appendFoldedLine(textChunks, budget, [\n 'Tool: ',\n typeof output === 'string' ? output : serializeFoldedValue(output),\n ]);\n }\n continue;\n }\n\n // A `tool_result` content block (e.g. an AIMessage(tool_call) followed by a\n // user message carrying the result). Preserve nested image blocks as-is\n // instead of JSON-stringifying them through the generic fallback.\n if (blockType === 'tool_result') {\n hasToolUseBlock = true;\n const inner = readFoldedDataProperty(block, 'content') as\n | ToolResultContent['content']\n | undefined;\n if (typeof inner === 'string') {\n if (inner) {\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_result] `,\n inner,\n ]);\n }\n } else if (Array.isArray(inner)) {\n for (const innerBlock of inner as Array<\n string | ExtendedMessageContent\n >) {\n if (!consumeFoldedWork(textChunks, budget)) {\n break;\n }\n if (typeof innerBlock === 'string') {\n if (innerBlock) {\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_result] `,\n innerBlock,\n ]);\n }\n } else {\n const innerTypeValue = readFoldedDataProperty(innerBlock, 'type');\n const innerType =\n typeof innerTypeValue === 'string' ? innerTypeValue : undefined;\n if (\n isAtomicToolContentBlock(innerBlock) &&\n PORTABLE_FOLDED_MEDIA_TYPES.has(innerType ?? '')\n ) {\n const blockChars = getToolContentCharLength([innerBlock]);\n if (blockChars <= budget.remainingChars) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...innerBlock } as MessageContentComplex);\n budget.remainingChars -= blockChars;\n } else {\n appendFoldedLine(textChunks, budget, [\n `${role}: [${innerType ?? 'media'} omitted: folded context limit]`,\n ]);\n }\n } else {\n const textValue = readFoldedDataProperty(innerBlock, 'text');\n const inputValue = readFoldedDataProperty(innerBlock, 'input');\n const innerText = textValue ?? inputValue;\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_result] `,\n typeof innerText === 'string' && innerText\n ? innerText\n : serializeFoldedValue(innerBlock),\n ]);\n }\n }\n }\n } else if (inner != null) {\n appendFoldedLine(textChunks, budget, [\n `${role}: [tool_result] `,\n serializeFoldedValue(inner),\n ]);\n }\n continue;\n }\n\n const text =\n readFoldedDataProperty(block, 'text') ??\n readFoldedDataProperty(block, 'input');\n if (typeof text === 'string' && text) {\n appendFoldedLine(textChunks, budget, [`${role}: `, text]);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (blockType != null && blockType !== '') {\n appendFoldedLine(textChunks, budget, [\n `${role}: [${blockType}] `,\n serializeFoldedValue(block),\n ]);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks, budget);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n budget: FoldContextBudget\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (aiMsg.tool_calls && aiMsg.tool_calls.length > 0) {\n for (const tc of aiMsg.tool_calls) {\n if (!consumeFoldedWork(textChunks, budget)) {\n break;\n }\n const name = readFoldedDataProperty(tc, 'name');\n const args = readFoldedDataProperty(tc, 'args');\n appendFoldedLine(textChunks, budget, [\n `AI: [tool_call] ${typeof name === 'string' ? name : ''}(`,\n serializeFoldedValue(args),\n ')',\n ]);\n }\n return;\n }\n // Fall back to raw provider tool calls kept only in additional_kwargs.\n const rawToolCalls = aiMsg.additional_kwargs.tool_calls;\n if (!Array.isArray(rawToolCalls)) {\n return;\n }\n for (const tc of rawToolCalls) {\n if (!consumeFoldedWork(textChunks, budget)) {\n break;\n }\n const fn = readFoldedDataProperty(tc, 'function');\n if (fn == null) {\n continue;\n }\n const name = readFoldedDataProperty(fn, 'name');\n const args = readFoldedDataProperty(fn, 'arguments');\n appendFoldedLine(textChunks, budget, [\n `AI: [tool_call] ${typeof name === 'string' ? name : ''}(`,\n typeof args === 'string' ? args : '',\n ')',\n ]);\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @param config - Optional RunnableConfig for structured agent logging\n * @param runStartIndex - Index in `messages` where the CURRENT run's own\n * appended AI/Tool messages begin (i.e. anything at this index or later\n * was just produced by this run's own iterations, not historical\n * context). When provided, AI messages at or after this index are\n * never converted to `[Previous agent context]` placeholders — Claude\n * can validly skip a thinking block before a tool_use (cf. PR #116),\n * so the agent's own in-run iterations must not be misclassified as\n * foreign history. Without the signal the function falls back to its\n * prior heuristic (`chainHasThinkingBlock`), preserving backward\n * compatibility for callers that don't yet pass the boundary.\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers,\n config?: RunnableConfig,\n runStartIndex?: number\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // Find the last HumanMessage. Only the trailing sequence after it needs\n // validation — earlier messages are history already accepted by the provider.\n let lastHumanIndex = -1;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (\n m instanceof HumanMessage ||\n ('role' in m && (m as any).role === 'user')\n ) {\n lastHumanIndex = k;\n break;\n }\n }\n\n if (lastHumanIndex === messages.length - 1) {\n return messages;\n }\n\n const result: BaseMessage[] =\n lastHumanIndex >= 0 ? messages.slice(0, lastHumanIndex + 1) : [];\n const foldBudget = createFoldContextBudget();\n let i = lastHumanIndex + 1;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n const type = readFoldedDataProperty(c, 'type');\n if (type === 'tool_use') {\n hasToolUse = true;\n } else if (\n type === ContentTypes.THINKING ||\n type === ContentTypes.REASONING_CONTENT ||\n type === ContentTypes.REASONING ||\n type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Current-run boundary check: anything at or after `runStartIndex`\n // is the current run's own work — preserve it. Claude is allowed\n // to skip a thinking block before a tool_use (cf. PR #116 in the\n // agents repo), so the agent's own first-iteration AI message can\n // legitimately have tool_calls without reasoning. Converting it to\n // a `[Previous agent context]` placeholder pollutes the next\n // iteration's prompt — the LLM sees the placeholder, treats it as\n // suspicious injected content, ignores its own real prior tool\n // result, and re-runs the tool to verify (which then often fails\n // because subsequent calls land in fresh sandboxes without the\n // file). Skip the conversion when we know this is in-run.\n if (runStartIndex !== undefined && i >= runStartIndex) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = [];\n appendFoldedLine(textChunks, foldBudget, ['[Previous agent context]']);\n\n appendMessageContent(msg, 'AI', textChunks, parts, foldBudget);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(\n messages[j],\n 'Tool',\n textChunks,\n parts,\n foldBudget\n );\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n if (appendSyntheticProviderContextMessage(result, parts)) {\n emitAgentLog(\n config,\n 'warn',\n 'format',\n 'ensureThinkingBlockInMessages: injecting [Previous agent context] HumanMessage' +\n ` (${parts.length} msgs at index ${i}, no thinking block in chain)`\n );\n }\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/** Whether a message carries tool content a tool-less agent cannot legally\n * send. Covers every representation a provider converter will serialize back\n * into a request: a ToolMessage, parsed `AIMessage.tool_calls`, raw\n * `additional_kwargs.tool_calls` (OpenAI keeps calls here when the parsed\n * array is empty), and `tool_use` / `tool_call` / `tool_result` content\n * blocks (`@langchain/aws` and the Anthropic converter map these to Converse\n * `toolUse` / `toolResult`). Missing the parent AI message is not just a\n * passthrough: folding its ToolMessage alone would leave an orphan\n * `assistant(tool_calls) -> user(...)` sequence. */\nfunction messageHasToolContent(msg: BaseMessage): boolean {\n if (isToolMessage(msg)) {\n return true;\n }\n const aiMsg = msg as AIMessage;\n if (aiMsg.tool_calls != null && aiMsg.tool_calls.length > 0) {\n return true;\n }\n const rawToolCalls = aiMsg.additional_kwargs.tool_calls;\n if (Array.isArray(rawToolCalls) && rawToolCalls.length > 0) {\n return true;\n }\n if (Array.isArray(msg.content)) {\n for (const block of msg.content as ExtendedMessageContent[]) {\n const type = readFoldedDataProperty(block, 'type');\n if (\n typeof block === 'object' &&\n (type === 'tool_use' || type === 'tool_call' || type === 'tool_result')\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** Whether a message carries a tool RESULT: a ToolMessage, or a message whose\n * content includes a `tool_result` block (the shape when a call/result pair is\n * split as `AIMessage(tool_call)` + `HumanMessage(tool_result)`). Such a result\n * belongs with the preceding tool call, so it is absorbed into the same fold\n * and labelled as tool output. */\nfunction isToolResultMessage(msg: BaseMessage): boolean {\n if (isToolMessage(msg)) {\n return true;\n }\n if (Array.isArray(msg.content)) {\n return (msg.content as ExtendedMessageContent[]).some(\n (block) =>\n typeof block === 'object' &&\n readFoldedDataProperty(block, 'type') === 'tool_result'\n );\n }\n return false;\n}\n\n/**\n * Folds tool_use / tool_result content into plain text for an agent that binds\n * no tools.\n *\n * In a multi-agent graph, a tool-less destination still inherits the prior\n * agent's conversation history, which can contain toolUse/toolResult blocks.\n * Because it binds no tools, the model is invoked with no tool schema — and\n * Bedrock's Converse API rejects any request that carries toolUse/toolResult\n * blocks without a top-level toolConfig (\"The toolConfig field must be defined\n * when using toolUse and toolResult content blocks\"). Adding a dummy toolConfig\n * is not an option: AWS requires at least one tool, and it would expose a\n * capability the destination was intentionally denied.\n *\n * Each tool-call turn plus its trailing tool results (ToolMessages or\n * `tool_result` content blocks) is collapsed into a single `[Previous tool\n * interaction]` HumanMessage that preserves the tool name, arguments and result\n * as text (image blocks are kept as-is). Runs in a single pass: non-tool\n * messages pass through, `result` is allocated lazily on the first fold, and the\n * original array is returned unchanged when it holds no tool content (the common\n * fresh-tool-less-agent case).\n */\nexport function foldToolBlocksForToollessAgent(\n messages: BaseMessage[],\n config?: RunnableConfig\n): BaseMessage[] {\n let result: BaseMessage[] | null = null;\n let foldedCount = 0;\n const foldBudget = createFoldContextBudget();\n let i = 0;\n while (i < messages.length) {\n const msg = messages[i];\n if (!messageHasToolContent(msg)) {\n result?.push(msg);\n i++;\n continue;\n }\n\n /** First fold — copy the untouched prefix once, then append from here. */\n if (result === null) {\n result = messages.slice(0, i);\n }\n\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = [];\n appendFoldedLine(textChunks, foldBudget, ['[Previous tool interaction]']);\n appendMessageContent(\n msg,\n isToolResultMessage(msg) ? 'Tool' : 'AI',\n textChunks,\n parts,\n foldBudget\n );\n foldedCount++;\n\n let j = i + 1;\n while (j < messages.length && isToolResultMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts, foldBudget);\n foldedCount++;\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n appendSyntheticProviderContextMessage(result, parts);\n i = j;\n }\n\n if (result === null) {\n return messages;\n }\n\n emitAgentLog(\n config,\n 'warn',\n 'format',\n `foldToolBlocksForToollessAgent: folded ${foldedCount} tool message(s) into text for a tool-less agent`\n );\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are part of the chain — keep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,CAAC;EAC9B,iBAAiB,YAAY,YAAY,CAAC,6BAA6B,CAAC;EACxE,qBACE,KACA,oBAAoB,GAAG,IAAI,SAAS,MACpC,YACA,OACA,UACF;EACA;EAEA,IAAI,IAAI,IAAI;EACZ,OAAO,IAAI,SAAS,UAAU,oBAAoB,SAAS,EAAE,GAAG;GAC9D,qBAAqB,SAAS,IAAI,QAAQ,YAAY,OAAO,UAAU;GACvE;GACA;EACF;EAEA,gBAAgB,YAAY,KAAK;EACjC,sCAAsC,QAAQ,KAAK;EACnD,IAAI;CACN;CAEA,IAAI,WAAW,MACb,OAAO;CAGT,eAAA,aACE,QACA,QACA,UACA,0CAA0C,YAAY,iDACxD;CAEA,OAAO;AACT;;;;;;;;;;;;AAaA,SAAS,sBACP,UACA,cACS;CACT,KAAK,IAAI,IAAI,eAAe,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,SAAS;EAGtB,IACE,gBAAgBZ,yBAAAA,gBACf,UAAU,QAAS,KAAa,SAAS,QAE1C,OAAO;EAST,IAJE,gBAAgBE,yBAAAA,aAChB,gBAAgBU,yBAAAA,kBACf,UAAU,QAAS,KAAa,SAAS,aAE9B;GACZ,MAAM,YAAY;GAElB,IAAI,MAAM,QAAQ,UAAU,OAAO,KAAK,UAAU,QAAQ,SAAS;QACjD,UAAU,QAEhB,MACL,MACC,OAAO,MAAM,aACZ,EAAE,SAAA,cACD,EAAE,SAAA,uBACF,EAAE,SAAA,eACF,EAAE,SAAS,oBACjB,GAEA,OAAO;GAAA;GAKX,IAAI,UAAU,kBAAkB,qBAAqB,MACnD,OAAO;EAEX;CAGF;CAEA,OAAO;AACT"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
require("./cache.cjs");
|
|
1
2
|
require("./core.cjs");
|
|
2
3
|
require("./ids.cjs");
|
|
3
4
|
require("./contextPruningSettings.cjs");
|
|
@@ -5,7 +6,6 @@ require("./contextPruning.cjs");
|
|
|
5
6
|
require("./prune.cjs");
|
|
6
7
|
require("./budget.cjs");
|
|
7
8
|
require("./format.cjs");
|
|
8
|
-
require("./cache.cjs");
|
|
9
9
|
require("./anthropicToolCache.cjs");
|
|
10
10
|
require("./content.cjs");
|
|
11
11
|
require("./tools.cjs");
|