@librechat/agents 3.1.72 → 3.1.74
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 +62 -20
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +11 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +1 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +27 -1
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +21 -11
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +37 -10
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +21 -2
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +62 -20
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +11 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -1
- package/dist/esm/messages/format.mjs +27 -1
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +22 -12
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +37 -11
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -12
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +21 -2
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +15 -0
- package/dist/types/messages/format.d.ts +11 -1
- package/dist/types/tools/CodeExecutor.d.ts +6 -0
- package/dist/types/types/tools.d.ts +9 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +66 -27
- package/src/agents/__tests__/AgentContext.test.ts +178 -0
- package/src/graphs/Graph.ts +12 -1
- package/src/messages/ensureThinkingBlock.test.ts +167 -0
- package/src/messages/format.ts +29 -1
- package/src/tools/BashExecutor.ts +37 -13
- package/src/tools/CodeExecutor.ts +55 -11
- package/src/tools/ProgrammaticToolCalling.ts +29 -14
- package/src/tools/ToolNode.ts +21 -2
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +60 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +124 -0
- package/src/types/tools.ts +9 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.cjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n SummaryContentBlock,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport { emitAgentLog } from '@/utils/events';\nimport { Providers, ContentTypes, Constants } from '@/common';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content as Array<\n MessageContentComplex | undefined | null\n >) {\n if (part == null) {\n continue;\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text != null ? part.text : '',\n });\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output != null ? output : '',\n })\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY\n ) {\n continue;\n } else {\n if (\n part.type === ContentTypes.TEXT &&\n !String(part.text ?? '').trim()\n ) {\n continue;\n }\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\n}\n\nfunction getSourceMessageId(message: Partial<TMessage>): string | undefined {\n const candidate =\n (message as { messageId?: string }).messageId ??\n (message as { id?: string }).id;\n if (typeof candidate !== 'string') {\n return undefined;\n }\n const normalized = candidate.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\ntype SummaryBoundary = {\n messageIndex: number;\n contentIndex: number;\n text: string;\n tokenCount: number;\n};\n\nfunction getLatestSummaryBoundary(\n payload: TPayload\n): SummaryBoundary | undefined {\n let summaryBoundary: SummaryBoundary | undefined;\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n for (let j = 0; j < message.content.length; j++) {\n const part = message.content[j] as MessageContentComplex | undefined;\n if (part == null || part.type !== ContentTypes.SUMMARY) {\n continue;\n }\n\n const summaryPart = part as Partial<SummaryContentBlock> & {\n text?: string;\n };\n\n // Try content array first (new format), then direct text (legacy format)\n let summaryText = (summaryPart.content ?? [])\n .map((block) =>\n 'text' in block ? (block as { text: string }).text : ''\n )\n .join('')\n .trim();\n\n // Fallback: legacy format where text was a direct field on the block\n if (summaryText.length === 0 && typeof summaryPart.text === 'string') {\n summaryText = summaryPart.text.trim();\n }\n\n if (summaryText.length === 0) {\n continue;\n }\n\n summaryBoundary = {\n messageIndex: i,\n contentIndex: j,\n text: summaryText,\n tokenCount:\n typeof summaryPart.tokenCount === 'number' &&\n Number.isFinite(summaryPart.tokenCount)\n ? summaryPart.tokenCount\n : 0,\n };\n }\n }\n\n return summaryBoundary;\n}\n\nfunction applySummaryBoundary(\n message: Partial<TMessage>,\n messageIndex: number,\n summaryBoundary?: SummaryBoundary\n): Partial<TMessage> | null {\n if (!summaryBoundary) {\n return message;\n }\n\n if (messageIndex < summaryBoundary.messageIndex) {\n return null;\n }\n\n if (\n messageIndex !== summaryBoundary.messageIndex ||\n !Array.isArray(message.content)\n ) {\n return message;\n }\n\n return {\n ...message,\n content: message.content.slice(summaryBoundary.contentIndex + 1),\n };\n}\n\nfunction contentPartCharLength(part: MessageContentComplex): number {\n const record = part as Record<string, unknown>;\n let len = 0;\n if (typeof record.text === 'string') {\n len += record.text.length;\n }\n if (typeof record.thinking === 'string') {\n len += record.thinking.length;\n }\n const { input } = record;\n if (typeof input === 'string') {\n len += input.length;\n } else if (input != null && typeof input === 'object') {\n len += JSON.stringify(input).length;\n }\n return len;\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n /** Pre-resolved skill bodies keyed by skill name. When present, HumanMessages\n * are reconstructed after skill ToolMessages to restore skill instructions\n * that were only in LangGraph state during the original run. */\n skills?: Map<string, string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n /** Cross-run summary extracted from the payload. Should be forwarded to the\n * agent run so it can be included in the system message via AgentContext. */\n summary?: { text: string; tokenCount: number };\n /** When a summary boundary sliced content from a message, the token count\n * was proportionally reduced. Returned so the caller can log it. */\n boundaryTokenAdjustment?: {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n };\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n let boundaryTokenAdjustment:\n | {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n }\n | undefined;\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n const summaryBoundary = getLatestSummaryBoundary(payload);\n\n // Summary metadata is returned to the caller so it can be forwarded to the\n // agent run and included in the single system message via AgentContext.\n // We intentionally do NOT create a SystemMessage here — that would conflict\n // with the agent's own system message (instructions + summary combined).\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const rawMessage = payload[i];\n const sourceMessageId = getSourceMessageId(rawMessage);\n let message = applySummaryBoundary(rawMessage, i, summaryBoundary);\n if (!message) {\n indexMapping[i] = [];\n continue;\n }\n\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message = {\n ...message,\n content: [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ],\n };\n } else if (Array.isArray(message.content) && message.content.length === 0) {\n indexMapping[i] = [];\n continue;\n }\n\n if (message.role !== 'assistant') {\n const formattedMessage = formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage;\n if (sourceMessageId != null && sourceMessageId !== '') {\n formattedMessage.id = sourceMessageId;\n }\n messages.push(formattedMessage);\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content != null && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n filteredContent.push(part);\n if (\n toolName === Constants.SKILL_TOOL &&\n skills?.size != null &&\n skills.size > 0\n ) {\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n /** When tools filtering is off, still detect skill tool_calls for body reconstruction */\n if (!discoveredTools && skills?.size != null && skills.size > 0) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n const formattedMessages = formatAssistantMessage(processedMessage);\n if (sourceMessageId != null && sourceMessageId !== '') {\n for (const formattedMessage of formattedMessages) {\n formattedMessage.id = sourceMessageId;\n }\n }\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution.\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size != null && pendingSkillNames.size > 0) {\n for (const skillName of pendingSkillNames) {\n const body = skills?.get(skillName) ?? '';\n if (body) {\n messages.push(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n })\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n let tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n if (\n summaryBoundary &&\n originalIndex === summaryBoundary.messageIndex &&\n Array.isArray(payload[originalIndex].content)\n ) {\n const content = payload[originalIndex]\n .content as MessageContentComplex[];\n const { contentIndex } = summaryBoundary;\n if (contentIndex >= 0 && contentIndex < content.length - 1) {\n let totalCharLen = 0;\n let remainingCharLen = 0;\n for (let p = 0; p < content.length; p++) {\n const charLen = contentPartCharLength(content[p]);\n totalCharLen += charLen;\n if (p > contentIndex) {\n remainingCharLen += charLen;\n }\n }\n if (totalCharLen > 0) {\n const original = tokenCount;\n tokenCount = Math.max(\n 1,\n Math.round(tokenCount * (remainingCharLen / totalCharLen))\n );\n boundaryTokenAdjustment = {\n original,\n adjusted: tokenCount,\n remainingChars: remainingCharLen,\n totalChars: totalCharLen,\n };\n }\n }\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n len += JSON.stringify(args).length;\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n summary: summaryBoundary\n ? { text: summaryBoundary.text, tokenCount: summaryBoundary.tokenCount }\n : undefined,\n boundaryTokenAdjustment,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Block types that contain binary image data and must be preserved structurally. */\nconst IMAGE_BLOCK_TYPES = new Set(['image_url', 'image']);\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Image blocks are shallow-copied into `parts` as-is so that\n * binary data (base64 images) never becomes text tokens. All other block\n * types are serialized to text — unrecognized types are JSON-serialized\n * rather than silently dropped.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content) {\n textChunks.push(`${role}: ${content}`);\n }\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (IMAGE_BLOCK_TYPES.has(block.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n continue;\n }\n\n if (block.type === 'tool_use') {\n hasToolUseBlock = true;\n textChunks.push(\n `${role}: [tool_use] ${String(block.name ?? '')} ${JSON.stringify(block.input ?? {})}`\n );\n continue;\n }\n\n const text = block.text ?? block.input;\n if (typeof text === 'string' && text) {\n textChunks.push(`${role}: ${text}`);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (block.type != null && block.type !== '') {\n textChunks.push(`${role}: [${block.type}] ${JSON.stringify(block)}`);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[]\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (!aiMsg.tool_calls || aiMsg.tool_calls.length === 0) {\n return;\n }\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @param config - Optional RunnableConfig for structured agent logging\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers,\n config?: RunnableConfig\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // Find the last HumanMessage. Only the trailing sequence after it needs\n // validation — earlier messages are history already accepted by the provider.\n let lastHumanIndex = -1;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (\n m instanceof HumanMessage ||\n ('role' in m && (m as any).role === 'user')\n ) {\n lastHumanIndex = k;\n break;\n }\n }\n\n if (lastHumanIndex === messages.length - 1) {\n return messages;\n }\n\n const result: BaseMessage[] =\n lastHumanIndex >= 0 ? messages.slice(0, lastHumanIndex + 1) : [];\n let i = lastHumanIndex + 1;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n if (c.type === 'tool_use') {\n hasToolUse = true;\n } else if (\n c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous agent context]'];\n\n appendMessageContent(msg, 'AI', textChunks, parts);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n emitAgentLog(\n config,\n 'warn',\n 'format',\n 'ensureThinkingBlockInMessages: injecting [Previous agent context] HumanMessage' +\n ` (${parts.length} msgs at index ${i}, no thinking block in chain)`\n );\n result.push(new HumanMessage({ content: parts }));\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are part of the chain — keep walking back\n }\n\n return false;\n}\n"],"names":["Providers","ContentTypes","HumanMessage","AIMessage","SystemMessage","ToolMessage","messages","Constants","AIMessageChunk","emitAgentLog"],"mappings":";;;;;;AAAA;AAoCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAKA,eAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAEC,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;IACf;IAEA,MAAM,CAAC,OAAO,GAAG;QACf,EAAE,IAAI,EAAEA,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;AAClD,QAAA,GAAG,UAAU;KACa;AAE5B,IAAA,OAAO,MAAM;AACf;AA+BA;;;;;AAKG;AACI,MAAM,aAAa,GAAG,CAA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../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n SummaryContentBlock,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport { emitAgentLog } from '@/utils/events';\nimport { Providers, ContentTypes, Constants } from '@/common';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content as Array<\n MessageContentComplex | undefined | null\n >) {\n if (part == null) {\n continue;\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text != null ? part.text : '',\n });\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = new AIMessage({ content: '' });\n formattedMessages.push(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output != null ? output : '',\n })\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE ||\n part.type === ContentTypes.SUMMARY\n ) {\n continue;\n } else {\n if (\n part.type === ContentTypes.TEXT &&\n !String(part.text ?? '').trim()\n ) {\n continue;\n }\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\n}\n\nfunction getSourceMessageId(message: Partial<TMessage>): string | undefined {\n const candidate =\n (message as { messageId?: string }).messageId ??\n (message as { id?: string }).id;\n if (typeof candidate !== 'string') {\n return undefined;\n }\n const normalized = candidate.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\ntype SummaryBoundary = {\n messageIndex: number;\n contentIndex: number;\n text: string;\n tokenCount: number;\n};\n\nfunction getLatestSummaryBoundary(\n payload: TPayload\n): SummaryBoundary | undefined {\n let summaryBoundary: SummaryBoundary | undefined;\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n for (let j = 0; j < message.content.length; j++) {\n const part = message.content[j] as MessageContentComplex | undefined;\n if (part == null || part.type !== ContentTypes.SUMMARY) {\n continue;\n }\n\n const summaryPart = part as Partial<SummaryContentBlock> & {\n text?: string;\n };\n\n // Try content array first (new format), then direct text (legacy format)\n let summaryText = (summaryPart.content ?? [])\n .map((block) =>\n 'text' in block ? (block as { text: string }).text : ''\n )\n .join('')\n .trim();\n\n // Fallback: legacy format where text was a direct field on the block\n if (summaryText.length === 0 && typeof summaryPart.text === 'string') {\n summaryText = summaryPart.text.trim();\n }\n\n if (summaryText.length === 0) {\n continue;\n }\n\n summaryBoundary = {\n messageIndex: i,\n contentIndex: j,\n text: summaryText,\n tokenCount:\n typeof summaryPart.tokenCount === 'number' &&\n Number.isFinite(summaryPart.tokenCount)\n ? summaryPart.tokenCount\n : 0,\n };\n }\n }\n\n return summaryBoundary;\n}\n\nfunction applySummaryBoundary(\n message: Partial<TMessage>,\n messageIndex: number,\n summaryBoundary?: SummaryBoundary\n): Partial<TMessage> | null {\n if (!summaryBoundary) {\n return message;\n }\n\n if (messageIndex < summaryBoundary.messageIndex) {\n return null;\n }\n\n if (\n messageIndex !== summaryBoundary.messageIndex ||\n !Array.isArray(message.content)\n ) {\n return message;\n }\n\n return {\n ...message,\n content: message.content.slice(summaryBoundary.contentIndex + 1),\n };\n}\n\nfunction contentPartCharLength(part: MessageContentComplex): number {\n const record = part as Record<string, unknown>;\n let len = 0;\n if (typeof record.text === 'string') {\n len += record.text.length;\n }\n if (typeof record.thinking === 'string') {\n len += record.thinking.length;\n }\n const { input } = record;\n if (typeof input === 'string') {\n len += input.length;\n } else if (input != null && typeof input === 'object') {\n len += JSON.stringify(input).length;\n }\n return len;\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n /** Pre-resolved skill bodies keyed by skill name. When present, HumanMessages\n * are reconstructed after skill ToolMessages to restore skill instructions\n * that were only in LangGraph state during the original run. */\n skills?: Map<string, string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n /** Cross-run summary extracted from the payload. Should be forwarded to the\n * agent run so it can be included in the system message via AgentContext. */\n summary?: { text: string; tokenCount: number };\n /** When a summary boundary sliced content from a message, the token count\n * was proportionally reduced. Returned so the caller can log it. */\n boundaryTokenAdjustment?: {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n };\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n let boundaryTokenAdjustment:\n | {\n original: number;\n adjusted: number;\n remainingChars: number;\n totalChars: number;\n }\n | undefined;\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n const summaryBoundary = getLatestSummaryBoundary(payload);\n\n // Summary metadata is returned to the caller so it can be forwarded to the\n // agent run and included in the single system message via AgentContext.\n // We intentionally do NOT create a SystemMessage here — that would conflict\n // with the agent's own system message (instructions + summary combined).\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const rawMessage = payload[i];\n const sourceMessageId = getSourceMessageId(rawMessage);\n let message = applySummaryBoundary(rawMessage, i, summaryBoundary);\n if (!message) {\n indexMapping[i] = [];\n continue;\n }\n\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message = {\n ...message,\n content: [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ],\n };\n } else if (Array.isArray(message.content) && message.content.length === 0) {\n indexMapping[i] = [];\n continue;\n }\n\n if (message.role !== 'assistant') {\n const formattedMessage = formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage;\n if (sourceMessageId != null && sourceMessageId !== '') {\n formattedMessage.id = sourceMessageId;\n }\n messages.push(formattedMessage);\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content != null && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n filteredContent.push(part);\n if (\n toolName === Constants.SKILL_TOOL &&\n skills?.size != null &&\n skills.size > 0\n ) {\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n /** When tools filtering is off, still detect skill tool_calls for body reconstruction */\n if (!discoveredTools && skills?.size != null && skills.size > 0) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args) ?? '';\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n const formattedMessages = formatAssistantMessage(processedMessage);\n if (sourceMessageId != null && sourceMessageId !== '') {\n for (const formattedMessage of formattedMessages) {\n formattedMessage.id = sourceMessageId;\n }\n }\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution.\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size != null && pendingSkillNames.size > 0) {\n for (const skillName of pendingSkillNames) {\n const body = skills?.get(skillName) ?? '';\n if (body) {\n messages.push(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n })\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n let tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n if (\n summaryBoundary &&\n originalIndex === summaryBoundary.messageIndex &&\n Array.isArray(payload[originalIndex].content)\n ) {\n const content = payload[originalIndex]\n .content as MessageContentComplex[];\n const { contentIndex } = summaryBoundary;\n if (contentIndex >= 0 && contentIndex < content.length - 1) {\n let totalCharLen = 0;\n let remainingCharLen = 0;\n for (let p = 0; p < content.length; p++) {\n const charLen = contentPartCharLength(content[p]);\n totalCharLen += charLen;\n if (p > contentIndex) {\n remainingCharLen += charLen;\n }\n }\n if (totalCharLen > 0) {\n const original = tokenCount;\n tokenCount = Math.max(\n 1,\n Math.round(tokenCount * (remainingCharLen / totalCharLen))\n );\n boundaryTokenAdjustment = {\n original,\n adjusted: tokenCount,\n remainingChars: remainingCharLen,\n totalChars: totalCharLen,\n };\n }\n }\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n len += JSON.stringify(args).length;\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n summary: summaryBoundary\n ? { text: summaryBoundary.text, tokenCount: summaryBoundary.tokenCount }\n : undefined,\n boundaryTokenAdjustment,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Block types that contain binary image data and must be preserved structurally. */\nconst IMAGE_BLOCK_TYPES = new Set(['image_url', 'image']);\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Image blocks are shallow-copied into `parts` as-is so that\n * binary data (base64 images) never becomes text tokens. All other block\n * types are serialized to text — unrecognized types are JSON-serialized\n * rather than silently dropped.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content) {\n textChunks.push(`${role}: ${content}`);\n }\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (IMAGE_BLOCK_TYPES.has(block.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n continue;\n }\n\n if (block.type === 'tool_use') {\n hasToolUseBlock = true;\n textChunks.push(\n `${role}: [tool_use] ${String(block.name ?? '')} ${JSON.stringify(block.input ?? {})}`\n );\n continue;\n }\n\n const text = block.text ?? block.input;\n if (typeof text === 'string' && text) {\n textChunks.push(`${role}: ${text}`);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (block.type != null && block.type !== '') {\n textChunks.push(`${role}: [${block.type}] ${JSON.stringify(block)}`);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[]\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (!aiMsg.tool_calls || aiMsg.tool_calls.length === 0) {\n return;\n }\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @param config - Optional RunnableConfig for structured agent logging\n * @param runStartIndex - Index in `messages` where the CURRENT run's own\n * appended AI/Tool messages begin (i.e. anything at this index or later\n * was just produced by this run's own iterations, not historical\n * context). When provided, AI messages at or after this index are\n * never converted to `[Previous agent context]` placeholders — Claude\n * can validly skip a thinking block before a tool_use (cf. PR #116),\n * so the agent's own in-run iterations must not be misclassified as\n * foreign history. Without the signal the function falls back to its\n * prior heuristic (`chainHasThinkingBlock`), preserving backward\n * compatibility for callers that don't yet pass the boundary.\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers,\n config?: RunnableConfig,\n runStartIndex?: number\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // Find the last HumanMessage. Only the trailing sequence after it needs\n // validation — earlier messages are history already accepted by the provider.\n let lastHumanIndex = -1;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (\n m instanceof HumanMessage ||\n ('role' in m && (m as any).role === 'user')\n ) {\n lastHumanIndex = k;\n break;\n }\n }\n\n if (lastHumanIndex === messages.length - 1) {\n return messages;\n }\n\n const result: BaseMessage[] =\n lastHumanIndex >= 0 ? messages.slice(0, lastHumanIndex + 1) : [];\n let i = lastHumanIndex + 1;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n if (c.type === 'tool_use') {\n hasToolUse = true;\n } else if (\n c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Current-run boundary check: anything at or after `runStartIndex`\n // is the current run's own work — preserve it. Claude is allowed\n // to skip a thinking block before a tool_use (cf. PR #116 in the\n // agents repo), so the agent's own first-iteration AI message can\n // legitimately have tool_calls without reasoning. Converting it to\n // a `[Previous agent context]` placeholder pollutes the next\n // iteration's prompt — the LLM sees the placeholder, treats it as\n // suspicious injected content, ignores its own real prior tool\n // result, and re-runs the tool to verify (which then often fails\n // because subsequent calls land in fresh sandboxes without the\n // file). Skip the conversion when we know this is in-run.\n if (runStartIndex !== undefined && i >= runStartIndex) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous agent context]'];\n\n appendMessageContent(msg, 'AI', textChunks, parts);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n emitAgentLog(\n config,\n 'warn',\n 'format',\n 'ensureThinkingBlockInMessages: injecting [Previous agent context] HumanMessage' +\n ` (${parts.length} msgs at index ${i}, no thinking block in chain)`\n );\n result.push(new HumanMessage({ content: parts }));\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are part of the chain — keep walking back\n }\n\n return false;\n}\n"],"names":["Providers","ContentTypes","HumanMessage","AIMessage","SystemMessage","ToolMessage","messages","Constants","AIMessageChunk","emitAgentLog"],"mappings":";;;;;;AAAA;AAoCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAKA,eAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAEC,kBAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;IACf;IAEA,MAAM,CAAC,OAAO,GAAG;QACf,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AI,KAAKA,kBAAY,CAAC,iBAAiB;AACzC,wBAAA,CAAC,CAAC,IAAI,KAAKA,kBAAY,CAAC,SAAS;AACjC,wBAAA,CAAC,CAAC,IAAI,KAAK,mBAAmB,CAAC,CACpC,EACD;AACA,oBAAA,OAAO,IAAI;gBACb;YACF;;YAGA,IAAI,SAAS,CAAC,iBAAiB,CAAC,iBAAiB,IAAI,IAAI,EAAE;AACzD,gBAAA,OAAO,IAAI;YACb;QACF;;IAGF;AAEA,IAAA,OAAO,KAAK;AACd;;;;;;;;;;;"}
|
|
@@ -8,10 +8,13 @@ var CodeExecutor = require('./CodeExecutor.cjs');
|
|
|
8
8
|
var _enum = require('../common/enum.cjs');
|
|
9
9
|
|
|
10
10
|
dotenv.config();
|
|
11
|
-
const imageMessage = 'Image is already displayed to the user';
|
|
12
11
|
const otherMessage = 'File is already downloaded by the user';
|
|
12
|
+
const inheritedFileMessage = 'Available as an input — already known to the user';
|
|
13
13
|
const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
|
|
14
14
|
const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
15
|
+
const inheritedFilesHeader = 'Available files (inputs, not generated by this execution):';
|
|
16
|
+
const generatedFilesHeader = 'Generated files:';
|
|
17
|
+
const inheritedNote = 'Note: Files in "Available files" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';
|
|
15
18
|
const baseEndpoint = CodeExecutor.getCodeBaseURL();
|
|
16
19
|
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
17
20
|
const BashExecutionToolSchema = {
|
|
@@ -168,17 +171,24 @@ function createBashExecutionTool(params = {}) {
|
|
|
168
171
|
if (result.stderr)
|
|
169
172
|
formattedOutput += `stderr:\n${result.stderr}\n`;
|
|
170
173
|
if (result.files && result.files.length > 0) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
174
|
+
/* Split inherited (read-only / unchanged-input passthroughs from
|
|
175
|
+
* codeapi) from genuine generated outputs. The LLM was previously
|
|
176
|
+
* shown skill files under "Generated files:" with the message
|
|
177
|
+
* "File is already downloaded by the user", which led it to
|
|
178
|
+
* (a) believe it had just produced files it merely referenced
|
|
179
|
+
* and (b) sometimes invent paths like /mnt/user-data/uploads/
|
|
180
|
+
* trying to find the "originals". Labeling them as inputs makes
|
|
181
|
+
* the mental model accurate. */
|
|
182
|
+
const inheritedFiles = result.files.filter((f) => f.inherited === true);
|
|
183
|
+
const generatedFiles = result.files.filter((f) => f.inherited !== true);
|
|
184
|
+
formattedOutput += CodeExecutor.renderFileSection(generatedFilesHeader, generatedFiles, otherMessage);
|
|
185
|
+
formattedOutput += CodeExecutor.renderFileSection(inheritedFilesHeader, inheritedFiles, inheritedFileMessage);
|
|
186
|
+
if (generatedFiles.length > 0) {
|
|
187
|
+
formattedOutput += `\n\n${accessMessage}`;
|
|
188
|
+
}
|
|
189
|
+
if (inheritedFiles.length > 0) {
|
|
190
|
+
formattedOutput += `\n\n${inheritedNote}`;
|
|
180
191
|
}
|
|
181
|
-
formattedOutput += `\n\n${accessMessage}`;
|
|
182
192
|
return [
|
|
183
193
|
formattedOutput.trim(),
|
|
184
194
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BashExecutor.cjs","sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":["config","getCodeBaseURL","Constants","tool","HttpsProxyAgent","imageExtRegex"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAER,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,YAAY,GAAGC,2BAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,uIAAuI;AAC1I,SAAA;AACF,KAAA;IACD,QAAQ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sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL, renderFileSection } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst otherMessage = 'File is already downloaded by the user';\nconst inheritedFileMessage =\n 'Available as an input — already known to the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\nconst inheritedFilesHeader =\n 'Available files (inputs, not generated by this execution):';\nconst generatedFilesHeader = 'Generated files:';\nconst inheritedNote =\n 'Note: Files in \"Available files\" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n /* Split inherited (read-only / unchanged-input passthroughs from\n * codeapi) from genuine generated outputs. The LLM was previously\n * shown skill files under \"Generated files:\" with the message\n * \"File is already downloaded by the user\", which led it to\n * (a) believe it had just produced files it merely referenced\n * and (b) sometimes invent paths like /mnt/user-data/uploads/\n * trying to find the \"originals\". Labeling them as inputs makes\n * the mental model accurate. */\n const inheritedFiles = result.files.filter(\n (f) => f.inherited === true\n );\n const generatedFiles = result.files.filter(\n (f) => f.inherited !== true\n );\n\n formattedOutput += renderFileSection(\n generatedFilesHeader,\n generatedFiles,\n otherMessage\n );\n formattedOutput += renderFileSection(\n inheritedFilesHeader,\n inheritedFiles,\n inheritedFileMessage\n );\n\n if (generatedFiles.length > 0) {\n formattedOutput += `\\n\\n${accessMessage}`;\n }\n if (inheritedFiles.length > 0) {\n formattedOutput += `\\n\\n${inheritedNote}`;\n }\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":["config","getCodeBaseURL","Constants","tool","HttpsProxyAgent","renderFileSection"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAER,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,oBAAoB,GACxB,mDAAmD;AACrD,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAC9D,MAAM,oBAAoB,GACxB,4DAA4D;AAC9D,MAAM,oBAAoB,GAAG,kBAAkB;AAC/C,MAAM,aAAa,GACjB,8MAA8M;AAEhN,MAAM,YAAY,GAAGC,2BAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,uIAAuI;AAC1I,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;;AAGhB,MAAM,4BAA4B,GAAG;;;;;;;CAO3C,CAAC,IAAI;AAEN;;;;;;;;;AASG;AACI,MAAM,6BAA6B,GAAG;;;;;;;;;CAS5C,CAAC,IAAI;AAEN;;;;;;AAMG;AACG,SAAU,iCAAiC,CAAC,OAEjD,EAAA;AACC,IAAA,IAAI,OAAO,EAAE,0BAA0B,KAAK,IAAI,EAAE;AAChD,QAAA,OAAO,CAAA,EAAG,4BAA4B,CAAA,IAAA,EAAO,6BAA6B,EAAE;IAC9E;AACA,IAAA,O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