@librechat/agents 3.0.17 → 3.0.18

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.
@@ -1 +1 @@
1
- {"version":3,"file":"format.cjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n MessageContentComplex,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes } from '@/common';\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\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 | HumanMessage\n | AIMessage\n | 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 new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\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<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | 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\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\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 let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ 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 = new AIMessage({\n content: part.text || '',\n });\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) {\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 (!_tool_call.name && (output == null || output === '')) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(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 (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output || '',\n })\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\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 * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number>,\n tools?: Set<string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[]> = {};\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\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.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\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 // If tools set is provided, we need to check if we need to convert tool messages to a string\n if (tools) {\n // First, check if this message contains tool calls\n let hasToolCalls = false;\n let hasInvalidTool = false;\n const toolNames: string[] = [];\n\n const content = message.content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n hasToolCalls = true;\n if (tools.size === 0) {\n hasInvalidTool = true;\n break;\n }\n // Protect against malformed tool call entries\n if (\n !part.tool_call ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n hasInvalidTool = true;\n continue;\n }\n const toolName = part.tool_call.name;\n toolNames.push(toolName);\n if (!tools.has(toolName)) {\n hasInvalidTool = true;\n }\n }\n }\n }\n\n // If this message has tool calls and at least one is invalid, we need to convert it\n if (hasToolCalls && hasInvalidTool) {\n // We need to collect all related messages (this message and any subsequent tool messages)\n const toolSequence: BaseMessage[] = [];\n let sequenceEndIndex = i;\n\n // Process the current assistant message to get the AIMessage with tool calls\n const formattedMessages = formatAssistantMessage(message);\n toolSequence.push(...formattedMessages);\n\n // Look ahead for any subsequent assistant messages that might be part of this tool sequence\n let j = i + 1;\n while (j < payload.length && payload[j].role === 'assistant') {\n // Check if this is a continuation of the tool sequence\n let isToolResponse = false;\n const content = payload[j].content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n isToolResponse = true;\n break;\n }\n }\n }\n\n if (isToolResponse) {\n // This is part of the tool sequence, add it\n const nextMessages = formatAssistantMessage(payload[j]);\n toolSequence.push(...nextMessages);\n sequenceEndIndex = j;\n j++;\n } else {\n // This is not part of the tool sequence, stop looking\n break;\n }\n }\n\n // Convert the sequence to a string\n const bufferString = getBufferString(toolSequence);\n messages.push(new AIMessage({ content: bufferString }));\n\n // Skip the messages we've already processed\n i = sequenceEndIndex;\n\n // Update the index mapping for this sequence\n const resultIndices = [messages.length - 1];\n for (let k = i; k >= i && k <= sequenceEndIndex; k++) {\n indexMapping[k] = resultIndices;\n }\n\n continue;\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(message);\n messages.push(...formattedMessages);\n\n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] =\n tokenCount - countPerMessage * (resultIndices.length - 1);\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\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"],"names":["Providers","ContentTypes","HumanMessage","AIMessage","SystemMessage","ToolMessage","messages","getBufferString"],"mappings":";;;;;AAAA;AA8BA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAKA,eAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAEC,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;;IAGf,MAAM,CAAC,OAAO,GAAG;QACf,EAAE,IAAI,EAAEA,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;AAClD,QAAA,GAAG,UAAU;KACa;AAE5B,IAAA,OAAO,MAAM;AACf;AA+BA;;;;;AAKG;AACU,MAAA,aAAa,GAAG,CAAC,EAC5B,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,aAAa,EACb,SAAS,GAAG,KAAK,GACG,KAIF;;AAElB,IAAA,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO;IAC5E,IAAI,KAAK,IAAI,K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;;AAE5D,qBAAC,CAAC;;;;;IAMV,OAAO;kBACLA,UAAQ;AACR,QAAA,kBAAkB,EAAE;AAClB,cAAE;AACF,cAAE,SAAS;KACd;AACH;AAEA;;;;;;;AAOG;AACa,SAAA,uBAAuB,CACrC,kBAA0C,EAC1C,sBAA8B,EAAA;;IAG9B,MAAM,UAAU,GAA2B,EAAE;AAC7C,IAAA,UAAU,CAAC,CAAC,CAAC,GAAG,sBAAsB;;AAGtC,IAAA,KAAK,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE;AACvE,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC9B,QAAA,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,UAAU;;AAGpC,IAAA,OAAO,UAAU;AACnB;;;;;;;;;"}
1
+ {"version":3,"file":"format.cjs","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 getBufferString,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes } from '@/common';\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\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 | HumanMessage\n | AIMessage\n | 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 new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\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<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | 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\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\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 let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ 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 = new AIMessage({\n content: part.text || '',\n });\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) {\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 (!_tool_call.name && (output == null || output === '')) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(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 (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output || '',\n })\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\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 * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number>,\n tools?: Set<string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[]> = {};\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\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.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\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 // If tools set is provided, we need to check if we need to convert tool messages to a string\n if (tools) {\n // First, check if this message contains tool calls\n let hasToolCalls = false;\n let hasInvalidTool = false;\n const toolNames: string[] = [];\n\n const content = message.content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n hasToolCalls = true;\n if (tools.size === 0) {\n hasInvalidTool = true;\n break;\n }\n // Protect against malformed tool call entries\n if (\n !part.tool_call ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n hasInvalidTool = true;\n continue;\n }\n const toolName = part.tool_call.name;\n toolNames.push(toolName);\n if (!tools.has(toolName)) {\n hasInvalidTool = true;\n }\n }\n }\n }\n\n // If this message has tool calls and at least one is invalid, we need to convert it\n if (hasToolCalls && hasInvalidTool) {\n // We need to collect all related messages (this message and any subsequent tool messages)\n const toolSequence: BaseMessage[] = [];\n let sequenceEndIndex = i;\n\n // Process the current assistant message to get the AIMessage with tool calls\n const formattedMessages = formatAssistantMessage(message);\n toolSequence.push(...formattedMessages);\n\n // Look ahead for any subsequent assistant messages that might be part of this tool sequence\n let j = i + 1;\n while (j < payload.length && payload[j].role === 'assistant') {\n // Check if this is a continuation of the tool sequence\n let isToolResponse = false;\n const content = payload[j].content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part.type === ContentTypes.TOOL_CALL) {\n isToolResponse = true;\n break;\n }\n }\n }\n\n if (isToolResponse) {\n // This is part of the tool sequence, add it\n const nextMessages = formatAssistantMessage(payload[j]);\n toolSequence.push(...nextMessages);\n sequenceEndIndex = j;\n j++;\n } else {\n // This is not part of the tool sequence, stop looking\n break;\n }\n }\n\n // Convert the sequence to a string\n const bufferString = getBufferString(toolSequence);\n messages.push(new AIMessage({ content: bufferString }));\n\n // Skip the messages we've already processed\n i = sequenceEndIndex;\n\n // Update the index mapping for this sequence\n const resultIndices = [messages.length - 1];\n for (let k = i; k >= i && k <= sequenceEndIndex; k++) {\n indexMapping[k] = resultIndices;\n }\n\n continue;\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(message);\n messages.push(...formattedMessages);\n\n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] =\n tokenCount - countPerMessage * (resultIndices.length - 1);\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\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/**\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 blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\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): BaseMessage[] {\n const result: BaseMessage[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n const isAI = msg instanceof AIMessage || msg instanceof AIMessageChunk;\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 firstContentType: string | undefined;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n const content = aiMsg.content as ExtendedMessageContent[];\n firstContentType = content[0]?.type;\n hasToolUse =\n hasToolUse ||\n content.some((c) => typeof c === 'object' && c.type === 'tool_use');\n }\n\n // If message has tool use but no thinking block, convert to buffer string\n if (\n hasToolUse &&\n firstContentType !== ContentTypes.THINKING &&\n firstContentType !== 'redacted_thinking'\n ) {\n // Collect the AI message and any following tool messages\n const toolSequence: BaseMessage[] = [msg];\n let j = i + 1;\n\n // Look ahead for tool messages that belong to this AI message\n while (j < messages.length && messages[j] instanceof ToolMessage) {\n toolSequence.push(messages[j]);\n j++;\n }\n\n // Convert the sequence to a buffer string and wrap in a HumanMessage\n // This avoids the thinking block requirement which only applies to AI messages\n const bufferString = getBufferString(toolSequence);\n result.push(\n new HumanMessage({\n content: `[Previous agent context]\\n${bufferString}`,\n })\n );\n\n // Skip the messages we've processed\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"],"names":["Providers","ContentTypes","HumanMessage","AIMessage","SystemMessage","ToolMessage","messages","getBufferString","AIMessageChunk"],"mappings":";;;;;AAAA;AAgCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAKA,eAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAEC,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;;IAGf,MAAM,CAAC,OAA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Y,CAAC;AAClD,YAAA,MAAM,CAAC,IAAI,CACT,IAAIL,qBAAY,CAAC;gBACf,OAAO,EAAE,CAA6B,0BAAA,EAAA,YAAY,CAAE,CAAA;AACrD,aAAA,CAAC,CACH;;YAGD,CAAC,GAAG,CAAC;;aACA;;AAEL,YAAA,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;AAChB,YAAA,CAAC,EAAE;;;AAIP,IAAA,OAAO,MAAM;AACf;;;;;;;;;;"}
@@ -122,6 +122,7 @@ class ChatModelStreamHandler {
122
122
  graph,
123
123
  stepKey,
124
124
  toolCallChunks: chunk.tool_call_chunks,
125
+ metadata,
125
126
  });
