@librechat/agents 3.0.774 → 3.0.776

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","sources":["../../../src/messages/cache.ts"],"sourcesContent":["import {\n BaseMessage,\n MessageContentComplex,\n AIMessage,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from '@langchain/core/messages';\nimport type { AnthropicMessage } from '@/types/messages';\nimport type Anthropic from '@anthropic-ai/sdk';\nimport { ContentTypes } from '@/common/enum';\n\ntype MessageWithContent = {\n content?: string | MessageContentComplex[];\n};\n\n/**\n * Deep clones a message's content to prevent mutation of the original.\n */\nfunction deepCloneContent<T extends string | MessageContentComplex[]>(\n content: T\n): T {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content.map((block) => ({ ...block })) as T;\n }\n return content;\n}\n\n/**\n * Simple shallow clone with deep-cloned content.\n * Used for stripping cache control where we don't need proper LangChain instances.\n */\nfunction shallowCloneMessage<T extends MessageWithContent>(message: T): T {\n return {\n ...message,\n content: deepCloneContent(message.content ?? ''),\n } as T;\n}\n\n/**\n * Creates a new LangChain message instance with the given content.\n * Required when adding cache points to ensure proper serialization.\n */\nfunction createNewMessage<T extends MessageWithContent>(\n message: T,\n content: MessageContentComplex[]\n): T {\n if ('getType' in message && typeof message.getType === 'function') {\n const baseMsg = message as unknown as BaseMessage;\n const msgType = baseMsg.getType();\n\n const baseFields = {\n content,\n name: baseMsg.name,\n additional_kwargs: { ...baseMsg.additional_kwargs },\n response_metadata: { ...baseMsg.response_metadata },\n id: baseMsg.id,\n };\n\n switch (msgType) {\n case 'human':\n return new HumanMessage(baseFields) as unknown as T;\n case 'ai': {\n const aiMsg = baseMsg as AIMessage;\n return new AIMessage({\n ...baseFields,\n tool_calls: aiMsg.tool_calls ? [...aiMsg.tool_calls] : [],\n invalid_tool_calls: aiMsg.invalid_tool_calls\n ? [...aiMsg.invalid_tool_calls]\n : [],\n usage_metadata: aiMsg.usage_metadata,\n }) as unknown as T;\n }\n case 'system':\n return new SystemMessage(baseFields) as unknown as T;\n case 'tool': {\n const toolMsg = baseMsg as ToolMessage;\n return new ToolMessage({\n ...baseFields,\n tool_call_id: toolMsg.tool_call_id,\n status: toolMsg.status,\n artifact: toolMsg.artifact,\n }) as unknown as T;\n }\n default:\n break;\n }\n }\n\n const cloned = { ...message, content } as T;\n const lcKwargs = (cloned as Record<string, unknown>).lc_kwargs as\n | Record<string, unknown>\n | undefined;\n if (lcKwargs != null) {\n (cloned as Record<string, unknown>).lc_kwargs = { ...lcKwargs, content };\n }\n return cloned;\n}\n\n/**\n * Checks if a message's content needs cache control stripping.\n * Returns true if content has cachePoint blocks or cache_control fields.\n */\nfunction needsCacheStripping(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n const block = content[i];\n if (isCachePoint(block)) return true;\n if ('cache_control' in block) return true;\n }\n return false;\n}\n\n/**\n * Anthropic API: Adds cache control to the appropriate user messages in the payload.\n * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,\n * then adds fresh cache control to the last 2 user messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache control added.\n */\nexport function addCacheControl<T extends AnthropicMessage | BaseMessage>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let userMessagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const isUserMessage =\n ('getType' in originalMessage && originalMessage.getType() === 'human') ||\n ('role' in originalMessage && originalMessage.role === 'user');\n\n const hasArrayContent = Array.isArray(originalMessage.content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(originalMessage.content as MessageContentComplex[]);\n const needsCacheAdd =\n userMessagesModified < 2 &&\n isUserMessage &&\n (typeof originalMessage.content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n const message = shallowCloneMessage(\n originalMessage as MessageWithContent\n ) as T;\n updatedMessages[i] = message;\n\n if (hasArrayContent) {\n message.content = (message.content as MessageContentComplex[]).filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof message.content;\n\n for (\n let j = 0;\n j < (message.content as MessageContentComplex[]).length;\n j++\n ) {\n const block = (message.content as MessageContentComplex[])[j] as Record<\n string,\n unknown\n >;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n if (userMessagesModified >= 2 || !isUserMessage) {\n continue;\n }\n\n if (typeof message.content === 'string') {\n message.content = [\n {\n type: 'text',\n text: message.content,\n cache_control: { type: 'ephemeral' },\n },\n ];\n userMessagesModified++;\n } else if (Array.isArray(message.content)) {\n for (let j = message.content.length - 1; j >= 0; j--) {\n const contentPart = message.content[j];\n if ('type' in contentPart && contentPart.type === 'text') {\n (contentPart as Anthropic.TextBlockParam).cache_control = {\n type: 'ephemeral',\n };\n userMessagesModified++;\n break;\n }\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a content block is a cache point\n */\nfunction isCachePoint(block: MessageContentComplex): boolean {\n return 'cachePoint' in block && !('type' in block);\n}\n\n/**\n * Checks if a message's content has Anthropic cache_control fields.\n */\nfunction hasAnthropicCacheControl(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if ('cache_control' in content[i]) return true;\n }\n return false;\n}\n\n/**\n * Removes all Anthropic cache_control fields from messages\n * Used when switching from Anthropic to Bedrock provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripAnthropicCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasAnthropicCacheControl(content)) {\n continue;\n }\n\n const message = shallowCloneMessage(originalMessage);\n updatedMessages[i] = message;\n\n for (\n let j = 0;\n j < (message.content as MessageContentComplex[]).length;\n j++\n ) {\n const block = (message.content as MessageContentComplex[])[j] as Record<\n string,\n unknown\n >;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a message's content has Bedrock cachePoint blocks.\n */\nfunction hasBedrockCachePoint(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if (isCachePoint(content[i])) return true;\n }\n return false;\n}\n\n/**\n * Removes all Bedrock cachePoint blocks from messages\n * Used when switching from Bedrock to Anthropic provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripBedrockCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasBedrockCachePoint(content)) {\n continue;\n }\n\n const message = shallowCloneMessage(originalMessage);\n updatedMessages[i] = message;\n\n message.content = (message.content as MessageContentComplex[]).filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof content;\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points to the last two messages.\n * Inserts `{ cachePoint: { type: 'default' } }` as a separate content block\n * immediately after the last text block in each targeted message.\n * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,\n * then adds fresh cache points to the last 2 messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache points added.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let messagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const isToolMessage =\n 'getType' in originalMessage &&\n typeof originalMessage.getType === 'function' &&\n originalMessage.getType() === 'tool';\n\n const content = originalMessage.content;\n const hasArrayContent = Array.isArray(content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(content as MessageContentComplex[]);\n const isEmptyString = typeof content === 'string' && content === '';\n const needsCacheAdd =\n messagesModified < 2 &&\n !isToolMessage &&\n !isEmptyString &&\n (typeof content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n let workingContent: MessageContentComplex[];\n\n if (hasArrayContent) {\n workingContent = deepCloneContent(\n content as MessageContentComplex[]\n ).filter((block) => !isCachePoint(block));\n\n for (let j = 0; j < workingContent.length; j++) {\n const block = workingContent[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n } else if (typeof content === 'string') {\n workingContent = [{ type: ContentTypes.TEXT, text: content }];\n } else {\n workingContent = [];\n }\n\n if (messagesModified >= 2 || isToolMessage || isEmptyString) {\n updatedMessages[i] = shallowCloneMessage(originalMessage);\n (updatedMessages[i] as MessageWithContent).content = workingContent;\n continue;\n }\n\n if (workingContent.length === 0) {\n continue;\n }\n\n let hasCacheableContent = false;\n for (const block of workingContent) {\n if (block.type === ContentTypes.TEXT) {\n if (typeof block.text === 'string' && block.text !== '') {\n hasCacheableContent = true;\n break;\n }\n }\n }\n\n if (!hasCacheableContent) {\n updatedMessages[i] = shallowCloneMessage(originalMessage);\n (updatedMessages[i] as MessageWithContent).content = workingContent;\n continue;\n }\n\n let inserted = false;\n for (let j = workingContent.length - 1; j >= 0; j--) {\n const block = workingContent[j] as MessageContentComplex;\n const type = (block as { type?: string }).type;\n if (type === ContentTypes.TEXT || type === 'text') {\n const text = (block as { text?: string }).text;\n if (text === '' || text === undefined) {\n continue;\n }\n workingContent.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n break;\n }\n }\n if (!inserted) {\n workingContent.push({\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n }\n\n updatedMessages[i] = createNewMessage(originalMessage, workingContent);\n messagesModified++;\n }\n\n return updatedMessages;\n}\n"],"names":[],"mappings":";;;AAgBA;;AAEG;AACH,SAAS,gBAAgB,CACvB,OAAU,EAAA;AAEV,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;AAEhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;AAC1B,QAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,GAAG,KAAK,EAAE,CAAC,CAAM;;AAEpD,IAAA,OAAO,OAAO;AAChB;AAEA;;;AAGG;AACH,SAAS,mBAAmB,CAA+B,OAAU,EAAA;IACnE,OAAO;AACL,QAAA,GAAG,OAAO;QACV,OAAO,EAAE,gBAAgB,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC;KAC5C;AACR;AAEA;;;AAGG;AACH,SAAS,gBAAgB,CACvB,OAAU,EACV,OAAgC,EAAA;IAEhC,IAAI,SAAS,IAAI,OAAO,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,UAAU,EAAE;QACjE,MAAM,OAAO,GAAG,OAAiC;AACjD,QAAA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE;AAEjC,QAAA,MAAM,UAAU,GAAG;YACjB,OAAO;YACP,IAAI,EAAE,OAAO,CAAC,IAAI;AAClB,YAAA,iBAAiB,EAAE,EAAE,GAAG,OAAO,CAAC,iBAAiB,EAAE;AACnD,YAAA,iBAAiB,EAAE,EAAE,GAAG,OAAO,CAAC,iBAAiB,EAAE;YACnD,EAAE,EAAE,OAAO,CAAC,EAAE;SACf;QAED,QAAQ,OAAO;AACf,YAAA,KAAK,OAAO;AACV,gB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I,IAAI,KAAK,MAAM,EAAE;AACjD,gBAAA,MAAM,IAAI,GAAI,KAA2B,CAAC,IAAI;gBAC9C,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,SAAS,EAAE;oBACrC;;gBAEF,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;AAC9B,oBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,iBAAA,CAAC;gBAC3B,QAAQ,GAAG,IAAI;gBACf;;;QAGJ,IAAI,CAAC,QAAQ,EAAE;YACb,cAAc,CAAC,IAAI,CAAC;AAClB,gBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,aAAA,CAAC;;QAG7B,eAAe,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,eAAe,EAAE,cAAc,CAAC;AACtE,QAAA,gBAAgB,EAAE;;AAGpB,IAAA,OAAO,eAAe;AACxB;;;;"}
1
+ {"version":3,"file":"cache.mjs","sources":["../../../src/messages/cache.ts"],"sourcesContent":["import { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { AnthropicMessage } from '@/types/messages';\nimport type Anthropic from '@anthropic-ai/sdk';\nimport { ContentTypes } from '@/common/enum';\n\ntype MessageWithContent = {\n content?: string | MessageContentComplex[];\n};\n\n/**\n * Deep clones a message's content to prevent mutation of the original.\n */\nfunction deepCloneContent<T extends string | MessageContentComplex[]>(\n content: T\n): T {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content.map((block) => ({ ...block })) as T;\n }\n return content;\n}\n\n/**\n * Clones a message with deep-cloned content, explicitly excluding LangChain\n * serialization metadata to prevent coercion issues.\n */\nfunction cloneMessage<T extends MessageWithContent>(\n message: T,\n content: string | MessageContentComplex[]\n): T {\n const {\n lc_kwargs: _lc_kwargs,\n lc_serializable: _lc_serializable,\n lc_namespace: _lc_namespace,\n ...rest\n } = message as T & {\n lc_kwargs?: unknown;\n lc_serializable?: unknown;\n lc_namespace?: unknown;\n };\n\n const cloned = { ...rest, content } as T;\n\n // LangChain messages don't have a direct 'role' property - derive it from getType()\n if (\n 'getType' in message &&\n typeof message.getType === 'function' &&\n !('role' in cloned)\n ) {\n const msgType = (message as unknown as BaseMessage).getType();\n const roleMap: Record<string, string> = {\n human: 'user',\n ai: 'assistant',\n system: 'system',\n tool: 'tool',\n };\n (cloned as Record<string, unknown>).role = roleMap[msgType] || msgType;\n }\n\n return cloned;\n}\n\n/**\n * Checks if a message's content needs cache control stripping.\n * Returns true if content has cachePoint blocks or cache_control fields.\n */\nfunction needsCacheStripping(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n const block = content[i];\n if (isCachePoint(block)) return true;\n if ('cache_control' in block) return true;\n }\n return false;\n}\n\n/**\n * Anthropic API: Adds cache control to the appropriate user messages in the payload.\n * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,\n * then adds fresh cache control to the last 2 user messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache control added.\n */\nexport function addCacheControl<T extends AnthropicMessage | BaseMessage>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let userMessagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n const isUserMessage =\n ('getType' in originalMessage && originalMessage.getType() === 'human') ||\n ('role' in originalMessage && originalMessage.role === 'user');\n\n const hasArrayContent = Array.isArray(content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(content as MessageContentComplex[]);\n const needsCacheAdd =\n userMessagesModified < 2 &&\n isUserMessage &&\n (typeof content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n let workingContent: MessageContentComplex[];\n\n if (hasArrayContent) {\n workingContent = deepCloneContent(\n content as MessageContentComplex[]\n ).filter((block) => !isCachePoint(block as MessageContentComplex));\n\n for (let j = 0; j < workingContent.length; j++) {\n const block = workingContent[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n } else if (typeof content === 'string') {\n workingContent = [\n { type: 'text', text: content },\n ] as MessageContentComplex[];\n } else {\n workingContent = [];\n }\n\n if (userMessagesModified >= 2 || !isUserMessage) {\n updatedMessages[i] = cloneMessage(\n originalMessage as MessageWithContent,\n workingContent\n ) as T;\n continue;\n }\n\n for (let j = workingContent.length - 1; j >= 0; j--) {\n const contentPart = workingContent[j];\n if ('type' in contentPart && contentPart.type === 'text') {\n (contentPart as Anthropic.TextBlockParam).cache_control = {\n type: 'ephemeral',\n };\n userMessagesModified++;\n break;\n }\n }\n\n updatedMessages[i] = cloneMessage(\n originalMessage as MessageWithContent,\n workingContent\n ) as T;\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a content block is a cache point\n */\nfunction isCachePoint(block: MessageContentComplex): boolean {\n return 'cachePoint' in block && !('type' in block);\n}\n\n/**\n * Checks if a message's content has Anthropic cache_control fields.\n */\nfunction hasAnthropicCacheControl(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if ('cache_control' in content[i]) return true;\n }\n return false;\n}\n\n/**\n * Removes all Anthropic cache_control fields from messages\n * Used when switching from Anthropic to Bedrock provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripAnthropicCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasAnthropicCacheControl(content)) {\n continue;\n }\n\n const clonedContent = deepCloneContent(content);\n for (let j = 0; j < clonedContent.length; j++) {\n const block = clonedContent[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n updatedMessages[i] = cloneMessage(originalMessage, clonedContent);\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a message's content has Bedrock cachePoint blocks.\n */\nfunction hasBedrockCachePoint(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if (isCachePoint(content[i])) return true;\n }\n return false;\n}\n\n/**\n * Removes all Bedrock cachePoint blocks from messages\n * Used when switching from Bedrock to Anthropic provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripBedrockCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasBedrockCachePoint(content)) {\n continue;\n }\n\n const clonedContent = deepCloneContent(content).filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n );\n updatedMessages[i] = cloneMessage(originalMessage, clonedContent);\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points to the last two messages.\n * Inserts `{ cachePoint: { type: 'default' } }` as a separate content block\n * immediately after the last text block in each targeted message.\n * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,\n * then adds fresh cache points to the last 2 messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache points added.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let messagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const isToolMessage =\n 'getType' in originalMessage &&\n typeof originalMessage.getType === 'function' &&\n originalMessage.getType() === 'tool';\n\n const content = originalMessage.content;\n const hasArrayContent = Array.isArray(content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(content as MessageContentComplex[]);\n const isEmptyString = typeof content === 'string' && content === '';\n const needsCacheAdd =\n messagesModified < 2 &&\n !isToolMessage &&\n !isEmptyString &&\n (typeof content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n let workingContent: MessageContentComplex[];\n\n if (hasArrayContent) {\n workingContent = deepCloneContent(\n content as MessageContentComplex[]\n ).filter((block) => !isCachePoint(block));\n\n for (let j = 0; j < workingContent.length; j++) {\n const block = workingContent[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n } else if (typeof content === 'string') {\n workingContent = [{ type: ContentTypes.TEXT, text: content }];\n } else {\n workingContent = [];\n }\n\n if (messagesModified >= 2 || isToolMessage || isEmptyString) {\n updatedMessages[i] = cloneMessage(originalMessage, workingContent);\n continue;\n }\n\n if (workingContent.length === 0) {\n continue;\n }\n\n let hasCacheableContent = false;\n for (const block of workingContent) {\n if (block.type === ContentTypes.TEXT) {\n if (typeof block.text === 'string' && block.text !== '') {\n hasCacheableContent = true;\n break;\n }\n }\n }\n\n if (!hasCacheableContent) {\n updatedMessages[i] = cloneMessage(originalMessage, workingContent);\n continue;\n }\n\n let inserted = false;\n for (let j = workingContent.length - 1; j >= 0; j--) {\n const block = workingContent[j] as MessageContentComplex;\n const type = (block as { type?: string }).type;\n if (type === ContentTypes.TEXT || type === 'text') {\n const text = (block as { text?: string }).text;\n if (text === '' || text === undefined) {\n continue;\n }\n workingContent.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n break;\n }\n }\n if (!inserted) {\n workingContent.push({\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n }\n\n updatedMessages[i] = cloneMessage(originalMessage, workingContent);\n messagesModified++;\n }\n\n return updatedMessages;\n}\n"],"names":[],"mappings":";;AASA;;AAE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AAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,iBAAA,CAAC;gBAC3B,QAAQ,GAAG,IAAI;gBACf;;;QAGJ,IAAI,CAAC,QAAQ,EAAE;YACb,cAAc,CAAC,IAAI,CAAC;AAClB,gBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,aAAA,CAAC;;QAG7B,eAAe,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,eAAe,EAAE,cAAc,CAAC;AAClE,QAAA,gBAAgB,EAAE;;AAGpB,IAAA,OAAO,eAAe;AACxB;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.0.774",
3
+ "version": "3.0.776",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -52,7 +52,7 @@
52
52
  "code_exec_files": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_files.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
53
53
  "code_exec_session": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_session.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
54
54
  "code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
55
- "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'openrouter' --name 'Jo' --location 'New York, NY'",
55
+ "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'bedrock' --name 'Jo' --location 'New York, NY'",
56
56
  "caching": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/caching.ts --name 'Jo' --location 'New York, NY'",
57
57
  "thinking": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/thinking.ts --name 'Jo' --location 'New York, NY'",
58
58
  "memory": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/memory.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
@@ -95,7 +95,7 @@
95
95
  "start:collab5": "node --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/collab_design_v5.ts",
96
96
  "start:dev": "node --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/main.ts",
97
97
  "supervised": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/supervised.ts --provider anthropic --name Jo --location \"New York, NY\"",
98
- "test": "jest",
98
+ "test": "NODE_OPTIONS='--experimental-vm-modules' jest",
99
99
  "test:memory": "NODE_OPTIONS='--expose-gc' npx jest src/specs/title.memory-leak.test.ts",
100
100
  "test:all": "npm test -- --testPathIgnorePatterns=title.memory-leak.test.ts && npm run test:memory",
101
101
  "reinstall": "npm run clean && npm ci && rm -rf ./dist && npm run build",
@@ -920,6 +920,54 @@ describe('Immutability - addCacheControl does not mutate original messages', ()
920
920
 
921
921
  expect('cache_control' in originalFirstBlock).toBe(true);
922
922
  });
923
+
924
+ it('should remove lc_kwargs to prevent serialization mismatch for LangChain messages', () => {
925
+ type LangChainLikeMsg = TestMsg & {
926
+ lc_kwargs?: { content?: MessageContentComplex[] };
927
+ };
928
+
929
+ const messagesWithLcKwargs: LangChainLikeMsg[] = [
930
+ {
931
+ role: 'user',
932
+ content: [{ type: ContentTypes.TEXT, text: 'First user message' }],
933
+ lc_kwargs: {
934
+ content: [{ type: ContentTypes.TEXT, text: 'First user message' }],
935
+ },
936
+ },
937
+ {
938
+ role: 'assistant',
939
+ content: [{ type: ContentTypes.TEXT, text: 'Assistant response' }],
940
+ lc_kwargs: {
941
+ content: [{ type: ContentTypes.TEXT, text: 'Assistant response' }],
942
+ },
943
+ },
944
+ {
945
+ role: 'user',
946
+ content: [{ type: ContentTypes.TEXT, text: 'Second user message' }],
947
+ lc_kwargs: {
948
+ content: [{ type: ContentTypes.TEXT, text: 'Second user message' }],
949
+ },
950
+ },
951
+ ];
952
+
953
+ const result = addCacheControl(messagesWithLcKwargs as never);
954
+
955
+ const resultFirst = result[0] as LangChainLikeMsg;
956
+ const resultThird = result[2] as LangChainLikeMsg;
957
+
958
+ expect(resultFirst.lc_kwargs).toBeUndefined();
959
+ expect(resultThird.lc_kwargs).toBeUndefined();
960
+
961
+ const firstContent = resultFirst.content as MessageContentComplex[];
962
+ expect('cache_control' in firstContent[0]).toBe(true);
963
+
964
+ const originalFirst = messagesWithLcKwargs[0];
965
+ const originalContent = originalFirst.content as MessageContentComplex[];
966
+ const originalLcContent = originalFirst.lc_kwargs
967
+ ?.content as MessageContentComplex[];
968
+ expect('cache_control' in originalContent[0]).toBe(false);
969
+ expect('cache_control' in originalLcContent[0]).toBe(false);
970
+ });
923
971
  });
924
972
 
925
973
  describe('Immutability - addBedrockCacheControl does not mutate original messages', () => {
@@ -1049,7 +1097,7 @@ describe('Immutability - addBedrockCacheControl does not mutate original message
1049
1097
  expect('cache_control' in anthropicFirstContent[0]).toBe(true);
1050
1098
  });
1051
1099
 
1052
- it('should keep lc_kwargs.content in sync with content for LangChain messages', () => {
1100
+ it('should remove lc_kwargs to prevent serialization mismatch for LangChain messages', () => {
1053
1101
  type LangChainLikeMsg = TestMsg & {
1054
1102
  lc_kwargs?: { content?: MessageContentComplex[] };
1055
1103
  };
@@ -1076,14 +1124,11 @@ describe('Immutability - addBedrockCacheControl does not mutate original message
1076
1124
  const resultFirst = bedrockResult[0] as LangChainLikeMsg;
1077
1125
  const resultSecond = bedrockResult[1] as LangChainLikeMsg;
1078
1126
 
1079
- expect(resultFirst.content).toEqual(resultFirst.lc_kwargs?.content);
1080
- expect(resultSecond.content).toEqual(resultSecond.lc_kwargs?.content);
1127
+ expect(resultFirst.lc_kwargs).toBeUndefined();
1128
+ expect(resultSecond.lc_kwargs).toBeUndefined();
1081
1129
 
1082
1130
  const firstContent = resultFirst.content as MessageContentComplex[];
1083
- const firstLcContent = resultFirst.lc_kwargs
1084
- ?.content as MessageContentComplex[];
1085
1131
  expect(firstContent.some((b) => 'cachePoint' in b)).toBe(true);
1086
- expect(firstLcContent.some((b) => 'cachePoint' in b)).toBe(true);
1087
1132
 
1088
1133
  const originalFirst = messagesWithLcKwargs[0];
1089
1134
  const originalContent = originalFirst.content as MessageContentComplex[];
@@ -1,11 +1,4 @@
1
- import {
2
- BaseMessage,
3
- MessageContentComplex,
4
- AIMessage,
5
- HumanMessage,
6
- SystemMessage,
7
- ToolMessage,
8
- } from '@langchain/core/messages';
1
+ import { BaseMessage, MessageContentComplex } from '@langchain/core/messages';
9
2
  import type { AnthropicMessage } from '@/types/messages';
10
3
  import type Anthropic from '@anthropic-ai/sdk';
11
4
  import { ContentTypes } from '@/common/enum';
@@ -30,73 +23,42 @@ function deepCloneContent<T extends string | MessageContentComplex[]>(
30
23
  }
31
24
 
32
25
  /**
33
- * Simple shallow clone with deep-cloned content.
34
- * Used for stripping cache control where we don't need proper LangChain instances.
26
+ * Clones a message with deep-cloned content, explicitly excluding LangChain
27
+ * serialization metadata to prevent coercion issues.
35
28
  */
36
- function shallowCloneMessage<T extends MessageWithContent>(message: T): T {
37
- return {
38
- ...message,
39
- content: deepCloneContent(message.content ?? ''),
40
- } as T;
41
- }
42
-
43
- /**
44
- * Creates a new LangChain message instance with the given content.
45
- * Required when adding cache points to ensure proper serialization.
46
- */
47
- function createNewMessage<T extends MessageWithContent>(
29
+ function cloneMessage<T extends MessageWithContent>(
48
30
  message: T,
49
- content: MessageContentComplex[]
31
+ content: string | MessageContentComplex[]
50
32
  ): T {
51
- if ('getType' in message && typeof message.getType === 'function') {
52
- const baseMsg = message as unknown as BaseMessage;
53
- const msgType = baseMsg.getType();
54
-
55
- const baseFields = {
56
- content,
57
- name: baseMsg.name,
58
- additional_kwargs: { ...baseMsg.additional_kwargs },
59
- response_metadata: { ...baseMsg.response_metadata },
60
- id: baseMsg.id,
33
+ const {
34
+ lc_kwargs: _lc_kwargs,
35
+ lc_serializable: _lc_serializable,
36
+ lc_namespace: _lc_namespace,
37
+ ...rest
38
+ } = message as T & {
39
+ lc_kwargs?: unknown;
40
+ lc_serializable?: unknown;
41
+ lc_namespace?: unknown;
42
+ };
43
+
44
+ const cloned = { ...rest, content } as T;
45
+
46
+ // LangChain messages don't have a direct 'role' property - derive it from getType()
47
+ if (
48
+ 'getType' in message &&
49
+ typeof message.getType === 'function' &&
50
+ !('role' in cloned)
51
+ ) {
52
+ const msgType = (message as unknown as BaseMessage).getType();
53
+ const roleMap: Record<string, string> = {
54
+ human: 'user',
55
+ ai: 'assistant',
56
+ system: 'system',
57
+ tool: 'tool',
61
58
  };
62
-
63
- switch (msgType) {
64
- case 'human':
65
- return new HumanMessage(baseFields) as unknown as T;
66
- case 'ai': {
67
- const aiMsg = baseMsg as AIMessage;
68
- return new AIMessage({
69
- ...baseFields,
70
- tool_calls: aiMsg.tool_calls ? [...aiMsg.tool_calls] : [],
71
- invalid_tool_calls: aiMsg.invalid_tool_calls
72
- ? [...aiMsg.invalid_tool_calls]
73
- : [],
74
- usage_metadata: aiMsg.usage_metadata,
75
- }) as unknown as T;
76
- }
77
- case 'system':
78
- return new SystemMessage(baseFields) as unknown as T;
79
- case 'tool': {
80
- const toolMsg = baseMsg as ToolMessage;
81
- return new ToolMessage({
82
- ...baseFields,
83
- tool_call_id: toolMsg.tool_call_id,
84
- status: toolMsg.status,
85
- artifact: toolMsg.artifact,
86
- }) as unknown as T;
87
- }
88
- default:
89
- break;
90
- }
59
+ (cloned as Record<string, unknown>).role = roleMap[msgType] || msgType;
91
60
  }
92
61
 
93
- const cloned = { ...message, content } as T;
94
- const lcKwargs = (cloned as Record<string, unknown>).lc_kwargs as
95
- | Record<string, unknown>
96
- | undefined;
97
- if (lcKwargs != null) {
98
- (cloned as Record<string, unknown>).lc_kwargs = { ...lcKwargs, content };
99
- }
100
62
  return cloned;
101
63
  }
102
64
 
@@ -134,73 +96,68 @@ export function addCacheControl<T extends AnthropicMessage | BaseMessage>(
134
96
 
135
97
  for (let i = updatedMessages.length - 1; i >= 0; i--) {
136
98
  const originalMessage = updatedMessages[i];
99
+ const content = originalMessage.content;
137
100
  const isUserMessage =
138
101
  ('getType' in originalMessage && originalMessage.getType() === 'human') ||
139
102
  ('role' in originalMessage && originalMessage.role === 'user');
140
103
 
141
- const hasArrayContent = Array.isArray(originalMessage.content);
104
+ const hasArrayContent = Array.isArray(content);
142
105
  const needsStripping =
143
106
  hasArrayContent &&
144
- needsCacheStripping(originalMessage.content as MessageContentComplex[]);
107
+ needsCacheStripping(content as MessageContentComplex[]);
145
108
  const needsCacheAdd =
146
109
  userMessagesModified < 2 &&
147
110
  isUserMessage &&
148
- (typeof originalMessage.content === 'string' || hasArrayContent);
111
+ (typeof content === 'string' || hasArrayContent);
149
112
 
150
113
  if (!needsStripping && !needsCacheAdd) {
151
114
  continue;
152
115
  }
153
116
 
154
- const message = shallowCloneMessage(
155
- originalMessage as MessageWithContent
156
- ) as T;
157
- updatedMessages[i] = message;
117
+ let workingContent: MessageContentComplex[];
158
118
 
159
119
  if (hasArrayContent) {
160
- message.content = (message.content as MessageContentComplex[]).filter(
161
- (block) => !isCachePoint(block as MessageContentComplex)
162
- ) as typeof message.content;
163
-
164
- for (
165
- let j = 0;
166
- j < (message.content as MessageContentComplex[]).length;
167
- j++
168
- ) {
169
- const block = (message.content as MessageContentComplex[])[j] as Record<
170
- string,
171
- unknown
172
- >;
120
+ workingContent = deepCloneContent(
121
+ content as MessageContentComplex[]
122
+ ).filter((block) => !isCachePoint(block as MessageContentComplex));
123
+
124
+ for (let j = 0; j < workingContent.length; j++) {
125
+ const block = workingContent[j] as Record<string, unknown>;
173
126
  if ('cache_control' in block) {
174
127
  delete block.cache_control;
175
128
  }
176
129
  }
130
+ } else if (typeof content === 'string') {
131
+ workingContent = [
132
+ { type: 'text', text: content },
133
+ ] as MessageContentComplex[];
134
+ } else {
135
+ workingContent = [];
177
136
  }
178
137
 
179
138
  if (userMessagesModified >= 2 || !isUserMessage) {
139
+ updatedMessages[i] = cloneMessage(
140
+ originalMessage as MessageWithContent,
141
+ workingContent
142
+ ) as T;
180
143
  continue;
181
144
  }
182
145
 
183
- if (typeof message.content === 'string') {
184
- message.content = [
185
- {
186
- type: 'text',
187
- text: message.content,
188
- cache_control: { type: 'ephemeral' },
189
- },
190
- ];
191
- userMessagesModified++;
192
- } else if (Array.isArray(message.content)) {
193
- for (let j = message.content.length - 1; j >= 0; j--) {
194
- const contentPart = message.content[j];
195
- if ('type' in contentPart && contentPart.type === 'text') {
196
- (contentPart as Anthropic.TextBlockParam).cache_control = {
197
- type: 'ephemeral',
198
- };
199
- userMessagesModified++;
200
- break;
201
- }
146
+ for (let j = workingContent.length - 1; j >= 0; j--) {
147
+ const contentPart = workingContent[j];
148
+ if ('type' in contentPart && contentPart.type === 'text') {
149
+ (contentPart as Anthropic.TextBlockParam).cache_control = {
150
+ type: 'ephemeral',
151
+ };
152
+ userMessagesModified++;
153
+ break;
202
154
  }
203
155
  }
156
+
157
+ updatedMessages[i] = cloneMessage(
158
+ originalMessage as MessageWithContent,
159
+ workingContent
160
+ ) as T;
204
161
  }
205
162
 
206
163
  return updatedMessages;
@@ -245,22 +202,14 @@ export function stripAnthropicCacheControl<T extends MessageWithContent>(
245
202
  continue;
246
203
  }
247
204
 
248
- const message = shallowCloneMessage(originalMessage);
249
- updatedMessages[i] = message;
250
-
251
- for (
252
- let j = 0;
253
- j < (message.content as MessageContentComplex[]).length;
254
- j++
255
- ) {
256
- const block = (message.content as MessageContentComplex[])[j] as Record<
257
- string,
258
- unknown
259
- >;
205
+ const clonedContent = deepCloneContent(content);
206
+ for (let j = 0; j < clonedContent.length; j++) {
207
+ const block = clonedContent[j] as Record<string, unknown>;
260
208
  if ('cache_control' in block) {
261
209
  delete block.cache_control;
262
210
  }
263
211
  }
212
+ updatedMessages[i] = cloneMessage(originalMessage, clonedContent);
264
213
  }
265
214
 
266
215
  return updatedMessages;
@@ -298,12 +247,10 @@ export function stripBedrockCacheControl<T extends MessageWithContent>(
298
247
  continue;
299
248
  }
300
249
 
301
- const message = shallowCloneMessage(originalMessage);
302
- updatedMessages[i] = message;
303
-
304
- message.content = (message.content as MessageContentComplex[]).filter(
250
+ const clonedContent = deepCloneContent(content).filter(
305
251
  (block) => !isCachePoint(block as MessageContentComplex)
306
- ) as typeof content;
252
+ );
253
+ updatedMessages[i] = cloneMessage(originalMessage, clonedContent);
307
254
  }
308
255
 
309
256
  return updatedMessages;
@@ -373,8 +320,7 @@ export function addBedrockCacheControl<
373
320
  }
374
321
 
375
322
  if (messagesModified >= 2 || isToolMessage || isEmptyString) {
376
- updatedMessages[i] = shallowCloneMessage(originalMessage);
377
- (updatedMessages[i] as MessageWithContent).content = workingContent;
323
+ updatedMessages[i] = cloneMessage(originalMessage, workingContent);
378
324
  continue;
379
325
  }
380
326
 
@@ -393,8 +339,7 @@ export function addBedrockCacheControl<
393
339
  }
394
340
 
395
341
  if (!hasCacheableContent) {
396
- updatedMessages[i] = shallowCloneMessage(originalMessage);
397
- (updatedMessages[i] as MessageWithContent).content = workingContent;
342
+ updatedMessages[i] = cloneMessage(originalMessage, workingContent);
398
343
  continue;
399
344
  }
400
345
 
@@ -420,7 +365,7 @@ export function addBedrockCacheControl<
420
365
  } as MessageContentComplex);
421
366
  }
422
367
 
423
- updatedMessages[i] = createNewMessage(originalMessage, workingContent);
368
+ updatedMessages[i] = cloneMessage(originalMessage, workingContent);
424
369
  messagesModified++;
425
370
  }
426
371