@librechat/agents 3.2.68 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +1 -1
  2. package/dist/cjs/common/enum.cjs +2 -0
  3. package/dist/cjs/common/enum.cjs.map +1 -1
  4. package/dist/cjs/graphs/Graph.cjs +14 -1
  5. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  6. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  7. package/dist/cjs/langfuseToolOutputTracing.cjs +4 -0
  8. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +1 -1
  10. package/dist/cjs/main.cjs +1 -0
  11. package/dist/cjs/messages/format.cjs +136 -4
  12. package/dist/cjs/messages/format.cjs.map +1 -1
  13. package/dist/cjs/prompts/activityLabel.cjs +101 -0
  14. package/dist/cjs/prompts/activityLabel.cjs.map +1 -0
  15. package/dist/cjs/run.cjs +162 -1
  16. package/dist/cjs/run.cjs.map +1 -1
  17. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -1
  18. package/dist/esm/agents/AgentContext.mjs +1 -1
  19. package/dist/esm/common/enum.mjs +2 -0
  20. package/dist/esm/common/enum.mjs.map +1 -1
  21. package/dist/esm/graphs/Graph.mjs +15 -2
  22. package/dist/esm/graphs/Graph.mjs.map +1 -1
  23. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  24. package/dist/esm/langfuseToolOutputTracing.mjs +4 -1
  25. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  26. package/dist/esm/llm/openai/index.mjs +1 -1
  27. package/dist/esm/main.mjs +2 -2
  28. package/dist/esm/messages/format.mjs +136 -5
  29. package/dist/esm/messages/format.mjs.map +1 -1
  30. package/dist/esm/prompts/activityLabel.mjs +100 -0
  31. package/dist/esm/prompts/activityLabel.mjs.map +1 -0
  32. package/dist/esm/run.mjs +163 -2
  33. package/dist/esm/run.mjs.map +1 -1
  34. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -1
  35. package/dist/types/common/enum.d.ts +3 -1
  36. package/dist/types/langfuseToolOutputTracing.d.ts +4 -0
  37. package/dist/types/messages/format.d.ts +22 -0
  38. package/dist/types/prompts/activityLabel.d.ts +31 -0
  39. package/dist/types/run.d.ts +14 -0
  40. package/dist/types/types/activityLabel.d.ts +53 -0
  41. package/dist/types/types/index.d.ts +1 -0
  42. package/dist/types/types/stream.d.ts +2 -0
  43. package/package.json +1 -1
  44. package/src/common/enum.ts +2 -0
  45. package/src/graphs/Graph.ts +20 -0
  46. package/src/langfuseToolOutputTracing.ts +4 -1
  47. package/src/messages/foldToollessToolBlocks.test.ts +438 -0
  48. package/src/messages/format.ts +233 -5
  49. package/src/prompts/activityLabel.ts +177 -0
  50. package/src/run.ts +298 -2
  51. package/src/specs/activity-label-prompt.test.ts +128 -0
  52. package/src/specs/activity-label-trace-seed.test.ts +47 -0
  53. package/src/specs/bedrock-toolless.live.test.ts +123 -0
  54. package/src/types/activityLabel.ts +55 -0
  55. package/src/types/index.ts +1 -0
  56. package/src/types/stream.ts +2 -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 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 ) {\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 ) {\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 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 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 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 return;\n }\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\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/**\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":";;;;;;;;;;;;;AAkDA,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,QAAQ;EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;AACT;;;;;;;AAeA,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E,SAASI,kBAAAA,mBAAmB,KAAK,EAAE,CAAC,GACvD,MACF,CACF;GACA,IAAI;EACN,OAAO;GAEL,OAAO,KAAK,GAAG;GACf;EACF;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;AAaA,SAAS,sBACP,UACA,cACS;CACT,KAAK,IAAI,IAAI,eAAe,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,SAAS;EAGtB,IACE,gBAAgBJ,yBAAAA,gBACf,UAAU,QAAS,KAAa,SAAS,QAE1C,OAAO;EAST,IAJE,gBAAgBE,yBAAAA,aAChB,gBAAgBK,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
+ {"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,IAA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B;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"}
@@ -0,0 +1,101 @@
1
+ const require_langfuseToolOutputTracing = require("../langfuseToolOutputTracing.cjs");
2
+ //#region src/prompts/activityLabel.ts
3
+ /**
4
+ * Default system prompt for fast-model activity labeling.
5
+ *
6
+ * Style synthesized from Claude Code's tool-use summary prompt (git-subject
7
+ * register, past tense, distinctive nouns) and claude.ai's observed group
8
+ * headers (5–9 words describing a mixed reasoning + tool block, e.g.
9
+ * "Synthesized version data and curated comparative framework").
10
+ */
11
+ const ACTIVITY_LABEL_PROMPT = `Write a short label describing what this block of agent activity accomplished. It appears as the header of a collapsed activity group in a chat UI.
12
+
13
+ Rules:
14
+ - 5 to 9 words, past-tense verb first
15
+ - Name the most distinctive subject (file, API, topic); drop articles and filler
16
+ - Describe outcomes, not mechanics; if something failed, say so plainly
17
+ - Output only the label — no quotes, no punctuation at the end, no preamble
18
+
19
+ Examples:
20
+ - Searched Node.js release notes and changelogs
21
+ - Compared runtime versions across official sources
22
+ - Fixed failing auth middleware tests
23
+ - Read project config and dependency manifests
24
+ - Attempted database migration, hit permission errors`;
25
+ /** Truncates a serialized value for the label prompt. */
26
+ function truncateForLabel(value, maxLength) {
27
+ if (value.length <= maxLength) return value;
28
+ return value.slice(0, Math.max(0, maxLength - 1)) + "…";
29
+ }
30
+ const ABORT_SERIALIZATION = Symbol("abort-label-serialization");
31
+ /**
32
+ * Serializes a tool value for the prompt WITHOUT materializing huge JSON:
33
+ * the output is clipped to a few hundred characters anyway, so a multi-
34
+ * megabyte tool result must not be stringified in full on the label path.
35
+ * Strings clip immediately; structured values serialize under a character
36
+ * budget and degrade to a shape summary once it is exhausted.
37
+ */
38
+ function serializeForLabel(value, limit) {
39
+ if (value == null) return "";
40
+ if (typeof value === "string") return value.length > limit ? value.slice(0, limit + 1) : value;
41
+ let budget = limit * 4;
42
+ try {
43
+ return JSON.stringify(value, (_key, nested) => {
44
+ if (budget <= 0) throw ABORT_SERIALIZATION;
45
+ if (typeof nested === "string") {
46
+ const clipped = nested.length > limit ? nested.slice(0, limit) : nested;
47
+ budget -= clipped.length;
48
+ return clipped;
49
+ }
50
+ budget -= 8;
51
+ return nested;
52
+ }) ?? "";
53
+ } catch (error) {
54
+ if (error === ABORT_SERIALIZATION) return Array.isArray(value) ? `[Array(${value.length})]` : "[Object]";
55
+ return String(value);
56
+ }
57
+ }
58
+ const INPUT_CONTEXT_LIMIT = 200;
59
+ const MAX_THINKING_EXCERPTS = 4;
60
+ /** A label is 5-9 words; no batch needs more than this many entries to
61
+ * produce one, and the cap keeps a 200-call programmatic batch from
62
+ * building an enormous prompt out of per-field-bounded pieces. */
63
+ const MAX_PROMPT_ENTRIES = 12;
64
+ /**
65
+ * Builds the user prompt for a fast-model activity label. Pure — exported
66
+ * for direct testing of redaction and truncation behavior.
67
+ */
68
+ function buildActivityLabelPrompt({ entries, charLimit, thinkingExcerpts, lastAssistantText, redaction }) {
69
+ const clip = truncateForLabel;
70
+ /** Reasoning and intent text can quote tool output verbatim — including
71
+ * output from EARLIER calls to a redacted tool that this batch does not
72
+ * contain — so any active policy (global disable or a configured
73
+ * redacted-name list) drops both wholesale. There is no reliable way to
74
+ * scrub a quoted fragment out of free-form model prose. */
75
+ const excerptsRedacted = redaction != null && (redaction.enabled === false || redaction.redactedToolNames.size > 0);
76
+ const sections = [];
77
+ /** Intent text is free-form assistant prose that can quote a redacted
78
+ * tool result just as reasoning can, so it shares the excerpts' fate. */
79
+ if (!excerptsRedacted && lastAssistantText != null && lastAssistantText.length > 0) sections.push(`Intent (assistant's last message): ${clip(lastAssistantText, INPUT_CONTEXT_LIMIT)}`);
80
+ if (!excerptsRedacted && thinkingExcerpts != null && thinkingExcerpts.length > 0) sections.push("Reasoning excerpts:\n" + thinkingExcerpts.slice(0, MAX_THINKING_EXCERPTS).map((excerpt) => `- ${clip(excerpt, charLimit)}`).join("\n"));
81
+ if (entries.length > 0) {
82
+ const shown = entries.slice(0, MAX_PROMPT_ENTRIES);
83
+ const omitted = entries.length - shown.length;
84
+ sections.push("Tool calls:\n" + shown.map((entry) => {
85
+ const input = clip(serializeForLabel(entry.toolInput, charLimit), charLimit);
86
+ const redacted = redaction != null && require_langfuseToolOutputTracing.shouldRedactTool(entry.toolName, redaction);
87
+ let outcome;
88
+ if (redacted) outcome = redaction.redactionText;
89
+ else if (entry.status === "error") outcome = `ERROR: ${clip(entry.error ?? "unknown error", charLimit)}`;
90
+ else outcome = clip(serializeForLabel(entry.toolOutput, charLimit), charLimit);
91
+ return `- ${entry.toolName}(${input}) → ${outcome}`;
92
+ }).join("\n") + (omitted > 0 ? `\n- …and ${omitted} more tool ${omitted === 1 ? "call" : "calls"}` : ""));
93
+ }
94
+ sections.push("Label:");
95
+ return sections.join("\n\n");
96
+ }
97
+ //#endregion
98
+ exports.ACTIVITY_LABEL_PROMPT = ACTIVITY_LABEL_PROMPT;
99
+ exports.buildActivityLabelPrompt = buildActivityLabelPrompt;
100
+
101
+ //# sourceMappingURL=activityLabel.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"activityLabel.cjs","names":["shouldRedactTool"],"sources":["../../../src/prompts/activityLabel.ts"],"sourcesContent":["import type { ResolvedLangfuseToolOutputTracingConfig } from '@/langfuseRuntimeContext';\nimport type { ActivityLabelToolEntry } from '@/types/activityLabel';\nimport { shouldRedactTool } from '@/langfuseToolOutputTracing';\n\n/**\n * Default system prompt for fast-model activity labeling.\n *\n * Style synthesized from Claude Code's tool-use summary prompt (git-subject\n * register, past tense, distinctive nouns) and claude.ai's observed group\n * headers (5–9 words describing a mixed reasoning + tool block, e.g.\n * \"Synthesized version data and curated comparative framework\").\n */\nexport const ACTIVITY_LABEL_PROMPT = `Write a short label describing what this block of agent activity accomplished. It appears as the header of a collapsed activity group in a chat UI.\n\nRules:\n- 5 to 9 words, past-tense verb first\n- Name the most distinctive subject (file, API, topic); drop articles and filler\n- Describe outcomes, not mechanics; if something failed, say so plainly\n- Output only the label — no quotes, no punctuation at the end, no preamble\n\nExamples:\n- Searched Node.js release notes and changelogs\n- Compared runtime versions across official sources\n- Fixed failing auth middleware tests\n- Read project config and dependency manifests\n- Attempted database migration, hit permission errors`;\n\n/** Truncates a serialized value for the label prompt. */\nexport function truncateForLabel(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return value.slice(0, Math.max(0, maxLength - 1)) + '…';\n}\n\nconst ABORT_SERIALIZATION = Symbol('abort-label-serialization');\n\n/**\n * Serializes a tool value for the prompt WITHOUT materializing huge JSON:\n * the output is clipped to a few hundred characters anyway, so a multi-\n * megabyte tool result must not be stringified in full on the label path.\n * Strings clip immediately; structured values serialize under a character\n * budget and degrade to a shape summary once it is exhausted.\n */\nfunction serializeForLabel(value: unknown, limit: number): string {\n if (value == null) {\n return '';\n }\n if (typeof value === 'string') {\n return value.length > limit ? value.slice(0, limit + 1) : value;\n }\n let budget = limit * 4;\n try {\n return (\n JSON.stringify(value, (_key, nested: unknown) => {\n if (budget <= 0) {\n throw ABORT_SERIALIZATION;\n }\n if (typeof nested === 'string') {\n const clipped =\n nested.length > limit ? nested.slice(0, limit) : nested;\n budget -= clipped.length;\n return clipped;\n }\n budget -= 8;\n return nested;\n }) ?? ''\n );\n } catch (error) {\n if (error === ABORT_SERIALIZATION) {\n return Array.isArray(value) ? `[Array(${value.length})]` : '[Object]';\n }\n return String(value);\n }\n}\n\nconst INPUT_CONTEXT_LIMIT = 200;\nconst MAX_THINKING_EXCERPTS = 4;\n/** A label is 5-9 words; no batch needs more than this many entries to\n * produce one, and the cap keeps a 200-call programmatic batch from\n * building an enormous prompt out of per-field-bounded pieces. */\nconst MAX_PROMPT_ENTRIES = 12;\n\nexport type BuildActivityLabelPromptParams = {\n entries: ActivityLabelToolEntry[];\n charLimit: number;\n thinkingExcerpts?: string[];\n lastAssistantText?: string;\n /**\n * Resolved tool-output tracing policy. The label prompt becomes Langfuse\n * generation input, so outputs/errors excluded from tracing (global\n * disable or `redactedToolNames`) must never appear in it — the same\n * redaction the span processor applies to structured tool observations.\n */\n redaction?: ResolvedLangfuseToolOutputTracingConfig;\n};\n\n/**\n * Builds the user prompt for a fast-model activity label. Pure — exported\n * for direct testing of redaction and truncation behavior.\n */\nexport function buildActivityLabelPrompt({\n entries,\n charLimit,\n thinkingExcerpts,\n lastAssistantText,\n redaction,\n}: BuildActivityLabelPromptParams): string {\n const clip = truncateForLabel;\n /** Reasoning and intent text can quote tool output verbatim — including\n * output from EARLIER calls to a redacted tool that this batch does not\n * contain — so any active policy (global disable or a configured\n * redacted-name list) drops both wholesale. There is no reliable way to\n * scrub a quoted fragment out of free-form model prose. */\n const excerptsRedacted =\n redaction != null &&\n (redaction.enabled === false || redaction.redactedToolNames.size > 0);\n const sections: string[] = [];\n /** Intent text is free-form assistant prose that can quote a redacted\n * tool result just as reasoning can, so it shares the excerpts' fate. */\n if (\n !excerptsRedacted &&\n lastAssistantText != null &&\n lastAssistantText.length > 0\n ) {\n sections.push(\n `Intent (assistant's last message): ${clip(lastAssistantText, INPUT_CONTEXT_LIMIT)}`\n );\n }\n if (\n !excerptsRedacted &&\n thinkingExcerpts != null &&\n thinkingExcerpts.length > 0\n ) {\n sections.push(\n 'Reasoning excerpts:\\n' +\n thinkingExcerpts\n .slice(0, MAX_THINKING_EXCERPTS)\n .map((excerpt) => `- ${clip(excerpt, charLimit)}`)\n .join('\\n')\n );\n }\n if (entries.length > 0) {\n const shown = entries.slice(0, MAX_PROMPT_ENTRIES);\n const omitted = entries.length - shown.length;\n sections.push(\n 'Tool calls:\\n' +\n shown\n .map((entry) => {\n const input = clip(\n serializeForLabel(entry.toolInput, charLimit),\n charLimit\n );\n const redacted =\n redaction != null && shouldRedactTool(entry.toolName, redaction);\n let outcome: string;\n if (redacted) {\n outcome = redaction.redactionText;\n } else if (entry.status === 'error') {\n outcome = `ERROR: ${clip(entry.error ?? 'unknown error', charLimit)}`;\n } else {\n outcome = clip(\n serializeForLabel(entry.toolOutput, charLimit),\n charLimit\n );\n }\n return `- ${entry.toolName}(${input}) → ${outcome}`;\n })\n .join('\\n') +\n (omitted > 0\n ? `\\n- …and ${omitted} more tool ${omitted === 1 ? 'call' : 'calls'}`\n : '')\n );\n }\n sections.push('Label:');\n return sections.join('\\n\\n');\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,wBAAwB;;;;;;;;;;;;;;;AAgBrC,SAAgB,iBAAiB,OAAe,WAA2B;CACzE,IAAI,MAAM,UAAU,WAClB,OAAO;CAET,OAAO,MAAM,MAAM,GAAG,KAAK,IAAI,GAAG,YAAY,CAAC,CAAC,IAAI;AACtD;AAEA,MAAM,sBAAsB,OAAO,2BAA2B;;;;;;;;AAS9D,SAAS,kBAAkB,OAAgB,OAAuB;CAChE,IAAI,SAAS,MACX,OAAO;CAET,IAAI,OAAO,UAAU,UACnB,OAAO,MAAM,SAAS,QAAQ,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI;CAE5D,IAAI,SAAS,QAAQ;CACrB,IAAI;EACF,OACE,KAAK,UAAU,QAAQ,MAAM,WAAoB;GAC/C,IAAI,UAAU,GACZ,MAAM;GAER,IAAI,OAAO,WAAW,UAAU;IAC9B,MAAM,UACJ,OAAO,SAAS,QAAQ,OAAO,MAAM,GAAG,KAAK,IAAI;IACnD,UAAU,QAAQ;IAClB,OAAO;GACT;GACA,UAAU;GACV,OAAO;EACT,CAAC,KAAK;CAEV,SAAS,OAAO;EACd,IAAI,UAAU,qBACZ,OAAO,MAAM,QAAQ,KAAK,IAAI,UAAU,MAAM,OAAO,MAAM;EAE7D,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,M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