126
127
  }
127
128
  if (isEmptyContent) {
@@ -134,7 +135,7 @@ class ChatModelStreamHandler {
134
135
  message_creation: {
135
136
  message_id,
136
137
  },
137
- });
138
+ }, metadata);
138
139
  }
139
140
  const stepId = graph.getStepIdByKey(stepKey);
140
141
  const runStep = graph.getRunStep(stepId);
@@ -197,7 +198,7 @@ hasToolCallChunks: ${hasToolCallChunks}
197
198
  message_creation: {
198
199
  message_id,
199
200
  },
200
- });
201
+ }, metadata);
201
202
  const newStepId = graph.getStepIdByKey(newStepKey);
202
203
  await graph.dispatchMessageDelta(newStepId, {
203
204
  content: [
@@ -1 +1 @@
1
- {"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null && tc.id !== '' && tc.name != null && tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["Providers","handleServerToolResult","handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC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Y,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;"}
1
+ {"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null && tc.id !== '' && tc.name != null && tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["Providers","handleServerToolResult","handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;YACvC;;;AAIF,QAAA,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,EAAE,QAAQ,CAAC;AAC5D,QAAA,cAAc,CAAC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;AAEC,aAAA,IAAI,KAAK,KAAKE,iBAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;"}
@@ -10,7 +10,7 @@ var ids = require('../messages/ids.cjs');
10
10
 
11
11
  /* eslint-disable no-console */
12
12
  // src/tools/handlers.ts
13
- async function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
13
+ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, metadata, }) {
14
14
  let prevStepId;
15
15
  let prevRunStep;
16
16
  try {
@@ -25,7 +25,7 @@ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
25
25
  message_creation: {
26
26
  message_id,
27
27
  },
28
- });
28
+ }, metadata);
29
29
  prevRunStep = graph.getRunStep(prevStepId);
30
30
  }
