@illuma-ai/agents 1.0.90 → 1.0.94
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 +98 -49
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/constants.cjs +25 -0
- package/dist/cjs/common/constants.cjs.map +1 -0
- package/dist/cjs/common/enum.cjs +30 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +9 -4
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +397 -92
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +223 -92
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs +30 -14
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +43 -11
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +10 -7
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +32 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +129 -101
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +489 -0
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +176 -0
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -0
- package/dist/cjs/llm/fake.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -1
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +59 -5
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +80 -2
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +60 -27
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +131 -108
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/content.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +3 -0
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +265 -47
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/ids.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +55 -2
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/messages/summarize.cjs +170 -0
- package/dist/cjs/messages/summarize.cjs.map +1 -0
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/run.cjs +87 -30
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/schemas/validate.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +59 -25
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/AskUser.cjs +131 -0
- package/dist/cjs/tools/AskUser.cjs.map +1 -0
- package/dist/cjs/tools/BrowserTools.cjs +11 -7
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
- package/dist/cjs/tools/Calculator.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +60 -5
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +36 -53
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/StreamingToolCallBuffer.cjs +208 -0
- package/dist/cjs/tools/StreamingToolCallBuffer.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +333 -30
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +66 -30
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +94 -8
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/tools/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/content.cjs.map +1 -1
- package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
- package/dist/cjs/tools/search/format.cjs.map +1 -1
- package/dist/cjs/tools/search/highlights.cjs.map +1 -1
- package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs +1 -0
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/search/utils.cjs.map +1 -1
- package/dist/cjs/types/graph.cjs +1 -1
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/cjs/utils/contextAnalytics.cjs +23 -6
- package/dist/cjs/utils/contextAnalytics.cjs.map +1 -1
- package/dist/cjs/utils/events.cjs.map +1 -1
- package/dist/cjs/utils/graph.cjs.map +1 -1
- package/dist/cjs/utils/handlers.cjs.map +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/misc.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs +3 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/schema.cjs.map +1 -1
- package/dist/cjs/utils/title.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +33 -58
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/cjs/utils/toolCallContinuation.cjs +55 -0
- package/dist/cjs/utils/toolCallContinuation.cjs.map +1 -0
- package/dist/cjs/utils/toonFormat.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +98 -49
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/constants.mjs +22 -0
- package/dist/esm/common/constants.mjs.map +1 -0
- package/dist/esm/common/enum.mjs +31 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +9 -4
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +393 -88
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +224 -93
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs +30 -14
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +43 -11
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +10 -7
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +32 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +128 -101
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +484 -0
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -0
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs +171 -0
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -0
- package/dist/esm/llm/fake.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -1
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +59 -5
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/text.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +80 -2
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +8 -3
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +131 -108
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/content.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +4 -1
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +267 -49
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/ids.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +56 -4
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/messages/summarize.mjs +161 -0
- package/dist/esm/messages/summarize.mjs.map +1 -0
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/run.mjs +88 -31
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/schemas/validate.mjs.map +1 -1
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +60 -26
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/AskUser.mjs +125 -0
- package/dist/esm/tools/AskUser.mjs.map +1 -0
- package/dist/esm/tools/BrowserTools.mjs +11 -7
- package/dist/esm/tools/BrowserTools.mjs.map +1 -1
- package/dist/esm/tools/Calculator.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +60 -5
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +37 -54
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/StreamingToolCallBuffer.mjs +206 -0
- package/dist/esm/tools/StreamingToolCallBuffer.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +333 -30
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +66 -30
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +95 -9
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/tools/schema.mjs.map +1 -1
- package/dist/esm/tools/search/content.mjs.map +1 -1
- package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
- package/dist/esm/tools/search/format.mjs.map +1 -1
- package/dist/esm/tools/search/highlights.mjs.map +1 -1
- package/dist/esm/tools/search/rerankers.mjs.map +1 -1
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs +1 -0
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/search/utils.mjs.map +1 -1
- package/dist/esm/types/graph.mjs +1 -1
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/esm/utils/contextAnalytics.mjs +23 -6
- package/dist/esm/utils/contextAnalytics.mjs.map +1 -1
- package/dist/esm/utils/events.mjs.map +1 -1
- package/dist/esm/utils/graph.mjs.map +1 -1
- package/dist/esm/utils/handlers.mjs.map +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/misc.mjs.map +1 -1
- package/dist/esm/utils/run.mjs +3 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/schema.mjs.map +1 -1
- package/dist/esm/utils/title.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +33 -59
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/esm/utils/toolCallContinuation.mjs +52 -0
- package/dist/esm/utils/toolCallContinuation.mjs.map +1 -0
- package/dist/esm/utils/toonFormat.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +14 -7
- package/dist/types/common/constants.d.ts +18 -0
- package/dist/types/common/enum.d.ts +28 -0
- package/dist/types/common/index.d.ts +1 -0
- package/dist/types/events.d.ts +10 -3
- package/dist/types/graphs/Graph.d.ts +37 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/llm/anthropic/index.d.ts +7 -1
- package/dist/types/llm/anthropic/types.d.ts +5 -2
- package/dist/types/llm/anthropic/utils/message_outputs.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +40 -33
- package/dist/types/llm/bedrock/utils/message_outputs.d.ts +1 -1
- package/dist/types/llm/google/index.d.ts +2 -3
- package/dist/types/llm/openrouter/index.d.ts +21 -1
- package/dist/types/llm/vertexai/index.d.ts +3 -2
- package/dist/types/messages/cache.d.ts +1 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/prune.d.ts +2 -7
- package/dist/types/messages/summarize.d.ts +33 -0
- package/dist/types/run.d.ts +6 -0
- package/dist/types/tools/AskUser.d.ts +408 -0
- package/dist/types/tools/BrowserTools.d.ts +2 -2
- package/dist/types/tools/CodeExecutor.d.ts +28 -4
- package/dist/types/tools/StreamingToolCallBuffer.d.ts +106 -0
- package/dist/types/tools/ToolNode.d.ts +55 -3
- package/dist/types/tools/ToolSearch.d.ts +9 -5
- package/dist/types/tools/handlers.d.ts +2 -2
- package/dist/types/types/graph.d.ts +9 -2
- package/dist/types/types/llm.d.ts +8 -3
- package/dist/types/types/run.d.ts +2 -0
- package/dist/types/types/tools.d.ts +20 -2
- package/dist/types/utils/contextAnalytics.d.ts +5 -4
- package/dist/types/utils/index.d.ts +1 -0
- package/dist/types/utils/tokens.d.ts +6 -19
- package/dist/types/utils/toolCallContinuation.d.ts +30 -0
- package/package.json +15 -8
- package/src/agents/AgentContext.js +782 -0
- package/src/agents/AgentContext.js.map +1 -0
- package/src/agents/AgentContext.test.js +421 -0
- package/src/agents/AgentContext.test.js.map +1 -0
- package/src/agents/AgentContext.ts +132 -64
- package/src/agents/__tests__/AgentContext.test.js +678 -0
- package/src/agents/__tests__/AgentContext.test.js.map +1 -0
- package/src/agents/__tests__/AgentContext.test.ts +25 -4
- package/src/agents/__tests__/resolveStructuredOutputMode.test.js +117 -0
- package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +1 -0
- package/src/common/__tests__/enum.test.ts +135 -0
- package/src/common/constants.ts +21 -0
- package/src/common/enum.js +192 -0
- package/src/common/enum.js.map +1 -0
- package/src/common/enum.ts +30 -0
- package/src/common/index.js +3 -0
- package/src/common/index.js.map +1 -0
- package/src/common/index.ts +2 -1
- package/src/events.js +166 -0
- package/src/events.js.map +1 -0
- package/src/events.ts +11 -14
- package/src/graphs/Graph.js +1857 -0
- package/src/graphs/Graph.js.map +1 -0
- package/src/graphs/Graph.ts +580 -162
- package/src/graphs/MultiAgentGraph.js +1092 -0
- package/src/graphs/MultiAgentGraph.js.map +1 -0
- package/src/graphs/MultiAgentGraph.ts +331 -112
- package/src/graphs/__tests__/adaptive-thinking.test.ts +369 -0
- package/src/graphs/__tests__/graph-direct-tool-names.test.ts +210 -0
- package/src/graphs/__tests__/multi-agent-edges.test.ts +237 -0
- package/src/graphs/__tests__/structured-output.integration.test.js +624 -0
- package/src/graphs/__tests__/structured-output.integration.test.js.map +1 -0
- package/src/graphs/__tests__/structured-output.test.js +144 -0
- package/src/graphs/__tests__/structured-output.test.js.map +1 -0
- package/src/graphs/contextManagement.e2e.test.js +718 -0
- package/src/graphs/contextManagement.e2e.test.js.map +1 -0
- package/src/graphs/contextManagement.e2e.test.ts +990 -0
- package/src/graphs/contextManagement.test.js +485 -0
- package/src/graphs/contextManagement.test.js.map +1 -0
- package/src/graphs/contextManagement.test.ts +625 -0
- package/src/graphs/handoffValidation.test.js +276 -0
- package/src/graphs/handoffValidation.test.js.map +1 -0
- package/src/graphs/handoffValidation.test.ts +353 -0
- package/src/graphs/index.js +3 -0
- package/src/graphs/index.js.map +1 -0
- package/src/index.js +28 -0
- package/src/index.js.map +1 -0
- package/src/index.ts +13 -0
- package/src/instrumentation.js +21 -0
- package/src/instrumentation.js.map +1 -0
- package/src/instrumentation.ts +38 -17
- package/src/llm/anthropic/index.js +319 -0
- package/src/llm/anthropic/index.js.map +1 -0
- package/src/llm/anthropic/index.ts +68 -15
- package/src/llm/anthropic/llm.spec.ts +402 -0
- package/src/llm/anthropic/types.js +46 -0
- package/src/llm/anthropic/types.js.map +1 -0
- package/src/llm/anthropic/types.ts +8 -2
- package/src/llm/anthropic/utils/message_inputs.js +627 -0
- package/src/llm/anthropic/utils/message_inputs.js.map +1 -0
- package/src/llm/anthropic/utils/message_inputs.ts +16 -33
- package/src/llm/anthropic/utils/message_outputs.js +290 -0
- package/src/llm/anthropic/utils/message_outputs.js.map +1 -0
- package/src/llm/anthropic/utils/message_outputs.ts +40 -1
- package/src/llm/anthropic/utils/output_parsers.js +89 -0
- package/src/llm/anthropic/utils/output_parsers.js.map +1 -0
- package/src/llm/anthropic/utils/tools.js +25 -0
- package/src/llm/anthropic/utils/tools.js.map +1 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.js +392 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +1 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +24 -40
- package/src/llm/bedrock/index.js +303 -0
- package/src/llm/bedrock/index.js.map +1 -0
- package/src/llm/bedrock/index.ts +171 -134
- package/src/llm/bedrock/llm.spec.ts +395 -52
- package/src/llm/bedrock/types.js +2 -0
- package/src/llm/bedrock/types.js.map +1 -0
- package/src/llm/bedrock/utils/index.js +6 -0
- package/src/llm/bedrock/utils/index.js.map +1 -0
- package/src/llm/bedrock/utils/message_inputs.js +463 -0
- package/src/llm/bedrock/utils/message_inputs.js.map +1 -0
- package/src/llm/bedrock/utils/message_inputs.ts +30 -5
- package/src/llm/bedrock/utils/message_outputs.js +269 -0
- package/src/llm/bedrock/utils/message_outputs.js.map +1 -0
- package/src/llm/bedrock/utils/message_outputs.ts +70 -22
- package/src/llm/fake.js +92 -0
- package/src/llm/fake.js.map +1 -0
- package/src/llm/google/index.js +215 -0
- package/src/llm/google/index.js.map +1 -0
- package/src/llm/google/index.ts +2 -3
- package/src/llm/google/types.js +12 -0
- package/src/llm/google/types.js.map +1 -0
- package/src/llm/google/utils/common.js +670 -0
- package/src/llm/google/utils/common.js.map +1 -0
- package/src/llm/google/utils/tools.js +111 -0
- package/src/llm/google/utils/tools.js.map +1 -0
- package/src/llm/google/utils/zod_to_genai_parameters.js +47 -0
- package/src/llm/google/utils/zod_to_genai_parameters.js.map +1 -0
- package/src/llm/openai/index.js +1033 -0
- package/src/llm/openai/index.js.map +1 -0
- package/src/llm/openai/types.js +2 -0
- package/src/llm/openai/types.js.map +1 -0
- package/src/llm/openai/utils/index.js +756 -0
- package/src/llm/openai/utils/index.js.map +1 -0
- package/src/llm/openai/utils/isReasoningModel.test.js +79 -0
- package/src/llm/openai/utils/isReasoningModel.test.js.map +1 -0
- package/src/llm/openrouter/index.js +261 -0
- package/src/llm/openrouter/index.js.map +1 -0
- package/src/llm/openrouter/index.ts +117 -6
- package/src/llm/openrouter/reasoning.test.js +181 -0
- package/src/llm/openrouter/reasoning.test.js.map +1 -0
- package/src/llm/openrouter/reasoning.test.ts +207 -0
- package/src/llm/providers.js +36 -0
- package/src/llm/providers.js.map +1 -0
- package/src/llm/text.js +65 -0
- package/src/llm/text.js.map +1 -0
- package/src/llm/vertexai/index.js +402 -0
- package/src/llm/vertexai/index.js.map +1 -0
- package/src/llm/vertexai/index.ts +115 -5
- package/src/llm/vertexai/llm.spec.ts +114 -0
- package/src/messages/__tests__/tools.test.js +392 -0
- package/src/messages/__tests__/tools.test.js.map +1 -0
- package/src/messages/cache.js +404 -0
- package/src/messages/cache.js.map +1 -0
- package/src/messages/cache.test.js +1167 -0
- package/src/messages/cache.test.js.map +1 -0
- package/src/messages/cache.test.ts +178 -16
- package/src/messages/cache.ts +152 -147
- package/src/messages/content.js +48 -0
- package/src/messages/content.js.map +1 -0
- package/src/messages/content.test.js +314 -0
- package/src/messages/content.test.js.map +1 -0
- package/src/messages/core.js +359 -0
- package/src/messages/core.js.map +1 -0
- package/src/messages/core.ts +5 -0
- package/src/messages/ensureThinkingBlock.test.js +997 -0
- package/src/messages/ensureThinkingBlock.test.js.map +1 -0
- package/src/messages/ensureThinkingBlock.test.ts +751 -10
- package/src/messages/format.js +973 -0
- package/src/messages/format.js.map +1 -0
- package/src/messages/format.ts +334 -57
- package/src/messages/formatAgentMessages.test.js +2278 -0
- package/src/messages/formatAgentMessages.test.js.map +1 -0
- package/src/messages/formatAgentMessages.test.ts +1175 -1
- package/src/messages/formatAgentMessages.tools.test.js +362 -0
- package/src/messages/formatAgentMessages.tools.test.js.map +1 -0
- package/src/messages/formatMessage.test.js +608 -0
- package/src/messages/formatMessage.test.js.map +1 -0
- package/src/messages/ids.js +18 -0
- package/src/messages/ids.js.map +1 -0
- package/src/messages/index.js +9 -0
- package/src/messages/index.js.map +1 -0
- package/src/messages/index.ts +1 -0
- package/src/messages/labelContentByAgent.test.js +725 -0
- package/src/messages/labelContentByAgent.test.js.map +1 -0
- package/src/messages/prune.js +438 -0
- package/src/messages/prune.js.map +1 -0
- package/src/messages/prune.ts +87 -25
- package/src/messages/reducer.js +60 -0
- package/src/messages/reducer.js.map +1 -0
- package/src/messages/shiftIndexTokenCountMap.test.js +63 -0
- package/src/messages/shiftIndexTokenCountMap.test.js.map +1 -0
- package/src/messages/summarize.js +146 -0
- package/src/messages/summarize.js.map +1 -0
- package/src/messages/summarize.test.js +332 -0
- package/src/messages/summarize.test.js.map +1 -0
- package/src/messages/summarize.test.ts +466 -0
- package/src/messages/summarize.ts +222 -0
- package/src/messages/tools.js +90 -0
- package/src/messages/tools.js.map +1 -0
- package/src/mockStream.js +81 -0
- package/src/mockStream.js.map +1 -0
- package/src/prompts/collab.js +7 -0
- package/src/prompts/collab.js.map +1 -0
- package/src/prompts/index.js +3 -0
- package/src/prompts/index.js.map +1 -0
- package/src/prompts/taskmanager.js +58 -0
- package/src/prompts/taskmanager.js.map +1 -0
- package/src/run.js +427 -0
- package/src/run.js.map +1 -0
- package/src/run.ts +101 -33
- package/src/schemas/index.js +3 -0
- package/src/schemas/index.js.map +1 -0
- package/src/schemas/schema-preparation.test.js +370 -0
- package/src/schemas/schema-preparation.test.js.map +1 -0
- package/src/schemas/validate.js +314 -0
- package/src/schemas/validate.js.map +1 -0
- package/src/schemas/validate.test.js +264 -0
- package/src/schemas/validate.test.js.map +1 -0
- package/src/scripts/abort.js +127 -0
- package/src/scripts/abort.js.map +1 -0
- package/src/scripts/ant_web_search.js +130 -0
- package/src/scripts/ant_web_search.js.map +1 -0
- package/src/scripts/ant_web_search.ts +1 -0
- package/src/scripts/ant_web_search_edge_case.js +133 -0
- package/src/scripts/ant_web_search_edge_case.js.map +1 -0
- package/src/scripts/ant_web_search_edge_case.ts +1 -0
- package/src/scripts/ant_web_search_error_edge_case.js +119 -0
- package/src/scripts/ant_web_search_error_edge_case.js.map +1 -0
- package/src/scripts/ant_web_search_error_edge_case.ts +1 -0
- package/src/scripts/args.js +41 -0
- package/src/scripts/args.js.map +1 -0
- package/src/scripts/bedrock-cache-debug.js +186 -0
- package/src/scripts/bedrock-cache-debug.js.map +1 -0
- package/src/scripts/bedrock-cache-debug.ts +250 -0
- package/src/scripts/bedrock-content-aggregation-test.js +195 -0
- package/src/scripts/bedrock-content-aggregation-test.js.map +1 -0
- package/src/scripts/bedrock-content-aggregation-test.ts +266 -0
- package/src/scripts/bedrock-merge-test.js +80 -0
- package/src/scripts/bedrock-merge-test.js.map +1 -0
- package/src/scripts/bedrock-merge-test.ts +107 -0
- package/src/scripts/bedrock-parallel-tools-test.js +150 -0
- package/src/scripts/bedrock-parallel-tools-test.js.map +1 -0
- package/src/scripts/bedrock-parallel-tools-test.ts +204 -0
- package/src/scripts/caching.js +106 -0
- package/src/scripts/caching.js.map +1 -0
- package/src/scripts/caching.ts +1 -0
- package/src/scripts/cli.js +152 -0
- package/src/scripts/cli.js.map +1 -0
- package/src/scripts/cli2.js +119 -0
- package/src/scripts/cli2.js.map +1 -0
- package/src/scripts/cli3.js +163 -0
- package/src/scripts/cli3.js.map +1 -0
- package/src/scripts/cli4.js +165 -0
- package/src/scripts/cli4.js.map +1 -0
- package/src/scripts/cli5.js +165 -0
- package/src/scripts/cli5.js.map +1 -0
- package/src/scripts/code_exec.js +171 -0
- package/src/scripts/code_exec.js.map +1 -0
- package/src/scripts/code_exec.ts +1 -0
- package/src/scripts/code_exec_files.js +180 -0
- package/src/scripts/code_exec_files.js.map +1 -0
- package/src/scripts/code_exec_files.ts +1 -0
- package/src/scripts/code_exec_multi_session.js +185 -0
- package/src/scripts/code_exec_multi_session.js.map +1 -0
- package/src/scripts/code_exec_multi_session.ts +9 -13
- package/src/scripts/code_exec_ptc.js +265 -0
- package/src/scripts/code_exec_ptc.js.map +1 -0
- package/src/scripts/code_exec_ptc.ts +1 -0
- package/src/scripts/code_exec_session.js +217 -0
- package/src/scripts/code_exec_session.js.map +1 -0
- package/src/scripts/code_exec_session.ts +1 -0
- package/src/scripts/code_exec_simple.js +120 -0
- package/src/scripts/code_exec_simple.js.map +1 -0
- package/src/scripts/code_exec_simple.ts +1 -0
- package/src/scripts/content.js +111 -0
- package/src/scripts/content.js.map +1 -0
- package/src/scripts/content.ts +1 -0
- package/src/scripts/empty_input.js +125 -0
- package/src/scripts/empty_input.js.map +1 -0
- package/src/scripts/handoff-test.js +96 -0
- package/src/scripts/handoff-test.js.map +1 -0
- package/src/scripts/image.js +138 -0
- package/src/scripts/image.js.map +1 -0
- package/src/scripts/image.ts +3 -1
- package/src/scripts/memory.js +83 -0
- package/src/scripts/memory.js.map +1 -0
- package/src/scripts/memory.ts +16 -6
- package/src/scripts/multi-agent-chain.js +271 -0
- package/src/scripts/multi-agent-chain.js.map +1 -0
- package/src/scripts/multi-agent-chain.ts +1 -0
- package/src/scripts/multi-agent-conditional.js +185 -0
- package/src/scripts/multi-agent-conditional.js.map +1 -0
- package/src/scripts/multi-agent-conditional.ts +1 -0
- package/src/scripts/multi-agent-document-review-chain.js +171 -0
- package/src/scripts/multi-agent-document-review-chain.js.map +1 -0
- package/src/scripts/multi-agent-document-review-chain.ts +1 -0
- package/src/scripts/multi-agent-hybrid-flow.js +264 -0
- package/src/scripts/multi-agent-hybrid-flow.js.map +1 -0
- package/src/scripts/multi-agent-hybrid-flow.ts +1 -0
- package/src/scripts/multi-agent-parallel-start.js +214 -0
- package/src/scripts/multi-agent-parallel-start.js.map +1 -0
- package/src/scripts/multi-agent-parallel-start.ts +4 -4
- package/src/scripts/multi-agent-parallel.js +346 -0
- package/src/scripts/multi-agent-parallel.js.map +1 -0
- package/src/scripts/multi-agent-parallel.ts +1 -0
- package/src/scripts/multi-agent-sequence.js +184 -0
- package/src/scripts/multi-agent-sequence.js.map +1 -0
- package/src/scripts/multi-agent-sequence.ts +4 -4
- package/src/scripts/multi-agent-supervisor.js +324 -0
- package/src/scripts/multi-agent-supervisor.js.map +1 -0
- package/src/scripts/multi-agent-supervisor.ts +1 -0
- package/src/scripts/multi-agent-test.js +147 -0
- package/src/scripts/multi-agent-test.js.map +1 -0
- package/src/scripts/multi-agent-test.ts +1 -0
- package/src/scripts/parallel-asymmetric-tools-test.js +202 -0
- package/src/scripts/parallel-asymmetric-tools-test.js.map +1 -0
- package/src/scripts/parallel-asymmetric-tools-test.ts +1 -0
- package/src/scripts/parallel-full-metadata-test.js +176 -0
- package/src/scripts/parallel-full-metadata-test.js.map +1 -0
- package/src/scripts/parallel-full-metadata-test.ts +1 -0
- package/src/scripts/parallel-tools-test.js +256 -0
- package/src/scripts/parallel-tools-test.js.map +1 -0
- package/src/scripts/parallel-tools-test.ts +1 -0
- package/src/scripts/poc-multi-agent-comprehensive.ts +1222 -0
- package/src/scripts/programmatic_exec.js +277 -0
- package/src/scripts/programmatic_exec.js.map +1 -0
- package/src/scripts/programmatic_exec_agent.js +168 -0
- package/src/scripts/programmatic_exec_agent.js.map +1 -0
- package/src/scripts/programmatic_exec_agent.ts +1 -0
- package/src/scripts/search.js +118 -0
- package/src/scripts/search.js.map +1 -0
- package/src/scripts/search.ts +1 -0
- package/src/scripts/sequential-full-metadata-test.js +143 -0
- package/src/scripts/sequential-full-metadata-test.js.map +1 -0
- package/src/scripts/sequential-full-metadata-test.ts +1 -0
- package/src/scripts/simple.js +174 -0
- package/src/scripts/simple.js.map +1 -0
- package/src/scripts/simple.ts +2 -1
- package/src/scripts/single-agent-metadata-test.js +152 -0
- package/src/scripts/single-agent-metadata-test.js.map +1 -0
- package/src/scripts/single-agent-metadata-test.ts +4 -6
- package/src/scripts/stream.js +113 -0
- package/src/scripts/stream.js.map +1 -0
- package/src/scripts/stream.ts +1 -0
- package/src/scripts/test-custom-prompt-key.js +132 -0
- package/src/scripts/test-custom-prompt-key.js.map +1 -0
- package/src/scripts/test-handoff-input.js +143 -0
- package/src/scripts/test-handoff-input.js.map +1 -0
- package/src/scripts/test-handoff-preamble.js +227 -0
- package/src/scripts/test-handoff-preamble.js.map +1 -0
- package/src/scripts/test-handoff-preamble.ts +1 -0
- package/src/scripts/test-handoff-steering.js +353 -0
- package/src/scripts/test-handoff-steering.js.map +1 -0
- package/src/scripts/test-handoff-steering.ts +430 -0
- package/src/scripts/test-multi-agent-list-handoff.js +318 -0
- package/src/scripts/test-multi-agent-list-handoff.js.map +1 -0
- package/src/scripts/test-multi-agent-list-handoff.ts +1 -0
- package/src/scripts/test-parallel-agent-labeling.js +253 -0
- package/src/scripts/test-parallel-agent-labeling.js.map +1 -0
- package/src/scripts/test-parallel-agent-labeling.ts +2 -0
- package/src/scripts/test-parallel-handoffs.js +229 -0
- package/src/scripts/test-parallel-handoffs.js.map +1 -0
- package/src/scripts/test-parallel-handoffs.ts +1 -0
- package/src/scripts/test-thinking-handoff-bedrock.js +132 -0
- package/src/scripts/test-thinking-handoff-bedrock.js.map +1 -0
- package/src/scripts/test-thinking-handoff-bedrock.ts +1 -0
- package/src/scripts/test-thinking-handoff.js +132 -0
- package/src/scripts/test-thinking-handoff.js.map +1 -0
- package/src/scripts/test-thinking-handoff.ts +1 -0
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +140 -0
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +1 -0
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +166 -0
- package/src/scripts/test-tool-before-handoff-role-order.js +223 -0
- package/src/scripts/test-tool-before-handoff-role-order.js.map +1 -0
- package/src/scripts/test-tool-before-handoff-role-order.ts +276 -0
- package/src/scripts/test-tools-before-handoff.js +187 -0
- package/src/scripts/test-tools-before-handoff.js.map +1 -0
- package/src/scripts/test-tools-before-handoff.ts +4 -8
- package/src/scripts/test_code_api.js +263 -0
- package/src/scripts/test_code_api.js.map +1 -0
- package/src/scripts/thinking-bedrock.js +128 -0
- package/src/scripts/thinking-bedrock.js.map +1 -0
- package/src/scripts/thinking-bedrock.ts +1 -0
- package/src/scripts/thinking-vertexai.js +130 -0
- package/src/scripts/thinking-vertexai.js.map +1 -0
- package/src/scripts/thinking-vertexai.ts +168 -0
- package/src/scripts/thinking.js +134 -0
- package/src/scripts/thinking.js.map +1 -0
- package/src/scripts/thinking.ts +1 -0
- package/src/scripts/tool_search.js +114 -0
- package/src/scripts/tool_search.js.map +1 -0
- package/src/scripts/tools.js +125 -0
- package/src/scripts/tools.js.map +1 -0
- package/src/scripts/tools.ts +5 -19
- package/src/specs/agent-handoffs-bedrock.integration.test.js +280 -0
- package/src/specs/agent-handoffs-bedrock.integration.test.js.map +1 -0
- package/src/specs/agent-handoffs-bedrock.integration.test.ts +412 -375
- package/src/specs/agent-handoffs.test.js +924 -0
- package/src/specs/agent-handoffs.test.js.map +1 -0
- package/src/specs/agent-handoffs.test.ts +152 -39
- package/src/specs/anthropic.simple.test.js +287 -0
- package/src/specs/anthropic.simple.test.js.map +1 -0
- package/src/specs/anthropic.simple.test.ts +7 -4
- package/src/specs/azure.simple.test.js +381 -0
- package/src/specs/azure.simple.test.js.map +1 -0
- package/src/specs/azure.simple.test.ts +143 -5
- package/src/specs/cache.simple.test.js +282 -0
- package/src/specs/cache.simple.test.js.map +1 -0
- package/src/specs/cache.simple.test.ts +9 -2
- package/src/specs/custom-event-await.test.js +148 -0
- package/src/specs/custom-event-await.test.js.map +1 -0
- package/src/specs/custom-event-await.test.ts +215 -0
- package/src/specs/deepseek.simple.test.js +189 -0
- package/src/specs/deepseek.simple.test.js.map +1 -0
- package/src/specs/deepseek.simple.test.ts +4 -2
- package/src/specs/emergency-prune.test.js +308 -0
- package/src/specs/emergency-prune.test.js.map +1 -0
- package/src/specs/moonshot.simple.test.js +237 -0
- package/src/specs/moonshot.simple.test.js.map +1 -0
- package/src/specs/moonshot.simple.test.ts +6 -2
- package/src/specs/observability.integration.test.js +1337 -0
- package/src/specs/observability.integration.test.js.map +1 -0
- package/src/specs/observability.integration.test.ts +2223 -0
- package/src/specs/openai.simple.test.js +233 -0
- package/src/specs/openai.simple.test.js.map +1 -0
- package/src/specs/openai.simple.test.ts +4 -2
- package/src/specs/openrouter.simple.test.js +202 -0
- package/src/specs/openrouter.simple.test.js.map +1 -0
- package/src/specs/openrouter.simple.test.ts +165 -4
- package/src/specs/prune.test.js +733 -0
- package/src/specs/prune.test.js.map +1 -0
- package/src/specs/prune.test.ts +1 -0
- package/src/specs/reasoning.test.js +144 -0
- package/src/specs/reasoning.test.js.map +1 -0
- package/src/specs/reasoning.test.ts +2 -2
- package/src/specs/spec.utils.js +4 -0
- package/src/specs/spec.utils.js.map +1 -0
- package/src/specs/thinking-handoff.test.js +486 -0
- package/src/specs/thinking-handoff.test.js.map +1 -0
- package/src/specs/thinking-handoff.test.ts +3 -2
- package/src/specs/thinking-prune.test.js +600 -0
- package/src/specs/thinking-prune.test.js.map +1 -0
- package/src/specs/token-distribution-edge-case.test.js +246 -0
- package/src/specs/token-distribution-edge-case.test.js.map +1 -0
- package/src/specs/token-memoization.test.js +32 -0
- package/src/specs/token-memoization.test.js.map +1 -0
- package/src/specs/token-memoization.test.ts +14 -5
- package/src/specs/tokens.test.js +49 -0
- package/src/specs/tokens.test.js.map +1 -0
- package/src/specs/tokens.test.ts +64 -0
- package/src/specs/tool-error.test.js +139 -0
- package/src/specs/tool-error.test.js.map +1 -0
- package/src/specs/tool-error.test.ts +2 -2
- package/src/splitStream.js +204 -0
- package/src/splitStream.js.map +1 -0
- package/src/splitStream.test.js +504 -0
- package/src/splitStream.test.js.map +1 -0
- package/src/stream.js +650 -0
- package/src/stream.js.map +1 -0
- package/src/stream.test.js +225 -0
- package/src/stream.test.js.map +1 -0
- package/src/stream.test.ts +25 -15
- package/src/stream.ts +82 -32
- package/src/test/mockTools.js +340 -0
- package/src/test/mockTools.js.map +1 -0
- package/src/tools/AskUser.ts +159 -0
- package/src/tools/BrowserTools.js +245 -0
- package/src/tools/BrowserTools.js.map +1 -0
- package/src/tools/BrowserTools.ts +12 -8
- package/src/tools/Calculator.js +38 -0
- package/src/tools/Calculator.js.map +1 -0
- package/src/tools/Calculator.test.js +225 -0
- package/src/tools/Calculator.test.js.map +1 -0
- package/src/tools/CodeExecutor.js +233 -0
- package/src/tools/CodeExecutor.js.map +1 -0
- package/src/tools/CodeExecutor.selfhealing.test.ts +435 -0
- package/src/tools/CodeExecutor.ts +82 -5
- package/src/tools/ProgrammaticToolCalling.js +602 -0
- package/src/tools/ProgrammaticToolCalling.js.map +1 -0
- package/src/tools/ProgrammaticToolCalling.ts +40 -52
- package/src/tools/StreamingToolCallBuffer.js +179 -0
- package/src/tools/StreamingToolCallBuffer.js.map +1 -0
- package/src/tools/StreamingToolCallBuffer.ts +218 -0
- package/src/tools/ToolNode.js +930 -0
- package/src/tools/ToolNode.js.map +1 -0
- package/src/tools/ToolNode.ts +454 -41
- package/src/tools/ToolSearch.js +904 -0
- package/src/tools/ToolSearch.js.map +1 -0
- package/src/tools/ToolSearch.ts +84 -33
- package/src/tools/__tests__/AskUser.test.ts +537 -0
- package/src/tools/__tests__/BrowserTools.test.js +306 -0
- package/src/tools/__tests__/BrowserTools.test.js.map +1 -0
- package/src/tools/__tests__/BrowserTools.test.ts +131 -6
- package/src/tools/__tests__/CodeExecutor.test.ts +76 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +276 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +1 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.js +807 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +1 -0
- package/src/tools/__tests__/StreamingToolCallBuffer.test.js +175 -0
- package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +1 -0
- package/src/tools/__tests__/StreamingToolCallBuffer.test.ts +263 -0
- package/src/tools/__tests__/ToolApproval.test.js +675 -0
- package/src/tools/__tests__/ToolApproval.test.js.map +1 -0
- package/src/tools/__tests__/ToolApproval.test.ts +194 -20
- package/src/tools/__tests__/ToolNode.hitl.test.ts +267 -0
- package/src/tools/__tests__/ToolNode.recovery.test.js +200 -0
- package/src/tools/__tests__/ToolNode.recovery.test.js.map +1 -0
- package/src/tools/__tests__/ToolNode.recovery.test.ts +276 -0
- package/src/tools/__tests__/ToolNode.session.test.js +319 -0
- package/src/tools/__tests__/ToolNode.session.test.js.map +1 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +465 -0
- package/src/tools/__tests__/ToolSearch.integration.test.js +125 -0
- package/src/tools/__tests__/ToolSearch.integration.test.js.map +1 -0
- package/src/tools/__tests__/ToolSearch.test.js +812 -0
- package/src/tools/__tests__/ToolSearch.test.js.map +1 -0
- package/src/tools/__tests__/ToolSearch.test.ts +78 -5
- package/src/tools/__tests__/handlers.test.js +799 -0
- package/src/tools/__tests__/handlers.test.js.map +1 -0
- package/src/tools/__tests__/handlers.test.ts +1100 -0
- package/src/tools/__tests__/truncation-recovery.integration.test.js +362 -0
- package/src/tools/__tests__/truncation-recovery.integration.test.js.map +1 -0
- package/src/tools/__tests__/truncation-recovery.integration.test.ts +560 -0
- package/src/tools/handlers.js +306 -0
- package/src/tools/handlers.js.map +1 -0
- package/src/tools/handlers.ts +119 -16
- package/src/tools/schema.js +25 -0
- package/src/tools/schema.js.map +1 -0
- package/src/tools/search/anthropic.js +34 -0
- package/src/tools/search/anthropic.js.map +1 -0
- package/src/tools/search/content.js +116 -0
- package/src/tools/search/content.js.map +1 -0
- package/src/tools/search/content.test.js +133 -0
- package/src/tools/search/content.test.js.map +1 -0
- package/src/tools/search/firecrawl.js +173 -0
- package/src/tools/search/firecrawl.js.map +1 -0
- package/src/tools/search/format.js +198 -0
- package/src/tools/search/format.js.map +1 -0
- package/src/tools/search/highlights.js +241 -0
- package/src/tools/search/highlights.js.map +1 -0
- package/src/tools/search/index.js +3 -0
- package/src/tools/search/index.js.map +1 -0
- package/src/tools/search/jina-reranker.test.js +106 -0
- package/src/tools/search/jina-reranker.test.js.map +1 -0
- package/src/tools/search/rerankers.js +165 -0
- package/src/tools/search/rerankers.js.map +1 -0
- package/src/tools/search/schema.js +102 -0
- package/src/tools/search/schema.js.map +1 -0
- package/src/tools/search/search.js +561 -0
- package/src/tools/search/search.js.map +1 -0
- package/src/tools/search/serper-scraper.js +126 -0
- package/src/tools/search/serper-scraper.js.map +1 -0
- package/src/tools/search/test.js +129 -0
- package/src/tools/search/test.js.map +1 -0
- package/src/tools/search/tool.js +453 -0
- package/src/tools/search/tool.js.map +1 -0
- package/src/tools/search/types.js +2 -0
- package/src/tools/search/types.js.map +1 -0
- package/src/tools/search/utils.js +59 -0
- package/src/tools/search/utils.js.map +1 -0
- package/src/types/graph.js +24 -0
- package/src/types/graph.js.map +1 -0
- package/src/types/graph.test.js +192 -0
- package/src/types/graph.test.js.map +1 -0
- package/src/types/graph.ts +26 -6
- package/src/types/index.js +7 -0
- package/src/types/index.js.map +1 -0
- package/src/types/llm.js +2 -0
- package/src/types/llm.js.map +1 -0
- package/src/types/llm.ts +8 -3
- package/src/types/messages.js +2 -0
- package/src/types/messages.js.map +1 -0
- package/src/types/run.js +2 -0
- package/src/types/run.js.map +1 -0
- package/src/types/run.ts +2 -0
- package/src/types/stream.js +2 -0
- package/src/types/stream.js.map +1 -0
- package/src/types/tools.js +2 -0
- package/src/types/tools.js.map +1 -0
- package/src/types/tools.ts +21 -2
- package/src/utils/contextAnalytics.js +79 -0
- package/src/utils/contextAnalytics.js.map +1 -0
- package/src/utils/contextAnalytics.test.js +166 -0
- package/src/utils/contextAnalytics.test.js.map +1 -0
- package/src/utils/contextAnalytics.test.ts +222 -0
- package/src/utils/contextAnalytics.ts +27 -9
- package/src/utils/events.js +26 -0
- package/src/utils/events.js.map +1 -0
- package/src/utils/graph.js +11 -0
- package/src/utils/graph.js.map +1 -0
- package/src/utils/handlers.js +65 -0
- package/src/utils/handlers.js.map +1 -0
- package/src/utils/index.js +10 -0
- package/src/utils/index.js.map +1 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/llm.js +21 -0
- package/src/utils/llm.js.map +1 -0
- package/src/utils/llmConfig.js +205 -0
- package/src/utils/llmConfig.js.map +1 -0
- package/src/utils/llmConfig.ts +5 -5
- package/src/utils/logging.js +37 -0
- package/src/utils/logging.js.map +1 -0
- package/src/utils/misc.js +51 -0
- package/src/utils/misc.js.map +1 -0
- package/src/utils/run.js +69 -0
- package/src/utils/run.js.map +1 -0
- package/src/utils/run.ts +108 -106
- package/src/utils/schema.js +21 -0
- package/src/utils/schema.js.map +1 -0
- package/src/utils/title.js +119 -0
- package/src/utils/title.js.map +1 -0
- package/src/utils/tokens.js +92 -0
- package/src/utils/tokens.js.map +1 -0
- package/src/utils/tokens.ts +118 -142
- package/src/utils/toolCallContinuation.ts +55 -0
- package/src/utils/toonFormat.js +379 -0
- package/src/utils/toonFormat.js.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.mjs","sources":["../../../src/schemas/validate.ts"],"sourcesContent":["// src/schemas/validate.ts\nimport { z } from 'zod';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\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\n/**\n * Keywords unsupported by native structured output providers.\n * These are stripped from schemas and moved to description fields when strict mode is enabled.\n */\nconst UNSUPPORTED_NUMERIC_KEYWORDS = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'] as const;\nconst UNSUPPORTED_STRING_KEYWORDS = ['minLength', 'maxLength', 'pattern', 'format'] as const;\nconst UNSUPPORTED_ARRAY_KEYWORDS = ['minItems', 'maxItems', 'uniqueItems'] as const;\nconst UNSUPPORTED_OBJECT_KEYWORDS = ['minProperties', 'maxProperties', 'patternProperties'] as const;\n\n/**\n * Result from schema preparation, includes the prepared schema and any warnings.\n */\nexport interface SchemaPreparationResult {\n schema: Record<string, unknown>;\n warnings: string[];\n}\n\n/**\n * Prepares a JSON Schema for a specific provider's native structured output API.\n *\n * This function normalizes the schema to comply with provider-specific requirements:\n * - Adds `additionalProperties: false` recursively to all objects (required by all providers in strict mode)\n * - Ensures all properties are listed in `required` (required by OpenAI and Anthropic)\n * - Strips unsupported constraint keywords (minimum, maxLength, etc.) and moves them to description\n * - Returns warnings for any modifications made\n *\n * @param schema - The original JSON Schema\n * @param provider - The LLM provider\n * @param strict - Whether strict mode is enabled (default: true)\n * @returns The prepared schema and any warnings\n */\nexport function prepareSchemaForProvider(\n schema: Record<string, unknown>,\n provider: Providers | string,\n strict = true,\n): SchemaPreparationResult {\n const warnings: string[] = [];\n\n if (!strict) {\n return { schema: { ...schema }, warnings };\n }\n\n const prepared = prepareObjectRecursive(schema, '', provider, warnings);\n return { schema: prepared, warnings };\n}\n\n/**\n * Recursively prepares a schema node for native structured output.\n */\nfunction prepareObjectRecursive(\n schema: Record<string, unknown>,\n path: string,\n provider: Providers | string,\n warnings: string[],\n depth = 0,\n): Record<string, unknown> {\n const result = { ...schema };\n const currentPath = path || 'root';\n\n // Warn on deep nesting (OpenAI limit is 5)\n if (depth > 5 && (provider === Providers.OPENAI || provider === Providers.AZURE)) {\n warnings.push(`${currentPath}: nesting depth ${depth} exceeds OpenAI's limit of 5 levels`);\n }\n\n // Handle object type\n if (result.type === 'object' || (result.properties && !result.type)) {\n if (!result.type) {\n result.type = 'object';\n }\n\n // Add additionalProperties: false\n if (result.additionalProperties !== false) {\n result.additionalProperties = false;\n if (path) {\n warnings.push(`${currentPath}: set additionalProperties to false for strict mode`);\n }\n }\n\n // Ensure all properties are in required\n if (result.properties && typeof result.properties === 'object') {\n const properties = result.properties as Record<string, Record<string, unknown>>;\n const propertyNames = Object.keys(properties);\n const currentRequired = Array.isArray(result.required) ? result.required as string[] : [];\n const missingRequired = propertyNames.filter(name => !currentRequired.includes(name));\n\n if (missingRequired.length > 0) {\n result.required = [...currentRequired, ...missingRequired];\n warnings.push(`${currentPath}: added ${missingRequired.join(', ')} to required (all properties must be required for strict mode; use type union with null for optional fields)`);\n }\n\n // Recursively prepare nested properties\n const preparedProperties: Record<string, Record<string, unknown>> = {};\n for (const [key, propSchema] of Object.entries(properties)) {\n preparedProperties[key] = preparePropertySchema(\n propSchema,\n path ? `${path}.${key}` : key,\n provider,\n warnings,\n depth + 1,\n );\n }\n result.properties = preparedProperties;\n }\n }\n\n // Handle array type\n if (result.type === 'array' && result.items && typeof result.items === 'object') {\n result.items = preparePropertySchema(\n result.items as Record<string, unknown>,\n `${currentPath}[]`,\n provider,\n warnings,\n depth + 1,\n );\n\n // Strip unsupported array keywords\n for (const keyword of UNSUPPORTED_ARRAY_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${currentPath}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Handle anyOf\n if (Array.isArray(result.anyOf)) {\n result.anyOf = (result.anyOf as Record<string, unknown>[]).map((variant, i) =>\n preparePropertySchema(variant, `${currentPath}.anyOf[${i}]`, provider, warnings, depth + 1)\n );\n }\n\n // Handle $defs / definitions\n for (const defsKey of ['$defs', 'definitions']) {\n if (result[defsKey] && typeof result[defsKey] === 'object') {\n const defs = result[defsKey] as Record<string, Record<string, unknown>>;\n const preparedDefs: Record<string, Record<string, unknown>> = {};\n for (const [key, defSchema] of Object.entries(defs)) {\n preparedDefs[key] = preparePropertySchema(\n defSchema,\n `${defsKey}.${key}`,\n provider,\n warnings,\n depth,\n );\n }\n result[defsKey] = preparedDefs;\n }\n }\n\n return result;\n}\n\n/**\n * Prepares a single property schema, stripping unsupported keywords based on type.\n */\nfunction preparePropertySchema(\n schema: Record<string, unknown>,\n path: string,\n provider: Providers | string,\n warnings: string[],\n depth: number,\n): Record<string, unknown> {\n const result = { ...schema };\n\n // Strip unsupported numeric keywords\n if (result.type === 'number' || result.type === 'integer') {\n for (const keyword of UNSUPPORTED_NUMERIC_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Strip unsupported string keywords\n if (result.type === 'string') {\n for (const keyword of UNSUPPORTED_STRING_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Strip unsupported object keywords\n if (result.type === 'object') {\n for (const keyword of UNSUPPORTED_OBJECT_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Recursively handle nested objects and arrays\n if (result.type === 'object' || result.properties || result.type === 'array' || result.anyOf || result.$defs || result.definitions) {\n return prepareObjectRecursive(result, path, provider, warnings, depth);\n }\n\n return result;\n}\n\n/**\n * Appends a constraint description to the schema's description field.\n */\nfunction appendToDescription(schema: Record<string, unknown>, constraint: string): void {\n const existing = typeof schema.description === 'string' ? schema.description : '';\n const constraintNote = `[Constraint: ${constraint}]`;\n schema.description = existing ? `${existing} ${constraintNote}` : constraintNote;\n}\n"],"names":[],"mappings":";;AAeA;;;;;;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,YAA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AA,CAAC;;;;;AAMrF,IAAA,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE;AAC5B,QAAA,KAAK,MAAM,OAAO,IAAI,2BAA2B,EAAE;AACjD,YAAA,IAAI,OAAO,IAAI,MAAM,EAAE;AACrB,gBAAA,mBAAmB,CAAC,MAAM,EAAE,CAAA,EAAG,OAAO,CAAA,EAAA,EAAK,MAAM,CAAC,OAAO,CAAC,CAAE,CAAA,CAAC;AAC7D,gBAAA,OAAO,MAAM,CAAC,OAAO,CAAC;gBACtB,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAG,IAAI,CAAgC,6BAAA,EAAA,OAAO,CAAkB,gBAAA,CAAA,CAAC;;;;;AAMrF,IAAA,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,IAAI,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,WAAW,EAAE;AAClI,QAAA,OAAO,sBAAsB,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC;;AAGxE,IAAA,OAAO,MAAM;AACf;AAEA;;AAEG;AACH,SAAS,mBAAmB,CAAC,MAA+B,EAAE,UAAkB,EAAA;AAC9E,IAAA,MAAM,QAAQ,GAAG,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,GAAG,MAAM,CAAC,WAAW,GAAG,EAAE;AACjF,IAAA,MAAM,cAAc,GAAG,CAAgB,aAAA,EAAA,UAAU,GAAG;AACpD,IAAA,MAAM,CAAC,WAAW,GAAG,QAAQ,GAAG,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,cAAc,CAAE,CAAA,GAAG,cAAc;AAClF;;;;"}
|
|
1
|
+
{"version":3,"file":"validate.mjs","sources":["../../../src/schemas/validate.ts"],"sourcesContent":["// src/schemas/validate.ts\nimport { z } from 'zod';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\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\n/**\n * Keywords unsupported by native structured output providers.\n * These are stripped from schemas and moved to description fields when strict mode is enabled.\n */\nconst UNSUPPORTED_NUMERIC_KEYWORDS = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'] as const;\nconst UNSUPPORTED_STRING_KEYWORDS = ['minLength', 'maxLength', 'pattern', 'format'] as const;\nconst UNSUPPORTED_ARRAY_KEYWORDS = ['minItems', 'maxItems', 'uniqueItems'] as const;\nconst UNSUPPORTED_OBJECT_KEYWORDS = ['minProperties', 'maxProperties', 'patternProperties'] as const;\n\n/**\n * Result from schema preparation, includes the prepared schema and any warnings.\n */\nexport interface SchemaPreparationResult {\n schema: Record<string, unknown>;\n warnings: string[];\n}\n\n/**\n * Prepares a JSON Schema for a specific provider's native structured output API.\n *\n * This function normalizes the schema to comply with provider-specific requirements:\n * - Adds `additionalProperties: false` recursively to all objects (required by all providers in strict mode)\n * - Ensures all properties are listed in `required` (required by OpenAI and Anthropic)\n * - Strips unsupported constraint keywords (minimum, maxLength, etc.) and moves them to description\n * - Returns warnings for any modifications made\n *\n * @param schema - The original JSON Schema\n * @param provider - The LLM provider\n * @param strict - Whether strict mode is enabled (default: true)\n * @returns The prepared schema and any warnings\n */\nexport function prepareSchemaForProvider(\n schema: Record<string, unknown>,\n provider: Providers | string,\n strict = true,\n): SchemaPreparationResult {\n const warnings: string[] = [];\n\n if (!strict) {\n return { schema: { ...schema }, warnings };\n }\n\n const prepared = prepareObjectRecursive(schema, '', provider, warnings);\n return { schema: prepared, warnings };\n}\n\n/**\n * Recursively prepares a schema node for native structured output.\n */\nfunction prepareObjectRecursive(\n schema: Record<string, unknown>,\n path: string,\n provider: Providers | string,\n warnings: string[],\n depth = 0,\n): Record<string, unknown> {\n const result = { ...schema };\n const currentPath = path || 'root';\n\n // Warn on deep nesting (OpenAI limit is 5)\n if (depth > 5 && (provider === Providers.OPENAI || provider === Providers.AZURE)) {\n warnings.push(`${currentPath}: nesting depth ${depth} exceeds OpenAI's limit of 5 levels`);\n }\n\n // Handle object type\n if (result.type === 'object' || (result.properties && !result.type)) {\n if (!result.type) {\n result.type = 'object';\n }\n\n // Add additionalProperties: false\n if (result.additionalProperties !== false) {\n result.additionalProperties = false;\n if (path) {\n warnings.push(`${currentPath}: set additionalProperties to false for strict mode`);\n }\n }\n\n // Ensure all properties are in required\n if (result.properties && typeof result.properties === 'object') {\n const properties = result.properties as Record<string, Record<string, unknown>>;\n const propertyNames = Object.keys(properties);\n const currentRequired = Array.isArray(result.required) ? result.required as string[] : [];\n const missingRequired = propertyNames.filter(name => !currentRequired.includes(name));\n\n if (missingRequired.length > 0) {\n result.required = [...currentRequired, ...missingRequired];\n warnings.push(`${currentPath}: added ${missingRequired.join(', ')} to required (all properties must be required for strict mode; use type union with null for optional fields)`);\n }\n\n // Recursively prepare nested properties\n const preparedProperties: Record<string, Record<string, unknown>> = {};\n for (const [key, propSchema] of Object.entries(properties)) {\n preparedProperties[key] = preparePropertySchema(\n propSchema,\n path ? `${path}.${key}` : key,\n provider,\n warnings,\n depth + 1,\n );\n }\n result.properties = preparedProperties;\n }\n }\n\n // Handle array type\n if (result.type === 'array' && result.items && typeof result.items === 'object') {\n result.items = preparePropertySchema(\n result.items as Record<string, unknown>,\n `${currentPath}[]`,\n provider,\n warnings,\n depth + 1,\n );\n\n // Strip unsupported array keywords\n for (const keyword of UNSUPPORTED_ARRAY_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${currentPath}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Handle anyOf\n if (Array.isArray(result.anyOf)) {\n result.anyOf = (result.anyOf as Record<string, unknown>[]).map((variant, i) =>\n preparePropertySchema(variant, `${currentPath}.anyOf[${i}]`, provider, warnings, depth + 1)\n );\n }\n\n // Handle $defs / definitions\n for (const defsKey of ['$defs', 'definitions']) {\n if (result[defsKey] && typeof result[defsKey] === 'object') {\n const defs = result[defsKey] as Record<string, Record<string, unknown>>;\n const preparedDefs: Record<string, Record<string, unknown>> = {};\n for (const [key, defSchema] of Object.entries(defs)) {\n preparedDefs[key] = preparePropertySchema(\n defSchema,\n `${defsKey}.${key}`,\n provider,\n warnings,\n depth,\n );\n }\n result[defsKey] = preparedDefs;\n }\n }\n\n return result;\n}\n\n/**\n * Prepares a single property schema, stripping unsupported keywords based on type.\n */\nfunction preparePropertySchema(\n schema: Record<string, unknown>,\n path: string,\n provider: Providers | string,\n warnings: string[],\n depth: number,\n): Record<string, unknown> {\n const result = { ...schema };\n\n // Strip unsupported numeric keywords\n if (result.type === 'number' || result.type === 'integer') {\n for (const keyword of UNSUPPORTED_NUMERIC_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Strip unsupported string keywords\n if (result.type === 'string') {\n for (const keyword of UNSUPPORTED_STRING_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Strip unsupported object keywords\n if (result.type === 'object') {\n for (const keyword of UNSUPPORTED_OBJECT_KEYWORDS) {\n if (keyword in result) {\n appendToDescription(result, `${keyword}: ${result[keyword]}`);\n delete result[keyword];\n warnings.push(`${path}: moved unsupported keyword '${keyword}' to description`);\n }\n }\n }\n\n // Recursively handle nested objects and arrays\n if (result.type === 'object' || result.properties || result.type === 'array' || result.anyOf || result.$defs || result.definitions) {\n return prepareObjectRecursive(result, path, provider, warnings, depth);\n }\n\n return result;\n}\n\n/**\n * Appends a constraint description to the schema's description field.\n */\nfunction appendToDescription(schema: Record<string, unknown>, constraint: string): void {\n const existing = typeof schema.description === 'string' ? schema.description : '';\n const constraintNote = `[Constraint: ${constraint}]`;\n schema.description = existing ? `${existing} ${constraintNote}` : constraintNote;\n}\n"],"names":[],"mappings":";;AAeA;;;;;;AAMG;AACG,SAAU,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,CAAA,CAAE;AAChD,gBAAA,GAAG,EAAE,IAAI;aACV;QACH;QAEA,OAAO;AACL,YAAA,OAAO,EAAE,IAAI;AACb,YAAA,IAAI,EAAE,IAA+B;SACtC;IACH;IAAE,OAAO,CAAC,EAAE;QACV,OAAO;AACL,YAAA,OAAO,EAAE,KAAK;AACd,YAAA,KAAK,EAAE,CAAA,wBAAA,EAA4B,CAAW,CAAC,OAAO,CAAA,C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CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,cAAc,CAAA,CAAE,GAAG,cAAc;AAClF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = [\n '. ',\n '?',\n '!',\n '۔',\n '- ',\n '。',\n '‥',\n ';',\n '¡',\n '¿',\n '\\n',\n '```',\n];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string;\n accumulate?: boolean;\n handlers: t.SplitStreamHandlers;\n blockThreshold?: number;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (\n type?: ContentTypes.TEXT | ContentTypes.THINK\n ): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({\n event: GraphEvents.ON_RUN_STEP,\n data: runStep,\n });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: messageDelta,\n });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({\n event: GraphEvents.ON_REASONING_DELTA,\n data: reasoningDelta,\n });\n };\n handleContent = (\n content: string,\n _type: ContentTypes.TEXT | ContentTypes.THINK\n ): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (\n this.currentLength > this.blockThreshold &&\n SEPARATORS.some((sep) => content.includes(sep))\n ) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n getDeltaContent(chunk?: t.CustomChunk): string {\n return (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.content ?? '';\n }\n getReasoningDelta(chunk?: t.CustomChunk): string {\n return (\n (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.[this.reasoningKey] ??\n ''\n );\n }\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = this.getDeltaContent(chunk);\n const reasoning_content = this.getReasoningDelta(chunk);\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</think>') && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock\n ? ContentTypes.THINK\n : ContentTypes.TEXT;\n const initialType = reasoning_content\n ? ContentTypes.THINK\n : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}\n"],"names":[],"mappings":";;;AAIa,MAAA,UAAU,GAAG;IACxB,IAAI;IACJ,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,KAAK;;MAGM,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK;IACnB,YAAY,GAAG,KAAK;AACp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YAAY,GAAG,IAAI;;AACnB,aAAA,IAAI,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;AACnE,YAAA,IAAI,CAAC,YAAY,GAAG,KAAK;;AAG3B,QAAA,IAAI,CAAC,SAAS,GAAG,OAAO;QAExB,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE;QAE5C,IAAI,CAAC,UAAU,EAAE;AACf,YAAA,MAAM,kBAAkB,GAAG,IAAI,CAAC;kBAC5B,YAAY,CAAC;AACf,kBAAE,YAAY,CAAC,IAAI;YACrB,MAAM,WAAW,GAAG;kBAChB,YAAY,CAAC;kBACb,kBAAkB;AACtB,YAAA,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC;AAChE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC;;QAGJ,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC;;aACpD;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC;;;AAGnD;;;;"}
|
|
1
|
+
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = [\n '. ',\n '?',\n '!',\n '۔',\n '- ',\n '。',\n '‥',\n ';',\n '¡',\n '¿',\n '\\n',\n '```',\n];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string;\n accumulate?: boolean;\n handlers: t.SplitStreamHandlers;\n blockThreshold?: number;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (\n type?: ContentTypes.TEXT | ContentTypes.THINK\n ): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({\n event: GraphEvents.ON_RUN_STEP,\n data: runStep,\n });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: messageDelta,\n });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({\n event: GraphEvents.ON_REASONING_DELTA,\n data: reasoningDelta,\n });\n };\n handleContent = (\n content: string,\n _type: ContentTypes.TEXT | ContentTypes.THINK\n ): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (\n this.currentLength > this.blockThreshold &&\n SEPARATORS.some((sep) => content.includes(sep))\n ) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n getDeltaContent(chunk?: t.CustomChunk): string {\n return (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.content ?? '';\n }\n getReasoningDelta(chunk?: t.CustomChunk): string {\n return (\n (chunk?.choices?.[0]?.delta as t.CustomChunkDelta)?.[this.reasoningKey] ??\n ''\n );\n }\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = this.getDeltaContent(chunk);\n const reasoning_content = this.getReasoningDelta(chunk);\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</think>') && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock\n ? ContentTypes.THINK\n : ContentTypes.TEXT;\n const initialType = reasoning_content\n ? ContentTypes.THINK\n : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}\n"],"names":[],"mappings":";;;AAIO,MAAM,UAAU,GAAG;IACxB,IAAI;IACJ,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,KAAK;;MAGM,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK;IACnB,YAAY,GAAG,KAAK;AACpB,IAAA,UAAU;IAClB,MAAM,GAAa,EAAE;IACrB,SAAS,GAAG,EAAE;IACd,eAAe,GAAa,EAAE;AAC9B,IAAA,aAAa;AACb,IAAA,gBAAgB;AAChB,IAAA,WAAW;IACX,aAAa,GAAG,CAAC;IACjB,YAAY,GAAsC,mBAAmB;IACrE,YAAY,GAAG,EAAE;IACjB,cAAc,GAAG,IAAI;;AAErB,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,WAAA,CAAY,EACV,KAAK,EACL,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,cAAc,GAOf,EAAA;AACC,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,QAAQ,GAAG,QA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AG,IAAI,CAAC;kBAC5B,YAAY,CAAC;AACf,kBAAE,YAAY,CAAC,IAAI;YACrB,MAAM,WAAW,GAAG;kBAChB,YAAY,CAAC;kBACb,kBAAkB;AACtB,YAAA,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC;AAChE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC;QACJ;QAEA,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC;QAC3D;aAAO;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC;QAChD;IACF;AACD;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { StepTypes, ContentTypes, Providers, GraphEvents, ToolCallTypes } from './common/enum.mjs';
|
|
2
2
|
import { handleServerToolResult, handleToolCalls, handleToolCallChunks } from './tools/handlers.mjs';
|
|
3
3
|
import './messages/core.mjs';
|
|
4
4
|
import { getMessageId } from './messages/ids.mjs';
|
|
@@ -309,6 +309,7 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
309
309
|
(chunk.tool_call_chunks?.length ?? 0) > 0)) {
|
|
310
310
|
agentContext.currentTokenType = ContentTypes.TEXT;
|
|
311
311
|
agentContext.tokenTypeSwitch = 'content';
|
|
312
|
+
agentContext.reasoningTransitionCount++;
|
|
312
313
|
}
|
|
313
314
|
else if (chunk.content != null &&
|
|
314
315
|
typeof chunk.content === 'string' &&
|
|
@@ -344,7 +345,7 @@ function createContentAggregator() {
|
|
|
344
345
|
const contentMetaMap = new Map();
|
|
345
346
|
const updateContent = (index, contentPart, finalUpdate = false) => {
|
|
346
347
|
if (!contentPart) {
|
|
347
|
-
console.warn(
|
|
348
|
+
console.warn("No content part found in 'updateContent'");
|
|
348
349
|
return;
|
|
349
350
|
}
|
|
350
351
|
const partType = contentPart.type ?? '';
|
|
@@ -352,7 +353,7 @@ function createContentAggregator() {
|
|
|
352
353
|
console.warn('No content type found in content part');
|
|
353
354
|
return;
|
|
354
355
|
}
|
|
355
|
-
if (!contentParts[index]) {
|
|
356
|
+
if (!contentParts[index] && partType !== ContentTypes.TOOL_CALL) {
|
|
356
357
|
contentParts[index] = { type: partType };
|
|
357
358
|
}
|
|
358
359
|
if (!partType.startsWith(contentParts[index]?.type ?? '')) {
|
|
@@ -412,19 +413,26 @@ function createContentAggregator() {
|
|
|
412
413
|
// 1. Incoming has a valid name (initial tool call setup), OR
|
|
413
414
|
// 2. It's a final update (ON_RUN_STEP_COMPLETED), OR
|
|
414
415
|
// 3. Existing content already has a name (delta streaming — grows args progressively)
|
|
415
|
-
const existingHasName = existingContent?.tool_call?.name != null &&
|
|
416
|
+
const existingHasName = existingContent?.tool_call?.name != null &&
|
|
417
|
+
existingContent.tool_call.name !== '';
|
|
416
418
|
if (!hasValidName && !finalUpdate && !existingHasName) {
|
|
417
419
|
return;
|
|
418
420
|
}
|
|
419
|
-
/** Concatenate string args for progressive streaming; replace when object (complete)
|
|
421
|
+
/** Concatenate string args for progressive streaming; replace when object (complete).
|
|
422
|
+
* When incoming delta has a valid name, treat as a complete replacement —
|
|
423
|
+
* this handles the Bedrock case where handleToolCalls sends complete args
|
|
424
|
+
* as a delta to an existing step that already has partial args from chunks. */
|
|
420
425
|
const existingArgs = existingContent?.tool_call?.args;
|
|
421
|
-
const existingIsEmptyObj = typeof existingArgs === 'object' &&
|
|
422
|
-
|
|
426
|
+
const existingIsEmptyObj = typeof existingArgs === 'object' &&
|
|
427
|
+
Object.keys(existingArgs).length === 0;
|
|
423
428
|
const existingIsString = typeof existingArgs === 'string' || existingIsEmptyObj;
|
|
424
|
-
let args = finalUpdate ||
|
|
429
|
+
let args = finalUpdate ||
|
|
430
|
+
hasValidName ||
|
|
431
|
+
(!existingIsString && typeof existingArgs === 'object') ||
|
|
425
432
|
typeof toolCallArgs === 'object'
|
|
426
433
|
? contentPart.tool_call.args
|
|
427
|
-
: ((existingIsEmptyObj ? '' : existingArgs) ?? '') +
|
|
434
|
+
: ((existingIsEmptyObj ? '' : existingArgs) ?? '') +
|
|
435
|
+
(toolCallArgs ?? '');
|
|
428
436
|
if (finalUpdate &&
|
|
429
437
|
args == null &&
|
|
430
438
|
existingContent?.tool_call?.args != null) {
|
|
@@ -463,15 +471,13 @@ function createContentAggregator() {
|
|
|
463
471
|
// Handle structured output - add the JSON response as a text content part
|
|
464
472
|
if (event === GraphEvents.ON_STRUCTURED_OUTPUT) {
|
|
465
473
|
const structuredData = data;
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
updateContent(nextIndex, contentPart);
|
|
474
|
-
}
|
|
474
|
+
const contentPart = {
|
|
475
|
+
type: ContentTypes.TEXT,
|
|
476
|
+
text: JSON.stringify(structuredData.structuredResponse, null, 2),
|
|
477
|
+
};
|
|
478
|
+
// Use the next available index
|
|
479
|
+
const nextIndex = contentParts.length;
|
|
480
|
+
updateContent(nextIndex, contentPart);
|
|
475
481
|
return;
|
|
476
482
|
}
|
|
477
483
|
if (event === GraphEvents.ON_RUN_STEP) {
|
|
@@ -497,21 +503,36 @@ function createContentAggregator() {
|
|
|
497
503
|
runStep.stepDetails.tool_calls) {
|
|
498
504
|
// Check if ALL tool calls are structured output tool calls
|
|
499
505
|
const toolCalls = runStep.stepDetails.tool_calls;
|
|
500
|
-
const allAreStructuredOutput = toolCalls.
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
toolName === '
|
|
504
|
-
|
|
505
|
-
|
|
506
|
+
const allAreStructuredOutput = toolCalls.length > 0 &&
|
|
507
|
+
toolCalls.every((toolCall) => {
|
|
508
|
+
const toolName = toolCall.name.toLowerCase();
|
|
509
|
+
return (toolName === 'response' ||
|
|
510
|
+
toolName === 'structuredresponse' ||
|
|
511
|
+
toolName === 'structured_response');
|
|
512
|
+
});
|
|
506
513
|
// If all tool calls are structured output, skip this entire step
|
|
507
514
|
if (allAreStructuredOutput) {
|
|
508
515
|
skippedStructuredOutputSteps.add(runStep.id);
|
|
509
516
|
return;
|
|
510
517
|
}
|
|
518
|
+
// When tool_calls is empty (Bedrock sends name/args only at model end),
|
|
519
|
+
// initialize a placeholder so contentParts[index] is not null.
|
|
520
|
+
// ON_RUN_STEP_COMPLETED or ON_RUN_STEP_DELTA will fill in the real data.
|
|
521
|
+
if (toolCalls.length === 0) {
|
|
522
|
+
contentParts[runStep.index] = {
|
|
523
|
+
type: ContentTypes.TOOL_CALL,
|
|
524
|
+
tool_call: {
|
|
525
|
+
args: '',
|
|
526
|
+
name: '',
|
|
527
|
+
id: '',
|
|
528
|
+
type: ToolCallTypes.TOOL_CALL,
|
|
529
|
+
},
|
|
530
|
+
};
|
|
531
|
+
}
|
|
511
532
|
toolCalls.forEach((toolCall) => {
|
|
512
533
|
// Skip structured output tool calls - these are synthetic tool calls
|
|
513
534
|
// used by withStructuredOutput() to extract JSON, not real tools
|
|
514
|
-
const toolName = toolCall.name
|
|
535
|
+
const toolName = toolCall.name.toLowerCase();
|
|
515
536
|
if (toolName === 'response' ||
|
|
516
537
|
toolName === 'structuredresponse' ||
|
|
517
538
|
toolName === 'structured_response') {
|
|
@@ -583,7 +604,20 @@ function createContentAggregator() {
|
|
|
583
604
|
if (runStepDelta.delta.type === StepTypes.TOOL_CALLS &&
|
|
584
605
|
runStepDelta.delta.tool_calls) {
|
|
585
606
|
runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
|
|
586
|
-
|
|
607
|
+
/** Use toolCallIdMap first; fall back to the delta's own id
|
|
608
|
+
* (Bedrock sends complete tool call data as a delta via handleToolCalls,
|
|
609
|
+
* which includes the id, but the map was never populated because
|
|
610
|
+
* the initial on_run_step had tool_calls: []) */
|
|
611
|
+
const toolCallId = toolCallIdMap.get(runStepDelta.id) ??
|
|
612
|
+
(toolCallDelta.id != null && toolCallDelta.id !== ''
|
|
613
|
+
? toolCallDelta.id
|
|
614
|
+
: undefined);
|
|
615
|
+
// Store the mapping for future lookups (e.g. on_run_step_completed)
|
|
616
|
+
if (toolCallId != null &&
|
|
617
|
+
toolCallId !== '' &&
|
|
618
|
+
!toolCallIdMap.has(runStepDelta.id)) {
|
|
619
|
+
toolCallIdMap.set(runStepDelta.id, toolCallId);
|
|
620
|
+
}
|
|
587
621
|
const contentPart = {
|
|
588
622
|
type: ContentTypes.TOOL_CALL,
|
|
589
623
|
tool_call: {
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n // Content presence signals end of reasoning phase - prefer content over reasoning\n // This handles transitional chunks that may have both reasoning and content\n if (typeof chunk?.content === 'string' && chunk.content !== '') {\n return chunk.content;\n }\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n c.type === 'redacted_thinking'\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT ||\n chunk.content[0]?.type === 'redacted_thinking')\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Only set reasoning as valid if content is NOT present (content signals end of reasoning)\n (chunk.content == null || chunk.content === '') &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n // Track step IDs for structured output tool calls that should be skipped\n const skippedStructuredOutputSteps = new Set<string>();\n // Track agentId and groupId for each content index (applied to content parts)\n const contentMetaMap = new Map<\n number,\n { agentId?: string; groupId?: number }\n >();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n // Allow processing if:\n // 1. Incoming has a valid name (initial tool call setup), OR\n // 2. It's a final update (ON_RUN_STEP_COMPLETED), OR\n // 3. Existing content already has a name (delta streaming — grows args progressively)\n const existingHasName = existingContent?.tool_call?.name != null && existingContent.tool_call.name !== '';\n if (!hasValidName && !finalUpdate && !existingHasName) {\n return;\n }\n\n /** Concatenate string args for progressive streaming; replace when object (complete) */\n const existingArgs = existingContent?.tool_call?.args;\n const existingIsEmptyObj = typeof existingArgs === 'object' && existingArgs != null\n && Object.keys(existingArgs as Record<string, unknown>).length === 0;\n const existingIsString = typeof existingArgs === 'string' || existingIsEmptyObj;\n let args =\n finalUpdate || (!existingIsString && typeof existingArgs === 'object') ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : ((existingIsEmptyObj ? '' : existingArgs) ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n\n // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts\n // - agentId present → MultiAgentGraph (show agent labels)\n // - groupId present → parallel execution (render columns)\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n (contentParts[index] as t.MessageContentComplex).agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n (contentParts[index] as t.MessageContentComplex).groupId = meta.groupId;\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent }\n | { structuredResponse: Record<string, unknown>; schema: Record<string, unknown> };\n }): void => {\n // Handle structured output - add the JSON response as a text content part\n if (event === GraphEvents.ON_STRUCTURED_OUTPUT) {\n const structuredData = data as { structuredResponse: Record<string, unknown>; schema: Record<string, unknown> };\n if (structuredData.structuredResponse) {\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TEXT,\n text: JSON.stringify(structuredData.structuredResponse, null, 2),\n };\n // Use the next available index\n const nextIndex = contentParts.length;\n updateContent(nextIndex, contentPart);\n }\n return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately\n // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)\n // - groupId: present only for parallel execution (enables column rendering)\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(runStep.index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(runStep.index, existingMeta);\n }\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n // Check if ALL tool calls are structured output tool calls\n const toolCalls = runStep.stepDetails.tool_calls as ToolCall[];\n const allAreStructuredOutput = toolCalls.every((toolCall) => {\n const toolName = toolCall.name?.toLowerCase() ?? '';\n return (\n toolName === 'response' ||\n toolName === 'structuredresponse' ||\n toolName === 'structured_response'\n );\n });\n\n // If all tool calls are structured output, skip this entire step\n if (allAreStructuredOutput) {\n skippedStructuredOutputSteps.add(runStep.id);\n return;\n }\n\n toolCalls.forEach((toolCall) => {\n // Skip structured output tool calls - these are synthetic tool calls\n // used by withStructuredOutput() to extract JSON, not real tools\n const toolName = toolCall.name?.toLowerCase() ?? '';\n if (\n toolName === 'response' ||\n toolName === 'structuredresponse' ||\n toolName === 'structured_response'\n ) {\n return;\n }\n\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n \n // Skip deltas for structured output tool calls\n if (skippedStructuredOutputSteps.has(runStepDelta.id)) {\n return;\n }\n \n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n // Skip completion events for structured output tool calls\n if (skippedStructuredOutputSteps.has(stepId)) {\n return;\n }\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IA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AU,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;AAErD,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;4BAC9B,IAAI,EAAE,aAAa,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;;AAG7B,YAAA,IAAI,4BAA4B,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;gBAC5C;;YAGF,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n // Content presence signals end of reasoning phase - prefer content over reasoning\n // This handles transitional chunks that may have both reasoning and content\n if (typeof chunk?.content === 'string' && chunk.content !== '') {\n return chunk.content;\n }\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n c.type === 'redacted_thinking'\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT ||\n chunk.content[0]?.type === 'redacted_thinking')\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Only set reasoning as valid if content is NOT present (content signals end of reasoning)\n (chunk.content == null || chunk.content === '') &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n agentContext.reasoningTransitionCount++;\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n // Track step IDs for structured output tool calls that should be skipped\n const skippedStructuredOutputSteps = new Set<string>();\n // Track agentId and groupId for each content index (applied to content parts)\n const contentMetaMap = new Map<\n number,\n { agentId?: string; groupId?: number }\n >();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn(\"No content part found in 'updateContent'\");\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index] && partType !== ContentTypes.TOOL_CALL) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n // Allow processing if:\n // 1. Incoming has a valid name (initial tool call setup), OR\n // 2. It's a final update (ON_RUN_STEP_COMPLETED), OR\n // 3. Existing content already has a name (delta streaming — grows args progressively)\n const existingHasName =\n existingContent?.tool_call?.name != null &&\n existingContent.tool_call.name !== '';\n if (!hasValidName && !finalUpdate && !existingHasName) {\n return;\n }\n\n /** Concatenate string args for progressive streaming; replace when object (complete).\n * When incoming delta has a valid name, treat as a complete replacement —\n * this handles the Bedrock case where handleToolCalls sends complete args\n * as a delta to an existing step that already has partial args from chunks. */\n const existingArgs = existingContent?.tool_call?.args;\n const existingIsEmptyObj =\n typeof existingArgs === 'object' &&\n Object.keys(existingArgs as Record<string, unknown>).length === 0;\n const existingIsString =\n typeof existingArgs === 'string' || existingIsEmptyObj;\n let args =\n finalUpdate ||\n hasValidName ||\n (!existingIsString && typeof existingArgs === 'object') ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : ((existingIsEmptyObj ? '' : existingArgs) ?? '') +\n (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n\n // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts\n // - agentId present → MultiAgentGraph (show agent labels)\n // - groupId present → parallel execution (render columns)\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n (contentParts[index] as t.MessageContentComplex).agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n (contentParts[index] as t.MessageContentComplex).groupId = meta.groupId;\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent }\n | {\n structuredResponse: Record<string, unknown>;\n schema: Record<string, unknown>;\n };\n }): void => {\n // Handle structured output - add the JSON response as a text content part\n if (event === GraphEvents.ON_STRUCTURED_OUTPUT) {\n const structuredData = data as {\n structuredResponse: Record<string, unknown>;\n schema: Record<string, unknown>;\n };\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TEXT,\n text: JSON.stringify(structuredData.structuredResponse, null, 2),\n };\n // Use the next available index\n const nextIndex = contentParts.length;\n updateContent(nextIndex, contentPart);\n return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately\n // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)\n // - groupId: present only for parallel execution (enables column rendering)\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(runStep.index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(runStep.index, existingMeta);\n }\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n // Check if ALL tool calls are structured output tool calls\n const toolCalls = runStep.stepDetails.tool_calls as ToolCall[];\n const allAreStructuredOutput =\n toolCalls.length > 0 &&\n toolCalls.every((toolCall) => {\n const toolName = toolCall.name.toLowerCase();\n return (\n toolName === 'response' ||\n toolName === 'structuredresponse' ||\n toolName === 'structured_response'\n );\n });\n\n // If all tool calls are structured output, skip this entire step\n if (allAreStructuredOutput) {\n skippedStructuredOutputSteps.add(runStep.id);\n return;\n }\n\n // When tool_calls is empty (Bedrock sends name/args only at model end),\n // initialize a placeholder so contentParts[index] is not null.\n // ON_RUN_STEP_COMPLETED or ON_RUN_STEP_DELTA will fill in the real data.\n if (toolCalls.length === 0) {\n contentParts[runStep.index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: '',\n name: '',\n id: '',\n type: ToolCallTypes.TOOL_CALL,\n },\n };\n }\n\n toolCalls.forEach((toolCall) => {\n // Skip structured output tool calls - these are synthetic tool calls\n // used by withStructuredOutput() to extract JSON, not real tools\n const toolName = toolCall.name.toLowerCase();\n if (\n toolName === 'response' ||\n toolName === 'structuredresponse' ||\n toolName === 'structured_response'\n ) {\n return;\n }\n\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n\n // Skip deltas for structured output tool calls\n if (skippedStructuredOutputSteps.has(runStepDelta.id)) {\n return;\n }\n\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n /** Use toolCallIdMap first; fall back to the delta's own id\n * (Bedrock sends complete tool call data as a delta via handleToolCalls,\n * which includes the id, but the map was never populated because\n * the initial on_run_step had tool_calls: []) */\n const toolCallId =\n toolCallIdMap.get(runStepDelta.id) ??\n (toolCallDelta.id != null && toolCallDelta.id !== ''\n ? toolCallDelta.id\n : undefined);\n\n // Store the mapping for future lookups (e.g. on_run_step_completed)\n if (\n toolCallId != null &&\n toolCallId !== '' &&\n !toolCallIdMap.has(runStepDelta.id)\n ) {\n toolCallIdMap.set(runStepDelta.id, toolCallId);\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n // Skip completion events for structured output tool calls\n if (skippedStructuredOutputSteps.has(stepId)) {\n return;\n }\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EA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