illuma-agents 1.0.37 → 1.0.39
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 +112 -14
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +5 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +148 -8
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +128 -61
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +22 -7
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +140 -46
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +1 -1
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +2 -2
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/schemas/validate.cjs +173 -0
- package/dist/cjs/schemas/validate.cjs.map +1 -0
- package/dist/cjs/stream.cjs +4 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +22 -21
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +101 -2
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +862 -0
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +112 -14
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +5 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +149 -9
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +127 -60
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +140 -46
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +1 -1
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +2 -2
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/schemas/validate.mjs +167 -0
- package/dist/esm/schemas/validate.mjs.map +1 -0
- package/dist/esm/stream.mjs +4 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BrowserTools.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +22 -21
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +102 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +827 -0
- package/dist/esm/tools/ToolSearch.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +51 -1
- package/dist/types/common/enum.d.ts +6 -2
- package/dist/types/graphs/Graph.d.ts +12 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/llm/bedrock/index.d.ts +89 -11
- package/dist/types/llm/bedrock/types.d.ts +27 -0
- package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
- package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
- package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
- package/dist/types/messages/cache.d.ts +4 -1
- package/dist/types/schemas/index.d.ts +1 -0
- package/dist/types/schemas/validate.d.ts +36 -0
- package/dist/types/tools/CodeExecutor.d.ts +0 -3
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
- package/dist/types/tools/ToolNode.d.ts +3 -1
- package/dist/types/tools/ToolSearch.d.ts +148 -0
- package/dist/types/types/graph.d.ts +71 -0
- package/dist/types/types/llm.d.ts +3 -1
- package/dist/types/types/tools.d.ts +42 -2
- package/package.json +13 -6
- package/src/agents/AgentContext.test.ts +312 -0
- package/src/agents/AgentContext.ts +144 -16
- package/src/common/enum.ts +5 -1
- package/src/graphs/Graph.ts +214 -13
- package/src/graphs/MultiAgentGraph.ts +350 -13
- package/src/index.ts +4 -1
- package/src/llm/bedrock/index.ts +221 -99
- package/src/llm/bedrock/llm.spec.ts +616 -0
- package/src/llm/bedrock/types.ts +51 -0
- package/src/llm/bedrock/utils/index.ts +18 -0
- package/src/llm/bedrock/utils/message_inputs.ts +563 -0
- package/src/llm/bedrock/utils/message_outputs.ts +310 -0
- package/src/messages/__tests__/tools.test.ts +21 -21
- package/src/messages/cache.test.ts +304 -0
- package/src/messages/cache.ts +183 -53
- package/src/messages/core.ts +1 -1
- package/src/messages/tools.ts +2 -2
- package/src/schemas/index.ts +2 -0
- package/src/schemas/validate.test.ts +358 -0
- package/src/schemas/validate.ts +238 -0
- package/src/scripts/caching.ts +27 -19
- package/src/scripts/code_exec_files.ts +58 -15
- package/src/scripts/code_exec_multi_session.ts +241 -0
- package/src/scripts/code_exec_session.ts +282 -0
- package/src/scripts/multi-agent-conditional.ts +1 -0
- package/src/scripts/multi-agent-supervisor.ts +1 -0
- package/src/scripts/programmatic_exec_agent.ts +4 -4
- package/src/scripts/test-handoff-preamble.ts +277 -0
- package/src/scripts/test-parallel-handoffs.ts +291 -0
- package/src/scripts/test-tools-before-handoff.ts +8 -4
- package/src/scripts/test_code_api.ts +361 -0
- package/src/scripts/thinking-bedrock.ts +159 -0
- package/src/scripts/thinking.ts +39 -18
- package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
- package/src/scripts/tools.ts +7 -3
- package/src/specs/cache.simple.test.ts +396 -0
- package/src/stream.ts +4 -2
- package/src/tools/BrowserTools.ts +39 -17
- package/src/tools/CodeExecutor.ts +26 -23
- package/src/tools/ProgrammaticToolCalling.ts +18 -14
- package/src/tools/ToolNode.ts +114 -1
- package/src/tools/ToolSearch.ts +1041 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
- package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
- package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
- package/src/types/graph.test.ts +183 -0
- package/src/types/graph.ts +73 -0
- package/src/types/llm.ts +3 -1
- package/src/types/tools.ts +51 -2
- package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
- package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
- package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
- package/src/tools/ToolSearchRegex.ts +0 -535
- package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.cjs","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/** Debug logger for cache operations - set ILLUMA_DEBUG_CACHE=true to enable */\nconst debugCache = (message: string, data?: unknown): void => {\n if (process.env.ILLUMA_DEBUG_CACHE === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[Cache] ${message}`,\n data !== undefined ? JSON.stringify(data, null, 2) : ''\n );\n }\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 * @param messages - The array of message objects.\n * @returns - The updated 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 = [...messages];\n let userMessagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const message = updatedMessages[i];\n const isUserMessage =\n ('getType' in message && message.getType() === 'human') ||\n ('role' in message && message.role === 'user');\n\n if (Array.isArray(message.content)) {\n message.content = message.content.filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof message.content;\n\n for (let j = 0; j < message.content.length; j++) {\n const block = message.content[j] as Record<string, unknown>;\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 * Removes all Anthropic cache_control fields from messages\n * Used when switching from Anthropic to Bedrock provider\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 = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const message = updatedMessages[i];\n const content = message.content;\n\n if (Array.isArray(content)) {\n for (let j = 0; j < content.length; j++) {\n const block = content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Removes all Bedrock cachePoint blocks from messages\n * Used when switching from Bedrock to Anthropic provider\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 = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const message = updatedMessages[i];\n const content = message.content;\n\n if (Array.isArray(content)) {\n message.content = content.filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof content;\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points using \"Stable Prefix Caching\" strategy.\n *\n * STRATEGY: Place cache point after the LAST ASSISTANT message only.\n * This ensures the prefix (everything before the cache point) remains STABLE\n * as the conversation grows, maximizing cache hits.\n *\n * Why this works:\n * - System message has its own cachePoint (added in AgentContext)\n * - Tools have their own cachePoint (added in CustomChatBedrockConverse)\n * - Conversation history grows, but the PREFIX stays the same\n * - Only the NEW user message is uncached (it's always different)\n *\n * Example conversation flow:\n * Request 1: [System+cachePoint][Tools+cachePoint][User1] → No conversation cache yet\n * Request 2: [System][Tools][User1][Assistant1+cachePoint][User2] → Cache User1+Assistant1\n * Request 3: [System][Tools][User1][Assistant1][User2][Assistant2+cachePoint][User3]\n * → Cache reads User1+A1+User2+A2, cache writes new portion\n *\n * Claude's \"Simplified Cache Management\" automatically looks back up to 20 content\n * blocks from the cache checkpoint to find the longest matching prefix.\n *\n * @param messages - The array of message objects (excluding system message).\n * @returns - The updated array with a single cache point after the last assistant message.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 1) {\n debugCache('addBedrockCacheControl: Skipping - no messages', {\n count: messages.length,\n });\n return messages;\n }\n\n debugCache(\n 'addBedrockCacheControl: Processing messages with stable prefix strategy',\n {\n count: messages.length,\n }\n );\n\n const updatedMessages: T[] = messages.slice();\n\n // First pass: Remove ALL existing cache points to ensure clean state\n // This prevents accumulation of stale cache points\n for (const message of updatedMessages) {\n const content = message.content;\n if (Array.isArray(content)) {\n message.content = content.filter(\n (block) => !isCachePoint(block)\n ) as typeof content;\n\n // Also remove Anthropic-style cache_control\n for (let j = 0; j < message.content.length; j++) {\n const block = message.content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n }\n\n // Helper function to check if a message contains reasoning/thinking blocks\n const hasReasoningBlock = (message: T): boolean => {\n const content = message.content;\n if (!Array.isArray(content)) {\n return false;\n }\n for (const block of content) {\n const type = (block as { type?: string }).type;\n // Check for all reasoning/thinking block types:\n // - reasoning_content: Bedrock Anthropic extended thinking\n // - reasoning: Generic reasoning format\n // - thinking: Anthropic direct API thinking\n // - redacted_thinking: Anthropic redacted thinking blocks\n if (\n type === 'reasoning_content' ||\n type === 'reasoning' ||\n type === 'thinking' ||\n type === 'redacted_thinking'\n ) {\n return true;\n }\n }\n return false;\n };\n\n // Second pass: Find the LAST assistant message WITHOUT reasoning blocks and add a cache point there\n // Messages with reasoning/thinking blocks cannot have cache points after them (Bedrock limitation)\n let lastAssistantIndex = -1;\n let skippedWithReasoning = 0;\n\n // Count message types for logging\n const messageTypes: Record<string, number> = {};\n for (const message of updatedMessages) {\n const msgType =\n 'getType' in message && typeof message.getType === 'function'\n ? message.getType()\n : 'unknown';\n messageTypes[msgType] = (messageTypes[msgType] || 0) + 1;\n }\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const message = updatedMessages[i];\n const messageType =\n 'getType' in message && typeof message.getType === 'function'\n ? message.getType()\n : 'unknown';\n\n if (messageType === 'ai') {\n // Skip assistant messages with reasoning blocks - cache points not allowed after them\n if (hasReasoningBlock(message)) {\n skippedWithReasoning++;\n debugCache(\n 'addBedrockCacheControl: Skipping assistant message with reasoning block',\n { index: i }\n );\n continue;\n }\n lastAssistantIndex = i;\n break;\n }\n }\n\n // Log message summary\n debugCache(\n `📨 Messages | total=${updatedMessages.length} | ${Object.entries(\n messageTypes\n )\n .map(([k, v]) => `${k}:${v}`)\n .join(' ')} | skippedReasoning=${skippedWithReasoning}`\n );\n\n // If no suitable assistant message found, skip conversation caching\n // (System and Tools caching are still handled separately)\n if (lastAssistantIndex === -1) {\n debugCache(\n '📨 Messages | No suitable assistant message for cachePoint (first turn or all have reasoning)'\n );\n return updatedMessages;\n }\n\n // Add cache point to the last assistant message (without reasoning blocks)\n const assistantMessage = updatedMessages[lastAssistantIndex];\n const content = assistantMessage.content;\n\n if (typeof content === 'string' && content !== '') {\n assistantMessage.content = [\n { type: ContentTypes.TEXT, text: content },\n { cachePoint: { type: 'default' } },\n ] as MessageContentComplex[];\n debugCache(\n `📍 Message cachePoint at index ${lastAssistantIndex} (string, ${content.length} chars)`\n );\n debugCache(\n 'addBedrockCacheControl: Added cachePoint to assistant message (string content)',\n {\n index: lastAssistantIndex,\n contentLength: content.length,\n }\n );\n } else if (\n Array.isArray(assistantMessage.content) &&\n assistantMessage.content.length > 0\n ) {\n // Double-check: If this message has reasoning blocks, skip adding cache point entirely\n // This handles edge cases where the initial skip check might have missed it\n if (hasReasoningBlock(assistantMessage)) {\n debugCache(\n `⚠️ Message cachePoint SKIPPED at index ${lastAssistantIndex} (has reasoning blocks)`\n );\n debugCache(\n 'addBedrockCacheControl: Skipping - assistant message has reasoning blocks (safety check)',\n {\n index: lastAssistantIndex,\n }\n );\n return updatedMessages;\n }\n\n // Find the last text block and insert cache point after it\n let inserted = false;\n for (let j = assistantMessage.content.length - 1; j >= 0; j--) {\n const block = assistantMessage.content[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 != null && text !== '') {\n assistantMessage.content.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n debugCache(\n `📍 Message cachePoint at index ${lastAssistantIndex} (array, block ${j}, ${text.length} chars)`\n );\n debugCache(\n 'addBedrockCacheControl: Added cachePoint after text block in assistant message',\n {\n index: lastAssistantIndex,\n textBlockIndex: j,\n contentLength: text.length,\n }\n );\n break;\n }\n }\n }\n\n // If no text block found, don't append cache point as the message structure is unexpected\n if (!inserted) {\n const contentTypes = assistantMessage.content.map(\n (b) => (b as { type?: string }).type\n );\n debugCache(\n `⚠️ Message cachePoint SKIPPED at index ${lastAssistantIndex} (no text block, types: ${contentTypes.join(',')})`\n );\n debugCache(\n 'addBedrockCacheControl: No suitable text block found, skipping cache point',\n {\n index: lastAssistantIndex,\n contentTypes,\n }\n );\n }\n }\n\n debugCache(\n 'addBedrockCacheControl: Complete - stable prefix caching applied',\n {\n lastAssistantIndex,\n totalMessages: updatedMessages.length,\n }\n );\n\n return updatedMessages;\n}\n"],"names":["ContentTypes"],"mappings":";;;;AASA;AACA,MAAM,UAAU,GAAG,CAAC,OAAe,EAAE,IAAc,KAAU;IAC3D,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,MAAM,EAAE;;AAE7C,QAAA,OAAO,CAAC,GAAG,CACT,CAAA,QAAA,EAAW,OAAO,CAAA,CAAE,EACpB,IAAI,KAAK,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,CACxD;;AAEL,CAAC;AAED;;;;;;;AAOG;AACG,SAAU,eAAe,CAC7B,QAAa,EAAA;AAEb,IAAA,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;AACnD,QAAA,OAAO,QAAQ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EAAE;AACxC,wBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,qBAAA,CAAC;oBAC3B,QAAQ,GAAG,IAAI;oBACf,UAAU,CACR,CAAkC,+BAAA,EAAA,kBAAkB,CAAkB,eAAA,EAAA,CAAC,CAAK,EAAA,EAAA,IAAI,CAAC,MAAM,CAAS,OAAA,CAAA,CACjG;oBACD,UAAU,CACR,gFAAgF,EAChF;AACE,wBAAA,KAAK,EAAE,kBAAkB;AACzB,wBAAA,cAAc,EAAE,CAAC;wBACjB,aAAa,EAAE,IAAI,CAAC,MAAM;AAC3B,qBAAA,CACF;oBACD;;;;;QAMN,IAAI,CAAC,QAAQ,EAAE;AACb,YAAA,MAAM,YAAY,GAAG,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAC/C,CAAC,CAAC,KAAM,CAAuB,CAAC,IAAI,CACrC;AACD,YAAA,UAAU,CACR,CAAA,uCAAA,EAA0C,kBAAkB,CAAA,wBAAA,EAA2B,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAG,CAAA,CAAA,CACjH;YACD,UAAU,CACR,4EAA4E,EAC5E;AACE,gBAAA,KAAK,EAAE,kBAAkB;gBACzB,YAAY;AACb,aAAA,CACF;;;IAIL,UAAU,CACR,kEAAkE,EAClE;QACE,kBAAkB;QAClB,aAAa,EAAE,eAAe,CAAC,MAAM;AACtC,KAAA,CACF;AAED,IAAA,OAAO,eAAe;AACxB;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"cache.cjs","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/** Debug logger for cache operations - set ILLUMA_DEBUG_CACHE=true to enable */\nconst debugCache = (message: string, data?: unknown): void => {\n if (process.env.ILLUMA_DEBUG_CACHE === 'true') {\n // eslint-disable-next-line no-console\n console.log(\n `[Cache] ${message}`,\n data !== undefined ? JSON.stringify(data, null, 2) : ''\n );\n }\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 * Keeps lc_kwargs in sync with content to prevent LangChain serialization 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 // Sync lc_kwargs.content with the new content to prevent LangChain coercion issues\n const lcKwargs = (message 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 = {\n ...lcKwargs,\n content: content,\n };\n }\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 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 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 * 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 * 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 * 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 * 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) as T;\n }\n\n return updatedMessages;\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) as T;\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points using \"Stable Prefix Caching\" strategy.\n *\n * STRATEGY: Place cache point after the LAST ASSISTANT message only.\n * This ensures the prefix (everything before the cache point) remains STABLE\n * as the conversation grows, maximizing cache hits.\n *\n * Why this works:\n * - System message has its own cachePoint (added in AgentContext)\n * - Tools have their own cachePoint (added in CustomChatBedrockConverse)\n * - Conversation history grows, but the PREFIX stays the same\n * - Only the NEW user message is uncached (it's always different)\n *\n * Example conversation flow:\n * Request 1: [System+cachePoint][Tools+cachePoint][User1] → No conversation cache yet\n * Request 2: [System][Tools][User1][Assistant1+cachePoint][User2] → Cache User1+Assistant1\n * Request 3: [System][Tools][User1][Assistant1][User2][Assistant2+cachePoint][User3]\n * → Cache reads User1+A1+User2+A2, cache writes new portion\n *\n * Claude's \"Simplified Cache Management\" automatically looks back up to 20 content\n * blocks from the cache checkpoint to find the longest matching prefix.\n *\n * @param messages - The array of message objects (excluding system message).\n * @returns - The updated array with a single cache point after the last assistant message.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 1) {\n debugCache('addBedrockCacheControl: Skipping - no messages', {\n count: messages.length,\n });\n return messages;\n }\n\n debugCache(\n 'addBedrockCacheControl: Processing messages with stable prefix strategy',\n {\n count: messages.length,\n }\n );\n\n const updatedMessages: T[] = messages.slice();\n\n // First pass: Remove ALL existing cache points to ensure clean state\n // This prevents accumulation of stale cache points\n for (const message of updatedMessages) {\n const content = message.content;\n if (Array.isArray(content)) {\n message.content = content.filter(\n (block) => !isCachePoint(block)\n ) as typeof content;\n\n // Also remove Anthropic-style cache_control\n for (let j = 0; j < message.content.length; j++) {\n const block = message.content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n }\n\n // Helper function to check if a message contains reasoning/thinking blocks\n const hasReasoningBlock = (message: T): boolean => {\n const content = message.content;\n if (!Array.isArray(content)) {\n return false;\n }\n for (const block of content) {\n const type = (block as { type?: string }).type;\n // Check for all reasoning/thinking block types:\n // - reasoning_content: Bedrock Anthropic extended thinking\n // - reasoning: Generic reasoning format\n // - thinking: Anthropic direct API thinking\n // - redacted_thinking: Anthropic redacted thinking blocks\n if (\n type === 'reasoning_content' ||\n type === 'reasoning' ||\n type === 'thinking' ||\n type === 'redacted_thinking'\n ) {\n return true;\n }\n }\n return false;\n };\n\n // Second pass: Find the LAST assistant message WITHOUT reasoning blocks and add a cache point there\n // Messages with reasoning/thinking blocks cannot have cache points after them (Bedrock limitation)\n let lastAssistantIndex = -1;\n let skippedWithReasoning = 0;\n\n // Count message types for logging\n const messageTypes: Record<string, number> = {};\n for (const message of updatedMessages) {\n const msgType =\n 'getType' in message && typeof message.getType === 'function'\n ? message.getType()\n : 'unknown';\n messageTypes[msgType] = (messageTypes[msgType] || 0) + 1;\n }\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const message = updatedMessages[i];\n const messageType =\n 'getType' in message && typeof message.getType === 'function'\n ? message.getType()\n : 'unknown';\n\n if (messageType === 'ai') {\n // Skip assistant messages with reasoning blocks - cache points not allowed after them\n if (hasReasoningBlock(message)) {\n skippedWithReasoning++;\n debugCache(\n 'addBedrockCacheControl: Skipping assistant message with reasoning block',\n { index: i }\n );\n continue;\n }\n lastAssistantIndex = i;\n break;\n }\n }\n\n // Log message summary\n debugCache(\n `📨 Messages | total=${updatedMessages.length} | ${Object.entries(\n messageTypes\n )\n .map(([k, v]) => `${k}:${v}`)\n .join(' ')} | skippedReasoning=${skippedWithReasoning}`\n );\n\n // If no suitable assistant message found, skip conversation caching\n // (System and Tools caching are still handled separately)\n if (lastAssistantIndex === -1) {\n debugCache(\n '📨 Messages | No suitable assistant message for cachePoint (first turn or all have reasoning)'\n );\n return updatedMessages;\n }\n\n // Add cache point to the last assistant message (without reasoning blocks)\n const assistantMessage = updatedMessages[lastAssistantIndex];\n const content = assistantMessage.content;\n\n if (typeof content === 'string' && content !== '') {\n assistantMessage.content = [\n { type: ContentTypes.TEXT, text: content },\n { cachePoint: { type: 'default' } },\n ] as MessageContentComplex[];\n debugCache(\n `📍 Message cachePoint at index ${lastAssistantIndex} (string, ${content.length} chars)`\n );\n debugCache(\n 'addBedrockCacheControl: Added cachePoint to assistant message (string content)',\n {\n index: lastAssistantIndex,\n contentLength: content.length,\n }\n );\n } else if (\n Array.isArray(assistantMessage.content) &&\n assistantMessage.content.length > 0\n ) {\n // Double-check: If this message has reasoning blocks, skip adding cache point entirely\n // This handles edge cases where the initial skip check might have missed it\n if (hasReasoningBlock(assistantMessage)) {\n debugCache(\n `⚠️ Message cachePoint SKIPPED at index ${lastAssistantIndex} (has reasoning blocks)`\n );\n debugCache(\n 'addBedrockCacheControl: Skipping - assistant message has reasoning blocks (safety check)',\n {\n index: lastAssistantIndex,\n }\n );\n return updatedMessages;\n }\n\n // Find the last text block and insert cache point after it\n let inserted = false;\n for (let j = assistantMessage.content.length - 1; j >= 0; j--) {\n const block = assistantMessage.content[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 != null && text !== '') {\n assistantMessage.content.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n debugCache(\n `📍 Message cachePoint at index ${lastAssistantIndex} (array, block ${j}, ${text.length} chars)`\n );\n debugCache(\n 'addBedrockCacheControl: Added cachePoint after text block in assistant message',\n {\n index: lastAssistantIndex,\n textBlockIndex: j,\n contentLength: text.length,\n }\n );\n break;\n }\n }\n }\n\n // If no text block found, don't append cache point as the message structure is unexpected\n if (!inserted) {\n const contentTypes = assistantMessage.content.map(\n (b) => (b as { type?: string }).type\n );\n debugCache(\n `⚠️ Message cachePoint SKIPPED at index ${lastAssistantIndex} (no text block, types: ${contentTypes.join(',')})`\n );\n debugCache(\n 'addBedrockCacheControl: No suitable text block found, skipping cache point',\n {\n index: lastAssistantIndex,\n contentTypes,\n }\n );\n }\n }\n\n debugCache(\n 'addBedrockCacheControl: Complete - stable prefix caching applied',\n {\n lastAssistantIndex,\n totalMessages: updatedMessages.length,\n }\n );\n\n return updatedMessages;\n}\n"],"names":["ContentTypes"],"mappings":";;;;AASA;AACA,MAAM,UAAU,GAAG,CAAC,OAAe,EAAE,IAAc,KAAU;IAC3D,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,MAAM,EAAE;;AAE7C,QAAA,OAAO,CAAC,GAAG,CACT,CAAA,QAAA,EAAW,OAAO,CAAA,CAAE,EACpB,IAAI,KAAK,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,CACxD;;AAEL,CAAC;AAED;;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;;;;AAIG;AACH,SAAS,YAAY,CACnB,OAAU,EACV,OAAyC,EAAA;AAEzC,IAAA,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,eAAe,EAAE,gBAAgB,EACjC,YAAY,EAAE,aAAa,EAC3B,GAAG,IAAI,EACR,GAAG,OAIH;IAED,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,OAAO,EAAO;;AAGxC,I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,CAAC,CAAK,EAAA,EAAA,IAAI,CAAC,MAAM,CAAS,OAAA,CAAA,CACjG;oBACD,UAAU,CACR,gFAAgF,EAChF;AACE,wBAAA,KAAK,EAAE,kBAAkB;AACzB,wBAAA,cAAc,EAAE,CAAC;wBACjB,aAAa,EAAE,IAAI,CAAC,MAAM;AAC3B,qBAAA,CACF;oBACD;;;;;QAMN,IAAI,CAAC,QAAQ,EAAE;AACb,YAAA,MAAM,YAAY,GAAG,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAC/C,CAAC,CAAC,KAAM,CAAuB,CAAC,IAAI,CACrC;AACD,YAAA,UAAU,CACR,CAAA,uCAAA,EAA0C,kBAAkB,CAAA,wBAAA,EAA2B,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAG,CAAA,CAAA,CACjH;YACD,UAAU,CACR,4EAA4E,EAC5E;AACE,gBAAA,KAAK,EAAE,kBAAkB;gBACzB,YAAY;AACb,aAAA,CACF;;;IAIL,UAAU,CACR,kEAAkE,EAClE;QACE,kBAAkB;QAClB,aAAa,EAAE,eAAe,CAAC,MAAM;AACtC,KAAA,CACF;AAED,IAAA,OAAO,eAAe;AACxB;;;;;;;"}
|
|
@@ -25,7 +25,7 @@ User: ${userMessage[1]}
|
|
|
25
25
|
const _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];
|
|
26
26
|
const allowedTypesByProvider = {
|
|
27
27
|
default: _allowedTypes,
|
|
28
|
-
[_enum.Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],
|
|
28
|
+
[_enum.Providers.ANTHROPIC]: [..._allowedTypes, 'thinking', 'redacted_thinking'],
|
|
29
29
|
[_enum.Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],
|
|
30
30
|
[_enum.Providers.OPENAI]: _allowedTypes,
|
|
31
31
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport {\n AIMessageChunk,\n HumanMessage,\n ToolMessage,\n AIMessage,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers, MessageTypes } from '@/common';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): t.ExtendedMessageContent[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = reduceBlocks(obj.content as ContentBlock[]);\n }\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent({\n provider,\n messageType,\n content: obj.content,\n });\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content,\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(\n (item) => item != null && item.type !== 'tool_use'\n );\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessage.getType() !== 'tool') return;\n const lastToolMessage = lastMessage as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n // Use getType() instead of instanceof to avoid module mismatch issues\n const hasArtifactContent = messages.some(\n (msg, i) =>\n i > latestAIParentIndex &&\n msg.getType() === MessageTypes.TOOL &&\n (msg as ToolMessage).artifact != null &&\n (msg as ToolMessage).artifact?.content != null &&\n Array.isArray((msg as ToolMessage).artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map((tc) => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (\n msg.getType() === MessageTypes.TOOL &&\n toolCallIds.includes((msg as ToolMessage).tool_call_id) &&\n (msg as ToolMessage).artifact != null &&\n Array.isArray((msg as ToolMessage).artifact?.content) &&\n Array.isArray(msg.content)\n ) {\n msg.content = (msg.content as t.MessageContentComplex[]).concat(\n (msg as ToolMessage).artifact.content\n );\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessageY.getType() !== 'tool') return;\n const lastToolMessage = lastMessageY as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n // Use getType() instead of instanceof to avoid module mismatch issues\n const hasArtifactContent = messages.some(\n (msg, i) =>\n i > latestAIParentIndex &&\n msg.getType() === MessageTypes.TOOL &&\n (msg as ToolMessage).artifact != null &&\n (msg as ToolMessage).artifact?.content != null &&\n Array.isArray((msg as ToolMessage).artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n // Use getType() instead of instanceof to avoid module mismatch issues\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter((msg) => msg.getType() === MessageTypes.TOOL) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach((msg) => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n let currentContent = msg.content;\n if (!Array.isArray(currentContent)) {\n currentContent = [\n {\n type: 'text',\n text: msg.content,\n },\n ];\n }\n aggregatedContent.push(...currentContent);\n msg.content =\n 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"names":["HumanMessage","Providers","AIMessage","messages","AIMessageChunk","MessageTypes"],"mappings":";;;;;AAAA;AAYM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,GAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAIA,qBA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AAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport {\n AIMessageChunk,\n HumanMessage,\n ToolMessage,\n AIMessage,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers, MessageTypes } from '@/common';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY,\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [..._allowedTypes, 'thinking', 'redacted_thinking'],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content,\n}: {\n provider: Providers;\n messageType: string;\n content: t.ExtendedMessageContent[];\n}): t.ExtendedMessageContent[] => {\n const allowedTypes =\n allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map((item) => {\n if (\n item &&\n typeof item === 'object' &&\n 'type' in item &&\n item.type != null &&\n item.type\n ) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (\n messageType === 'ai' &&\n newType === 'tool_use' &&\n 'input' in item &&\n item.input === ''\n ) {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock =\n | Partial<t.BedrockReasoningContentText>\n | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1] as ContentBlock | undefined;\n\n // Merge consecutive 'reasoning_content'\n if (\n block.type === 'reasoning_content' &&\n lastBlock?.type === 'reasoning_content'\n ) {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).text =\n (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (\n block.reasoningText?.signature != null &&\n block.reasoningText.signature\n ) {\n (\n lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']\n ).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock?.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(\n provider: Providers,\n obj?: AIMessageChunk\n): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = (obj as Partial<AIMessageChunk>)._getType\n ? obj._getType()\n : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = reduceBlocks(obj.content as ContentBlock[]);\n }\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent({\n provider,\n messageType,\n content: obj.content,\n });\n }\n if (\n (obj as Partial<AIMessageChunk>).lc_kwargs &&\n Array.isArray(obj.lc_kwargs.content)\n ) {\n obj.lc_kwargs.content = modifyContent({\n provider,\n messageType,\n content: obj.lc_kwargs.content,\n });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map((tc) => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>(\n (acc, item) => {\n if (typeof item === 'object') {\n const extendedItem = item as t.ExtendedMessageContent;\n if (\n extendedItem.type === 'text' &&\n extendedItem.text != null &&\n extendedItem.text\n ) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (\n extendedItem.type === 'tool_use' &&\n extendedItem.id != null &&\n extendedItem.id\n ) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } else if (\n 'input' in extendedItem &&\n extendedItem.input != null &&\n extendedItem.input\n ) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(\n (tc) => tc.args.input === parsedInput.input\n );\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string,\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n },\n []\n );\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(\n (toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args,\n },\n })\n );\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n },\n });\n}\n\nexport function convertMessagesToContent(\n messages: BaseMessage[]\n): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content =\n message?.lc_kwargs.content != null\n ? message.lc_kwargs.content\n : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content,\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(\n (item) => item != null && item.type !== 'tool_use'\n );\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (\n messageType === 'ai' &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (tool_call.id == null || !tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (\n messageType === 'tool' &&\n (message as ToolMessage).tool_call_id\n ) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n if (currentAIMessageIndex === -1) {\n processedContent.push({ type: 'text', text: '' });\n currentAIMessageIndex = processedContent.length - 1;\n }\n const contentPart = processedContent[currentAIMessageIndex];\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessage.getType() !== 'tool') return;\n const lastToolMessage = lastMessage as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n // Use getType() instead of instanceof to avoid module mismatch issues\n const hasArtifactContent = messages.some(\n (msg, i) =>\n i > latestAIParentIndex &&\n msg.getType() === MessageTypes.TOOL &&\n (msg as ToolMessage).artifact != null &&\n (msg as ToolMessage).artifact?.content != null &&\n Array.isArray((msg as ToolMessage).artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map((tc) => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (\n msg.getType() === MessageTypes.TOOL &&\n toolCallIds.includes((msg as ToolMessage).tool_call_id) &&\n (msg as ToolMessage).artifact != null &&\n Array.isArray((msg as ToolMessage).artifact?.content) &&\n Array.isArray(msg.content)\n ) {\n msg.content = (msg.content as t.MessageContentComplex[]).concat(\n (msg as ToolMessage).artifact.content\n );\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessageY.getType() !== 'tool') return;\n const lastToolMessage = lastMessageY as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n // Use getType() instead of instanceof to avoid module mismatch issues\n const hasArtifactContent = messages.some(\n (msg, i) =>\n i > latestAIParentIndex &&\n msg.getType() === MessageTypes.TOOL &&\n (msg as ToolMessage).artifact != null &&\n (msg as ToolMessage).artifact?.content != null &&\n Array.isArray((msg as ToolMessage).artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n // Use getType() instead of instanceof to avoid module mismatch issues\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter((msg) => msg.getType() === MessageTypes.TOOL) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach((msg) => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n let currentContent = msg.content;\n if (!Array.isArray(currentContent)) {\n currentContent = [\n {\n type: 'text',\n text: msg.content,\n },\n ];\n }\n aggregatedContent.push(...currentContent);\n msg.content =\n 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(\n array: T[],\n predicate: (value: T) => boolean\n): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n"],"names":["HumanMessage","Providers","AIMessage","messages","AIMessageChunk","MessageTypes"],"mappings":";;;;;AAAA;AAYM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,GAKb,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MAAM,GAAG,CAAC,EAAE;AAChC,QAAAF,UAAQ,CAAC,IAAI,CAAC,IAAIH,qBAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;;AAEnE;AAEgB,SAAA,aAAa,CAC3B,KAAU,EACV,SAAgC,EAAA;AAEhC,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
|
@@ -39,7 +39,7 @@ function extractToolDiscoveries(messages$1) {
|
|
|
39
39
|
if (msg.getType() !== _enum.MessageTypes.TOOL)
|
|
40
40
|
continue;
|
|
41
41
|
const toolMsg = msg;
|
|
42
|
-
if (toolMsg.name !== _enum.Constants.
|
|
42
|
+
if (toolMsg.name !== _enum.Constants.TOOL_SEARCH)
|
|
43
43
|
continue;
|
|
44
44
|
if (!toolCallIds.has(toolMsg.tool_call_id))
|
|
45
45
|
continue;
|
|
@@ -79,7 +79,7 @@ function hasToolSearchInCurrentTurn(messages$1) {
|
|
|
79
79
|
for (let i = latestAIParentIndex + 1; i < messages$1.length; i++) {
|
|
80
80
|
const msg = messages$1[i];
|
|
81
81
|
if (msg.getType() === _enum.MessageTypes.TOOL &&
|
|
82
|
-
msg.name === _enum.Constants.
|
|
82
|
+
msg.name === _enum.Constants.TOOL_SEARCH &&
|
|
83
83
|
toolCallIds.has(msg.tool_call_id)) {
|
|
84
84
|
return true;
|
|
85
85
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.cjs","sources":["../../../src/messages/tools.ts"],"sourcesContent":["// src/messages/toolDiscovery.ts\nimport { AIMessageChunk, ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { Constants, MessageTypes } from '@/common';\nimport { findLastIndex } from './core';\n\ntype ToolSearchArtifact = {\n tool_references?: Array<{ tool_name: string }>;\n};\n\n/**\n * Extracts discovered tool names from tool search results in the current turn.\n * Only processes tool search messages after the latest AI message with tool calls.\n *\n * Similar pattern to formatArtifactPayload - finds relevant messages efficiently\n * by identifying the latest AI parent and only processing subsequent tool messages.\n *\n * @param messages - All messages in the conversation\n * @returns Array of discovered tool names (empty if no new discoveries)\n */\nexport function extractToolDiscoveries(messages: BaseMessage[]): string[] {\n const lastMessage = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessage.getType() !== MessageTypes.TOOL) return [];\n const lastToolMessage = lastMessage as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return [];\n\n // Collect tool_call_ids from the AI message\n const aiMessage = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = new Set(aiMessage.tool_calls?.map((tc) => tc.id) ?? []);\n\n // Only process tool search results after the AI message that belong to this turn\n const discoveredNames: string[] = [];\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (msg.getType() !== MessageTypes.TOOL) continue;\n const toolMsg = msg as ToolMessage;\n if (toolMsg.name !== Constants.
|
|
1
|
+
{"version":3,"file":"tools.cjs","sources":["../../../src/messages/tools.ts"],"sourcesContent":["// src/messages/toolDiscovery.ts\nimport { AIMessageChunk, ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { Constants, MessageTypes } from '@/common';\nimport { findLastIndex } from './core';\n\ntype ToolSearchArtifact = {\n tool_references?: Array<{ tool_name: string }>;\n};\n\n/**\n * Extracts discovered tool names from tool search results in the current turn.\n * Only processes tool search messages after the latest AI message with tool calls.\n *\n * Similar pattern to formatArtifactPayload - finds relevant messages efficiently\n * by identifying the latest AI parent and only processing subsequent tool messages.\n *\n * @param messages - All messages in the conversation\n * @returns Array of discovered tool names (empty if no new discoveries)\n */\nexport function extractToolDiscoveries(messages: BaseMessage[]): string[] {\n const lastMessage = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessage.getType() !== MessageTypes.TOOL) return [];\n const lastToolMessage = lastMessage as ToolMessage;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return [];\n\n // Collect tool_call_ids from the AI message\n const aiMessage = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = new Set(aiMessage.tool_calls?.map((tc) => tc.id) ?? []);\n\n // Only process tool search results after the AI message that belong to this turn\n const discoveredNames: string[] = [];\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (msg.getType() !== MessageTypes.TOOL) continue;\n const toolMsg = msg as ToolMessage;\n if (toolMsg.name !== Constants.TOOL_SEARCH) continue;\n if (!toolCallIds.has(toolMsg.tool_call_id)) continue;\n\n // This is a tool search result from the current turn\n if (typeof toolMsg.artifact === 'object' && toolMsg.artifact != null) {\n const artifact = toolMsg.artifact as ToolSearchArtifact;\n if (artifact.tool_references && artifact.tool_references.length > 0) {\n for (const ref of artifact.tool_references) {\n discoveredNames.push(ref.tool_name);\n }\n }\n }\n }\n\n return discoveredNames;\n}\n\n/**\n * Checks if the current turn has any tool search results.\n * Quick check to avoid full extraction when not needed.\n */\nexport function hasToolSearchInCurrentTurn(messages: BaseMessage[]): boolean {\n const lastMessage = messages[messages.length - 1];\n // Use getType() instead of instanceof to avoid module mismatch issues\n if (lastMessage.getType() !== MessageTypes.TOOL) return false;\n const lastToolMessage = lastMessage as ToolMessage;\n\n // Find the latest AIMessage with tool_calls\n const latestAIParentIndex = findLastIndex(\n messages,\n (msg) =>\n (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some((tc) => tc.id === lastToolMessage.tool_call_id)) ??\n false\n );\n\n if (latestAIParentIndex === -1) return false;\n\n const aiMessage = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = new Set(aiMessage.tool_calls?.map((tc) => tc.id) ?? []);\n\n // Check if any tool search results exist after the AI message\n // Use getType() instead of instanceof to avoid module mismatch issues\n for (let i = latestAIParentIndex + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (\n msg.getType() === MessageTypes.TOOL &&\n (msg as ToolMessage).name === Constants.TOOL_SEARCH &&\n toolCallIds.has((msg as ToolMessage).tool_call_id)\n ) {\n return true;\n }\n }\n\n return false;\n}\n"],"names":["messages","MessageTypes","findLastIndex","AIMessageChunk","Constants"],"mappings":";;;;;;AAAA;AAUA;;;;;;;;;AASG;AACG,SAAU,sBAAsB,CAACA,UAAuB,EAAA;IAC5D,MAAM,WAAW,GAAGA,UAAQ,CAACA,UAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;;AAEjD,IAAA,IAAI,WAAW,CAAC,OAAO,EAAE,KAAKC,kBAAY,CAAC,IAAI;AAAE,QAAA,OAAO,EAAE;IAC1D,MAAM,eAAe,GAAG,WAA0B;;AAGlD,IAAA,MAAM,mBAAmB,GAAGC,kBAAa,CACvCF,UAAQ,EACR,CAAC,GAAG,KACF,CAAC,GAAG,YAAYG,uBAAc;QAC5B,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACjC,QAAA,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,EA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,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Validates structured output against a JSON Schema.
|
|
5
|
+
*
|
|
6
|
+
* @param output - The output to validate
|
|
7
|
+
* @param schema - JSON Schema to validate against
|
|
8
|
+
* @returns Validation result with success flag and data or error
|
|
9
|
+
*/
|
|
10
|
+
function validateStructuredOutput(output, schema) {
|
|
11
|
+
try {
|
|
12
|
+
// Parse output if it's a string
|
|
13
|
+
const data = typeof output === 'string' ? JSON.parse(output) : output;
|
|
14
|
+
// Basic JSON Schema validation
|
|
15
|
+
const errors = validateAgainstJsonSchema(data, schema);
|
|
16
|
+
if (errors.length > 0) {
|
|
17
|
+
return {
|
|
18
|
+
success: false,
|
|
19
|
+
error: `Validation failed: ${errors.join('; ')}`,
|
|
20
|
+
raw: data,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
success: true,
|
|
25
|
+
data: data,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
return {
|
|
30
|
+
success: false,
|
|
31
|
+
error: `Failed to parse output: ${e.message}`,
|
|
32
|
+
raw: output,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Validates data against a JSON Schema (simplified implementation).
|
|
38
|
+
* For complex schemas, consider using ajv or similar library.
|
|
39
|
+
*/
|
|
40
|
+
function validateAgainstJsonSchema(data, schema, path = '') {
|
|
41
|
+
const errors = [];
|
|
42
|
+
if (schema.type === 'object' && typeof data !== 'object') {
|
|
43
|
+
errors.push(`${path || 'root'}: expected object, got ${typeof data}`);
|
|
44
|
+
return errors;
|
|
45
|
+
}
|
|
46
|
+
if (schema.type === 'array' && !Array.isArray(data)) {
|
|
47
|
+
errors.push(`${path || 'root'}: expected array, got ${typeof data}`);
|
|
48
|
+
return errors;
|
|
49
|
+
}
|
|
50
|
+
if (schema.type === 'string' && typeof data !== 'string') {
|
|
51
|
+
errors.push(`${path || 'root'}: expected string, got ${typeof data}`);
|
|
52
|
+
return errors;
|
|
53
|
+
}
|
|
54
|
+
if (schema.type === 'number' && typeof data !== 'number') {
|
|
55
|
+
errors.push(`${path || 'root'}: expected number, got ${typeof data}`);
|
|
56
|
+
return errors;
|
|
57
|
+
}
|
|
58
|
+
if (schema.type === 'boolean' && typeof data !== 'boolean') {
|
|
59
|
+
errors.push(`${path || 'root'}: expected boolean, got ${typeof data}`);
|
|
60
|
+
return errors;
|
|
61
|
+
}
|
|
62
|
+
// Validate required properties
|
|
63
|
+
if (schema.type === 'object' &&
|
|
64
|
+
Array.isArray(schema.required) &&
|
|
65
|
+
typeof data === 'object' &&
|
|
66
|
+
data !== null) {
|
|
67
|
+
for (const requiredProp of schema.required) {
|
|
68
|
+
if (!(requiredProp in data)) {
|
|
69
|
+
errors.push(`${path || 'root'}: missing required property '${requiredProp}'`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// Validate nested properties
|
|
74
|
+
if (schema.type === 'object' &&
|
|
75
|
+
schema.properties &&
|
|
76
|
+
typeof data === 'object' &&
|
|
77
|
+
data !== null) {
|
|
78
|
+
const properties = schema.properties;
|
|
79
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
80
|
+
if (key in data) {
|
|
81
|
+
const nestedErrors = validateAgainstJsonSchema(data[key], propSchema, path ? `${path}.${key}` : key);
|
|
82
|
+
errors.push(...nestedErrors);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Validate array items
|
|
87
|
+
if (schema.type === 'array' && schema.items && Array.isArray(data)) {
|
|
88
|
+
const itemSchema = schema.items;
|
|
89
|
+
for (let i = 0; i < data.length; i++) {
|
|
90
|
+
const nestedErrors = validateAgainstJsonSchema(data[i], itemSchema, `${path || 'root'}[${i}]`);
|
|
91
|
+
errors.push(...nestedErrors);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// Validate enum values
|
|
95
|
+
if (schema.enum && Array.isArray(schema.enum)) {
|
|
96
|
+
if (!schema.enum.includes(data)) {
|
|
97
|
+
errors.push(`${path || 'root'}: value '${data}' not in enum [${schema.enum.join(', ')}]`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return errors;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Converts a Zod schema to JSON Schema format.
|
|
104
|
+
* This is a simplified converter for common types.
|
|
105
|
+
*/
|
|
106
|
+
function zodToJsonSchema(zodSchema) {
|
|
107
|
+
// Use the zod-to-json-schema library if available
|
|
108
|
+
// For now, provide a basic implementation
|
|
109
|
+
try {
|
|
110
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
111
|
+
const { zodToJsonSchema: convert } = require('zod-to-json-schema');
|
|
112
|
+
return convert(zodSchema);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Fallback: return a generic object schema
|
|
116
|
+
return {
|
|
117
|
+
type: 'object',
|
|
118
|
+
additionalProperties: true,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Creates a structured output error message for retry.
|
|
124
|
+
*/
|
|
125
|
+
function createValidationErrorMessage(result, customMessage) {
|
|
126
|
+
if (customMessage) {
|
|
127
|
+
return customMessage;
|
|
128
|
+
}
|
|
129
|
+
return `The response did not match the expected schema. Error: ${result.error}. Please try again and ensure your response exactly matches the required format.`;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Checks if a value is a valid JSON Schema object.
|
|
133
|
+
*/
|
|
134
|
+
function isValidJsonSchema(value) {
|
|
135
|
+
if (typeof value !== 'object' || value === null) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
const schema = value;
|
|
139
|
+
// Basic check: must have a type or properties
|
|
140
|
+
return (typeof schema.type === 'string' ||
|
|
141
|
+
typeof schema.properties === 'object' ||
|
|
142
|
+
typeof schema.$schema === 'string');
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Normalizes a JSON Schema by adding defaults and cleaning up.
|
|
146
|
+
*/
|
|
147
|
+
function normalizeJsonSchema(schema, config) {
|
|
148
|
+
const normalized = { ...schema };
|
|
149
|
+
// Ensure type is set
|
|
150
|
+
if (!normalized.type && normalized.properties) {
|
|
151
|
+
normalized.type = 'object';
|
|
152
|
+
}
|
|
153
|
+
// Add title from config name
|
|
154
|
+
if (config?.name && !normalized.title) {
|
|
155
|
+
normalized.title = config.name;
|
|
156
|
+
}
|
|
157
|
+
// Add description from config
|
|
158
|
+
if (config?.description && !normalized.description) {
|
|
159
|
+
normalized.description = config.description;
|
|
160
|
+
}
|
|
161
|
+
// Enable additionalProperties: false for strict mode
|
|
162
|
+
if (config?.strict !== false && normalized.type === 'object') {
|
|
163
|
+
normalized.additionalProperties = normalized.additionalProperties ?? false;
|
|
164
|
+
}
|
|
165
|
+
return normalized;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
exports.createValidationErrorMessage = createValidationErrorMessage;
|
|
169
|
+
exports.isValidJsonSchema = isValidJsonSchema;
|
|
170
|
+
exports.normalizeJsonSchema = normalizeJsonSchema;
|
|
171
|
+
exports.validateStructuredOutput = validateStructuredOutput;
|
|
172
|
+
exports.zodToJsonSchema = zodToJsonSchema;
|
|
173
|
+
//# sourceMappingURL=validate.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate.cjs","sources":["../../../src/schemas/validate.ts"],"sourcesContent":["// src/schemas/validate.ts\nimport { z } from 'zod';\nimport type * as t from '@/types';\n\n/**\n * Validation result from structured output\n */\nexport interface ValidationResult<T = Record<string, unknown>> {\n success: boolean;\n data?: T;\n error?: string;\n raw?: unknown;\n}\n\n/**\n * Validates structured output against a JSON Schema.\n *\n * @param output - The output to validate\n * @param schema - JSON Schema to validate against\n * @returns Validation result with success flag and data or error\n */\nexport function validateStructuredOutput(\n output: unknown,\n schema: Record<string, unknown>\n): ValidationResult {\n try {\n // Parse output if it's a string\n const data = typeof output === 'string' ? JSON.parse(output) : output;\n\n // Basic JSON Schema validation\n const errors = validateAgainstJsonSchema(data, schema);\n\n if (errors.length > 0) {\n return {\n success: false,\n error: `Validation failed: ${errors.join('; ')}`,\n raw: data,\n };\n }\n\n return {\n success: true,\n data: data as Record<string, unknown>,\n };\n } catch (e) {\n return {\n success: false,\n error: `Failed to parse output: ${(e as Error).message}`,\n raw: output,\n };\n }\n}\n\n/**\n * Validates data against a JSON Schema (simplified implementation).\n * For complex schemas, consider using ajv or similar library.\n */\nfunction validateAgainstJsonSchema(\n data: unknown,\n schema: Record<string, unknown>,\n path = ''\n): string[] {\n const errors: string[] = [];\n\n if (schema.type === 'object' && typeof data !== 'object') {\n errors.push(`${path || 'root'}: expected object, got ${typeof data}`);\n return errors;\n }\n\n if (schema.type === 'array' && !Array.isArray(data)) {\n errors.push(`${path || 'root'}: expected array, got ${typeof data}`);\n return errors;\n }\n\n if (schema.type === 'string' && typeof data !== 'string') {\n errors.push(`${path || 'root'}: expected string, got ${typeof data}`);\n return errors;\n }\n\n if (schema.type === 'number' && typeof data !== 'number') {\n errors.push(`${path || 'root'}: expected number, got ${typeof data}`);\n return errors;\n }\n\n if (schema.type === 'boolean' && typeof data !== 'boolean') {\n errors.push(`${path || 'root'}: expected boolean, got ${typeof data}`);\n return errors;\n }\n\n // Validate required properties\n if (\n schema.type === 'object' &&\n Array.isArray(schema.required) &&\n typeof data === 'object' &&\n data !== null\n ) {\n for (const requiredProp of schema.required as string[]) {\n if (!(requiredProp in data)) {\n errors.push(\n `${path || 'root'}: missing required property '${requiredProp}'`\n );\n }\n }\n }\n\n // Validate nested properties\n if (\n schema.type === 'object' &&\n schema.properties &&\n typeof data === 'object' &&\n data !== null\n ) {\n const properties = schema.properties as Record<\n string,\n Record<string, unknown>\n >;\n for (const [key, propSchema] of Object.entries(properties)) {\n if (key in data) {\n const nestedErrors = validateAgainstJsonSchema(\n (data as Record<string, unknown>)[key],\n propSchema,\n path ? `${path}.${key}` : key\n );\n errors.push(...nestedErrors);\n }\n }\n }\n\n // Validate array items\n if (schema.type === 'array' && schema.items && Array.isArray(data)) {\n const itemSchema = schema.items as Record<string, unknown>;\n for (let i = 0; i < data.length; i++) {\n const nestedErrors = validateAgainstJsonSchema(\n data[i],\n itemSchema,\n `${path || 'root'}[${i}]`\n );\n errors.push(...nestedErrors);\n }\n }\n\n // Validate enum values\n if (schema.enum && Array.isArray(schema.enum)) {\n if (!schema.enum.includes(data)) {\n errors.push(\n `${path || 'root'}: value '${data}' not in enum [${(schema.enum as unknown[]).join(', ')}]`\n );\n }\n }\n\n return errors;\n}\n\n/**\n * Converts a Zod schema to JSON Schema format.\n * This is a simplified converter for common types.\n */\nexport function zodToJsonSchema(zodSchema: z.ZodType): Record<string, unknown> {\n // Use the zod-to-json-schema library if available\n // For now, provide a basic implementation\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { zodToJsonSchema: convert } = require('zod-to-json-schema');\n return convert(zodSchema) as Record<string, unknown>;\n } catch {\n // Fallback: return a generic object schema\n return {\n type: 'object',\n additionalProperties: true,\n };\n }\n}\n\n/**\n * Creates a structured output error message for retry.\n */\nexport function createValidationErrorMessage(\n result: ValidationResult,\n customMessage?: string\n): string {\n if (customMessage) {\n return customMessage;\n }\n\n return `The response did not match the expected schema. Error: ${result.error}. Please try again and ensure your response exactly matches the required format.`;\n}\n\n/**\n * Checks if a value is a valid JSON Schema object.\n */\nexport function isValidJsonSchema(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const schema = value as Record<string, unknown>;\n\n // Basic check: must have a type or properties\n return (\n typeof schema.type === 'string' ||\n typeof schema.properties === 'object' ||\n typeof schema.$schema === 'string'\n );\n}\n\n/**\n * Normalizes a JSON Schema by adding defaults and cleaning up.\n */\nexport function normalizeJsonSchema(\n schema: Record<string, unknown>,\n config?: t.StructuredOutputConfig\n): Record<string, unknown> {\n const normalized = { ...schema };\n\n // Ensure type is set\n if (!normalized.type && normalized.properties) {\n normalized.type = 'object';\n }\n\n // Add title from config name\n if (config?.name && !normalized.title) {\n normalized.title = config.name;\n }\n\n // Add description from config\n if (config?.description && !normalized.description) {\n normalized.description = config.description;\n }\n\n // Enable additionalProperties: false for strict mode\n if (config?.strict !== false && normalized.type === 'object') {\n normalized.additionalProperties = normalized.additionalProperties ?? false;\n }\n\n return normalized;\n}\n"],"names":[],"mappings":";;AAcA;;;;;;AAMG;AACa,SAAA,wBAAwB,CACtC,MAAe,EACf,MAA+B,EAAA;AAE/B,IAAA,IAAI;;AAEF,QAAA,MAAM,IAAI,GAAG,OAAO,MAAM,KAAK,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM;;QAGrE,MAAM,MAAM,GAAG,yBAAyB,CAAC,IAAI,EAAE,MAAM,CAAC;AAEtD,QAAA,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;YACrB,OAAO;AACL,gBAAA,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,sBAAsB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAA;AAChD,gBAAA,GAAG,EAAE,IAAI;aACV;;QAGH,OAAO;AACL,YAAA,OAAO,EAAE,IAAI;AACb,YAAA,IAAI,EAAE,IAA+B;SACtC;;IACD,OAAO,CAAC,EAAE;QACV,OAAO;AACL,YAAA,OAAO,EAAE,KAAK;AACd,YAAA,KAAK,EAAE,CAAA,wBAAA,EAA4B,CAAW,CAAC,OAAO,CAAE,CAAA;AACxD,YAAA,GAAG,EAAE,MAAM;SACZ;;AAEL;AAEA;;;AAGG;AACH,SAAS,yBAAyB,CAChC,IAAa,EACb,MAA+B,EAC/B,IAAI,GAAG,EAAE,EAAA;IAET,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE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AAEA;;AAEG;AACa,SAAA,mBAAmB,CACjC,MAA+B,EAC/B,MAAiC,EAAA;AAEjC,IAAA,MAAM,UAAU,GAAG,EAAE,GAAG,MAAM,EAAE;;IAGhC,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,UAAU,EAAE;AAC7C,QAAA,UAAU,CAAC,IAAI,GAAG,QAAQ;;;IAI5B,IAAI,MAAM,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE;AACrC,QAAA,UAAU,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI;;;IAIhC,IAAI,MAAM,EAAE,WAAW,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE;AAClD,QAAA,UAAU,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW;;;AAI7C,IAAA,IAAI,MAAM,EAAE,MAAM,KAAK,KAAK,IAAI,UAAU,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC5D,UAAU,CAAC,oBAAoB,GAAG,UAAU,CAAC,oBAAoB,IAAI,KAAK;;AAG5E,IAAA,OAAO,UAAU;AACnB;;;;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -254,7 +254,8 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
254
254
|
}
|
|
255
255
|
else if (content.every((c) => (c.type?.startsWith(_enum.ContentTypes.THINKING) ?? false) ||
|
|
256
256
|
(c.type?.startsWith(_enum.ContentTypes.REASONING) ?? false) ||
|
|
257
|
-
(c.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT) ?? false)
|
|
257
|
+
(c.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT) ?? false) ||
|
|
258
|
+
c.type === 'redacted_thinking')) {
|
|
258
259
|
await graph.dispatchReasoningDelta(stepId, {
|
|
259
260
|
content: content.map((c) => ({
|
|
260
261
|
type: _enum.ContentTypes.THINK,
|
|
@@ -271,7 +272,8 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
271
272
|
if (Array.isArray(chunk.content) &&
|
|
272
273
|
(chunk.content[0]?.type === _enum.ContentTypes.THINKING ||
|
|
273
274
|
chunk.content[0]?.type === _enum.ContentTypes.REASONING ||
|
|
274
|
-
chunk.content[0]?.type === _enum.ContentTypes.REASONING_CONTENT
|
|
275
|
+
chunk.content[0]?.type === _enum.ContentTypes.REASONING_CONTENT ||
|
|
276
|
+
chunk.content[0]?.type === 'redacted_thinking')) {
|
|
275
277
|
reasoning_content = 'valid';
|
|
276
278
|
}
|
|
277
279
|
else if ((agentContext.provider === _enum.Providers.OPENAI ||
|