@librechat/agents 3.3.9 → 3.3.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +4 -0
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +21 -2
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/langfuseToolOutputTracing.cjs +228 -16
- package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
- package/dist/cjs/llm/init.cjs +1 -1
- package/dist/cjs/llm/invoke.cjs +14 -7
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +188 -11
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +4 -3
- package/dist/cjs/messages/core.cjs +592 -27
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/run.cjs +11 -1
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +2 -2
- package/dist/cjs/tools/ToolNode.cjs +1 -1
- package/dist/cjs/tools/search/tool.cjs +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/esm/agents/AgentContext.mjs +4 -0
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +21 -2
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/langfuseToolOutputTracing.mjs +228 -16
- package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
- package/dist/esm/llm/init.mjs +1 -1
- package/dist/esm/llm/invoke.mjs +14 -7
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +190 -13
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +5 -5
- package/dist/esm/messages/core.mjs +592 -28
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/run.mjs +11 -1
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +2 -2
- package/dist/esm/tools/ToolNode.mjs +1 -1
- package/dist/esm/tools/search/tool.mjs +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/types/agents/AgentContext.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +5 -0
- package/dist/types/langfuseToolOutputTracing.d.ts +1 -0
- package/dist/types/llm/invoke.d.ts +1 -1
- package/dist/types/messages/core.d.ts +11 -6
- package/dist/types/run.d.ts +7 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +5 -0
- package/src/graphs/Graph.ts +39 -0
- package/src/langfuseToolOutputTracing.ts +410 -14
- package/src/llm/custom-chat-models.smoke.test.ts +747 -0
- package/src/llm/invoke.test.ts +98 -0
- package/src/llm/invoke.ts +34 -23
- package/src/llm/openai/index.ts +334 -25
- package/src/llm/openai/llm.spec.ts +107 -6
- package/src/messages/core.ts +1290 -42
- package/src/messages/formatAgentMessages.test.ts +2623 -0
- package/src/run.ts +15 -0
- package/src/specs/discovered-tools.test.ts +217 -0
- package/src/specs/langfuse-tool-output-tracing.test.ts +887 -0
- package/src/specs/preemptSeal.test.ts +374 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","names":["HumanMessage","toLangChainContent","AIMessage","compactToolContent","getBoundedCacheControlledTextToolContent","getBoundedSingleTextToolContent","serializeToolContentBounded","stripAnthropicCacheControl","ToolMessage","hasComputerCallOutputMarker","getComputerCallOutputScreenshot","cloneToolMessageWithContent","HARD_MAX_TOOL_RESULT_CHARS","AIMessageChunk","isComputerCallOutputMessage"],"sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport { isProxy } from 'node:util/types';\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n cloneToolMessageWithContent,\n compactToolContent,\n getBoundedCacheControlledTextToolContent,\n getBoundedSingleTextToolContent,\n getComputerCallOutputScreenshot,\n hasComputerCallOutputMarker,\n isComputerCallOutputMessage,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { stripAnthropicCacheControl } from './cache';\nimport { ContentTypes, Providers } from '@/common';\nimport { toLangChainContent } from './langchain';\n\ntype ReasoningSummary = { summary?: Array<{ text?: string }> };\ntype ReasoningDetail = { type?: string; text?: string };\ntype ReasoningAdditionalKwargs = {\n reasoning_content?: string | Partial<ReasoningSummary> | null;\n reasoning?: string | Partial<ReasoningSummary> | null;\n reasoning_details?: ReasoningDetail[] | null;\n};\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [\n ..._allowedTypes,\n 'thinking',\n 'redacted_thinking',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): (t.ExtendedMessageContent | null)[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item: t.ExtendedMessageContent | null) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nfunction getReasoningText(\n value: string | Partial<ReasoningSummary> | null | undefined\n): string | undefined {\n if (typeof value === 'string') {\n return value !== '' ? value : undefined;\n }\n const summaryText = value?.summary\n ?.map((summary) => summary.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return summaryText != null && summaryText !== '' ? summaryText : undefined;\n}\n\nfunction getReasoningDetailsText(\n value: ReasoningDetail[] | null | undefined\n): string | undefined {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const reasoningText = value\n .filter((detail) => detail.type === 'reasoning.text')\n .map((detail) => detail.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return reasoningText !== '' ? reasoningText : undefined;\n}\n\nfunction getAdditionalReasoningContent(\n message: BaseMessage\n): string | undefined {\n const additionalKwargs = message.additional_kwargs as\n | ReasoningAdditionalKwargs\n | undefined;\n if (additionalKwargs == null) {\n return undefined;\n }\n\n const reasoningContent = getReasoningText(additionalKwargs.reasoning_content);\n if (reasoningContent != null) {\n return reasoningContent;\n }\n\n const reasoning = getReasoningText(additionalKwargs.reasoning);\n if (reasoning != null) {\n return reasoning;\n }\n\n return getReasoningDetailsText(additionalKwargs.reasoning_details);\n}\n\nfunction hasReasoningContent(content: BaseMessage['content']): boolean {\n if (!Array.isArray(content)) {\n return false;\n }\n return content.some((item) => {\n if (typeof item !== 'object' || !('type' in item)) {\n return false;\n }\n return (\n item.type === ContentTypes.THINK ||\n item.type === ContentTypes.THINKING ||\n item.type === ContentTypes.REASONING ||\n item.type === ContentTypes.REASONING_CONTENT ||\n item.type === 'redacted_thinking'\n );\n });\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n reduceBlocks(obj.content as ContentBlock[])\n );\n }\n if (Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n modifyContent({\n provider,\n messageType,\n content: obj.content as t.ExtendedMessageContent[],\n }) as t.MessageContentComplex[]\n );\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n if (provider === Providers.BEDROCK) {\n obj.lc_kwargs.content = reduceBlocks(\n obj.lc_kwargs.content as ContentBlock[]\n );\n }\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: toLangChainContent(message.content) });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: toLangChainContent(formattedContent),\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addToolCallBoundary = (): number => {\n processedContent.push({ type: ContentTypes.TEXT, text: '' });\n return processedContent.length - 1;\n };\n\n const addContentPart = (message: BaseMessage | null): number | undefined => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return undefined;\n }\n const reasoningContent =\n message?._getType() === 'ai' && !hasReasoningContent(content)\n ? getAdditionalReasoningContent(message)\n : undefined;\n if (reasoningContent != null) {\n processedContent.push({\n type: ContentTypes.THINK,\n think: reasoningContent,\n });\n }\n if (typeof content === 'string') {\n if (content === '') {\n return undefined;\n }\n processedContent.push({\n type: ContentTypes.TEXT,\n text: content,\n });\n return processedContent.length - 1;\n } else if (Array.isArray(content)) {\n let textContentIndex: number | undefined;\n for (const item of content) {\n if (item == null || item.type === 'tool_use') {\n continue;\n }\n processedContent.push(item);\n if (item.type === ContentTypes.TEXT) {\n textContentIndex = processedContent.length - 1;\n }\n }\n return textContentIndex;\n }\n return undefined;\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n currentAIMessageIndex = addContentPart(message) ?? addToolCallBoundary();\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nfunction stringifyToolMessageContent(\n content: ToolMessage['content'] | null | undefined\n): string {\n return content == null ? '' : String(content);\n}\n\nfunction appendContentBlocks(\n target: t.MessageContentComplex[],\n content: BaseMessage['content']\n): void {\n if (typeof content === 'string') {\n target.push({ type: ContentTypes.TEXT, text: content });\n return;\n }\n for (const block of content) {\n target.push(block as t.MessageContentComplex);\n }\n}\n\n/**\n * Appends one artifact/tool-content segment without retaining an unbounded\n * intermediate block array. Both operands are compacted before they are\n * combined, and the combined result is compacted again under the aggregate\n * cap.\n */\nfunction appendBoundedContent(\n current: BaseMessage['content'] | undefined,\n next: unknown,\n maxChars: number\n): BaseMessage['content'] {\n const boundedNext = compactToolContent(next, maxChars).content;\n if (current == null) {\n return boundedNext;\n }\n\n const combined: t.MessageContentComplex[] = [];\n appendContentBlocks(combined, current);\n appendContentBlocks(combined, boundedNext);\n return compactToolContent(toLangChainContent(combined), maxChars).content;\n}\n\nfunction cloneAIMessageWithToolCalls(\n message: AIMessage,\n toolCalls: ToolCall[],\n removedCallIds: ReadonlySet<string>\n): AIMessage {\n const descriptors = Object.getOwnPropertyDescriptors(message) as Record<\n string,\n PropertyDescriptor | undefined\n >;\n let descriptor = descriptors.tool_calls;\n descriptors.tool_calls = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: toolCalls,\n writable: descriptor?.writable ?? true,\n };\n const toolCallChunks = descriptors.tool_call_chunks?.value as\n | ToolCallChunk[]\n | undefined;\n if (Array.isArray(toolCallChunks)) {\n descriptor = descriptors.tool_call_chunks;\n descriptors.tool_call_chunks = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: toolCallChunks.filter(\n (chunk) => typeof chunk.id !== 'string' || !removedCallIds.has(chunk.id)\n ),\n writable: descriptor?.writable ?? true,\n };\n }\n return Object.create(\n Object.getPrototypeOf(message),\n descriptors as PropertyDescriptorMap\n ) as AIMessage;\n}\n\nfunction cloneAIMessageWithContent(\n message: AIMessage,\n content: AIMessage['content']\n): AIMessage {\n const descriptors = Object.getOwnPropertyDescriptors(message) as Record<\n string,\n PropertyDescriptor | undefined\n >;\n const descriptor = descriptors.content;\n descriptors.content = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: content,\n writable: descriptor?.writable ?? true,\n };\n const lcKwargs = descriptors.lc_kwargs;\n if (\n lcKwargs != null &&\n 'value' in lcKwargs &&\n typeof lcKwargs.value === 'object' &&\n lcKwargs.value != null\n ) {\n descriptors.lc_kwargs = {\n ...lcKwargs,\n value: {\n ...(lcKwargs.value as Record<string, unknown>),\n content,\n },\n };\n }\n return Object.create(\n Object.getPrototypeOf(message),\n descriptors as PropertyDescriptorMap\n ) as AIMessage;\n}\n\n/**\n * Drops incomplete streamed text-input fragments that some providers retain\n * beside the assembled parsed tool call. They are neither user-visible text\n * nor valid content blocks for a subsequent provider.\n */\nexport function projectToolStreamContentForProvider(\n messages: BaseMessage[]\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (message.getType() !== 'ai' || !Array.isArray(message.content)) {\n continue;\n }\n const content = message.content.filter((block) => {\n if (block == null || typeof block !== 'object') {\n return true;\n }\n try {\n if (isProxy(block)) {\n return false;\n }\n const type = Object.getOwnPropertyDescriptor(block, 'type');\n if (type == null) {\n return true;\n }\n if (type.enumerable !== true || !('value' in type)) {\n return false;\n }\n if (type.value !== 'text') {\n return true;\n }\n const text = Object.getOwnPropertyDescriptor(block, 'text');\n return (\n text?.enumerable === true &&\n 'value' in text &&\n typeof text.value === 'string' &&\n text.value !== ''\n );\n } catch {\n return false;\n }\n });\n if (content.length === message.content.length) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneAIMessageWithContent(\n message as AIMessage,\n toLangChainContent(content)\n );\n }\n return projected ?? messages;\n}\n\ntype CacheControlledTextProjection = 'serialize' | 'preserve' | 'text';\n\nfunction projectStructuredOpenAIToolContent(\n content: ToolMessage['content'],\n maxChars: number,\n cacheControlledTextProjection: CacheControlledTextProjection\n): ToolMessage['content'] {\n if (cacheControlledTextProjection !== 'serialize') {\n const cacheControlledContent = getBoundedCacheControlledTextToolContent(\n content,\n maxChars\n );\n if (cacheControlledContent != null) {\n return cacheControlledTextProjection === 'preserve'\n ? cacheControlledContent\n : cacheControlledContent[0].text;\n }\n const singleTextContent = getBoundedSingleTextToolContent(\n content,\n maxChars\n );\n if (singleTextContent != null) {\n return singleTextContent;\n }\n }\n const serializableContent =\n cacheControlledTextProjection === 'preserve'\n ? stripAnthropicCacheControl([{ content }])[0].content\n : content;\n return serializeToolContentBounded(serializableContent, maxChars);\n}\n\n/**\n * OpenAI Chat tool messages only accept strings or text-only parts, while the\n * Responses API serializes any structured ToolMessage after graph accounting.\n * Project every non-string tool result to one bounded string before the final\n * provider payload is measured so both APIs receive the exact representation\n * the budget guard counted. Native Responses computer screenshots stay\n * structured because their dedicated converter sends the media block directly.\n */\nfunction projectOpenAIToolMessageContentInternal(\n messages: BaseMessage[],\n maxChars: number,\n deduplicateResponsesComputerCalls: boolean,\n cacheControlledTextProjection: CacheControlledTextProjection\n): BaseMessage[] {\n const pendingComputerCallIds: string[] = [];\n const seenComputerCallIds = new Set<string>();\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const messageRole = (message as BaseMessage & { role?: unknown }).role;\n const isAssistant =\n message.getType() === 'ai' || messageRole === 'assistant';\n if (isAssistant) {\n const parsedComputerCallIds = new Set<string>();\n const toolCalls = (message as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n const record = toolCall as ToolCall & {\n isComputerTool?: unknown;\n };\n if (\n record.type !== 'tool_call' ||\n record.isComputerTool !== true ||\n typeof record.id !== 'string' ||\n record.id === ''\n ) {\n continue;\n }\n if (parsedComputerCallIds.has(record.id)) {\n throw new Error(`Duplicate computer call id \"${record.id}\"`);\n }\n parsedComputerCallIds.add(record.id);\n if (seenComputerCallIds.has(record.id)) {\n throw new Error(`Duplicate computer call id \"${record.id}\"`);\n }\n seenComputerCallIds.add(record.id);\n pendingComputerCallIds.push(record.id);\n }\n }\n\n const rawOutput = (\n message.response_metadata as {\n output?: unknown;\n }\n ).output;\n const fallbackOutput = (\n message.additional_kwargs as {\n tool_outputs?: unknown;\n }\n ).tool_outputs;\n let actualToolOutputs: unknown[] = [];\n if (Array.isArray(rawOutput) && rawOutput.length > 0) {\n actualToolOutputs = rawOutput;\n } else if (Array.isArray(fallbackOutput)) {\n actualToolOutputs = fallbackOutput;\n }\n const rawComputerCallIds = new Set<string>();\n for (const item of actualToolOutputs) {\n if (item == null || typeof item !== 'object') {\n continue;\n }\n const record = item as {\n type?: unknown;\n call_id?: unknown;\n };\n if (\n record.type !== 'computer_call' ||\n typeof record.call_id !== 'string' ||\n record.call_id === ''\n ) {\n continue;\n }\n if (rawComputerCallIds.has(record.call_id)) {\n throw new Error(`Duplicate computer call id \"${record.call_id}\"`);\n }\n rawComputerCallIds.add(record.call_id);\n // LangChain can retain the same call in parsed and raw forms. It sends\n // one logical call, so collapse that representation duplicate.\n if (parsedComputerCallIds.has(record.call_id)) {\n continue;\n }\n if (seenComputerCallIds.has(record.call_id)) {\n throw new Error(`Duplicate computer call id \"${record.call_id}\"`);\n }\n seenComputerCallIds.add(record.call_id);\n pendingComputerCallIds.push(record.call_id);\n }\n\n if (\n deduplicateResponsesComputerCalls &&\n Array.isArray(toolCalls) &&\n rawComputerCallIds.size > 0\n ) {\n /**\n * The non-streaming Responses converter marks parsed computer calls,\n * but the streaming converter currently emits the same call as an\n * ordinary parsed `computer_use` tool call. In both cases the raw\n * `computer_call` item is authoritative and is replayed by LangChain,\n * so remove every parsed representation with the same call id.\n */\n const projectedToolCalls = toolCalls.filter(\n (toolCall) =>\n typeof toolCall.id !== 'string' ||\n !rawComputerCallIds.has(toolCall.id)\n );\n if (projectedToolCalls.length !== toolCalls.length) {\n projected ??= [...messages];\n projected[i] = cloneAIMessageWithToolCalls(\n message as AIMessage,\n projectedToolCalls,\n rawComputerCallIds\n );\n }\n }\n }\n\n if (\n message instanceof ToolMessage &&\n hasComputerCallOutputMarker(message)\n ) {\n const screenshot = getComputerCallOutputScreenshot(message.content);\n if (screenshot == null) {\n throw new Error('Invalid computer call output screenshot');\n }\n if (pendingComputerCallIds[0] !== message.tool_call_id) {\n throw new Error(\n `Invalid computer call output pairing for \"${message.tool_call_id}\"`\n );\n }\n pendingComputerCallIds.shift();\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(message, [screenshot]);\n continue;\n }\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n projectStructuredOpenAIToolContent(\n message.content,\n maxChars,\n cacheControlledTextProjection\n )\n );\n }\n if (pendingComputerCallIds.length > 0) {\n throw new Error(\n `Missing computer call output for \"${pendingComputerCallIds[0]}\"`\n );\n }\n return projected ?? messages;\n}\n\n/** Projects OpenAI-compatible tool content without changing parsed call parents. */\nexport function projectOpenAIToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'serialize'\n );\n}\n\n/** Projects an actual OpenAI-compatible Chat attempt and removes cache metadata. */\nexport function projectOpenAIChatToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'text'\n );\n}\n\n/** Preserves OpenRouter's cache-decorated text blocks for a Chat attempt. */\nexport function projectOpenRouterToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'preserve'\n );\n}\n\n/** Projects Responses tool content and collapses parsed/raw computer-call mirrors. */\nexport function projectOpenAIResponsesToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n true,\n 'text'\n );\n}\n\n/** Removes Anthropic/OpenRouter cache metadata before unsupported providers run. */\nexport function projectCacheControlledToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n const cacheControlledContent = getBoundedCacheControlledTextToolContent(\n message.content,\n maxChars\n );\n if (cacheControlledContent == null) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n cacheControlledContent[0].text\n );\n }\n return projected ?? messages;\n}\n\n/** Unwraps a canonical single text block after provider cache markers are removed. */\nexport function projectSingleTextToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n const text = getBoundedSingleTextToolContent(message.content, maxChars);\n if (text == null) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(message, text);\n }\n return projected ?? messages;\n}\n\n/** Serializes provider-neutral structured tool outputs without media pairing. */\nexport function projectStructuredToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string' ||\n hasComputerCallOutputMarker(message)\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n serializeToolContentBounded(message.content, maxChars)\n );\n }\n return projected ?? messages;\n}\n\n/**\n * Non-Responses providers cannot consume native computer screenshots. Keep\n * the tool-call structure intact, but replace screenshot bytes with a bounded\n * text marker at the actual invocation boundary.\n */\nexport function projectComputerCallOutputsToText(\n messages: BaseMessage[]\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n !hasComputerCallOutputMarker(message)\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n '[Computer screenshot omitted for this provider]'\n );\n }\n return projected ?? messages;\n}\n\nexport function projectAnthropicArtifactContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return messages;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n ((msg instanceof AIMessage || msg instanceof AIMessageChunk) &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return messages;\n\n // Build tool call ID set and merge artifact content in a single forward pass.\n const message = messages[latestAIParentIndex] as AIMessage | AIMessageChunk;\n const toolCallIdSet = new Set<string>();\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n if (tc.id != null) {\n toolCallIdSet.add(tc.id);\n }\n }\n }\n\n let formattedMessages: BaseMessage[] | undefined;\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (\n msg instanceof ToolMessage &&\n !isComputerCallOutputMessage(msg) &&\n toolCallIdSet.has(msg.tool_call_id) &&\n msg.artifact != null &&\n ((typeof msg.artifact?.content === 'string' &&\n msg.artifact.content.length > 0) ||\n (Array.isArray(msg.artifact?.content) &&\n msg.artifact.content.length > 0))\n ) {\n const artifactContent =\n typeof msg.artifact.content === 'string'\n ? [\n {\n type: ContentTypes.TEXT,\n text: msg.artifact.content,\n },\n ]\n : msg.artifact.content;\n const baseContent = Array.isArray(msg.content)\n ? msg.content\n : stringifyToolMessageContent(msg.content);\n const content = appendBoundedContent(\n compactToolContent(baseContent, maxChars).content,\n artifactContent,\n maxChars\n );\n formattedMessages ??= [...messages];\n formattedMessages[j] = cloneToolMessageWithContent(msg, content, {\n ...msg.artifact,\n content: [],\n });\n }\n }\n return formattedMessages ?? messages;\n}\n\n/**\n * Mutating compatibility wrapper retained for existing package consumers.\n * New provider-call paths should use `projectAnthropicArtifactContent`.\n */\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const projected = projectAnthropicArtifactContent(messages);\n if (projected === messages) {\n return;\n }\n for (let i = 0; i < messages.length; i++) {\n if (\n messages[i] instanceof ToolMessage &&\n projected[i] instanceof ToolMessage &&\n projected[i] !== messages[i]\n ) {\n messages[i].content = projected[i].content;\n }\n }\n}\n\nexport function projectArtifactPayload(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return messages;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n ((msg instanceof AIMessage || msg instanceof AIMessageChunk) &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessageY.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return messages;\n\n // Single pass: collect relevant tool messages with artifacts and aggregate\n let aggregatedContent: BaseMessage['content'] | undefined;\n let formattedMessages: BaseMessage[] | undefined;\n\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (\n !(msg instanceof ToolMessage) ||\n isComputerCallOutputMessage(msg) ||\n !(\n (typeof msg.artifact?.content === 'string' &&\n msg.artifact.content.length > 0) ||\n (Array.isArray(msg.artifact?.content) &&\n msg.artifact.content.length > 0)\n )\n ) {\n continue;\n }\n aggregatedContent = appendBoundedContent(\n aggregatedContent,\n msg.content,\n maxChars\n );\n formattedMessages ??= [...messages];\n formattedMessages[i] = cloneToolMessageWithContent(\n msg,\n 'Tool response is included in the next message as a Human message',\n {\n ...msg.artifact,\n content: [],\n }\n );\n aggregatedContent = appendBoundedContent(\n aggregatedContent,\n msg.artifact.content,\n maxChars\n );\n }\n\n if (aggregatedContent != null) {\n formattedMessages?.push(new HumanMessage({ content: aggregatedContent }));\n }\n return formattedMessages ?? messages;\n}\n\n/**\n * Mutating compatibility wrapper retained for existing package consumers.\n * New provider-call paths should use `projectArtifactPayload`.\n */\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const originalLength = messages.length;\n const projected = projectArtifactPayload(messages);\n if (projected === messages) {\n return;\n }\n for (let i = 0; i < originalLength; i++) {\n if (\n messages[i] instanceof ToolMessage &&\n projected[i] instanceof ToolMessage &&\n projected[i] !== messages[i]\n ) {\n messages[i].content = projected[i].content;\n }\n }\n messages.push(...projected.slice(originalLength));\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;AAkCA,SAAgB,2BAA2B,EACzC,aACA,cACA,gBAKe;CAiBf,OAAO,IAAIA,yBAAAA,aAAa;QAflB,YAAY,GAAG;;;;;;IAMnB,cAAc,QAAQ;;;IAGtB,cAAc,YAAY,KAAK,MAAM,EAAE;;;IAGvC,aAAa,QAAQ;CAGQ;AACjC;AAEA,MAAM,gBAAgB;CAAC;CAAa;CAAQ;CAAY;AAAa;AACrE,MAAM,yBAAmD;CACvD,SAAS;gBACc;EACrB,GAAG;EACH;EACA;EACA;EACA;EACA;CACF;cACqB,CAAC,GAAG,eAAe,mBAAmB;aACvC;AACtB;AAEA,MAAM,iBAAiB,EACrB,UACA,aACA,cAKyC;CACzC,MAAM,eACJ,uBAAuB,aAAa,uBAAuB;CAC7D,OAAO,QAAQ,KAAK,SAA0C;EAC5D,IACE,QACA,OAAO,SAAS,YAChB,UAAU,QACV,KAAK,QAAQ,QACb,KAAK,MACL;GACA,IAAI,UAAU,KAAK;GACnB,IAAI,QAAQ,SAAS,QAAQ,GAC3B,UAAU,QAAQ,QAAQ,UAAU,EAAE;GAExC,IAAI,CAAC,aAAa,SAAS,OAAO,GAChC,UAAU;GAIZ,IACE,gBAAgB,QAChB,YAAY,cACZ,WAAW,QACX,KAAK,UAAU,IAEf,OAAO;IAAE,GAAG;IAAM,MAAM;IAAS,OAAO;GAAK;GAG/C,OAAO;IAAE,GAAG;IAAM,MAAM;GAAQ;EAClC;EACA,OAAO;CACT,CAAC;AACH;AAMA,SAAS,aAAa,QAAwC;CAC5D,MAAM,UAA0B,CAAC;CAEjC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,YAAY,QAAQ,QAAQ,SAAS;EAG3C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QAAQ,SAAS,IAGlC;EAEF,oBAAoB,qBAClB,mBACA,IAAI,SACJ,QACF;EACA,sBAAsB,CAAC,GAAG,QAAQ;EAClC,kBAAkB,KAAKH,oBAAAA,4BACrB,KACA,oEACA;GACE,GAAG,IAAI;GACP,SAAS,CAAC;EACZ,CACF;EACA,oBAAoB,qBAClB,mBACA,IAAI,SAAS,SACb,QACF;CACF;CAEA,IAAI,qBAAqB,MACvB,mBAAmB,KAAK,IAAIX,yBAAAA,aAAa,EAAE,SAAS,kBAAkB,CAAC,CAAC;CAE1E,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,sBAAsB,UAA+B;CACnE,MAAM,iBAAiB,SAAS;CAChC,MAAM,YAAY,uBAAuB,QAAQ;CACjD,IAAI,cAAc,UAChB;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,gBAAgB,KAClC,IACE,SAAS,cAAcQ,yBAAAA,eACvB,UAAU,cAAcA,yBAAAA,eACxB,UAAU,OAAO,SAAS,IAE1B,SAAS,EAAE,CAAC,UAAU,UAAU,EAAE,CAAC;CAGvC,SAAS,KAAK,GAAG,UAAU,MAAM,cAAc,CAAC;AAClD;AAEA,SAAgB,cACd,OACA,WACQ;CACR,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KACrC,IAAI,UAAU,MAAM,EAAE,GACpB,OAAO;CAGX,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"core.cjs","names":["HumanMessage","toLangChainContent","AIMessage","compactToolContent","serializeToolContentBounded","HARD_MAX_TOOL_RESULT_CHARS","getBoundedCacheControlledTextToolContent","getBoundedSingleTextToolContent","stripAnthropicCacheControl","ToolMessage","hasComputerCallOutputMarker","getComputerCallOutputScreenshot","cloneToolMessageWithContent","AIMessageChunk","isComputerCallOutputMessage"],"sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport { isProxy } from 'node:util/types';\nimport {\n AIMessage,\n BaseMessage,\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type { ContentBlock as LangChainContentBlock } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n cloneToolMessageWithContent,\n compactToolContent,\n getBoundedCacheControlledTextToolContent,\n getBoundedSingleTextToolContent,\n getComputerCallOutputScreenshot,\n hasComputerCallOutputMarker,\n isComputerCallOutputMessage,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { stripAnthropicCacheControl } from './cache';\nimport { ContentTypes, Providers } from '@/common';\nimport { toLangChainContent } from './langchain';\n\ntype ReasoningSummary = { summary?: Array<{ text?: string }> };\ntype ReasoningDetail = { type?: string; text?: string };\ntype ReasoningAdditionalKwargs = {\n reasoning_content?: string | Partial<ReasoningSummary> | null;\n reasoning?: string | Partial<ReasoningSummary> | null;\n reasoning_details?: ReasoningDetail[] | null;\n};\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [\n ..._allowedTypes,\n 'thinking',\n 'redacted_thinking',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): (t.ExtendedMessageContent | null)[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item: t.ExtendedMessageContent | null) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nfunction getReasoningText(\n value: string | Partial<ReasoningSummary> | null | undefined\n): string | undefined {\n if (typeof value === 'string') {\n return value !== '' ? value : undefined;\n }\n const summaryText = value?.summary\n ?.map((summary) => summary.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return summaryText != null && summaryText !== '' ? summaryText : undefined;\n}\n\nfunction getReasoningDetailsText(\n value: ReasoningDetail[] | null | undefined\n): string | undefined {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const reasoningText = value\n .filter((detail) => detail.type === 'reasoning.text')\n .map((detail) => detail.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return reasoningText !== '' ? reasoningText : undefined;\n}\n\nfunction getAdditionalReasoningContent(\n message: BaseMessage\n): string | undefined {\n const additionalKwargs = message.additional_kwargs as\n | ReasoningAdditionalKwargs\n | undefined;\n if (additionalKwargs == null) {\n return undefined;\n }\n\n const reasoningContent = getReasoningText(additionalKwargs.reasoning_content);\n if (reasoningContent != null) {\n return reasoningContent;\n }\n\n const reasoning = getReasoningText(additionalKwargs.reasoning);\n if (reasoning != null) {\n return reasoning;\n }\n\n return getReasoningDetailsText(additionalKwargs.reasoning_details);\n}\n\nfunction hasReasoningContent(content: BaseMessage['content']): boolean {\n if (!Array.isArray(content)) {\n return false;\n }\n return content.some((item) => {\n if (typeof item !== 'object' || !('type' in item)) {\n return false;\n }\n return (\n item.type === ContentTypes.THINK ||\n item.type === ContentTypes.THINKING ||\n item.type === ContentTypes.REASONING ||\n item.type === ContentTypes.REASONING_CONTENT ||\n item.type === 'redacted_thinking'\n );\n });\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n reduceBlocks(obj.content as ContentBlock[])\n );\n }\n if (Array.isArray(obj.content)) {\n obj.content = toLangChainContent(\n modifyContent({\n provider,\n messageType,\n content: obj.content as t.ExtendedMessageContent[],\n }) as t.MessageContentComplex[]\n );\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n if (provider === Providers.BEDROCK) {\n obj.lc_kwargs.content = reduceBlocks(\n obj.lc_kwargs.content as ContentBlock[]\n );\n }\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: toLangChainContent(message.content) });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: toLangChainContent(formattedContent),\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addToolCallBoundary = (): number => {\n processedContent.push({ type: ContentTypes.TEXT, text: '' });\n return processedContent.length - 1;\n };\n\n const addContentPart = (message: BaseMessage | null): number | undefined => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return undefined;\n }\n const reasoningContent =\n message?._getType() === 'ai' && !hasReasoningContent(content)\n ? getAdditionalReasoningContent(message)\n : undefined;\n if (reasoningContent != null) {\n processedContent.push({\n type: ContentTypes.THINK,\n think: reasoningContent,\n });\n }\n if (typeof content === 'string') {\n if (content === '') {\n return undefined;\n }\n processedContent.push({\n type: ContentTypes.TEXT,\n text: content,\n });\n return processedContent.length - 1;\n } else if (Array.isArray(content)) {\n let textContentIndex: number | undefined;\n for (const item of content) {\n if (item == null || item.type === 'tool_use') {\n continue;\n }\n processedContent.push(item);\n if (item.type === ContentTypes.TEXT) {\n textContentIndex = processedContent.length - 1;\n }\n }\n return textContentIndex;\n }\n return undefined;\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n currentAIMessageIndex = addContentPart(message) ?? addToolCallBoundary();\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nfunction stringifyToolMessageContent(\n content: ToolMessage['content'] | null | undefined\n): string {\n return content == null ? '' : String(content);\n}\n\nfunction appendContentBlocks(\n target: t.MessageContentComplex[],\n content: BaseMessage['content']\n): void {\n if (typeof content === 'string') {\n target.push({ type: ContentTypes.TEXT, text: content });\n return;\n }\n for (const block of content) {\n target.push(block as t.MessageContentComplex);\n }\n}\n\n/**\n * Appends one artifact/tool-content segment without retaining an unbounded\n * intermediate block array. Both operands are compacted before they are\n * combined, and the combined result is compacted again under the aggregate\n * cap.\n */\nfunction appendBoundedContent(\n current: BaseMessage['content'] | undefined,\n next: unknown,\n maxChars: number\n): BaseMessage['content'] {\n const boundedNext = compactToolContent(next, maxChars).content;\n if (current == null) {\n return boundedNext;\n }\n\n const combined: t.MessageContentComplex[] = [];\n appendContentBlocks(combined, current);\n appendContentBlocks(combined, boundedNext);\n return compactToolContent(toLangChainContent(combined), maxChars).content;\n}\n\nfunction cloneAIMessageWithToolCalls(\n message: AIMessage,\n toolCalls: ToolCall[],\n removedCallIds: ReadonlySet<string>\n): AIMessage {\n const descriptors = Object.getOwnPropertyDescriptors(message) as Record<\n string,\n PropertyDescriptor | undefined\n >;\n let descriptor = descriptors.tool_calls;\n descriptors.tool_calls = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: toolCalls,\n writable: descriptor?.writable ?? true,\n };\n const toolCallChunks = descriptors.tool_call_chunks?.value as\n | ToolCallChunk[]\n | undefined;\n if (Array.isArray(toolCallChunks)) {\n descriptor = descriptors.tool_call_chunks;\n descriptors.tool_call_chunks = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: toolCallChunks.filter(\n (chunk) => typeof chunk.id !== 'string' || !removedCallIds.has(chunk.id)\n ),\n writable: descriptor?.writable ?? true,\n };\n }\n return Object.create(\n Object.getPrototypeOf(message),\n descriptors as PropertyDescriptorMap\n ) as AIMessage;\n}\n\nfunction cloneAIMessageWithContent(\n message: AIMessage,\n content: AIMessage['content']\n): AIMessage {\n const descriptors = Object.getOwnPropertyDescriptors(message) as Record<\n string,\n PropertyDescriptor | undefined\n >;\n const descriptor = descriptors.content;\n descriptors.content = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value: content,\n writable: descriptor?.writable ?? true,\n };\n const lcKwargs = descriptors.lc_kwargs;\n if (\n lcKwargs != null &&\n 'value' in lcKwargs &&\n typeof lcKwargs.value === 'object' &&\n lcKwargs.value != null\n ) {\n descriptors.lc_kwargs = {\n ...lcKwargs,\n value: {\n ...(lcKwargs.value as Record<string, unknown>),\n ...(message.response_metadata.output_version === 'v1'\n ? { content: undefined, contentBlocks: content }\n : { content }),\n },\n };\n }\n return Object.create(\n Object.getPrototypeOf(message),\n descriptors as PropertyDescriptorMap\n ) as AIMessage;\n}\n\nfunction cloneAIMessageWithResponsesReplayState(\n message: AIMessage,\n content: AIMessage['content'],\n id: string | undefined,\n additionalKwargs: AIMessage['additional_kwargs'],\n responseMetadata: AIMessage['response_metadata']\n): AIMessage {\n const descriptors = Object.getOwnPropertyDescriptors(message) as Record<\n string,\n PropertyDescriptor | undefined\n >;\n const replacements = {\n content,\n id,\n additional_kwargs: additionalKwargs,\n response_metadata: responseMetadata,\n };\n for (const [key, value] of Object.entries(replacements)) {\n const descriptor = descriptors[key];\n descriptors[key] = {\n configurable: descriptor?.configurable ?? true,\n enumerable: descriptor?.enumerable ?? true,\n value,\n writable: descriptor?.writable ?? true,\n };\n }\n const lcKwargs = descriptors.lc_kwargs;\n if (\n lcKwargs != null &&\n 'value' in lcKwargs &&\n typeof lcKwargs.value === 'object' &&\n lcKwargs.value != null\n ) {\n descriptors.lc_kwargs = {\n ...lcKwargs,\n value: {\n ...(lcKwargs.value as Record<string, unknown>),\n ...replacements,\n ...(responseMetadata.output_version === 'v1'\n ? { content: undefined, contentBlocks: content }\n : {}),\n },\n };\n }\n return Object.create(\n Object.getPrototypeOf(message),\n descriptors as PropertyDescriptorMap\n ) as AIMessage;\n}\n\nfunction hasReplayableEncryptedReasoning(reasoning: unknown): boolean {\n if (reasoning == null || typeof reasoning !== 'object') {\n return false;\n }\n const item = reasoning as {\n encrypted_content?: unknown;\n id?: unknown;\n status?: unknown;\n summary?: unknown;\n type?: unknown;\n };\n return (\n item.type === 'reasoning' &&\n typeof item.id === 'string' &&\n item.id.length > 0 &&\n Array.isArray(item.summary) &&\n typeof item.encrypted_content === 'string' &&\n item.encrypted_content.length > 0 &&\n (item.status === undefined ||\n item.status === 'completed' ||\n item.status === 'incomplete')\n );\n}\n\ntype ResponsesReplayProjection = 'fallback' | 'native';\n\nexport const OPENAI_RESPONSES_REPLAY_POSITIONS_KEY =\n '__openai_responses_replay_positions__';\n\nexport type ResponsesReplayPosition = {\n contentIndex?: number;\n itemId: string;\n kind: 'message' | 'output' | 'reasoning' | 'text';\n outputIndex: number;\n};\n\ntype CompletedGeneratedImages = {\n blocks: PositionedResponsesReplayBlock[];\n data: Set<string>;\n ids: Set<string>;\n};\n\ntype ResponsesReplayArtifacts = {\n generatedImages: CompletedGeneratedImages;\n messagePositions: ResponsesReplayPosition[];\n positionsByItemId: Map<string, ResponsesReplayItemPosition>;\n positionedServerToolResultIds: Set<string>;\n serverToolResults: PositionedResponsesReplayBlock[];\n textPositions: ResponsesReplayPosition[];\n};\n\ntype ResponsesReplayItemPosition = Pick<\n PositionedResponsesReplayBlock,\n 'outputIndex' | 'textIndex'\n>;\n\ntype PositionedResponsesReplayBlock = {\n block: LangChainContentBlock.Standard;\n outputIndex: number;\n subIndex: number;\n textIndex?: number;\n};\n\ntype PositionedResponsesImage = {\n block: LangChainContentBlock.Multimodal.Image;\n textIndex: number;\n};\n\ntype PositionedResponsesImages = {\n blocks: PositionedResponsesImage[];\n textCount: number;\n};\n\nfunction isProviderGeneratedImageBlock(\n block: LangChainContentBlock.Multimodal.Image,\n generatedImages: CompletedGeneratedImages,\n allowDataFallback = true\n): boolean {\n if (typeof block.id === 'string' && block.id.length > 0) {\n return generatedImages.ids.has(block.id);\n }\n return (\n allowDataFallback &&\n typeof block.data === 'string' &&\n generatedImages.data.has(block.data) &&\n block.metadata != null &&\n typeof block.metadata === 'object' &&\n block.metadata.status === 'completed'\n );\n}\n\nfunction hasMeaningfulServerToolOutput(output: unknown): boolean {\n if (output == null || output === '') {\n return false;\n }\n if (Array.isArray(output)) {\n return output.length > 0;\n }\n if (typeof output !== 'object') {\n return true;\n }\n try {\n return Object.keys(output).length > 0;\n } catch {\n return false;\n }\n}\n\nfunction createServerToolResultExtras(toolName?: string): {\n librechatServerToolResult: { toolName?: string };\n} {\n return {\n librechatServerToolResult: {\n ...(toolName != null ? { toolName } : {}),\n },\n };\n}\n\nfunction createNeutralServerToolResult(\n output: unknown,\n status: 'error' | 'success',\n maxChars: number,\n toolName?: string\n): LangChainContentBlock.Text | undefined {\n if (!hasMeaningfulServerToolOutput(output)) {\n return undefined;\n }\n return {\n type: 'text',\n text: serializeToolContentBounded(\n {\n serverToolResult: {\n librechatResponsesReplay: true,\n ...(toolName != null ? { toolName } : {}),\n status,\n output,\n },\n },\n maxChars\n ),\n extras: createServerToolResultExtras(toolName),\n };\n}\n\nfunction isCompleteToolStreamContentBlock(block: unknown): boolean {\n if (block == null || typeof block !== 'object') {\n return true;\n }\n try {\n if (isProxy(block)) {\n return false;\n }\n const type = Object.getOwnPropertyDescriptor(block, 'type');\n if (type == null) {\n return true;\n }\n if (type.enumerable !== true || !('value' in type)) {\n return false;\n }\n if (type.value !== 'text') {\n return true;\n }\n const text = Object.getOwnPropertyDescriptor(block, 'text');\n return (\n text?.enumerable === true &&\n 'value' in text &&\n typeof text.value === 'string' &&\n text.value !== ''\n );\n } catch {\n return false;\n }\n}\n\nfunction projectPreemptedResponsesV1Content(\n content: AIMessage['content'],\n reasoning: unknown,\n maxChars: number,\n replayProjection: ResponsesReplayProjection,\n generatedImages?: CompletedGeneratedImages,\n originalImages?: PositionedResponsesImages,\n serverToolResults?: PositionedResponsesReplayBlock[],\n positionedServerToolResultIds?: ReadonlySet<string>,\n reasoningPosition?: ResponsesReplayItemPosition,\n textPositions?: readonly ResponsesReplayPosition[],\n messagePositions?: readonly ResponsesReplayPosition[]\n): {\n content: AIMessage['content'];\n preservedServerToolResult: boolean;\n} {\n if (!Array.isArray(content)) {\n return { content, preservedServerToolResult: false };\n }\n\n const contentBlocks = content as LangChainContentBlock.Standard[];\n const encryptedReasoning =\n replayProjection === 'native' && hasReplayableEncryptedReasoning(reasoning)\n ? reasoning\n : undefined;\n const positionedReasoning: PositionedResponsesReplayBlock | undefined =\n encryptedReasoning != null && reasoningPosition != null\n ? {\n block: {\n type: 'non_standard' as const,\n value: encryptedReasoning,\n },\n ...reasoningPosition,\n subIndex: 0,\n }\n : undefined;\n const projected: LangChainContentBlock.Standard[] = [];\n let changed = false;\n let hasEncryptedReasoning = false;\n let preservedServerToolResult = false;\n let reasoningInsertionIndex: number | undefined;\n let generatedImageIndex = 0;\n let originalImageIndex = 0;\n let reasoningPending = positionedReasoning;\n let serverToolResultIndex = 0;\n let sourceTextIndex = 0;\n const serverToolNamesByCallId = new Map<string, string>();\n\n const appendOriginalImages = (throughTextIndex?: number): void => {\n if (replayProjection !== 'native' || originalImages == null) {\n return;\n }\n while (originalImageIndex < originalImages.blocks.length) {\n const positionedImage = originalImages.blocks[originalImageIndex];\n if (\n throughTextIndex != null &&\n positionedImage.textIndex > throughTextIndex\n ) {\n return;\n }\n originalImageIndex++;\n if (\n generatedImages != null &&\n isProviderGeneratedImageBlock(\n positionedImage.block,\n generatedImages,\n false\n )\n ) {\n continue;\n }\n projected.push(positionedImage.block);\n changed = true;\n }\n };\n\n const appendReplayBlocks = (\n throughTextIndex?: number,\n beforeOutputIndex?: number\n ): void => {\n for (;;) {\n const generatedImage = generatedImages?.blocks[generatedImageIndex];\n const serverToolResult = serverToolResults?.[serverToolResultIndex];\n const candidates: Array<{\n kind: 'generatedImage' | 'reasoning' | 'serverToolResult';\n value: PositionedResponsesReplayBlock;\n }> = [];\n if (generatedImage != null) {\n candidates.push({ kind: 'generatedImage', value: generatedImage });\n }\n if (serverToolResult != null) {\n candidates.push({ kind: 'serverToolResult', value: serverToolResult });\n }\n if (reasoningPending != null) {\n candidates.push({ kind: 'reasoning', value: reasoningPending });\n }\n if (candidates.length === 0) {\n return;\n }\n candidates.sort((a, b) =>\n comparePositionedResponsesReplayBlocks(a.value, b.value)\n );\n const selected = candidates[0];\n const positionedResult = selected.value;\n if (\n throughTextIndex != null &&\n (positionedResult.textIndex == null ||\n positionedResult.textIndex > throughTextIndex)\n ) {\n return;\n }\n if (\n beforeOutputIndex != null &&\n positionedResult.outputIndex >= beforeOutputIndex\n ) {\n return;\n }\n if (selected.kind === 'generatedImage') {\n generatedImageIndex++;\n } else if (selected.kind === 'serverToolResult') {\n serverToolResultIndex++;\n } else {\n reasoningPending = undefined;\n }\n if (\n replayProjection === 'fallback' &&\n positionedResult.block.type === 'text'\n ) {\n projected.push({\n type: 'text',\n text: positionedResult.block.text,\n });\n } else {\n projected.push(positionedResult.block);\n }\n changed = true;\n preservedServerToolResult ||= selected.kind === 'serverToolResult';\n }\n };\n\n const appendPositionedOriginalImages = (throughTextIndex?: number): void => {\n const nextOriginalImage = originalImages?.blocks[originalImageIndex];\n if (\n nextOriginalImage == null ||\n (throughTextIndex != null &&\n nextOriginalImage.textIndex > throughTextIndex)\n ) {\n return;\n }\n const followingTextPosition = textPositions?.[nextOriginalImage.textIndex];\n const imageOnlyMessagePosition =\n originalImages?.textCount === 0 ? messagePositions?.[0] : undefined;\n const outputBoundary = followingTextPosition ?? imageOnlyMessagePosition;\n if (outputBoundary != null) {\n appendReplayBlocks(\n nextOriginalImage.textIndex,\n outputBoundary.outputIndex\n );\n }\n appendOriginalImages(throughTextIndex);\n };\n\n for (let i = 0; i < contentBlocks.length; i++) {\n const block = contentBlocks[i];\n if (!isCompleteToolStreamContentBlock(block)) {\n changed = true;\n continue;\n }\n if (block.type === 'reasoning') {\n reasoningInsertionIndex ??= projected.length;\n changed = true;\n continue;\n }\n if (block.type === 'non_standard') {\n if (\n replayProjection === 'native' &&\n !hasEncryptedReasoning &&\n hasReplayableEncryptedReasoning(block.value)\n ) {\n hasEncryptedReasoning = true;\n if (positionedReasoning == null) {\n projected.push(block);\n } else {\n changed = true;\n }\n } else {\n changed = true;\n }\n continue;\n }\n if (block.type === 'text') {\n appendPositionedOriginalImages(sourceTextIndex);\n appendReplayBlocks(sourceTextIndex);\n if (replayProjection === 'fallback') {\n projected.push({ type: 'text', text: block.text });\n changed = true;\n } else {\n projected.push(block);\n }\n sourceTextIndex++;\n continue;\n }\n if (originalImages != null && sourceTextIndex >= originalImages.textCount) {\n appendPositionedOriginalImages();\n }\n if (\n block.type === 'server_tool_call' ||\n block.type === 'server_tool_call_chunk'\n ) {\n if (\n typeof block.id === 'string' &&\n block.id.length > 0 &&\n typeof block.name === 'string' &&\n block.name.length > 0\n ) {\n serverToolNamesByCallId.set(block.id, block.name);\n }\n changed = true;\n continue;\n }\n if (block.type === 'server_tool_call_result') {\n if (positionedServerToolResultIds?.has(block.toolCallId) === true) {\n changed = true;\n continue;\n }\n const result = createNeutralServerToolResult(\n block.output,\n block.status,\n maxChars,\n serverToolNamesByCallId.get(block.toolCallId)\n );\n changed = true;\n if (result != null) {\n projected.push(\n replayProjection === 'fallback'\n ? { type: 'text', text: result.text }\n : result\n );\n preservedServerToolResult = true;\n }\n continue;\n }\n if (block.type === 'image') {\n if (\n replayProjection === 'fallback' ||\n (generatedImages != null &&\n isProviderGeneratedImageBlock(block, generatedImages))\n ) {\n changed = true;\n continue;\n }\n }\n projected.push(block);\n }\n\n if (\n encryptedReasoning != null &&\n !hasEncryptedReasoning &&\n positionedReasoning == null\n ) {\n const reasoningBlock: LangChainContentBlock.Standard = {\n type: 'non_standard',\n value: encryptedReasoning,\n };\n projected.splice(reasoningInsertionIndex ?? 0, 0, reasoningBlock);\n changed = true;\n }\n appendPositionedOriginalImages();\n appendReplayBlocks();\n return {\n content: changed ? toLangChainContent(projected) : content,\n preservedServerToolResult,\n };\n}\n\nfunction getAuthoritativeResponsesOutput(message: AIMessage): unknown[] {\n const responseOutput = message.response_metadata.output;\n const toolOutputs = message.additional_kwargs.tool_outputs;\n if (Array.isArray(responseOutput) && responseOutput.length > 0) {\n return responseOutput;\n }\n return Array.isArray(toolOutputs) ? toolOutputs : [];\n}\n\nfunction isResponsesReplayPosition(\n value: unknown\n): value is ResponsesReplayPosition {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n const position = value as Partial<ResponsesReplayPosition>;\n return (\n (position.kind === 'message' ||\n position.kind === 'output' ||\n position.kind === 'reasoning' ||\n position.kind === 'text') &&\n typeof position.itemId === 'string' &&\n position.itemId.length > 0 &&\n typeof position.outputIndex === 'number' &&\n Number.isSafeInteger(position.outputIndex) &&\n position.outputIndex >= 0 &&\n (position.contentIndex == null ||\n (typeof position.contentIndex === 'number' &&\n Number.isSafeInteger(position.contentIndex) &&\n position.contentIndex >= 0))\n );\n}\n\nfunction getGeneratedImageMimeType(data: string): string {\n const bytes = Buffer.from(data.slice(0, 16), 'base64');\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return 'image/jpeg';\n }\n if (\n bytes[0] === 0x52 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x46 &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n ) {\n return 'image/webp';\n }\n return 'image/png';\n}\n\nfunction getResponsesReplayItemKey(\n item: Record<string, unknown>\n): string | undefined {\n if (typeof item.id === 'string' && item.id.length > 0) {\n return item.id;\n }\n return typeof item.call_id === 'string' && item.call_id.length > 0\n ? item.call_id\n : undefined;\n}\n\nfunction comparePositionedResponsesReplayBlocks(\n a: PositionedResponsesReplayBlock,\n b: PositionedResponsesReplayBlock\n): number {\n return (\n (a.textIndex ?? Number.MAX_SAFE_INTEGER) -\n (b.textIndex ?? Number.MAX_SAFE_INTEGER) ||\n a.outputIndex - b.outputIndex ||\n a.subIndex - b.subIndex\n );\n}\n\nconst RESPONSES_REPLAY_OUTPUT_TOOL_NAMES = {\n apply_patch_call_output: 'apply_patch',\n local_shell_call_output: 'local_shell',\n shell_call_output: 'shell',\n} as const;\n\nfunction getResponsesReplayArtifacts(\n output: readonly unknown[],\n maxChars: number,\n replayProjection: ResponsesReplayProjection,\n replayPositionValue?: unknown\n): ResponsesReplayArtifacts {\n const blocks: PositionedResponsesReplayBlock[] = [];\n const data = new Set<string>();\n const ids = new Set<string>();\n const emittedData = new Set<string>();\n const emittedIds = new Set<string>();\n const positionedServerToolResultIds = new Set<string>();\n const rawOutputIndices = new Map<Record<string, unknown>, number>();\n const serverToolResults: PositionedResponsesReplayBlock[] = [];\n const replayPositions = Array.isArray(replayPositionValue)\n ? replayPositionValue.filter(isResponsesReplayPosition)\n : [];\n const authoritativeOutputIndicesByItemId = new Map<string, number>();\n const messagePositionsByKey = new Map<string, ResponsesReplayPosition>();\n const outputPositionsByItemId = new Map<string, ResponsesReplayPosition>();\n const textPositionsByKey = new Map<string, ResponsesReplayPosition>();\n for (const position of replayPositions) {\n if (position.kind === 'output' || position.kind === 'reasoning') {\n outputPositionsByItemId.set(position.itemId, position);\n continue;\n }\n if (position.kind === 'message') {\n messagePositionsByKey.set(\n `${position.itemId}:${position.outputIndex}`,\n position\n );\n continue;\n }\n textPositionsByKey.set(\n `${position.itemId}:${position.outputIndex}:${position.contentIndex ?? 0}`,\n position\n );\n }\n let hasAuthoritativeMessage = false;\n for (let outputIndex = 0; outputIndex < output.length; outputIndex++) {\n const item = output[outputIndex];\n if (item == null || typeof item !== 'object') {\n continue;\n }\n const itemRecord = item as Record<string, unknown>;\n rawOutputIndices.set(itemRecord, outputIndex);\n const itemKey = getResponsesReplayItemKey(itemRecord);\n if (itemKey != null) {\n authoritativeOutputIndicesByItemId.set(itemKey, outputIndex);\n }\n if (!('type' in item) || item.type !== 'message') {\n continue;\n }\n hasAuthoritativeMessage = true;\n const messageItemId =\n 'id' in item && typeof item.id === 'string'\n ? item.id\n : `message-${outputIndex}`;\n messagePositionsByKey.set(`${messageItemId}:${outputIndex}`, {\n itemId: messageItemId,\n kind: 'message',\n outputIndex,\n });\n if (!('content' in item) || !Array.isArray(item.content)) {\n continue;\n }\n for (\n let contentIndex = 0;\n contentIndex < item.content.length;\n contentIndex++\n ) {\n const content = item.content[contentIndex];\n if (\n content == null ||\n typeof content !== 'object' ||\n !('type' in content) ||\n content.type !== 'output_text' ||\n !('text' in content) ||\n typeof content.text !== 'string' ||\n content.text.length === 0\n ) {\n continue;\n }\n const itemId =\n 'id' in item && typeof item.id === 'string'\n ? item.id\n : `message-${outputIndex}`;\n textPositionsByKey.set(`${itemId}:${outputIndex}:${contentIndex}`, {\n contentIndex,\n itemId,\n kind: 'text',\n outputIndex,\n });\n }\n }\n if (hasAuthoritativeMessage) {\n for (const [itemId, outputIndex] of authoritativeOutputIndicesByItemId) {\n outputPositionsByItemId.set(itemId, {\n itemId,\n kind: 'output',\n outputIndex,\n });\n }\n }\n const textPositions = [...textPositionsByKey.values()].sort(\n (a, b) =>\n a.outputIndex - b.outputIndex ||\n (a.contentIndex ?? 0) - (b.contentIndex ?? 0)\n );\n const messagePositions = [...messagePositionsByKey.values()].sort(\n (a, b) => a.outputIndex - b.outputIndex\n );\n const textCountBeforeOutputIndex = new Map<number, number>();\n const positionedOutputIndexSet = new Set<number>();\n for (const position of outputPositionsByItemId.values()) {\n positionedOutputIndexSet.add(position.outputIndex);\n }\n if (hasAuthoritativeMessage) {\n for (const outputIndex of rawOutputIndices.values()) {\n positionedOutputIndexSet.add(outputIndex);\n }\n }\n const positionedOutputIndices = [...positionedOutputIndexSet].sort(\n (a, b) => a - b\n );\n let textPositionIndex = 0;\n for (const outputIndex of positionedOutputIndices) {\n while (\n textPositionIndex < textPositions.length &&\n textPositions[textPositionIndex].outputIndex < outputIndex\n ) {\n textPositionIndex++;\n }\n textCountBeforeOutputIndex.set(outputIndex, textPositionIndex);\n }\n const positionsByItemId = new Map<string, ResponsesReplayItemPosition>();\n for (const [itemId, position] of outputPositionsByItemId) {\n positionsByItemId.set(itemId, {\n outputIndex: position.outputIndex,\n textIndex: textCountBeforeOutputIndex.get(position.outputIndex) ?? 0,\n });\n }\n const getPosition = (\n item: Record<string, unknown>\n ): ResponsesReplayItemPosition => {\n const itemId = getResponsesReplayItemKey(item);\n const position = itemId != null ? positionsByItemId.get(itemId) : undefined;\n if (position == null) {\n const rawOutputIndex = rawOutputIndices.get(item);\n return {\n outputIndex: rawOutputIndex ?? Number.MAX_SAFE_INTEGER,\n ...(hasAuthoritativeMessage && rawOutputIndex != null\n ? {\n textIndex: textCountBeforeOutputIndex.get(rawOutputIndex) ?? 0,\n }\n : {}),\n };\n }\n return position;\n };\n const pushServerToolResult = (\n block: LangChainContentBlock.Standard | undefined,\n item: Record<string, unknown>,\n subIndex = 0\n ): void => {\n if (block == null) {\n return;\n }\n const itemId = getResponsesReplayItemKey(item);\n if (itemId != null) {\n positionedServerToolResultIds.add(itemId);\n }\n serverToolResults.push({ block, ...getPosition(item), subIndex });\n };\n for (const item of output) {\n if (item == null || typeof item !== 'object' || !('type' in item)) {\n continue;\n }\n if (item.type === 'code_interpreter_call') {\n if (\n !('outputs' in item) ||\n !Array.isArray(item.outputs) ||\n !('status' in item)\n ) {\n continue;\n }\n const resultStatus = item.status === 'completed' ? 'success' : 'error';\n const returnCode = item.status === 'completed' ? 0 : 1;\n for (\n let resultIndex = 0;\n resultIndex < item.outputs.length;\n resultIndex++\n ) {\n const result = item.outputs[resultIndex];\n if (\n result == null ||\n typeof result !== 'object' ||\n !('type' in result)\n ) {\n continue;\n }\n if (\n result.type === 'logs' &&\n 'logs' in result &&\n typeof result.logs === 'string'\n ) {\n pushServerToolResult(\n createNeutralServerToolResult(\n {\n type: 'code_interpreter_output',\n returnCode,\n stdout: result.logs,\n },\n resultStatus,\n maxChars,\n 'code_interpreter'\n ),\n item,\n resultIndex\n );\n continue;\n }\n if (\n result.type !== 'image' ||\n !('url' in result) ||\n typeof result.url !== 'string' ||\n result.url.length === 0\n ) {\n continue;\n }\n const resultUrl: string = result.url;\n if (\n replayProjection === 'native' &&\n resultUrl.startsWith('data:image/')\n ) {\n pushServerToolResult(\n {\n type: 'image',\n url: resultUrl,\n extras: createServerToolResultExtras('code_interpreter'),\n },\n item,\n resultIndex\n );\n continue;\n }\n const mediaResult = createNeutralServerToolResult(\n { type: 'code_interpreter_image', url: resultUrl },\n resultStatus,\n maxChars,\n 'code_interpreter'\n );\n pushServerToolResult(mediaResult, item, resultIndex);\n }\n continue;\n }\n if (item.type === 'file_search_call') {\n const result = createNeutralServerToolResult(\n 'results' in item && Array.isArray(item.results)\n ? { results: item.results }\n : undefined,\n 'status' in item && item.status === 'completed' ? 'success' : 'error',\n maxChars,\n 'file_search'\n );\n pushServerToolResult(result, item);\n continue;\n }\n if (item.type === 'web_search_call') {\n const result = createNeutralServerToolResult(\n {\n ...('action' in item ? { action: item.action } : {}),\n ...('results' in item && Array.isArray(item.results)\n ? { results: item.results }\n : {}),\n },\n 'status' in item && item.status === 'completed' ? 'success' : 'error',\n maxChars,\n 'web_search'\n );\n pushServerToolResult(result, item);\n continue;\n }\n if (item.type === 'tool_search_output') {\n const result = createNeutralServerToolResult(\n 'tools' in item && Array.isArray(item.tools)\n ? { tools: item.tools }\n : undefined,\n 'status' in item && item.status === 'completed' ? 'success' : 'error',\n maxChars,\n 'tool_search'\n );\n pushServerToolResult(result, item);\n continue;\n }\n if (item.type === 'mcp_list_tools') {\n const hasError =\n 'error' in item &&\n typeof item.error === 'string' &&\n item.error.length > 0;\n const listToolsResult = createNeutralServerToolResult(\n {\n ...('server_label' in item && typeof item.server_label === 'string'\n ? { serverLabel: item.server_label }\n : {}),\n ...('tools' in item && Array.isArray(item.tools)\n ? { tools: item.tools }\n : {}),\n ...(hasError ? { error: item.error } : {}),\n },\n hasError ? 'error' : 'success',\n maxChars,\n 'mcp_list_tools'\n );\n pushServerToolResult(listToolsResult, item);\n continue;\n }\n if (item.type === 'mcp_call') {\n const hasOutput =\n 'output' in item &&\n typeof item.output === 'string' &&\n item.output.length > 0;\n const hasError =\n 'error' in item &&\n typeof item.error === 'string' &&\n item.error.length > 0;\n if (!hasOutput && !hasError) {\n continue;\n }\n const mcpOutput = {\n ...('name' in item && typeof item.name === 'string'\n ? { name: item.name }\n : {}),\n ...('server_label' in item && typeof item.server_label === 'string'\n ? { serverLabel: item.server_label }\n : {}),\n ...('output' in item && typeof item.output === 'string'\n ? { output: item.output }\n : {}),\n ...('error' in item && typeof item.error === 'string'\n ? { error: item.error }\n : {}),\n };\n const mcpResult = createNeutralServerToolResult(\n mcpOutput,\n hasError ||\n ('status' in item &&\n (item.status === 'failed' || item.status === 'incomplete'))\n ? 'error'\n : 'success',\n maxChars,\n 'name' in item && typeof item.name === 'string' && item.name.length > 0\n ? item.name\n : 'mcp'\n );\n pushServerToolResult(mcpResult, item);\n continue;\n }\n if (\n item.type === 'local_shell_call_output' ||\n item.type === 'shell_call_output' ||\n item.type === 'apply_patch_call_output'\n ) {\n if (!('output' in item)) {\n continue;\n }\n const result = createNeutralServerToolResult(\n item.output,\n 'status' in item &&\n (item.status === 'failed' || item.status === 'incomplete')\n ? 'error'\n : 'success',\n maxChars,\n RESPONSES_REPLAY_OUTPUT_TOOL_NAMES[item.type]\n );\n pushServerToolResult(result, item);\n continue;\n }\n if (item.type === 'program_output') {\n if (!('result' in item)) {\n continue;\n }\n const result = createNeutralServerToolResult(\n item.result,\n 'status' in item && item.status === 'incomplete' ? 'error' : 'success',\n maxChars,\n 'program'\n );\n pushServerToolResult(result, item);\n continue;\n }\n if (item.type !== 'image_generation_call') {\n continue;\n }\n if ('id' in item && typeof item.id === 'string' && item.id.length > 0) {\n ids.add(item.id);\n }\n if (\n !('result' in item) ||\n typeof item.result !== 'string' ||\n item.result.length === 0\n ) {\n continue;\n }\n data.add(item.result);\n if ('status' in item && item.status === 'completed') {\n const itemId =\n 'id' in item && typeof item.id === 'string' && item.id.length > 0\n ? item.id\n : undefined;\n if (\n (itemId != null && emittedIds.has(itemId)) ||\n (itemId == null && emittedData.has(item.result))\n ) {\n continue;\n }\n if (itemId != null) {\n emittedIds.add(itemId);\n } else {\n emittedData.add(item.result);\n }\n blocks.push({\n block: {\n type: 'image',\n mimeType: getGeneratedImageMimeType(item.result),\n data: item.result,\n extras: createServerToolResultExtras('image_generation'),\n },\n ...getPosition(item),\n subIndex: 0,\n });\n }\n }\n return {\n generatedImages: {\n blocks: blocks.sort(comparePositionedResponsesReplayBlocks),\n data,\n ids,\n },\n messagePositions,\n positionedServerToolResultIds,\n positionsByItemId,\n serverToolResults: serverToolResults.sort(\n comparePositionedResponsesReplayBlocks\n ),\n textPositions,\n };\n}\n\nfunction getSelfContainedResponsesV0Images(\n message: AIMessage\n): PositionedResponsesImages {\n if (!Array.isArray(message.content)) {\n return { blocks: [], textCount: 0 };\n }\n const images: PositionedResponsesImage[] = [];\n let textCount = 0;\n for (const block of message.content as LangChainContentBlock.Standard[]) {\n if (block.type === 'text') {\n if (isCompleteToolStreamContentBlock(block)) {\n textCount++;\n }\n continue;\n }\n if (\n block.type === 'image' &&\n (('fileId' in block &&\n typeof block.fileId === 'string' &&\n block.fileId.length > 0) ||\n ('url' in block &&\n typeof block.url === 'string' &&\n block.url.length > 0) ||\n ('data' in block &&\n ((typeof block.data === 'string' && block.data.length > 0) ||\n (block.data instanceof Uint8Array && block.data.length > 0))))\n ) {\n images.push({ block, textIndex: textCount });\n }\n }\n return { blocks: images, textCount };\n}\n\nfunction getResponsesV0ContentBlocks(\n message: AIMessage,\n authoritativeOutput: unknown[]\n): AIMessage['content'] {\n let content = message.content;\n if (typeof content === 'string') {\n content = toLangChainContent(\n content.length > 0 ? [{ type: 'text', text: content }] : []\n );\n }\n const translationMessage = cloneAIMessageWithResponsesReplayState(\n message,\n content,\n message.id,\n {\n ...message.additional_kwargs,\n tool_outputs: authoritativeOutput,\n },\n {\n ...message.response_metadata,\n model_provider: 'openai',\n }\n );\n return toLangChainContent(translationMessage.contentBlocks);\n}\n\nfunction isPreemptedOpenAIResponsesMessage(message: AIMessage): boolean {\n const metadata = message.response_metadata;\n if (metadata.preempted !== true || metadata.model_provider !== 'openai') {\n return false;\n }\n if (\n message.id?.startsWith('msg_') === true ||\n message.id?.startsWith('resp_') === true ||\n (typeof metadata.id === 'string' && metadata.id.startsWith('resp_')) ||\n Array.isArray(metadata.output) ||\n metadata.tool_outputs != null ||\n Array.isArray(message.additional_kwargs.tool_outputs) ||\n message.additional_kwargs[OPENAI_RESPONSES_REPLAY_POSITIONS_KEY] != null ||\n message.additional_kwargs.__openai_function_call_ids__ != null ||\n message.additional_kwargs.__openai_custom_tool_call_ids__ != null ||\n (message.additional_kwargs.reasoning != null &&\n typeof message.additional_kwargs.reasoning === 'object')\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * A sealed Responses turn cannot prove that provider-side item ids were\n * retained: the response object does not echo the request's `store` flag.\n * Project a provider-neutral clone while preserving self-contained encrypted\n * reasoning and the original graph/checkpoint message.\n */\nfunction projectPreemptedOpenAIResponsesMessage(\n message: AIMessage,\n maxChars: number,\n replayProjection: ResponsesReplayProjection\n): AIMessage {\n if (!isPreemptedOpenAIResponsesMessage(message)) {\n return message;\n }\n\n const metadata = message.response_metadata;\n const additionalKwargs = { ...message.additional_kwargs };\n const retainsEncryptedReasoning =\n replayProjection === 'native' &&\n hasReplayableEncryptedReasoning(additionalKwargs.reasoning);\n const authoritativeOutput = getAuthoritativeResponsesOutput(message);\n const {\n generatedImages,\n messagePositions,\n positionedServerToolResultIds,\n positionsByItemId,\n serverToolResults,\n textPositions,\n } = getResponsesReplayArtifacts(\n authoritativeOutput,\n maxChars,\n replayProjection,\n additionalKwargs[OPENAI_RESPONSES_REPLAY_POSITIONS_KEY]\n );\n const reasoningItemId =\n retainsEncryptedReasoning &&\n additionalKwargs.reasoning != null &&\n typeof additionalKwargs.reasoning === 'object' &&\n 'id' in additionalKwargs.reasoning &&\n typeof additionalKwargs.reasoning.id === 'string'\n ? additionalKwargs.reasoning.id\n : undefined;\n const reasoningPosition =\n reasoningItemId != null\n ? positionsByItemId.get(reasoningItemId)\n : undefined;\n const isV1 = metadata.output_version === 'v1';\n const translatesV0 =\n !isV1 &&\n (replayProjection === 'fallback' || authoritativeOutput.length > 0);\n const originalImages =\n replayProjection === 'native' && translatesV0\n ? getSelfContainedResponsesV0Images(message)\n : undefined;\n let contentForProjection = message.content;\n if (!isV1 && translatesV0) {\n contentForProjection = getResponsesV0ContentBlocks(\n message,\n authoritativeOutput\n );\n }\n const projectedContent = projectPreemptedResponsesV1Content(\n contentForProjection,\n isV1 || translatesV0 ? additionalKwargs.reasoning : undefined,\n maxChars,\n replayProjection,\n replayProjection === 'native' ? generatedImages : undefined,\n originalImages,\n serverToolResults,\n positionedServerToolResultIds,\n reasoningPosition,\n textPositions,\n messagePositions\n );\n const promotesV0 =\n !isV1 &&\n (replayProjection === 'fallback' ||\n generatedImages.blocks.length > 0 ||\n projectedContent.preservedServerToolResult);\n const unpromotedV0Content =\n contentForProjection === message.content\n ? projectedContent.content\n : projectPreemptedResponsesV1Content(\n message.content,\n undefined,\n maxChars,\n replayProjection\n ).content;\n const content =\n isV1 || promotesV0 ? projectedContent.content : unpromotedV0Content;\n const hasUnsafeProviderReferences =\n content !== message.content ||\n message.id?.startsWith('msg_') === true ||\n (!retainsEncryptedReasoning && additionalKwargs.reasoning != null) ||\n additionalKwargs.tool_outputs != null ||\n additionalKwargs[OPENAI_RESPONSES_REPLAY_POSITIONS_KEY] != null ||\n additionalKwargs.__openai_function_call_ids__ != null ||\n additionalKwargs.__openai_custom_tool_call_ids__ != null ||\n metadata.id != null ||\n metadata.output != null ||\n metadata.tool_outputs != null;\n if (!hasUnsafeProviderReferences) {\n return message;\n }\n if (!retainsEncryptedReasoning) {\n delete additionalKwargs.reasoning;\n }\n delete additionalKwargs.tool_outputs;\n delete additionalKwargs[OPENAI_RESPONSES_REPLAY_POSITIONS_KEY];\n delete additionalKwargs.__openai_function_call_ids__;\n delete additionalKwargs.__openai_custom_tool_call_ids__;\n\n const responseMetadata: AIMessage['response_metadata'] = { ...metadata };\n delete responseMetadata.id;\n delete responseMetadata.output;\n delete responseMetadata.tool_outputs;\n if (promotesV0) {\n responseMetadata.output_version = 'v1';\n }\n\n return cloneAIMessageWithResponsesReplayState(\n message,\n content,\n message.id?.startsWith('msg_') === true ? undefined : message.id,\n additionalKwargs,\n responseMetadata\n );\n}\n\n/** Applies sealed-Responses safety and drops incomplete streamed text input. */\nexport function projectToolStreamContentForProvider(\n messages: BaseMessage[],\n responsesReplayProjection?: ResponsesReplayProjection,\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (message.getType() !== 'ai') {\n continue;\n }\n const assistantMessage = message as AIMessage;\n if (\n responsesReplayProjection != null &&\n isPreemptedOpenAIResponsesMessage(assistantMessage)\n ) {\n const replaySafeMessage = projectPreemptedOpenAIResponsesMessage(\n assistantMessage,\n maxChars,\n responsesReplayProjection\n );\n if (replaySafeMessage !== assistantMessage) {\n projected ??= [...messages];\n projected[i] = replaySafeMessage;\n }\n continue;\n }\n if (!Array.isArray(assistantMessage.content)) {\n continue;\n }\n const content = assistantMessage.content.filter(\n isCompleteToolStreamContentBlock\n );\n if (content.length === assistantMessage.content.length) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneAIMessageWithContent(\n assistantMessage,\n toLangChainContent(content)\n );\n }\n return projected ?? messages;\n}\n\ntype CacheControlledTextProjection = 'serialize' | 'preserve' | 'text';\n\nfunction projectStructuredOpenAIToolContent(\n content: ToolMessage['content'],\n maxChars: number,\n cacheControlledTextProjection: CacheControlledTextProjection\n): ToolMessage['content'] {\n if (cacheControlledTextProjection !== 'serialize') {\n const cacheControlledContent = getBoundedCacheControlledTextToolContent(\n content,\n maxChars\n );\n if (cacheControlledContent != null) {\n return cacheControlledTextProjection === 'preserve'\n ? cacheControlledContent\n : cacheControlledContent[0].text;\n }\n const singleTextContent = getBoundedSingleTextToolContent(\n content,\n maxChars\n );\n if (singleTextContent != null) {\n return singleTextContent;\n }\n }\n const serializableContent =\n cacheControlledTextProjection === 'preserve'\n ? stripAnthropicCacheControl([{ content }])[0].content\n : content;\n return serializeToolContentBounded(serializableContent, maxChars);\n}\n\n/**\n * OpenAI Chat tool messages only accept strings or text-only parts, while the\n * Responses API serializes any structured ToolMessage after graph accounting.\n * Project every non-string tool result to one bounded string before the final\n * provider payload is measured so both APIs receive the exact representation\n * the budget guard counted. Native Responses computer screenshots stay\n * structured because their dedicated converter sends the media block directly.\n */\nfunction projectOpenAIToolMessageContentInternal(\n messages: BaseMessage[],\n maxChars: number,\n nativeResponsesProjection: boolean,\n cacheControlledTextProjection: CacheControlledTextProjection\n): BaseMessage[] {\n const pendingComputerCallIds: string[] = [];\n const seenComputerCallIds = new Set<string>();\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const messageRole = (message as BaseMessage & { role?: unknown }).role;\n const isAssistant =\n message.getType() === 'ai' || messageRole === 'assistant';\n if (isAssistant) {\n let assistantMessage = message as AIMessage;\n if (nativeResponsesProjection) {\n const replaySafeMessage = projectPreemptedOpenAIResponsesMessage(\n assistantMessage,\n maxChars,\n 'native'\n );\n if (replaySafeMessage !== assistantMessage) {\n projected ??= [...messages];\n projected[i] = replaySafeMessage;\n assistantMessage = replaySafeMessage;\n }\n }\n const parsedComputerCallIds = new Set<string>();\n const toolCalls = assistantMessage.tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const toolCall of toolCalls) {\n const record = toolCall as ToolCall & {\n isComputerTool?: unknown;\n };\n if (\n record.type !== 'tool_call' ||\n record.isComputerTool !== true ||\n typeof record.id !== 'string' ||\n record.id === ''\n ) {\n continue;\n }\n if (parsedComputerCallIds.has(record.id)) {\n throw new Error(`Duplicate computer call id \"${record.id}\"`);\n }\n parsedComputerCallIds.add(record.id);\n if (seenComputerCallIds.has(record.id)) {\n throw new Error(`Duplicate computer call id \"${record.id}\"`);\n }\n seenComputerCallIds.add(record.id);\n pendingComputerCallIds.push(record.id);\n }\n }\n\n const rawOutput = (\n assistantMessage.response_metadata as {\n output?: unknown;\n }\n ).output;\n const fallbackOutput = (\n assistantMessage.additional_kwargs as {\n tool_outputs?: unknown;\n }\n ).tool_outputs;\n let actualToolOutputs: unknown[] = [];\n if (Array.isArray(rawOutput) && rawOutput.length > 0) {\n actualToolOutputs = rawOutput;\n } else if (Array.isArray(fallbackOutput)) {\n actualToolOutputs = fallbackOutput;\n }\n const rawComputerCallIds = new Set<string>();\n for (const item of actualToolOutputs) {\n if (item == null || typeof item !== 'object') {\n continue;\n }\n const record = item as {\n type?: unknown;\n call_id?: unknown;\n };\n if (\n record.type !== 'computer_call' ||\n typeof record.call_id !== 'string' ||\n record.call_id === ''\n ) {\n continue;\n }\n if (rawComputerCallIds.has(record.call_id)) {\n throw new Error(`Duplicate computer call id \"${record.call_id}\"`);\n }\n rawComputerCallIds.add(record.call_id);\n // LangChain can retain the same call in parsed and raw forms. It sends\n // one logical call, so collapse that representation duplicate.\n if (parsedComputerCallIds.has(record.call_id)) {\n continue;\n }\n if (seenComputerCallIds.has(record.call_id)) {\n throw new Error(`Duplicate computer call id \"${record.call_id}\"`);\n }\n seenComputerCallIds.add(record.call_id);\n pendingComputerCallIds.push(record.call_id);\n }\n\n if (\n nativeResponsesProjection &&\n Array.isArray(toolCalls) &&\n rawComputerCallIds.size > 0\n ) {\n /**\n * The non-streaming Responses converter marks parsed computer calls,\n * but the streaming converter currently emits the same call as an\n * ordinary parsed `computer_use` tool call. In both cases the raw\n * `computer_call` item is authoritative and is replayed by LangChain,\n * so remove every parsed representation with the same call id.\n */\n const projectedToolCalls = toolCalls.filter(\n (toolCall) =>\n typeof toolCall.id !== 'string' ||\n !rawComputerCallIds.has(toolCall.id)\n );\n if (projectedToolCalls.length !== toolCalls.length) {\n projected ??= [...messages];\n projected[i] = cloneAIMessageWithToolCalls(\n assistantMessage,\n projectedToolCalls,\n rawComputerCallIds\n );\n }\n }\n }\n\n if (\n message instanceof ToolMessage &&\n hasComputerCallOutputMarker(message)\n ) {\n const screenshot = getComputerCallOutputScreenshot(message.content);\n if (screenshot == null) {\n throw new Error('Invalid computer call output screenshot');\n }\n if (pendingComputerCallIds[0] !== message.tool_call_id) {\n throw new Error(\n `Invalid computer call output pairing for \"${message.tool_call_id}\"`\n );\n }\n pendingComputerCallIds.shift();\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(message, [screenshot]);\n continue;\n }\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n projectStructuredOpenAIToolContent(\n message.content,\n maxChars,\n cacheControlledTextProjection\n )\n );\n }\n if (pendingComputerCallIds.length > 0) {\n throw new Error(\n `Missing computer call output for \"${pendingComputerCallIds[0]}\"`\n );\n }\n return projected ?? messages;\n}\n\n/** Projects OpenAI-compatible tool content without changing parsed call parents. */\nexport function projectOpenAIToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'serialize'\n );\n}\n\n/** Projects an actual OpenAI-compatible Chat attempt and removes cache metadata. */\nexport function projectOpenAIChatToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'text'\n );\n}\n\n/** Preserves OpenRouter's cache-decorated text blocks for a Chat attempt. */\nexport function projectOpenRouterToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n false,\n 'preserve'\n );\n}\n\n/** Projects Responses tool content and collapses parsed/raw computer-call mirrors. */\nexport function projectOpenAIResponsesToolMessageContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n return projectOpenAIToolMessageContentInternal(\n messages,\n maxChars,\n true,\n 'text'\n );\n}\n\n/** Removes Anthropic/OpenRouter cache metadata before unsupported providers run. */\nexport function projectCacheControlledToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n const cacheControlledContent = getBoundedCacheControlledTextToolContent(\n message.content,\n maxChars\n );\n if (cacheControlledContent == null) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n cacheControlledContent[0].text\n );\n }\n return projected ?? messages;\n}\n\n/** Unwraps a canonical single text block after provider cache markers are removed. */\nexport function projectSingleTextToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string'\n ) {\n continue;\n }\n const text = getBoundedSingleTextToolContent(message.content, maxChars);\n if (text == null) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(message, text);\n }\n return projected ?? messages;\n}\n\n/** Serializes provider-neutral structured tool outputs without media pairing. */\nexport function projectStructuredToolOutputsToText(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n typeof message.content === 'string' ||\n hasComputerCallOutputMarker(message)\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n serializeToolContentBounded(message.content, maxChars)\n );\n }\n return projected ?? messages;\n}\n\n/**\n * Non-Responses providers cannot consume native computer screenshots. Keep\n * the tool-call structure intact, but replace screenshot bytes with a bounded\n * text marker at the actual invocation boundary.\n */\nexport function projectComputerCallOutputsToText(\n messages: BaseMessage[]\n): BaseMessage[] {\n let projected: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n if (\n !(message instanceof ToolMessage) ||\n !hasComputerCallOutputMarker(message)\n ) {\n continue;\n }\n projected ??= [...messages];\n projected[i] = cloneToolMessageWithContent(\n message,\n '[Computer screenshot omitted for this provider]'\n );\n }\n return projected ?? messages;\n}\n\nexport function projectAnthropicArtifactContent(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return messages;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n ((msg instanceof AIMessage || msg instanceof AIMessageChunk) &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return messages;\n\n // Build tool call ID set and merge artifact content in a single forward pass.\n const message = messages[latestAIParentIndex] as AIMessage | AIMessageChunk;\n const toolCallIdSet = new Set<string>();\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n if (tc.id != null) {\n toolCallIdSet.add(tc.id);\n }\n }\n }\n\n let formattedMessages: BaseMessage[] | undefined;\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (\n msg instanceof ToolMessage &&\n !isComputerCallOutputMessage(msg) &&\n toolCallIdSet.has(msg.tool_call_id) &&\n msg.artifact != null &&\n ((typeof msg.artifact?.content === 'string' &&\n msg.artifact.content.length > 0) ||\n (Array.isArray(msg.artifact?.content) &&\n msg.artifact.content.length > 0))\n ) {\n const artifactContent =\n typeof msg.artifact.content === 'string'\n ? [\n {\n type: ContentTypes.TEXT,\n text: msg.artifact.content,\n },\n ]\n : msg.artifact.content;\n const baseContent = Array.isArray(msg.content)\n ? msg.content\n : stringifyToolMessageContent(msg.content);\n const content = appendBoundedContent(\n compactToolContent(baseContent, maxChars).content,\n artifactContent,\n maxChars\n );\n formattedMessages ??= [...messages];\n formattedMessages[j] = cloneToolMessageWithContent(msg, content, {\n ...msg.artifact,\n content: [],\n });\n }\n }\n return formattedMessages ?? messages;\n}\n\n/**\n * Mutating compatibility wrapper retained for existing package consumers.\n * New provider-call paths should use `projectAnthropicArtifactContent`.\n */\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const projected = projectAnthropicArtifactContent(messages);\n if (projected === messages) {\n return;\n }\n for (let i = 0; i < messages.length; i++) {\n if (\n messages[i] instanceof ToolMessage &&\n projected[i] instanceof ToolMessage &&\n projected[i] !== messages[i]\n ) {\n messages[i].content = projected[i].content;\n }\n }\n}\n\nexport function projectArtifactPayload(\n messages: BaseMessage[],\n maxChars = HARD_MAX_TOOL_RESULT_CHARS\n): BaseMessage[] {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return messages;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n ((msg instanceof AIMessage || msg instanceof AIMessageChunk) &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastMessageY.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return messages;\n\n // Single pass: collect relevant tool messages with artifacts and aggregate\n let aggregatedContent: BaseMessage['content'] | undefined;\n let formattedMessages: BaseMessage[] | undefined;\n\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (\n !(msg instanceof ToolMessage) ||\n isComputerCallOutputMessage(msg) ||\n !(\n (typeof msg.artifact?.content === 'string' &&\n msg.artifact.content.length > 0) ||\n (Array.isArray(msg.artifact?.content) &&\n msg.artifact.content.length > 0)\n )\n ) {\n continue;\n }\n aggregatedContent = appendBoundedContent(\n aggregatedContent,\n msg.content,\n maxChars\n );\n formattedMessages ??= [...messages];\n formattedMessages[i] = cloneToolMessageWithContent(\n msg,\n 'Tool response is included in the next message as a Human message',\n {\n ...msg.artifact,\n content: [],\n }\n );\n aggregatedContent = appendBoundedContent(\n aggregatedContent,\n msg.artifact.content,\n maxChars\n );\n }\n\n if (aggregatedContent != null) {\n formattedMessages?.push(new HumanMessage({ content: aggregatedContent }));\n }\n return formattedMessages ?? messages;\n}\n\n/**\n * Mutating compatibility wrapper retained for existing package consumers.\n * New provider-call paths should use `projectArtifactPayload`.\n */\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const originalLength = messages.length;\n const projected = projectArtifactPayload(messages);\n if (projected === messages) {\n return;\n }\n for (let i = 0; i < originalLength; i++) {\n if (\n messages[i] instanceof ToolMessage &&\n projected[i] instanceof ToolMessage &&\n projected[i] !== messages[i]\n ) {\n messages[i].content = projected[i].content;\n }\n }\n messages.push(...projected.slice(originalLength));\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;AAmCA,SAAgB,2BAA2B,EACzC,aACA,cACA,gBAKe;CAiBf,OAAO,IAAIA,yBAAAA,aAAa;QAflB,YAAY,GAAG;;;;;;IAMnB,cAAc,QAAQ;;;IAGtB,cAAc,YAAY,KAAK,MAAM,EAAE;;;IAGvC,aAAa,QAAQ;CAGQ;AACjC;AAEA,MAAM,gBAAgB;CAAC;CAAa;CAAQ;CAAY;AAAa;AACrE,MAAM,yBAAmD;CACvD,SAAS;gBACc;EACrB,GAAG;EACH;EACA;EACA;EACA;EACA;CACF;cACqB,CAAC,GAAG,eAAe,mBAAmB;aACvC;AACtB;AAEA,MAAM,iBAAiB,EACrB,UACA,aACA,cAKyC;CACzC,MAAM,eACJ,uBAAuB,aAAa,uBAAuB;CAC7D,OAAO,QAAQ,KAAK,SAA0C;EAC5D,IACE,QACA,OAAO,SAAS,YAChB,UAAU,QACV,KAAK,QAAQ,QACb,KAAK,MACL;GACA,IAAI,UAAU,KAAK;GACnB,IAAI,QAAQ,SAAS,QAAQ,GAC3B,UAAU,QAAQ,QAAQ,UAAU,EAAE;GAExC,IAAI,CAAC,aAAa,SAAS,OAAO,GAChC,UAAU;GAIZ,IACE,gBAAgB,QAChB,YAAY,cACZ,WAAW,QACX,KAAK,UAAU,IAEf,OAAO;IAAE,GAAG;IAAM,MAAM;IAAS,OAAO;GAAK;GAG/C,OAAO;IAAE,GAAG;IA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AAE,eAAeJ,yBAAAA,gBACjBK,oBAAAA,4BAA4B,GAAG,KAC/B,EACG,OAAO,IAAI,UAAU,YAAY,YAChC,IAAI,SAAS,QAAQ,SAAS,KAC/B,MAAM,QAAQ,IAAI,UAAU,OAAO,KAClC,IAAI,SAAS,QAAQ,SAAS,IAGlC;EAEF,oBAAoB,qBAClB,mBACA,IAAI,SACJ,QACF;EACA,sBAAsB,CAAC,GAAG,QAAQ;EAClC,kBAAkB,KAAKF,oBAAAA,4BACrB,KACA,oEACA;GACE,GAAG,IAAI;GACP,SAAS,CAAC;EACZ,CACF;EACA,oBAAoB,qBAClB,mBACA,IAAI,SAAS,SACb,QACF;CACF;CAEA,IAAI,qBAAqB,MACvB,mBAAmB,KAAK,IAAIZ,yBAAAA,aAAa,EAAE,SAAS,kBAAkB,CAAC,CAAC;CAE1E,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,sBAAsB,UAA+B;CACnE,MAAM,iBAAiB,SAAS;CAChC,MAAM,YAAY,uBAAuB,QAAQ;CACjD,IAAI,cAAc,UAChB;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,gBAAgB,KAClC,IACE,SAAS,cAAcS,yBAAAA,eACvB,UAAU,cAAcA,yBAAAA,eACxB,UAAU,OAAO,SAAS,IAE1B,SAAS,EAAE,CAAC,UAAU,UAAU,EAAE,CAAC;CAGvC,SAAS,KAAK,GAAG,UAAU,MAAM,cAAc,CAAC;AAClD;AAEA,SAAgB,cACd,OACA,WACQ;CACR,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KACrC,IAAI,UAAU,MAAM,EAAE,GACpB,OAAO;CAGX,OAAO;AACT"}
|
package/dist/cjs/run.cjs
CHANGED
|
@@ -10,8 +10,8 @@ const require_callbacks = require("./utils/callbacks.cjs");
|
|
|
10
10
|
const require_title = require("./utils/title.cjs");
|
|
11
11
|
const require_tokens = require("./utils/tokens.cjs");
|
|
12
12
|
const require_instrumentation = require("./instrumentation.cjs");
|
|
13
|
-
const require_preempt = require("./llm/preempt.cjs");
|
|
14
13
|
const require_llm = require("./utils/llm.cjs");
|
|
14
|
+
const require_preempt = require("./llm/preempt.cjs");
|
|
15
15
|
const require_events = require("./events.cjs");
|
|
16
16
|
const require_init = require("./llm/init.cjs");
|
|
17
17
|
const require_executeHooks = require("./hooks/executeHooks.cjs");
|
|
@@ -377,6 +377,16 @@ var Run = class Run {
|
|
|
377
377
|
return this.Graph.getRunMessages();
|
|
378
378
|
}
|
|
379
379
|
/**
|
|
380
|
+
* Returns a defensive snapshot of tools discovered by the current run.
|
|
381
|
+
* Pass an agent id for that context, or omit it for the ordered union across
|
|
382
|
+
* contexts. Interrupted state is available immediately for host persistence;
|
|
383
|
+
* completed runs retain their final snapshot through graph cleanup.
|
|
384
|
+
*/
|
|
385
|
+
getDiscoveredTools(agentId) {
|
|
386
|
+
if (!this.Graph) throw new Error("Graph not initialized. Make sure to use Run.create() to instantiate the Run.");
|
|
387
|
+
return this.Graph.getDiscoveredTools(agentId);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
380
390
|
* Returns the current calibration ratio (EMA of provider-vs-estimate token ratios).
|
|
381
391
|
* Hosts should persist this value and pass it back as `RunConfig.calibrationRatio`
|
|
382
392
|
* on the next run for the same conversation so the pruner starts with an accurate
|