31
31
  const _stepId = graph.getStepIdByKey(stepKey);
@@ -69,7 +69,7 @@ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
69
69
  stepId = await graph.dispatchRunStep(stepKey, {
70
70
  type: _enum.StepTypes.TOOL_CALLS,
71
71
  tool_calls,
72
- });
72
+ }, metadata);
73
73
  }
74
74
  await graph.dispatchRunStepDelta(stepId, {
75
75
  type: _enum.StepTypes.TOOL_CALLS,
@@ -130,14 +130,14 @@ const handleToolCalls = async (toolCalls, metadata, graph) => {
130
130
  message_creation: {
131
131
  message_id: messageId,
132
132
  },
133
- });
133
+ }, metadata);
134
134
  await dispatchToolCallIds(stepId);
135
135
  graph.messageStepHasToolCalls.set(prevStepId, true);
136
136
  }
137
137
  await graph.dispatchRunStep(stepKey, {
138
138
  type: _enum.StepTypes.TOOL_CALLS,
139
139
  tool_calls: [tool_call],
140
- });
140
+ }, metadata);
141
141
  }
142
142
  };
143
143
  const toolResultTypes = new Set([
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.cjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { MultiAgentGraph, StandardGraph } from '@/graphs';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport async function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): Promise<void> {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n await graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n await graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = async (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n): Promise<void> => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = async (\n lastMessageStepId: string\n ): Promise<void> => {\n await graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n await dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n await dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport async function handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): Promise<boolean> {\n let skipHandling = false;\n if (agentContext?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n await handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nasync function handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: StandardGraph | MultiAgentGraph;\n}): Promise<void> {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":["getMessageId","StepTypes","ToolCallTypes","ContentTypes","nanoid","Providers","isAnthropicWebSearchResult","coerceAnthropicSearchResults","Constants","formatResultsForLLM","ToolMessage","GraphEvents"],"mappings":";;;;;;;;;;AAAA;AACA;AAuBO,eAAe,oBAAoB,CAAC,EACzC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC;AAC1C,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAC1C,IAAA,MAAM;;AAEN,QAAA,MAAM,UAAU,GAAGA,gBAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC3D,QAAA,UAAU,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;YAChD,IAAI,EAAEC,eAAS,CAAC,gBAAgB;AAChC,YAAA,gBAAgB,EAAE;gBAChB,UAAU;AACX,aAAA;AACF,SAAA,CAAC;AACF,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CA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QAAQ,CAAC,IAAI;AAC1B,IAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,MAAM,QAAQ,GAAG;AACf,QAAA,CAACC,eAAS,CAAC,UAAU,GAAG,gBAAgB;KACzC;AACD,IAAA,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAGC,0BAAmB,CACrD,IAAI,EACJ,gBAAgB,CACjB;AACD,IAAA,MAAM,MAAM,GAAG,IAAIC,oBAAW,CAAC;QAC7B,IAAI;QACJ,QAAQ;AACR,QAAA,OAAO,EAAE,eAAe;QACxB,YAAY,EAAE,QAAQ,CAAC,EAAG;AAC3B,KAAA,CAAC;AACF,IAAA,MAAM,WAAW,GAAkB;QACjC,KAAK;QACL,MAAM;KACP;IACD,MAAM,KAAK,CAAC;AACV,UAAE,UAAU,CAACC,iBAAW,CAAC,QAAQ;AACjC,UAAE,MAAM,CAACA,iBAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,CAAC;AAE9D,IAAA,IAAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;;;;"}
1
+ {"version":3,"file":"handlers.cjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { MultiAgentGraph, StandardGraph } from '@/graphs';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport async function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n metadata,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n await graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n },\n metadata\n );\n }\n await graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = async (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n): Promise<void> => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = async (\n lastMessageStepId: string\n ): Promise<void> => {\n await graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n await dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n await dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n },\n metadata\n );\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport async function handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): Promise<boolean> {\n let skipHandling = false;\n if (agentContext?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n await handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nasync function handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: StandardGraph | MultiAgentGraph;\n}): Promise<void> {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":["getMessageId","StepTypes","ToolCallTypes","ContentTypes","nanoid","Providers","isAnthropicWebSearchResult","coerceAnthropicSearchResults","Constants","formatResultsForLLM","ToolMessage","GraphEvents"],"mappings":";;;;;;;;;;AAAA;AACA;AAuBO,eAAe,oBAAoB,CAAC,EACz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AAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;;;;"}
@@ -7,6 +7,7 @@ import { SystemMessage, AIMessageChunk, ToolMessage } from '@langchain/core/mess
7
7
  import { GraphNodeKeys, ContentTypes, Providers, GraphEvents, StepTypes } from '../common/enum.mjs';
8
8
  import { convertMessagesToContent, modifyDeltaProperties, formatAnthropicArtifactContent, formatArtifactPayload } from '../messages/core.mjs';
9
9
  import { createPruneMessages } from '../messages/prune.mjs';
10
+ import { ensureThinkingBlockInMessages } from '../messages/format.mjs';
10
11
  import { addCacheControl, addBedrockCacheControl } from '../messages/cache.mjs';
11
12
  import { formatContentStrings } from '../messages/content.mjs';
12
13
  import { resetIfNotEmpty, joinKeys } from '../utils/graph.mjs';
@@ -179,6 +180,54 @@ class StandardGraph extends Graph {
179
180
  getContentParts() {
180
181
  return convertMessagesToContent(this.messages.slice(this.startIndex));
181
182
  }
183
+ /**
184
+ * Get all run steps, optionally filtered by agent ID
185
+ */
186
+ getRunSteps(agentId) {
187
+ if (!agentId) {
188
+ return [...this.contentData];
189
+ }
190
+ return this.contentData.filter((step) => step.agentId === agentId);
191
+ }
192
+ /**
193
+ * Get run steps grouped by agent ID
194
+ */
195
+ getRunStepsByAgent() {
196
+ const stepsByAgent = new Map();
197
+ for (const step of this.contentData) {
198
+ if (!step.agentId)
199
+ continue;
200
+ const steps = stepsByAgent.get(step.agentId) ?? [];
201
+ steps.push(step);
202
+ stepsByAgent.set(step.agentId, steps);
203
+ }
204
+ return stepsByAgent;
205
+ }
206
+ /**
207
+ * Get agent IDs that participated in this run
208
+ */
209
+ getActiveAgentIds() {
210
+ const agentIds = new Set();
211
+ for (const step of this.contentData) {
212
+ if (step.agentId) {
213
+ agentIds.add(step.agentId);
214
+ }
215
+ }
216
+ return Array.from(agentIds);
217
+ }
218
+ /**
219
+ * Maps contentPart indices to agent IDs for post-run analysis
220
+ * Returns a map where key is the contentPart index and value is the agentId
221
+ */
222
+ getContentPartAgentMap() {
223
+ const contentPartAgentMap = new Map();
224
+ for (const step of this.contentData) {
225
+ if (step.agentId && step.index != null) {
226
+ contentPartAgentMap.set(step.index, step.agentId);
227
+ }
228
+ }
229
+ return contentPartAgentMap;
230
+ }
182
231
  /* Graph */
183
232
  createSystemRunnable({ provider, clientOptions, instructions, additional_instructions, }) {
184
233
  let finalInstructions = instructions;
@@ -412,6 +461,20 @@ class StandardGraph extends Graph {
412
461
  finalMessages = addBedrockCacheControl(finalMessages);
413
462
  }
414
463
  }
464
+ /**
465
+ * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,
466
+ * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.
467
+ * This is required by Anthropic/Bedrock when thinking is enabled.
468
+ */
469
+ const isAnthropicWithThinking = (agentContext.provider === Providers.ANTHROPIC &&
470
+ agentContext.clientOptions.thinking !=
471
+ null) ||
472
+ (agentContext.provider === Providers.BEDROCK &&
473
+ agentContext.clientOptions
474
+ .additionalModelRequestFields?.['thinking'] != null);
475
+ if (isAnthropicWithThinking) {
476
+ finalMessages = ensureThinkingBlockInMessages(finalMessages, agentContext.provider);
477
+ }
415
478
  if (agentContext.lastStreamCall != null &&
416
479
  agentContext.streamBuffer != null) {
417
480
  const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;
@@ -540,7 +603,7 @@ class StandardGraph extends Graph {
540
603
  /**
541
604
  * Dispatches a run step to the client, returns the step ID
542
605
  */
543
- async dispatchRunStep(stepKey, stepDetails) {
606
+ async dispatchRunStep(stepKey, stepDetails, metadata) {
544
607
  if (!this.config) {
545
608
  throw new Error('No config provided');
546
609
  }
@@ -566,6 +629,20 @@ class StandardGraph extends Graph {
566
629
  if (runId) {
567
630
  runStep.runId = runId;
568
631
  }
632
+ /**
633
+ * Extract and store agentId from metadata
634
+ */
635
+ if (metadata) {
636
+ try {
637
+ const agentContext = this.getAgentContext(metadata);
638
+ if (agentContext.agentId) {
639
+ runStep.agentId = agentContext.agentId;
640
+ }
641
+ }
642
+ catch (_e) {
643
+ /** If we can't get agent context, that's okay - agentId remains undefined */
644
+ }
645
+ }
569
646
  this.contentData.push(runStep);
570
647
  this.contentIndexMap.set(stepId, runStep.index);
571
648
  await safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep, this.config);