@librechat/agents 3.3.8 → 3.3.9

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.
Files changed (148) hide show
  1. package/dist/cjs/graphs/Graph.cjs +47 -13
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +35 -2
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/hitl/askUserQuestion.cjs +3 -2
  6. package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
  7. package/dist/cjs/instrumentation.cjs +18 -48
  8. package/dist/cjs/instrumentation.cjs.map +1 -1
  9. package/dist/cjs/langfuse.cjs +174 -29
  10. package/dist/cjs/langfuse.cjs.map +1 -1
  11. package/dist/cjs/langfuseConfig.cjs +12 -0
  12. package/dist/cjs/langfuseConfig.cjs.map +1 -1
  13. package/dist/cjs/langfuseRuntimeContext.cjs +23 -2
  14. package/dist/cjs/langfuseRuntimeContext.cjs.map +1 -1
  15. package/dist/cjs/langfuseRuntimeScope.cjs +39 -8
  16. package/dist/cjs/langfuseRuntimeScope.cjs.map +1 -1
  17. package/dist/cjs/langfuseSpanRegistry.cjs +95 -0
  18. package/dist/cjs/langfuseSpanRegistry.cjs.map +1 -0
  19. package/dist/cjs/langfuseTraceShaping.cjs +121 -4
  20. package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
  21. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +39 -15
  22. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  23. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +25 -5
  24. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  25. package/dist/cjs/llm/init.cjs +3 -3
  26. package/dist/cjs/llm/invoke.cjs +5 -5
  27. package/dist/cjs/llm/openai/index.cjs +1 -1
  28. package/dist/cjs/main.cjs +10 -10
  29. package/dist/cjs/messages/prune.cjs +13 -1
  30. package/dist/cjs/messages/prune.cjs.map +1 -1
  31. package/dist/cjs/prompts/activityLabel.cjs +24 -12
  32. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  33. package/dist/cjs/run.cjs +47 -22
  34. package/dist/cjs/run.cjs.map +1 -1
  35. package/dist/cjs/session/messageSerialization.cjs +6 -0
  36. package/dist/cjs/session/messageSerialization.cjs.map +1 -1
  37. package/dist/cjs/stream.cjs +21 -10
  38. package/dist/cjs/stream.cjs.map +1 -1
  39. package/dist/cjs/summarization/node.cjs +5 -0
  40. package/dist/cjs/summarization/node.cjs.map +1 -1
  41. package/dist/cjs/tools/ToolNode.cjs +253 -24
  42. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  43. package/dist/cjs/tools/handlers.cjs +1 -1
  44. package/dist/cjs/tools/search/tool.cjs +1 -1
  45. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -1
  46. package/dist/cjs/utils/index.cjs +2 -2
  47. package/dist/esm/graphs/Graph.mjs +48 -14
  48. package/dist/esm/graphs/Graph.mjs.map +1 -1
  49. package/dist/esm/graphs/MultiAgentGraph.mjs +35 -2
  50. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  51. package/dist/esm/hitl/askUserQuestion.mjs +3 -2
  52. package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
  53. package/dist/esm/instrumentation.mjs +18 -48
  54. package/dist/esm/instrumentation.mjs.map +1 -1
  55. package/dist/esm/langfuse.mjs +176 -28
  56. package/dist/esm/langfuse.mjs.map +1 -1
  57. package/dist/esm/langfuseConfig.mjs +10 -1
  58. package/dist/esm/langfuseConfig.mjs.map +1 -1
  59. package/dist/esm/langfuseRuntimeContext.mjs +21 -3
  60. package/dist/esm/langfuseRuntimeContext.mjs.map +1 -1
  61. package/dist/esm/langfuseRuntimeScope.mjs +39 -10
  62. package/dist/esm/langfuseRuntimeScope.mjs.map +1 -1
  63. package/dist/esm/langfuseSpanRegistry.mjs +91 -0
  64. package/dist/esm/langfuseSpanRegistry.mjs.map +1 -0
  65. package/dist/esm/langfuseTraceShaping.mjs +121 -4
  66. package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
  67. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +39 -15
  68. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  69. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +25 -5
  70. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  71. package/dist/esm/llm/init.mjs +2 -2
  72. package/dist/esm/llm/invoke.mjs +5 -5
  73. package/dist/esm/llm/openai/index.mjs +1 -1
  74. package/dist/esm/main.mjs +8 -8
  75. package/dist/esm/messages/prune.mjs +13 -1
  76. package/dist/esm/messages/prune.mjs.map +1 -1
  77. package/dist/esm/prompts/activityLabel.mjs +24 -12
  78. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  79. package/dist/esm/run.mjs +47 -22
  80. package/dist/esm/run.mjs.map +1 -1
  81. package/dist/esm/session/messageSerialization.mjs +6 -0
  82. package/dist/esm/session/messageSerialization.mjs.map +1 -1
  83. package/dist/esm/stream.mjs +21 -10
  84. package/dist/esm/stream.mjs.map +1 -1
  85. package/dist/esm/summarization/node.mjs +5 -0
  86. package/dist/esm/summarization/node.mjs.map +1 -1
  87. package/dist/esm/tools/ToolNode.mjs +254 -25
  88. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  89. package/dist/esm/tools/handlers.mjs +1 -1
  90. package/dist/esm/tools/search/tool.mjs +1 -1
  91. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -1
  92. package/dist/esm/utils/index.mjs +2 -2
  93. package/dist/types/graphs/Graph.d.ts +19 -0
  94. package/dist/types/hitl/askUserQuestion.d.ts +11 -1
  95. package/dist/types/langfuse.d.ts +16 -8
  96. package/dist/types/langfuseConfig.d.ts +6 -0
  97. package/dist/types/langfuseRuntimeContext.d.ts +27 -1
  98. package/dist/types/langfuseRuntimeScope.d.ts +17 -2
  99. package/dist/types/langfuseSpanRegistry.d.ts +17 -0
  100. package/dist/types/langfuseTraceShaping.d.ts +2 -1
  101. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  102. package/dist/types/session/types.d.ts +1 -0
  103. package/dist/types/tools/ToolNode.d.ts +7 -1
  104. package/dist/types/types/hitl.d.ts +8 -0
  105. package/dist/types/types/tools.d.ts +30 -0
  106. package/package.json +7 -4
  107. package/src/__tests__/stream.eagerArgsDivergence.test.ts +753 -0
  108. package/src/graphs/Graph.ts +69 -20
  109. package/src/graphs/MultiAgentGraph.ts +56 -2
  110. package/src/graphs/__tests__/composition.smoke.test.ts +4 -0
  111. package/src/hitl/askUserQuestion.ts +14 -1
  112. package/src/instrumentation.ts +35 -77
  113. package/src/langfuse.ts +320 -43
  114. package/src/langfuseConfig.ts +24 -0
  115. package/src/langfuseRuntimeContext.ts +43 -1
  116. package/src/langfuseRuntimeScope.ts +94 -21
  117. package/src/langfuseSpanRegistry.ts +131 -0
  118. package/src/langfuseTraceShaping.ts +194 -7
  119. package/src/llm/anthropic/utils/message_inputs.ts +70 -19
  120. package/src/llm/anthropic/utils/streaming-tool-input.test.ts +186 -11
  121. package/src/llm/bedrock/utils/message_inputs.test.ts +120 -4
  122. package/src/llm/bedrock/utils/message_inputs.ts +32 -7
  123. package/src/messages/prune.ts +12 -1
  124. package/src/prompts/activityLabel.ts +23 -6
  125. package/src/run.ts +76 -45
  126. package/src/scripts/activity-labels/captured.json +56 -0
  127. package/src/scripts/activity-labels/checks.cjs +205 -0
  128. package/src/scripts/activity-labels/corpus.cjs +473 -0
  129. package/src/scripts/activity-labels/report.cjs +203 -0
  130. package/src/scripts/activity-labels/rescore.cjs +102 -0
  131. package/src/scripts/activity-labels/run.ts +705 -0
  132. package/src/scripts/activity-labels/variants.ts +71 -0
  133. package/src/session/messageSerialization.ts +12 -1
  134. package/src/session/types.ts +1 -0
  135. package/src/specs/activity-label-prompt.test.ts +26 -10
  136. package/src/specs/agent-handoffs.test.ts +306 -0
  137. package/src/specs/langfuse-callbacks.test.ts +456 -0
  138. package/src/specs/langfuse-routing.integration.test.ts +138 -1
  139. package/src/specs/langfuse-span-registry.test.ts +70 -0
  140. package/src/specs/langfuse-trace-shaping.test.ts +294 -0
  141. package/src/specs/prune.test.ts +38 -1
  142. package/src/stream.ts +70 -6
  143. package/src/summarization/node.ts +5 -0
  144. package/src/tools/ToolNode.ts +400 -9
  145. package/src/tools/__tests__/ToolNode.invalidToolCalls.test.ts +757 -0
  146. package/src/tools/__tests__/hitl.test.ts +58 -0
  147. package/src/types/hitl.ts +8 -0
  148. package/src/types/tools.ts +35 -1
@@ -1 +1 @@
1
- {"version":3,"file":"stream.mjs","names":["completeData"],"sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n streamedToolCallAdapterAllowsSequentialSeal,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n serializeStructuredValueBounded,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { resolveToolOutcome, outcomeFieldsFromResult } from '@/tools/intentArg';\nimport { TOOL_OUTPUT_REF_PATTERN } from '@/tools/toolOutputReferences';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { isGoogleLike } from '@/utils/llm';\nimport { getMessageId } from '@/messages';\n\nconst LOCAL_CODING_BUNDLE_NAME_SET: ReadonlySet<string> = new Set(\n LOCAL_CODING_BUNDLE_NAMES\n);\n\ntype ReasoningSummaryLike = {\n summary?: Array<{ text?: string }>;\n};\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\nfunction isBatchSensitiveToolExecution(\n graph: StandardGraph,\n metadata?: Record<string, unknown>\n): boolean {\n /**\n * Resolve the hook-session id exactly the way ToolNode will: its hook\n * lookups read `config.configurable.run_id` ONLY, so that source wins here\n * too (a subagent child graph carries its own `graph.runId`, but its\n * ToolNode executes hooks under the PARENT's inherited configurable run\n * id). The metadata / graph.runId fallbacks only apply when no\n * configurable id exists and can only be conservative — a false positive\n * merely skips eager prestart.\n */\n const runId =\n (graph.config?.configurable?.run_id as string | undefined) ??\n (metadata?.run_id as string | undefined) ??\n graph.runId;\n return (\n graph.hookRegistry?.hasResultAlteringHooks(runId) === true ||\n graph.humanInTheLoop?.enabled === true\n );\n}\n\nfunction hasToolOutputReference(value: unknown): boolean {\n if (typeof value === 'string') {\n return TOOL_OUTPUT_REF_PATTERN.test(value);\n }\n if (Array.isArray(value)) {\n return value.some((item) => hasToolOutputReference(item));\n }\n if (value !== null && typeof value === 'object') {\n return Object.values(value as Record<string, unknown>).some((item) =>\n hasToolOutputReference(item)\n );\n }\n return false;\n}\n\nfunction isEagerExecutionExcludedTool(\n name: string,\n graph: StandardGraph\n): boolean {\n if (name === '') {\n return false;\n }\n const excluded = graph.eagerEventToolExecution?.excludeToolNames;\n if (excluded != null && excluded.includes(name)) {\n return true;\n }\n // A code-session participant writes to the shared sandbox, so it is\n // side-effecting: never prestart it speculatively (a revised/superseded turn\n // would leave the write applied). Implies exclusion without the host having\n // to also list the name in excludeToolNames.\n if (graph.codeSessionToolNames?.includes(name) === true) {\n return true;\n }\n // With stateful sessions on, execute_code/bash run against a DURABLE warm\n // runtime. Speculative prestart there is unsafe: if the model revises the\n // args, ToolNode discards the eager result but the mutation has already\n // landed in the session workspace, corrupting later runs. Stateless mode\n // uses a throwaway VM per call, so eager prestart stays safe there.\n return (\n graph.toolExecution?.sandbox?.statefulSessions === true &&\n CODE_EXECUTION_TOOLS.has(name)\n );\n}\n\nfunction isDirectGraphTool(\n name: string,\n agentContext: AgentContext | undefined\n): boolean {\n if (name.startsWith(Constants.LC_TRANSFER_TO_)) {\n return true;\n }\n return (\n (agentContext?.graphTools as t.GenericTool[] | undefined)?.some(\n (tool) => 'name' in tool && tool.name === name\n ) === true\n );\n}\n\nfunction isDirectLocalTool(name: string, graph: StandardGraph): boolean {\n const toolExecution = graph.toolExecution;\n const engine = toolExecution?.engine;\n if (\n toolExecution == null ||\n (engine !== 'local' && engine !== 'cloudflare-sandbox')\n ) {\n return false;\n }\n const includeCodingTools =\n engine === 'cloudflare-sandbox'\n ? toolExecution.cloudflare?.includeCodingTools\n : toolExecution.local?.includeCodingTools;\n if (includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE &&\n graph.codeSessionToolNames?.includes(name) !== true\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph, metadata)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (\n graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&\n graph.eventToolExecutionAvailable !== true\n ) {\n return false;\n }\n return true;\n}\n\nfunction hasFinalToolCallSignal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n const finishReason =\n metadata?.finish_reason ??\n metadata?.finishReason ??\n metadata?.stop_reason ??\n metadata?.stopReason;\n return finishReason === 'tool_calls' || finishReason === 'tool_use';\n}\n\nfunction canPrestartSequentialStreamedToolChunks(\n agentContext: AgentContext | undefined\n): boolean {\n // Anthropic seals each prior streamed tool-use block when the next indexed\n // tool-use block begins. Live Kimi/Moonshot streams can still revise prior\n // args after advancing to the next index, so keep those on the final\n // tool-call path unless they grow an explicit adapter seal.\n return agentContext?.provider === Providers.ANTHROPIC;\n}\n\nfunction hasExplicitStreamedToolCallSeals(\n chunk: Partial<AIMessageChunk>\n): boolean {\n return (\n getStreamedToolCallAdapter(\n chunk.response_metadata as Record<string, unknown> | undefined\n ) != null\n );\n}\n\n/**\n * True when a provider adapter marked every tool call on this chunk as\n * complete on arrival (seal kind `all`), e.g. Google GenAI / Vertex AI, whose\n * protocol delivers function calls as whole objects rather than arg deltas.\n */\nfunction hasOnArrivalToolCallSeal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n return (\n getStreamedToolCallAdapter(metadata) != null &&\n getStreamedToolCallSeal(metadata)?.kind === 'all'\n );\n}\n\nfunction hasDirectToolCallInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n}): boolean {\n const { graph, agentContext, toolCalls } = args;\n return toolCalls.some(\n (toolCall) =>\n toolCall.name !== '' &&\n (isDirectGraphTool(toolCall.name, agentContext) ||\n isDirectLocalTool(toolCall.name, graph))\n );\n}\n\nfunction hasPotentialDirectToolInStreamContext(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, agentContext } = args;\n const engine = graph.toolExecution?.engine;\n if (engine === 'local' || engine === 'cloudflare-sandbox') {\n return true;\n }\n if ((agentContext?.graphTools?.length ?? 0) > 0) {\n return true;\n }\n return false;\n}\n\nfunction hasDirectToolCallChunkInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCallChunks?: ToolCallChunk[];\n}): boolean {\n const { graph, agentContext, toolCallChunks } = args;\n return (\n toolCallChunks?.some(\n (toolCallChunk) =>\n toolCallChunk.name != null &&\n toolCallChunk.name !== '' &&\n (isDirectGraphTool(toolCallChunk.name, agentContext) ||\n isDirectLocalTool(toolCallChunk.name, graph))\n ) === true\n );\n}\n\nfunction hasDirectToolCallChunkStateInStep(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n stepKey: string;\n}): boolean {\n const { graph, agentContext, stepKey } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n const name = state.name;\n if (\n name != null &&\n name !== '' &&\n (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction isGoogleServerSideToolContentPart(\n contentPart: t.MessageContentComplex\n): boolean {\n return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';\n}\n\nfunction isTextContentPart(contentPart: t.MessageContentComplex): boolean {\n return contentPart.type?.startsWith(ContentTypes.TEXT) ?? false;\n}\n\nfunction isReasoningContentPart(contentPart: t.MessageContentComplex): boolean {\n return (\n (contentPart.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n contentPart.type === 'redacted_thinking'\n );\n}\n\nfunction getReasoningTextFromContentPart(\n contentPart: t.MessageContentComplex\n): string {\n return (\n (contentPart as t.ThinkingContentText).thinking ??\n (contentPart as Partial<t.GoogleReasoningContentText>).reasoning ??\n (contentPart as Partial<t.BedrockReasoningContentText>).reasoningText\n ?.text ??\n ''\n );\n}\n\nfunction getReasoningTextFromChunk(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n): string {\n const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (typeof reasoning === 'string') {\n return reasoning;\n }\n return reasoning?.summary?.[0]?.text ?? '';\n}\n\nconst googleServerSideToolStepIdsByGraph = new WeakMap<\n StandardGraph,\n Set<string>\n>();\n\nfunction markGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): void {\n const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();\n stepIds.add(stepId);\n googleServerSideToolStepIdsByGraph.set(graph, stepIds);\n}\n\nfunction isGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): boolean {\n return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;\n}\n\nfunction shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n}: {\n graph: StandardGraph;\n stepId: string;\n runStep?: t.RunStep;\n content: string | t.MessageContentComplex[];\n}): boolean {\n if (\n runStep?.type !== StepTypes.MESSAGE_CREATION ||\n !isGoogleServerSideToolMessageStep(graph, stepId)\n ) {\n return false;\n }\n if (typeof content === 'string') {\n return true;\n }\n return (\n content.every((c) => isTextContentPart(c)) ||\n content.every((c) => isReasoningContentPart(c))\n );\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n metadata?: Record<string, unknown>;\n}): Promise<string> {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n return graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n}\n\nasync function dispatchMessageContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n for (const contentPart of content) {\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n if (isGoogleServerSideToolContentPart(contentPart)) {\n markGoogleServerSideToolMessageStep(graph, currentStepId);\n }\n await graph.dispatchMessageDelta(\n currentStepId,\n {\n content: [contentPart],\n },\n metadata\n );\n }\n}\n\nasync function dispatchReasoningContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n if (content.length === 0) {\n return;\n }\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n await graph.dispatchReasoningDelta(\n currentStepId,\n {\n content,\n },\n metadata\n );\n}\n\nasync function dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n const reasoningContent: t.MessageContentComplex[] = [];\n const reasoningText = getReasoningTextFromChunk(chunk, agentContext);\n if (reasoningText !== '') {\n reasoningContent.push({\n type: ContentTypes.THINK,\n think: reasoningText,\n });\n }\n reasoningContent.push(\n ...content\n .filter((contentPart) => isReasoningContentPart(contentPart))\n .map((contentPart) => ({\n type: ContentTypes.THINK,\n think: getReasoningTextFromContentPart(contentPart),\n }))\n .filter((contentPart) => contentPart.think !== '')\n );\n await dispatchReasoningContentParts({\n graph,\n stepKey,\n content: reasoningContent,\n metadata,\n });\n\n const messageContent = content.filter(\n (contentPart) =>\n isTextContentPart(contentPart) ||\n isGoogleServerSideToolContentPart(contentPart)\n );\n await dispatchMessageContentParts({\n graph,\n stepKey,\n content: messageContent,\n metadata,\n });\n}\n\ntype EagerToolExecutionEntry = {\n id: string;\n toolName: string;\n coercedArgs: Record<string, unknown>;\n request: t.ToolCallRequest;\n};\n\nfunction createEagerToolExecutionPlan(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): EagerToolExecutionEntry[] | undefined {\n const {\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting = false,\n } = args;\n if (\n !isEagerToolExecutionEnabledForBatch({\n graph,\n metadata,\n agentContext,\n })\n ) {\n return undefined;\n }\n\n if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {\n return undefined;\n }\n if (\n graph.toolOutputReferences?.enabled === true &&\n toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))\n ) {\n return undefined;\n }\n\n const unstartedToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n // Drop host-excluded tools only AFTER the batch-level guards above have run\n // against the full batch, so excluding a call never hides a sibling direct\n // tool from `hasDirectToolCallInBatch`. Excluded calls fall through to normal\n // ToolNode execution; siblings may still eager-execute.\n const candidateToolCalls = unstartedToolCalls.filter(\n (toolCall) => !isEagerExecutionExcludedTool(toolCall.name, graph)\n );\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n /* No runtimeSessionHint here on purpose: the eager path is speculative, and\n * code-session tools (the only ones that carry a hint) are excluded from\n * eager prestart entirely when stateful sessions are on — see\n * isEagerExecutionExcludedTool. The durable runtime is only ever touched by\n * the committed ToolNode path. */\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const records: t.EagerEventToolExecution[] = [];\n const promise: Promise<t.EagerEventToolExecutionOutcome> = new Promise<\n t.ToolExecuteResult[]\n >((resolve, reject) => {\n let dispatchSettled = false;\n let resultSettled = false;\n let settledResults: t.ToolExecuteResult[] | undefined;\n const maybeResolve = (): void => {\n if (dispatchSettled && resultSettled) {\n resolve(settledResults ?? []);\n }\n };\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: entries.map((entry) => entry.request),\n userId: graph.config?.configurable?.user_id as string | undefined,\n agentId: agentContext?.agentId,\n configurable: graph.config?.configurable as\n | Record<string, unknown>\n | undefined,\n metadata,\n resolve: (results): void => {\n resultSettled = true;\n settledResults = results;\n maybeResolve();\n },\n reject,\n };\n\n void safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n graph.config\n )\n .then(() => {\n dispatchSettled = true;\n maybeResolve();\n })\n .catch(reject);\n }).then(\n async (results): Promise<t.EagerEventToolExecutionOutcome> => {\n await dispatchEagerToolCompletions({\n graph,\n agentContext,\n records,\n results,\n });\n return { results };\n },\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n const record: t.EagerEventToolExecution = {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\n };\n records.push(record);\n graph.eagerEventToolExecutions.set(entry.id, record);\n }\n}\n\nasync function dispatchEagerToolCompletions(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n records: t.EagerEventToolExecution[];\n results: t.ToolExecuteResult[];\n}): Promise<void> {\n const { graph, agentContext, records, results } = args;\n const recordById = new Map(\n records.map((record) => [record.toolCallId, record])\n );\n const maxToolResultChars =\n agentContext?.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext?.maxContextTokens);\n\n for (const result of results) {\n const record = recordById.get(result.toolCallId);\n if (record == null) {\n continue;\n }\n if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {\n continue;\n }\n const stepId =\n record.request.stepId ??\n graph.toolCallStepIds.get(result.toolCallId) ??\n '';\n if (stepId === '') {\n continue;\n }\n let output: string;\n if (result.status === 'error') {\n output = truncateToolResultContent(\n `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`,\n maxToolResultChars\n );\n } else if (typeof result.content === 'string') {\n output = truncateToolResultContent(result.content, maxToolResultChars);\n } else {\n output = serializeStructuredValueBounded(\n result.content,\n maxToolResultChars\n ).content;\n }\n const outcome = resolveToolOutcome(\n record.request.args,\n outcomeFieldsFromResult(result),\n { isError: result.status === 'error' }\n );\n\n try {\n const dispatched = await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: record.request.turn ?? 0,\n type: 'tool_call' as const,\n eager: true,\n tool_call: {\n args: serializeToolContentBounded(\n record.request.args,\n maxToolResultChars\n ),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\n ...(outcome != null && { outcome }),\n } as t.ProcessedToolCall,\n },\n },\n graph.config\n );\n if (dispatched === false) {\n continue;\n }\n record.completionDispatched = true;\n } catch (error) {\n // Let ToolNode dispatch the completion through the normal path later.\n\n console.warn(\n `[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`,\n error instanceof Error ? error.message : error\n );\n }\n }\n}\n\nfunction getEagerToolChunkKey(\n stepKey: string,\n toolCallChunk: ToolCallChunk\n): string | undefined {\n let chunkKey: string | undefined;\n if (typeof toolCallChunk.index === 'number') {\n chunkKey = String(toolCallChunk.index);\n } else if (toolCallChunk.id != null && toolCallChunk.id !== '') {\n chunkKey = toolCallChunk.id;\n }\n if (chunkKey == null) {\n return undefined;\n }\n return `${stepKey}\\u0000${chunkKey}`;\n}\n\nfunction getEagerToolChunkIndex(\n toolCallChunk: ToolCallChunk\n): number | undefined {\n return typeof toolCallChunk.index === 'number'\n ? toolCallChunk.index\n : undefined;\n}\n\nfunction pruneEagerToolCallChunkStates(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallIds?: ReadonlySet<string>;\n clearStep?: boolean;\n}): void {\n const { graph, stepKey, toolCallIds, clearStep = false } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (\n clearStep ||\n (state.id != null && toolCallIds?.has(state.id) === true)\n ) {\n graph.eagerEventToolCallChunks.delete(key);\n }\n }\n}\n\nfunction isEagerToolChunkStateComplete(\n state: t.EagerEventToolCallChunkState\n): boolean {\n return (\n state.id != null &&\n state.id !== '' &&\n state.name != null &&\n state.name !== '' &&\n coerceRecordArgs(state.argsText) != null\n );\n}\n\nfunction mergeToolCallArgsText(existing: string, incoming: string): string {\n if (incoming === '') {\n return existing;\n }\n if (existing === '') {\n return incoming;\n }\n if (incoming === existing) {\n try {\n JSON.parse(incoming);\n return incoming;\n } catch {\n return `${existing}${incoming}`;\n }\n }\n if (incoming.startsWith(existing)) {\n return incoming;\n }\n if (existing.startsWith(incoming)) {\n return existing;\n }\n try {\n JSON.parse(existing);\n JSON.parse(incoming);\n return incoming;\n } catch {\n // Fall through to delta concatenation.\n }\n for (\n let overlap = Math.min(existing.length, incoming.length);\n overlap >= 8;\n overlap -= 1\n ) {\n if (existing.endsWith(incoming.slice(0, overlap))) {\n return `${existing}${incoming.slice(overlap)}`;\n }\n }\n return `${existing}${incoming}`;\n}\n\nfunction recordEagerToolCallChunks(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n}): void {\n const { graph, stepKey, toolCallChunks } = args;\n if (toolCallChunks == null || toolCallChunks.length === 0) {\n return;\n }\n\n // Streamed args can be cumulative and parseable before the provider has\n // sealed the call. Recording stays separate from dispatch so the boundary\n // logic can wait for either a later tool index or the final tool-call signal.\n for (const toolCallChunk of toolCallChunks) {\n const key = getEagerToolChunkKey(stepKey, toolCallChunk);\n if (key == null) {\n continue;\n }\n\n const incomingId =\n toolCallChunk.id != null && toolCallChunk.id !== ''\n ? toolCallChunk.id\n : undefined;\n const incomingName =\n toolCallChunk.name != null && toolCallChunk.name !== ''\n ? toolCallChunk.name\n : undefined;\n const previous = graph.eagerEventToolCallChunks.get(key);\n const shouldReset =\n previous != null &&\n ((incomingId != null &&\n previous.id != null &&\n incomingId !== previous.id) ||\n (incomingName != null &&\n previous.name != null &&\n incomingName !== previous.name));\n const existing =\n previous == null || shouldReset\n ? {\n argsText: '',\n }\n : previous;\n const id = incomingId ?? existing.id;\n const name = incomingName ?? existing.name;\n const incomingArgs = toolCallChunk.args ?? '';\n const isRepeatedObservedFragment =\n incomingArgs !== '' &&\n incomingArgs.length > 1 &&\n incomingArgs === existing.lastArgsFragment;\n const argsText = isRepeatedObservedFragment\n ? existing.argsText\n : mergeToolCallArgsText(existing.argsText, incomingArgs);\n const next = {\n id,\n name,\n argsText,\n index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,\n lastArgsFragment:\n incomingArgs !== '' ? incomingArgs : existing.lastArgsFragment,\n };\n graph.eagerEventToolCallChunks.set(key, next);\n }\n}\n\nfunction getStreamedReadyToolCalls(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): ToolCall[] {\n const {\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal = false,\n sealAll = false,\n } = args;\n const currentIndices = new Set<number>();\n for (const toolCallChunk of toolCallChunks ?? []) {\n const index = getEagerToolChunkIndex(toolCallChunk);\n if (index != null) {\n currentIndices.add(index);\n }\n }\n const highestCurrentIndex =\n currentIndices.size > 0 ? Math.max(...currentIndices) : undefined;\n const prefix = `${stepKey}\\u0000`;\n const readyEntries: Array<{\n key: string;\n state: t.EagerEventToolCallChunkState;\n }> = [];\n\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {\n graph.eagerEventToolCallChunks.delete(key);\n continue;\n }\n if (!isEagerToolChunkStateComplete(state)) {\n continue;\n }\n const isSealedByLaterChunk =\n allowSequentialSeal &&\n highestCurrentIndex != null &&\n state.index != null &&\n state.index < highestCurrentIndex &&\n !currentIndices.has(state.index);\n const isSealedExplicitly =\n seal?.kind === 'single' &&\n ((seal.id != null && state.id === seal.id) ||\n (seal.index != null && state.index === seal.index));\n if (\n sealAll ||\n seal?.kind === 'all' ||\n isSealedByLaterChunk ||\n isSealedExplicitly\n ) {\n readyEntries.push({ key, state });\n }\n }\n\n pruneEagerToolCallChunkStates({\n graph,\n stepKey,\n toolCallIds: new Set(\n readyEntries\n .map(({ state }) => state.id)\n .filter((id): id is string => id != null && id !== '')\n ),\n });\n if (sealAll) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n\n return readyEntries\n .sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0))\n .flatMap(({ state }) => {\n const args = coerceRecordArgs(state.argsText);\n if (args == null) {\n return [];\n }\n return [\n {\n id: state.id,\n name: state.name ?? '',\n args,\n },\n ];\n });\n}\n\nfunction startReadyStreamedEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): void {\n const {\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n } = args;\n if (\n hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||\n hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||\n hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||\n !isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })\n ) {\n return;\n }\n const toolCalls = getStreamedReadyToolCalls({\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n });\n if (toolCalls.length === 0) {\n return;\n }\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting: true,\n });\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 isGoogleLike(provider) &&\n Array.isArray(chunk?.content) &&\n chunk.content.some((c) => isGoogleServerSideToolContentPart(c))\n ) {\n return chunk.content;\n }\n\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 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 const reasoningContent = chunk?.additional_kwargs?.reasoning_content as\n | string\n | undefined;\n if (reasoningContent != null && reasoningContent !== '') {\n return reasoningContent;\n }\n return chunk?.content;\n }\n const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey] as\n | string\n | undefined;\n if (\n typeof chunk?.content === 'string' &&\n chunk.content !== '' &&\n keyedReasoning != null &&\n keyedReasoning !== ''\n ) {\n return chunk.content;\n }\n return ((keyedReasoning as string | undefined) ?? '') || chunk?.content;\n}\n\nfunction isDisableStreamingEnabled(\n clientOptions: t.ClientOptions | undefined\n): boolean {\n return (\n clientOptions != null &&\n 'disableStreaming' in clientOptions &&\n clientOptions.disableStreaming === true\n );\n}\n\nfunction hasReasoningContent(\n value: string | ReasoningSummaryLike | object[] | null | undefined\n): boolean {\n if (typeof value === 'string') {\n return value !== '';\n }\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n if (value == null) {\n return false;\n }\n return (\n value.summary?.some(\n (summary) => summary.text != null && summary.text.length > 0\n ) === true\n );\n}\n\nfunction shouldDeferMixedFinalReasoningChunk({\n chunk,\n agentContext,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n}): boolean {\n if (\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n typeof chunk.content !== 'string' ||\n chunk.content === ''\n ) {\n return false;\n }\n const additionalKwargs = chunk.additional_kwargs;\n if (\n agentContext.provider === Providers.OPENROUTER &&\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n ) {\n return true;\n }\n if (!isDisableStreamingEnabled(agentContext.clientOptions)) {\n return false;\n }\n return (\n hasReasoningContent(\n additionalKwargs?.[agentContext.reasoningKey] as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning_content as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n );\n}\n\nfunction hasCurrentTextDeltaStep({\n graph,\n metadata,\n}: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (metadata == null) {\n return false;\n }\n const baseStepKey = graph.getStepBaseKey(metadata);\n for (const [stepKey, stepIds] of graph.stepKeyIds) {\n if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {\n continue;\n }\n if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) {\n return true;\n }\n }\n return false;\n}\n\nfunction shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (\n agentContext.provider !== Providers.OPENROUTER ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n (chunk.content != null && chunk.content !== '')\n ) {\n return false;\n }\n return (\n (hasReasoningContent(chunk.additional_kwargs?.reasoning as string) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_content as string\n ) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_details as object[]\n )) &&\n hasCurrentTextDeltaStep({ graph, metadata })\n );\n}\n\n/**\n * Brands a handler as one that dispatches content parts for the SDK — either\n * `ChatModelStreamHandler` itself or a wrapper forwarding to one.\n *\n * Identity alone is not a usable contract here. Hosts compose and wrap\n * handlers (`composeEventHandlers`, `createRunHandlers`), and every wrapper\n * fails `instanceof` while still driving the same dispatch. A brand survives\n * wrapping, so \"does this handler own content-part dispatch\" can be answered\n * about a value the SDK did not construct.\n */\nexport const SDK_STREAM_DISPATCH = Symbol.for(\n '@librechat/agents:chatModelStreamDispatch'\n);\n\n/** True when `handler` is, or forwards to, the SDK's stream dispatcher. */\nexport function dispatchesChatModelStream(handler?: t.EventHandler): boolean {\n if (handler == null) {\n return false;\n }\n if (handler instanceof ChatModelStreamHandler) {\n return true;\n }\n return Reflect.get(handler, SDK_STREAM_DISPATCH) === true;\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n readonly [SDK_STREAM_DISPATCH] = true;\n\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\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\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 if (shouldDeferMixedFinalReasoningChunk({ chunk, agentContext })) {\n return;\n }\n if (\n shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n })\n ) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n const stepKey = graph.getStepKey(metadata);\n let hasToolCalls = false;\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const hasGoogleServerSideToolContent =\n isGoogleLike(agentContext.provider) &&\n Array.isArray(content) &&\n content.some((c) => isGoogleServerSideToolContentPart(c));\n if (hasGoogleServerSideToolContent && Array.isArray(content)) {\n await dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n });\n }\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 if (hasFinalToolCallSignal(chunk)) {\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n if (!hasToolCallChunks) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n } else if (\n hasOnArrivalToolCallSeal(chunk) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext })\n ) {\n // Providers like Google never signal `tool_calls`/`tool_use` as the\n // finish reason, but their adapters seal calls on arrival — prestart\n // these mid-stream under the same direct-tool guard as streamed\n // chunk sealing.\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n }\n }\n\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 graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\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 const streamedToolCallSeal = getStreamedToolCallSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const allowSequentialSeal =\n canPrestartSequentialStreamedToolChunks(agentContext) ||\n streamedToolCallAdapterAllowsSequentialSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const canStreamEager =\n (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext }) &&\n isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext });\n if (canStreamEager) {\n recordEagerToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n if (canStreamEager) {\n startReadyStreamedEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n seal: streamedToolCallSeal,\n allowSequentialSeal,\n sealAll: hasFinalToolCallSignal(chunk),\n });\n }\n }\n\n if (isEmptyContent) {\n return;\n }\n\n if (hasGoogleServerSideToolContent) {\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 let stepId = graph.getStepIdByKey(stepKey);\n let runStep = graph.getRunStep(stepId);\n if (\n shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n })\n ) {\n stepId = await dispatchMessageCreationStep({ graph, stepKey, metadata });\n runStep = graph.getRunStep(stepId);\n }\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(\n stepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n },\n metadata\n );\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n },\n metadata\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(\n newStepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n },\n metadata\n );\n }\n } else {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n },\n metadata\n );\n }\n } else if (content.every((c) => isTextContentPart(c))) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content,\n },\n metadata\n );\n } else if (content.every((c) => isReasoningContentPart(c))) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\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\n ?.text ??\n '',\n })),\n },\n metadata\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 (typeof chunk.additional_kwargs?.reasoning_content === 'string' &&\n chunk.additional_kwargs.reasoning_content !== ''))\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 type ToolStepContentState = {\n indices: Set<number>;\n chunkIndices: Map<number, number>;\n unclaimedIndices: Set<number>;\n unboundIndices: Set<number>;\n callIdsByIndex: Map<number, string>;\n };\n\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallContentIndexMap = new Map<string, number>();\n const sourceContentIndexMap = new Map<number, number>();\n const toolStepContentMap = new Map<string, ToolStepContentState>();\n let indexedContentLength = 0;\n /** Physical append cursor; event/chunk indices are correlation keys, not array offsets. */\n let nextContentIndex = 0;\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 /** A delta's content may carry several parts (e.g. Google server-side tool\n * chunks emit multiple reasoning entries at once); every entry must reach\n * the step's slot, in order, or streamed text is silently lost. */\n const getDeltaContentParts = (\n content?: t.MessageDelta['content'] | t.MessageContentComplex\n ): t.MessageContentComplex[] => {\n if (content == null) {\n return [];\n }\n return Array.isArray(content) ? content : [content];\n };\n const indexContentPart = (\n index: number,\n contentPart?: t.MessageContentComplex\n ): void => {\n if (contentPart == null) {\n return;\n }\n if (contentPart.type === ContentTypes.TOOL_CALL) {\n const toolCallId = contentPart.tool_call.id;\n if (toolCallId != null && toolCallId !== '') {\n toolCallContentIndexMap.set(toolCallId, index);\n }\n }\n const hasAgentId =\n contentPart.agentId != null && contentPart.agentId !== '';\n const hasGroupId = contentPart.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = contentPart.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = contentPart.groupId;\n }\n contentMetaMap.set(index, existingMeta);\n }\n };\n const syncSeededContent = (): void => {\n /** Hosts can seed pre-pause content after creating the aggregator. */\n for (\n let index = indexedContentLength;\n index < contentParts.length;\n index++\n ) {\n indexContentPart(index, contentParts[index]);\n }\n indexedContentLength = contentParts.length;\n nextContentIndex = Math.max(nextContentIndex, contentParts.length);\n };\n const getToolCallContentIndex = (\n toolCallId: string | undefined\n ): number | undefined => {\n if (toolCallId == null || toolCallId === '') {\n return undefined;\n }\n syncSeededContent();\n return toolCallContentIndexMap.get(toolCallId);\n };\n const allocateContentIndex = (minimumIndex = 0): number => {\n syncSeededContent();\n const contentIndex = Math.max(nextContentIndex, minimumIndex);\n nextContentIndex = contentIndex + 1;\n return contentIndex;\n };\n const resolveSourceContentIndex = (sourceIndex: number): number => {\n const existingIndex = sourceContentIndexMap.get(sourceIndex);\n if (existingIndex != null) {\n return existingIndex;\n }\n const contentIndex = allocateContentIndex(sourceIndex);\n sourceContentIndexMap.set(sourceIndex, contentIndex);\n return contentIndex;\n };\n const createToolStepContentState = (\n contentIndex: number\n ): ToolStepContentState => ({\n indices: new Set<number>([contentIndex]),\n chunkIndices: new Map<number, number>(),\n unclaimedIndices: new Set<number>([contentIndex]),\n unboundIndices: new Set<number>([contentIndex]),\n callIdsByIndex: new Map<number, string>(),\n });\n const registerToolContentIndex = (\n state: ToolStepContentState,\n contentIndex: number,\n toolCallId?: string\n ): void => {\n if (!state.indices.has(contentIndex)) {\n state.indices.add(contentIndex);\n state.unclaimedIndices.add(contentIndex);\n state.unboundIndices.add(contentIndex);\n }\n if (toolCallId != null && toolCallId !== '') {\n const existingToolCallId = state.callIdsByIndex.get(contentIndex);\n if (\n existingToolCallId != null &&\n existingToolCallId !== toolCallId &&\n toolCallContentIndexMap.get(existingToolCallId) === contentIndex\n ) {\n toolCallContentIndexMap.delete(existingToolCallId);\n }\n toolCallContentIndexMap.set(toolCallId, contentIndex);\n state.callIdsByIndex.set(contentIndex, toolCallId);\n state.unboundIndices.delete(contentIndex);\n }\n };\n const takeFirstIndex = (indices: Set<number>): number | undefined => {\n const contentIndex = indices.values().next().value;\n if (contentIndex != null) {\n indices.delete(contentIndex);\n }\n return contentIndex;\n };\n const setContentMeta = (index: number, runStep: t.RunStep): void => {\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (!hasAgentId && !hasGroupId) {\n return;\n }\n const existingMeta = contentMetaMap.get(index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(index, existingMeta);\n };\n const applyContentMetadata = (index: number): void => {\n const contentPart = contentParts[index];\n if (contentPart == null) {\n return;\n }\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n contentPart.agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n contentPart.groupId = meta.groupId;\n }\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 (partType === 'toolCall' || partType === 'toolResponse') {\n contentParts[index] = contentPart;\n } else if (partType === ContentTypes.SUMMARY) {\n const currentSummary = contentParts[index] as\n | t.SummaryContentBlock\n | undefined;\n const incoming = contentPart as t.SummaryContentBlock;\n contentParts[index] = {\n ...incoming,\n content: [\n ...(currentSummary?.content ?? []),\n ...(incoming.content ?? []),\n ],\n };\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 // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart & t.PartMetadata;\n })\n | undefined;\n if (!finalUpdate && existingContent?.tool_call?.progress === 1) {\n return;\n }\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (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 const existingToolCallId = existingContent?.tool_call?.id;\n if (\n existingToolCallId != null &&\n existingToolCallId !== '' &&\n existingToolCallId !== id &&\n toolCallContentIndexMap.get(existingToolCallId) === index\n ) {\n toolCallContentIndexMap.delete(existingToolCallId);\n }\n\n const newToolCall: ToolCall & t.PartMetadata & { outcome?: string } = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n const auth =\n contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;\n const expiresAt =\n contentPart.tool_call.expires_at ??\n existingContent?.tool_call?.expires_at;\n if (auth != null) {\n newToolCall.auth = auth;\n newToolCall.expires_at = expiresAt;\n }\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n const outcome = (contentPart.tool_call as t.ToolCallPart).outcome;\n if (outcome != null) {\n newToolCall.outcome = outcome;\n }\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n indexContentPart(index, contentParts[index]);\n indexedContentLength = Math.max(indexedContentLength, index + 1);\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 applyContentMetadata(index);\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.ReasoningDeltaEvent\n | t.RunStepDeltaEvent\n | t.SummarizeDeltaData\n | t.SummarizeCompleteEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_SUMMARIZE_DELTA) {\n const deltaData = data as t.SummarizeDeltaData;\n const runStep = stepMap.get(deltaData.id);\n if (!runStep) {\n console.warn('No run step found for summarize delta event');\n return;\n }\n updateContent(runStep.index, deltaData.delta.summary);\n return;\n }\n\n if (event === GraphEvents.ON_SUMMARIZE_COMPLETE) {\n const completeData = data as t.SummarizeCompleteEvent;\n const summary = completeData.summary;\n if (!summary?.boundary) {\n return;\n }\n const runStep = stepMap.get(summary.boundary.messageId);\n if (!runStep) {\n return;\n }\n // Replace accumulated delta text with the authoritative final summary.\n // Multi-stage summarization streams deltas from each chunk, which\n // concatenate in updateContent. This event carries only the correct\n // final text from the last stage.\n contentParts[runStep.index] = summary;\n applyContentMetadata(runStep.index);\n return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const incomingRunStep = data as t.RunStep;\n const toolCalls =\n incomingRunStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (incomingRunStep.stepDetails.tool_calls as ToolCall[] | undefined)\n : undefined;\n syncSeededContent();\n let runStepIndex: number;\n const toolCallIndices: number[] = [];\n if (toolCalls && toolCalls.length > 0) {\n for (let index = 0; index < toolCalls.length; index++) {\n const toolCallId = toolCalls[index].id;\n let contentIndex = getToolCallContentIndex(toolCallId);\n if (contentIndex == null) {\n contentIndex =\n index === 0\n ? resolveSourceContentIndex(incomingRunStep.index)\n : allocateContentIndex();\n } else if (index === 0) {\n sourceContentIndexMap.set(incomingRunStep.index, contentIndex);\n }\n toolCallIndices.push(contentIndex);\n }\n runStepIndex = toolCallIndices[0];\n } else {\n runStepIndex = resolveSourceContentIndex(incomingRunStep.index);\n }\n const runStep =\n runStepIndex !== incomingRunStep.index\n ? { ...incomingRunStep, index: runStepIndex }\n : incomingRunStep;\n stepMap.set(runStep.id, runStep);\n\n setContentMeta(runStep.index, runStep);\n\n if (runStep.summary != null) {\n updateContent(runStep.index, runStep.summary);\n }\n\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS) {\n const toolStepContent =\n toolStepContentMap.get(runStep.id) ??\n createToolStepContentState(runStep.index);\n registerToolContentIndex(toolStepContent, runStep.index);\n (runStep.stepDetails.tool_calls as ToolCall[] | undefined)?.forEach(\n (toolCall, toolCallIndex) => {\n const contentIndex =\n toolCallIndices[toolCallIndex] ?? runStep.index;\n const toolCallId = toolCall.id ?? '';\n registerToolContentIndex(toolStepContent, contentIndex, toolCallId);\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 setContentMeta(contentIndex, runStep);\n updateContent(contentIndex, contentPart);\n }\n );\n toolStepContentMap.set(runStep.id, toolStepContent);\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 for (const contentPart of getDeltaContentParts(messageDelta.delta.content)) {\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 const contentIndex = resolveSourceContentIndex(\n contentPart.agent_update.index\n );\n updateContent(contentIndex, {\n ...contentPart,\n agent_update: {\n ...contentPart.agent_update,\n index: contentIndex,\n },\n });\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 for (const contentPart of getDeltaContentParts(reasoningDelta.delta.content)) {\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\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 const toolStepContent =\n toolStepContentMap.get(runStepDelta.id) ??\n createToolStepContentState(runStep.index);\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const chunkIndex =\n typeof toolCallDelta.index === 'number'\n ? toolCallDelta.index\n : undefined;\n const explicitToolCallId =\n toolCallDelta.id != null && toolCallDelta.id !== ''\n ? toolCallDelta.id\n : undefined;\n let contentIndex = getToolCallContentIndex(explicitToolCallId);\n if (contentIndex == null && chunkIndex != null) {\n contentIndex = toolStepContent.chunkIndices.get(chunkIndex);\n }\n const soleContentIndex =\n toolStepContent.indices.size === 1\n ? toolStepContent.indices.values().next().value\n : undefined;\n if (\n contentIndex == null &&\n explicitToolCallId == null &&\n soleContentIndex != null &&\n (chunkIndex == null ||\n toolStepContent.callIdsByIndex.has(soleContentIndex) ||\n toolStepContent.unclaimedIndices.has(soleContentIndex))\n ) {\n contentIndex = soleContentIndex;\n }\n if (contentIndex == null) {\n if (chunkIndex == null && explicitToolCallId == null) {\n console.warn(\n 'No tool call id or chunk index found for run step delta event'\n );\n return;\n }\n contentIndex =\n explicitToolCallId == null\n ? takeFirstIndex(toolStepContent.unclaimedIndices)\n : takeFirstIndex(toolStepContent.unboundIndices);\n contentIndex ??= allocateContentIndex();\n }\n registerToolContentIndex(\n toolStepContent,\n contentIndex,\n explicitToolCallId\n );\n if (chunkIndex != null) {\n toolStepContent.chunkIndices.set(chunkIndex, contentIndex);\n toolStepContent.unclaimedIndices.delete(contentIndex);\n toolStepContent.unboundIndices.delete(contentIndex);\n }\n const toolCallId =\n explicitToolCallId ??\n toolStepContent.callIdsByIndex.get(contentIndex);\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 auth: runStepDelta.delta.auth,\n expires_at: runStepDelta.delta.expires_at,\n },\n };\n\n setContentMeta(contentIndex, runStep);\n updateContent(contentIndex, contentPart);\n });\n toolStepContentMap.set(runStepDelta.id, toolStepContent);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as {\n result:\n | t.ToolEndEvent\n | (t.SummaryCompleted & { id: string; index: number });\n };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n\n if (result.type === ContentTypes.SUMMARY && 'summary' in result) {\n if (!runStep) {\n console.warn('No run step or runId found for completed step event');\n return;\n }\n contentParts[runStep.index] = result.summary as t.MessageContentComplex;\n applyContentMetadata(runStep.index);\n } else if ('tool_call' in result) {\n let contentIndex = getToolCallContentIndex(result.tool_call.id);\n if (contentIndex == null && runStep != null) {\n const toolStepContent = toolStepContentMap.get(runStep.id);\n if (toolStepContent?.indices.size === 1) {\n contentIndex = toolStepContent.indices.values().next().value;\n } else if (toolStepContent == null) {\n const declaredToolCalls =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? runStep.stepDetails.tool_calls\n : undefined;\n if ((declaredToolCalls?.length ?? 0) <= 1) {\n contentIndex = runStep.index;\n }\n }\n }\n if (contentIndex == null) {\n console.warn(\n 'No run step or tool call found for completed step event'\n );\n return;\n }\n if (runStep != null) {\n setContentMeta(contentIndex, runStep);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: (result as t.ToolEndEvent).tool_call,\n };\n updateContent(contentIndex, contentPart, true);\n }\n }\n };\n\n return { contentParts, aggregateContent,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MAAM,kBAAkB,mBAAmB,IAAI,QAAQ,EAAE;KACzD,IAAI,iBAAiB,QAAQ,SAAS,GACpC,eAAe,gBAAgB,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;UAClD,IAAI,mBAAmB;YAE1B,QAAQ,YAAY,SAAA,eAChB,QAAQ,YAAY,aACpB,KAAA,EAAA,EACkB,UAAU,MAAM,GACtC,eAAe,QAAQ;KAAA;IAG7B;IACA,IAAI,gBAAgB,MAAM;KACxB,QAAQ,KACN,yDACF;KACA;IACF;IACA,IAAI,WAAW,MACb,eAAe,cAAc,OAAO;IAEtC,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAY,OAA0B;IACxC;IACA,cAAc,cAAc,aAAa,IAAI;GAC/C;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
1
+ {"version":3,"file":"stream.mjs","names":["completeData"],"sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n streamedToolCallAdapterAllowsSequentialSeal,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n serializeStructuredValueBounded,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { resolveToolOutcome, outcomeFieldsFromResult } from '@/tools/intentArg';\nimport { TOOL_OUTPUT_REF_PATTERN } from '@/tools/toolOutputReferences';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { isGoogleLike } from '@/utils/llm';\nimport { getMessageId } from '@/messages';\n\nconst LOCAL_CODING_BUNDLE_NAME_SET: ReadonlySet<string> = new Set(\n LOCAL_CODING_BUNDLE_NAMES\n);\n\ntype ReasoningSummaryLike = {\n summary?: Array<{ text?: string }>;\n};\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\nfunction isBatchSensitiveToolExecution(\n graph: StandardGraph,\n metadata?: Record<string, unknown>\n): boolean {\n /**\n * Resolve the hook-session id exactly the way ToolNode will: its hook\n * lookups read `config.configurable.run_id` ONLY, so that source wins here\n * too (a subagent child graph carries its own `graph.runId`, but its\n * ToolNode executes hooks under the PARENT's inherited configurable run\n * id). The metadata / graph.runId fallbacks only apply when no\n * configurable id exists and can only be conservative — a false positive\n * merely skips eager prestart.\n */\n const runId =\n (graph.config?.configurable?.run_id as string | undefined) ??\n (metadata?.run_id as string | undefined) ??\n graph.runId;\n return (\n graph.hookRegistry?.hasResultAlteringHooks(runId) === true ||\n graph.humanInTheLoop?.enabled === true\n );\n}\n\nfunction hasToolOutputReference(value: unknown): boolean {\n if (typeof value === 'string') {\n return TOOL_OUTPUT_REF_PATTERN.test(value);\n }\n if (Array.isArray(value)) {\n return value.some((item) => hasToolOutputReference(item));\n }\n if (value !== null && typeof value === 'object') {\n return Object.values(value as Record<string, unknown>).some((item) =>\n hasToolOutputReference(item)\n );\n }\n return false;\n}\n\nfunction isEagerExecutionExcludedTool(\n name: string,\n graph: StandardGraph\n): boolean {\n if (name === '') {\n return false;\n }\n const excluded = graph.eagerEventToolExecution?.excludeToolNames;\n if (excluded != null && excluded.includes(name)) {\n return true;\n }\n // Run-scoped circuit breaker: once a prestart for this tool diverged from\n // the final request (\"changed after eager execution started\"), stop\n // prestarting it so the model's retry executes normally instead of\n // re-diverging in a loop (LibreChat#14371).\n if (graph.eagerEventToolSuppressions?.has(name) === true) {\n return true;\n }\n // A code-session participant writes to the shared sandbox, so it is\n // side-effecting: never prestart it speculatively (a revised/superseded turn\n // would leave the write applied). Implies exclusion without the host having\n // to also list the name in excludeToolNames.\n if (graph.codeSessionToolNames?.includes(name) === true) {\n return true;\n }\n // With stateful sessions on, execute_code/bash run against a DURABLE warm\n // runtime. Speculative prestart there is unsafe: if the model revises the\n // args, ToolNode discards the eager result but the mutation has already\n // landed in the session workspace, corrupting later runs. Stateless mode\n // uses a throwaway VM per call, so eager prestart stays safe there.\n return (\n graph.toolExecution?.sandbox?.statefulSessions === true &&\n CODE_EXECUTION_TOOLS.has(name)\n );\n}\n\nfunction isDirectGraphTool(\n name: string,\n agentContext: AgentContext | undefined\n): boolean {\n if (name.startsWith(Constants.LC_TRANSFER_TO_)) {\n return true;\n }\n return (\n (agentContext?.graphTools as t.GenericTool[] | undefined)?.some(\n (tool) => 'name' in tool && tool.name === name\n ) === true\n );\n}\n\nfunction isDirectLocalTool(name: string, graph: StandardGraph): boolean {\n const toolExecution = graph.toolExecution;\n const engine = toolExecution?.engine;\n if (\n toolExecution == null ||\n (engine !== 'local' && engine !== 'cloudflare-sandbox')\n ) {\n return false;\n }\n const includeCodingTools =\n engine === 'cloudflare-sandbox'\n ? toolExecution.cloudflare?.includeCodingTools\n : toolExecution.local?.includeCodingTools;\n if (includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE &&\n graph.codeSessionToolNames?.includes(name) !== true\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph, metadata)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (\n graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&\n graph.eventToolExecutionAvailable !== true\n ) {\n return false;\n }\n return true;\n}\n\nfunction hasFinalToolCallSignal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n const finishReason =\n metadata?.finish_reason ??\n metadata?.finishReason ??\n metadata?.stop_reason ??\n metadata?.stopReason;\n return finishReason === 'tool_calls' || finishReason === 'tool_use';\n}\n\nfunction canPrestartSequentialStreamedToolChunks(\n agentContext: AgentContext | undefined\n): boolean {\n // Anthropic seals each prior streamed tool-use block when the next indexed\n // tool-use block begins. Live Kimi/Moonshot streams can still revise prior\n // args after advancing to the next index, so keep those on the final\n // tool-call path unless they grow an explicit adapter seal.\n return agentContext?.provider === Providers.ANTHROPIC;\n}\n\nfunction hasExplicitStreamedToolCallSeals(\n chunk: Partial<AIMessageChunk>\n): boolean {\n return (\n getStreamedToolCallAdapter(\n chunk.response_metadata as Record<string, unknown> | undefined\n ) != null\n );\n}\n\n/**\n * True when a provider adapter marked every tool call on this chunk as\n * complete on arrival (seal kind `all`), e.g. Google GenAI / Vertex AI, whose\n * protocol delivers function calls as whole objects rather than arg deltas.\n */\nfunction hasOnArrivalToolCallSeal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n return (\n getStreamedToolCallAdapter(metadata) != null &&\n getStreamedToolCallSeal(metadata)?.kind === 'all'\n );\n}\n\nfunction hasDirectToolCallInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n}): boolean {\n const { graph, agentContext, toolCalls } = args;\n return toolCalls.some(\n (toolCall) =>\n toolCall.name !== '' &&\n (isDirectGraphTool(toolCall.name, agentContext) ||\n isDirectLocalTool(toolCall.name, graph))\n );\n}\n\nfunction hasPotentialDirectToolInStreamContext(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, agentContext } = args;\n const engine = graph.toolExecution?.engine;\n if (engine === 'local' || engine === 'cloudflare-sandbox') {\n return true;\n }\n if ((agentContext?.graphTools?.length ?? 0) > 0) {\n return true;\n }\n return false;\n}\n\nfunction hasDirectToolCallChunkInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCallChunks?: ToolCallChunk[];\n}): boolean {\n const { graph, agentContext, toolCallChunks } = args;\n return (\n toolCallChunks?.some(\n (toolCallChunk) =>\n toolCallChunk.name != null &&\n toolCallChunk.name !== '' &&\n (isDirectGraphTool(toolCallChunk.name, agentContext) ||\n isDirectLocalTool(toolCallChunk.name, graph))\n ) === true\n );\n}\n\nfunction hasDirectToolCallChunkStateInStep(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n stepKey: string;\n}): boolean {\n const { graph, agentContext, stepKey } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n const name = state.name;\n if (\n name != null &&\n name !== '' &&\n (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction isGoogleServerSideToolContentPart(\n contentPart: t.MessageContentComplex\n): boolean {\n return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';\n}\n\nfunction isTextContentPart(contentPart: t.MessageContentComplex): boolean {\n return contentPart.type?.startsWith(ContentTypes.TEXT) ?? false;\n}\n\nfunction isReasoningContentPart(contentPart: t.MessageContentComplex): boolean {\n return (\n (contentPart.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n contentPart.type === 'redacted_thinking'\n );\n}\n\nfunction getReasoningTextFromContentPart(\n contentPart: t.MessageContentComplex\n): string {\n return (\n (contentPart as t.ThinkingContentText).thinking ??\n (contentPart as Partial<t.GoogleReasoningContentText>).reasoning ??\n (contentPart as Partial<t.BedrockReasoningContentText>).reasoningText\n ?.text ??\n ''\n );\n}\n\nfunction getReasoningTextFromChunk(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n): string {\n const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (typeof reasoning === 'string') {\n return reasoning;\n }\n return reasoning?.summary?.[0]?.text ?? '';\n}\n\nconst googleServerSideToolStepIdsByGraph = new WeakMap<\n StandardGraph,\n Set<string>\n>();\n\nfunction markGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): void {\n const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();\n stepIds.add(stepId);\n googleServerSideToolStepIdsByGraph.set(graph, stepIds);\n}\n\nfunction isGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): boolean {\n return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;\n}\n\nfunction shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n}: {\n graph: StandardGraph;\n stepId: string;\n runStep?: t.RunStep;\n content: string | t.MessageContentComplex[];\n}): boolean {\n if (\n runStep?.type !== StepTypes.MESSAGE_CREATION ||\n !isGoogleServerSideToolMessageStep(graph, stepId)\n ) {\n return false;\n }\n if (typeof content === 'string') {\n return true;\n }\n return (\n content.every((c) => isTextContentPart(c)) ||\n content.every((c) => isReasoningContentPart(c))\n );\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n metadata?: Record<string, unknown>;\n}): Promise<string> {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n return graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n}\n\nasync function dispatchMessageContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n for (const contentPart of content) {\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n if (isGoogleServerSideToolContentPart(contentPart)) {\n markGoogleServerSideToolMessageStep(graph, currentStepId);\n }\n await graph.dispatchMessageDelta(\n currentStepId,\n {\n content: [contentPart],\n },\n metadata\n );\n }\n}\n\nasync function dispatchReasoningContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n if (content.length === 0) {\n return;\n }\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n await graph.dispatchReasoningDelta(\n currentStepId,\n {\n content,\n },\n metadata\n );\n}\n\nasync function dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n const reasoningContent: t.MessageContentComplex[] = [];\n const reasoningText = getReasoningTextFromChunk(chunk, agentContext);\n if (reasoningText !== '') {\n reasoningContent.push({\n type: ContentTypes.THINK,\n think: reasoningText,\n });\n }\n reasoningContent.push(\n ...content\n .filter((contentPart) => isReasoningContentPart(contentPart))\n .map((contentPart) => ({\n type: ContentTypes.THINK,\n think: getReasoningTextFromContentPart(contentPart),\n }))\n .filter((contentPart) => contentPart.think !== '')\n );\n await dispatchReasoningContentParts({\n graph,\n stepKey,\n content: reasoningContent,\n metadata,\n });\n\n const messageContent = content.filter(\n (contentPart) =>\n isTextContentPart(contentPart) ||\n isGoogleServerSideToolContentPart(contentPart)\n );\n await dispatchMessageContentParts({\n graph,\n stepKey,\n content: messageContent,\n metadata,\n });\n}\n\ntype EagerToolExecutionEntry = {\n id: string;\n toolName: string;\n coercedArgs: Record<string, unknown>;\n request: t.ToolCallRequest;\n};\n\nfunction createEagerToolExecutionPlan(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): EagerToolExecutionEntry[] | undefined {\n const {\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting = false,\n } = args;\n if (\n !isEagerToolExecutionEnabledForBatch({\n graph,\n metadata,\n agentContext,\n })\n ) {\n return undefined;\n }\n\n if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {\n return undefined;\n }\n if (\n graph.toolOutputReferences?.enabled === true &&\n toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))\n ) {\n return undefined;\n }\n\n const unstartedToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n // Drop host-excluded tools only AFTER the batch-level guards above have run\n // against the full batch, so excluding a call never hides a sibling direct\n // tool from `hasDirectToolCallInBatch`. Excluded calls fall through to normal\n // ToolNode execution; siblings may still eager-execute.\n const candidateToolCalls = unstartedToolCalls.filter(\n (toolCall) => !isEagerExecutionExcludedTool(toolCall.name, graph)\n );\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n /* No runtimeSessionHint here on purpose: the eager path is speculative, and\n * code-session tools (the only ones that carry a hint) are excluded from\n * eager prestart entirely when stateful sessions are on — see\n * isEagerExecutionExcludedTool. The durable runtime is only ever touched by\n * the committed ToolNode path. */\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const records: t.EagerEventToolExecution[] = [];\n const promise: Promise<t.EagerEventToolExecutionOutcome> = new Promise<\n t.ToolExecuteResult[]\n >((resolve, reject) => {\n let dispatchSettled = false;\n let resultSettled = false;\n let settledResults: t.ToolExecuteResult[] | undefined;\n const maybeResolve = (): void => {\n if (dispatchSettled && resultSettled) {\n resolve(settledResults ?? []);\n }\n };\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: entries.map((entry) => entry.request),\n userId: graph.config?.configurable?.user_id as string | undefined,\n agentId: agentContext?.agentId,\n configurable: graph.config?.configurable as\n | Record<string, unknown>\n | undefined,\n metadata,\n resolve: (results): void => {\n resultSettled = true;\n settledResults = results;\n maybeResolve();\n },\n reject,\n };\n\n void safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n graph.config\n )\n .then(() => {\n dispatchSettled = true;\n maybeResolve();\n })\n .catch(reject);\n }).then(\n async (results): Promise<t.EagerEventToolExecutionOutcome> => {\n await dispatchEagerToolCompletions({\n graph,\n agentContext,\n records,\n results,\n });\n return { results };\n },\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n const record: t.EagerEventToolExecution = {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\n };\n records.push(record);\n graph.eagerEventToolExecutions.set(entry.id, record);\n }\n}\n\nasync function dispatchEagerToolCompletions(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n records: t.EagerEventToolExecution[];\n results: t.ToolExecuteResult[];\n}): Promise<void> {\n const { graph, agentContext, records, results } = args;\n const recordById = new Map(\n records.map((record) => [record.toolCallId, record])\n );\n const maxToolResultChars =\n agentContext?.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext?.maxContextTokens);\n\n for (const result of results) {\n const record = recordById.get(result.toolCallId);\n if (record == null) {\n continue;\n }\n if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {\n continue;\n }\n const stepId =\n record.request.stepId ??\n graph.toolCallStepIds.get(result.toolCallId) ??\n '';\n if (stepId === '') {\n continue;\n }\n let output: string;\n if (result.status === 'error') {\n output = truncateToolResultContent(\n `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`,\n maxToolResultChars\n );\n } else if (typeof result.content === 'string') {\n output = truncateToolResultContent(result.content, maxToolResultChars);\n } else {\n output = serializeStructuredValueBounded(\n result.content,\n maxToolResultChars\n ).content;\n }\n const outcome = resolveToolOutcome(\n record.request.args,\n outcomeFieldsFromResult(result),\n { isError: result.status === 'error' }\n );\n\n try {\n const dispatched = await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: record.request.turn ?? 0,\n type: 'tool_call' as const,\n eager: true,\n tool_call: {\n args: serializeToolContentBounded(\n record.request.args,\n maxToolResultChars\n ),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\n ...(outcome != null && { outcome }),\n } as t.ProcessedToolCall,\n },\n },\n graph.config\n );\n if (dispatched === false) {\n continue;\n }\n record.completionDispatched = true;\n } catch (error) {\n // Let ToolNode dispatch the completion through the normal path later.\n\n console.warn(\n `[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`,\n error instanceof Error ? error.message : error\n );\n }\n }\n}\n\nfunction getEagerToolChunkKey(\n stepKey: string,\n toolCallChunk: ToolCallChunk\n): string | undefined {\n let chunkKey: string | undefined;\n if (typeof toolCallChunk.index === 'number') {\n chunkKey = String(toolCallChunk.index);\n } else if (toolCallChunk.id != null && toolCallChunk.id !== '') {\n chunkKey = toolCallChunk.id;\n }\n if (chunkKey == null) {\n return undefined;\n }\n return `${stepKey}\\u0000${chunkKey}`;\n}\n\nfunction getEagerToolChunkIndex(\n toolCallChunk: ToolCallChunk\n): number | undefined {\n return typeof toolCallChunk.index === 'number'\n ? toolCallChunk.index\n : undefined;\n}\n\nfunction pruneEagerToolCallChunkStates(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallIds?: ReadonlySet<string>;\n clearStep?: boolean;\n}): void {\n const { graph, stepKey, toolCallIds, clearStep = false } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (\n clearStep ||\n (state.id != null && toolCallIds?.has(state.id) === true)\n ) {\n graph.eagerEventToolCallChunks.delete(key);\n }\n }\n}\n\nfunction isEagerToolChunkStateComplete(\n state: t.EagerEventToolCallChunkState\n): boolean {\n return (\n state.id != null &&\n state.id !== '' &&\n state.name != null &&\n state.name !== '' &&\n coerceRecordArgs(state.argsText) != null\n );\n}\n\nfunction mergeToolCallArgsText(existing: string, incoming: string): string {\n if (incoming === '') {\n return existing;\n }\n if (existing === '') {\n return incoming;\n }\n if (incoming === existing) {\n try {\n JSON.parse(incoming);\n return incoming;\n } catch {\n return `${existing}${incoming}`;\n }\n }\n if (incoming.startsWith(existing)) {\n return incoming;\n }\n if (existing.startsWith(incoming)) {\n return existing;\n }\n try {\n JSON.parse(existing);\n JSON.parse(incoming);\n return incoming;\n } catch {\n // Fall through to delta concatenation.\n }\n for (\n let overlap = Math.min(existing.length, incoming.length);\n overlap >= 8;\n overlap -= 1\n ) {\n if (existing.endsWith(incoming.slice(0, overlap))) {\n return `${existing}${incoming.slice(overlap)}`;\n }\n }\n return `${existing}${incoming}`;\n}\n\nfunction recordEagerToolCallChunks(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n}): void {\n const { graph, stepKey, toolCallChunks, seal } = args;\n if (toolCallChunks == null || toolCallChunks.length === 0) {\n return;\n }\n\n // Streamed args can be cumulative and parseable before the provider has\n // sealed the call. Recording stays separate from dispatch so the boundary\n // logic can wait for either a later tool index or the final tool-call signal.\n for (const toolCallChunk of toolCallChunks) {\n const key = getEagerToolChunkKey(stepKey, toolCallChunk);\n if (key == null) {\n continue;\n }\n\n const incomingId =\n toolCallChunk.id != null && toolCallChunk.id !== ''\n ? toolCallChunk.id\n : undefined;\n const incomingName =\n toolCallChunk.name != null && toolCallChunk.name !== ''\n ? toolCallChunk.name\n : undefined;\n const previous = graph.eagerEventToolCallChunks.get(key);\n const shouldReset =\n previous != null &&\n ((incomingId != null &&\n previous.id != null &&\n incomingId !== previous.id) ||\n (incomingName != null &&\n previous.name != null &&\n incomingName !== previous.name));\n const existing =\n previous == null || shouldReset\n ? {\n argsText: '',\n }\n : previous;\n const id = incomingId ?? existing.id;\n const name = incomingName ?? existing.name;\n const incomingArgs = toolCallChunk.args ?? '';\n const isRepeatedObservedFragment =\n incomingArgs !== '' &&\n incomingArgs.length > 1 &&\n incomingArgs === existing.lastArgsFragment;\n const argsText = isRepeatedObservedFragment\n ? existing.argsText\n : mergeToolCallArgsText(existing.argsText, incomingArgs);\n const index = getEagerToolChunkIndex(toolCallChunk) ?? existing.index;\n // Only a chunk whose explicit adapter seal covers THIS call may supply a\n // full-args restatement (OpenAI Responses `arguments.done`). Pure-signal\n // seals carry empty args and never set this.\n const sealCoversChunk =\n seal != null &&\n (seal.kind === 'all' ||\n (seal.kind === 'single' &&\n ((seal.id != null && seal.id === id) ||\n (seal.index != null && seal.index === index))));\n const next = {\n id,\n name,\n argsText,\n // Canonical accumulation length: LangChain concats fragments verbatim\n // to build the final request, and every reconciliation branch above\n // yields text no longer than that concat — equal exactly when every\n // merge was a pure append. Tracking the length (not the text) keeps\n // cumulative/restating streams from retaining every prefix.\n rawArgsLength: (existing.rawArgsLength ?? 0) + incomingArgs.length,\n index,\n lastArgsFragment:\n incomingArgs !== '' ? incomingArgs : existing.lastArgsFragment,\n sealedArgsFragment:\n sealCoversChunk && incomingArgs !== ''\n ? incomingArgs\n : existing.sealedArgsFragment,\n };\n graph.eagerEventToolCallChunks.set(key, next);\n }\n}\n\nfunction getStreamedReadyToolCalls(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): ToolCall[] {\n const {\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal = false,\n sealAll = false,\n } = args;\n const currentIndices = new Set<number>();\n for (const toolCallChunk of toolCallChunks ?? []) {\n const index = getEagerToolChunkIndex(toolCallChunk);\n if (index != null) {\n currentIndices.add(index);\n }\n }\n const highestCurrentIndex =\n currentIndices.size > 0 ? Math.max(...currentIndices) : undefined;\n const prefix = `${stepKey}\\u0000`;\n const readyEntries: Array<{\n key: string;\n state: t.EagerEventToolCallChunkState;\n sealedByAdapter: boolean;\n }> = [];\n\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {\n graph.eagerEventToolCallChunks.delete(key);\n continue;\n }\n if (!isEagerToolChunkStateComplete(state)) {\n continue;\n }\n const isSealedByLaterChunk =\n allowSequentialSeal &&\n highestCurrentIndex != null &&\n state.index != null &&\n state.index < highestCurrentIndex &&\n !currentIndices.has(state.index);\n const isSealedExplicitly =\n seal?.kind === 'single' &&\n ((seal.id != null && state.id === seal.id) ||\n (seal.index != null && state.index === seal.index));\n if (\n sealAll ||\n seal?.kind === 'all' ||\n isSealedByLaterChunk ||\n isSealedExplicitly\n ) {\n readyEntries.push({\n key,\n state,\n sealedByAdapter: isSealedExplicitly || seal?.kind === 'all',\n });\n }\n }\n\n pruneEagerToolCallChunkStates({\n graph,\n stepKey,\n toolCallIds: new Set(\n readyEntries\n .map(({ state }) => state.id)\n .filter((id): id is string => id != null && id !== '')\n ),\n });\n if (sealAll) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n\n return readyEntries\n .sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0))\n .flatMap(({ state, sealedByAdapter }) => {\n const args = coerceRecordArgs(state.argsText);\n if (args == null) {\n return [];\n }\n // The final request's args come from LangChain's canonical verbatim\n // concatenation of fragments, while `argsText` reconciles provider\n // quirks with lossy heuristics that can also swallow legitimately\n // repetitive payload fragments (LibreChat#14371). `argsText` can never\n // be LONGER than the plain concat, so length equality proves it IS the\n // canonical accumulation.\n const isCanonicalAccumulation =\n state.rawArgsLength != null &&\n state.argsText.length === state.rawArgsLength;\n // Adapter seals may instead restate the finished call's full args on\n // the seal chunk itself (OpenAI Responses\n // `function_call_arguments.done`). Only when the seal-carrying chunk\n // supplied that fragment AND the accumulated text IS that restatement\n // has the adapter vouched for it — plain concatenation intentionally\n // differs there. Pure-signal seals (Bedrock contentBlockStop,\n // `args: ''`) never qualify.\n const isAuthoritativeRestatement =\n sealedByAdapter &&\n state.sealedArgsFragment != null &&\n state.sealedArgsFragment === state.argsText;\n // Prestarting an unconfirmed snapshot trips the \"changed after eager\n // execution started\" guard and burns a retry loop — leave unconfirmed\n // calls to normal ToolNode execution with final args.\n if (!isCanonicalAccumulation && !isAuthoritativeRestatement) {\n return [];\n }\n return [\n {\n id: state.id,\n name: state.name ?? '',\n args,\n },\n ];\n });\n}\n\nfunction startReadyStreamedEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): void {\n const {\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n } = args;\n if (\n hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||\n hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||\n hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||\n !isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })\n ) {\n return;\n }\n const toolCalls = getStreamedReadyToolCalls({\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n });\n if (toolCalls.length === 0) {\n return;\n }\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting: true,\n });\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 isGoogleLike(provider) &&\n Array.isArray(chunk?.content) &&\n chunk.content.some((c) => isGoogleServerSideToolContentPart(c))\n ) {\n return chunk.content;\n }\n\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 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 const reasoningContent = chunk?.additional_kwargs?.reasoning_content as\n | string\n | undefined;\n if (reasoningContent != null && reasoningContent !== '') {\n return reasoningContent;\n }\n return chunk?.content;\n }\n const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey] as\n | string\n | undefined;\n if (\n typeof chunk?.content === 'string' &&\n chunk.content !== '' &&\n keyedReasoning != null &&\n keyedReasoning !== ''\n ) {\n return chunk.content;\n }\n return ((keyedReasoning as string | undefined) ?? '') || chunk?.content;\n}\n\nfunction isDisableStreamingEnabled(\n clientOptions: t.ClientOptions | undefined\n): boolean {\n return (\n clientOptions != null &&\n 'disableStreaming' in clientOptions &&\n clientOptions.disableStreaming === true\n );\n}\n\nfunction hasReasoningContent(\n value: string | ReasoningSummaryLike | object[] | null | undefined\n): boolean {\n if (typeof value === 'string') {\n return value !== '';\n }\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n if (value == null) {\n return false;\n }\n return (\n value.summary?.some(\n (summary) => summary.text != null && summary.text.length > 0\n ) === true\n );\n}\n\nfunction shouldDeferMixedFinalReasoningChunk({\n chunk,\n agentContext,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n}): boolean {\n if (\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n typeof chunk.content !== 'string' ||\n chunk.content === ''\n ) {\n return false;\n }\n const additionalKwargs = chunk.additional_kwargs;\n if (\n agentContext.provider === Providers.OPENROUTER &&\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n ) {\n return true;\n }\n if (!isDisableStreamingEnabled(agentContext.clientOptions)) {\n return false;\n }\n return (\n hasReasoningContent(\n additionalKwargs?.[agentContext.reasoningKey] as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning_content as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n );\n}\n\nfunction hasCurrentTextDeltaStep({\n graph,\n metadata,\n}: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (metadata == null) {\n return false;\n }\n const baseStepKey = graph.getStepBaseKey(metadata);\n for (const [stepKey, stepIds] of graph.stepKeyIds) {\n if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {\n continue;\n }\n if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) {\n return true;\n }\n }\n return false;\n}\n\nfunction shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (\n agentContext.provider !== Providers.OPENROUTER ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n (chunk.content != null && chunk.content !== '')\n ) {\n return false;\n }\n return (\n (hasReasoningContent(chunk.additional_kwargs?.reasoning as string) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_content as string\n ) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_details as object[]\n )) &&\n hasCurrentTextDeltaStep({ graph, metadata })\n );\n}\n\n/**\n * Brands a handler as one that dispatches content parts for the SDK — either\n * `ChatModelStreamHandler` itself or a wrapper forwarding to one.\n *\n * Identity alone is not a usable contract here. Hosts compose and wrap\n * handlers (`composeEventHandlers`, `createRunHandlers`), and every wrapper\n * fails `instanceof` while still driving the same dispatch. A brand survives\n * wrapping, so \"does this handler own content-part dispatch\" can be answered\n * about a value the SDK did not construct.\n */\nexport const SDK_STREAM_DISPATCH = Symbol.for(\n '@librechat/agents:chatModelStreamDispatch'\n);\n\n/** True when `handler` is, or forwards to, the SDK's stream dispatcher. */\nexport function dispatchesChatModelStream(handler?: t.EventHandler): boolean {\n if (handler == null) {\n return false;\n }\n if (handler instanceof ChatModelStreamHandler) {\n return true;\n }\n return Reflect.get(handler, SDK_STREAM_DISPATCH) === true;\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n readonly [SDK_STREAM_DISPATCH] = true;\n\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\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\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 if (shouldDeferMixedFinalReasoningChunk({ chunk, agentContext })) {\n return;\n }\n if (\n shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n })\n ) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n const stepKey = graph.getStepKey(metadata);\n let hasToolCalls = false;\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const hasGoogleServerSideToolContent =\n isGoogleLike(agentContext.provider) &&\n Array.isArray(content) &&\n content.some((c) => isGoogleServerSideToolContentPart(c));\n if (hasGoogleServerSideToolContent && Array.isArray(content)) {\n await dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n });\n }\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 if (hasFinalToolCallSignal(chunk)) {\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n if (!hasToolCallChunks) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n } else if (\n hasOnArrivalToolCallSeal(chunk) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext })\n ) {\n // Providers like Google never signal `tool_calls`/`tool_use` as the\n // finish reason, but their adapters seal calls on arrival — prestart\n // these mid-stream under the same direct-tool guard as streamed\n // chunk sealing.\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n }\n }\n\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 graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\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 const streamedToolCallSeal = getStreamedToolCallSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const allowSequentialSeal =\n canPrestartSequentialStreamedToolChunks(agentContext) ||\n streamedToolCallAdapterAllowsSequentialSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const canStreamEager =\n (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext }) &&\n isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext });\n if (canStreamEager) {\n recordEagerToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n seal: streamedToolCallSeal,\n });\n }\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n if (canStreamEager) {\n startReadyStreamedEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n seal: streamedToolCallSeal,\n allowSequentialSeal,\n sealAll: hasFinalToolCallSignal(chunk),\n });\n }\n }\n\n if (isEmptyContent) {\n return;\n }\n\n if (hasGoogleServerSideToolContent) {\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 let stepId = graph.getStepIdByKey(stepKey);\n let runStep = graph.getRunStep(stepId);\n if (\n shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n })\n ) {\n stepId = await dispatchMessageCreationStep({ graph, stepKey, metadata });\n runStep = graph.getRunStep(stepId);\n }\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(\n stepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n },\n metadata\n );\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n },\n metadata\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(\n newStepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n },\n metadata\n );\n }\n } else {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n },\n metadata\n );\n }\n } else if (content.every((c) => isTextContentPart(c))) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content,\n },\n metadata\n );\n } else if (content.every((c) => isReasoningContentPart(c))) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\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\n ?.text ??\n '',\n })),\n },\n metadata\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 (typeof chunk.additional_kwargs?.reasoning_content === 'string' &&\n chunk.additional_kwargs.reasoning_content !== ''))\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 type ToolStepContentState = {\n indices: Set<number>;\n chunkIndices: Map<number, number>;\n unclaimedIndices: Set<number>;\n unboundIndices: Set<number>;\n callIdsByIndex: Map<number, string>;\n };\n\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallContentIndexMap = new Map<string, number>();\n const sourceContentIndexMap = new Map<number, number>();\n const toolStepContentMap = new Map<string, ToolStepContentState>();\n let indexedContentLength = 0;\n /** Physical append cursor; event/chunk indices are correlation keys, not array offsets. */\n let nextContentIndex = 0;\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 /** A delta's content may carry several parts (e.g. Google server-side tool\n * chunks emit multiple reasoning entries at once); every entry must reach\n * the step's slot, in order, or streamed text is silently lost. */\n const getDeltaContentParts = (\n content?: t.MessageDelta['content'] | t.MessageContentComplex\n ): t.MessageContentComplex[] => {\n if (content == null) {\n return [];\n }\n return Array.isArray(content) ? content : [content];\n };\n const indexContentPart = (\n index: number,\n contentPart?: t.MessageContentComplex\n ): void => {\n if (contentPart == null) {\n return;\n }\n if (contentPart.type === ContentTypes.TOOL_CALL) {\n const toolCallId = contentPart.tool_call.id;\n if (toolCallId != null && toolCallId !== '') {\n toolCallContentIndexMap.set(toolCallId, index);\n }\n }\n const hasAgentId =\n contentPart.agentId != null && contentPart.agentId !== '';\n const hasGroupId = contentPart.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = contentPart.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = contentPart.groupId;\n }\n contentMetaMap.set(index, existingMeta);\n }\n };\n const syncSeededContent = (): void => {\n /** Hosts can seed pre-pause content after creating the aggregator. */\n for (\n let index = indexedContentLength;\n index < contentParts.length;\n index++\n ) {\n indexContentPart(index, contentParts[index]);\n }\n indexedContentLength = contentParts.length;\n nextContentIndex = Math.max(nextContentIndex, contentParts.length);\n };\n const getToolCallContentIndex = (\n toolCallId: string | undefined\n ): number | undefined => {\n if (toolCallId == null || toolCallId === '') {\n return undefined;\n }\n syncSeededContent();\n return toolCallContentIndexMap.get(toolCallId);\n };\n const allocateContentIndex = (minimumIndex = 0): number => {\n syncSeededContent();\n const contentIndex = Math.max(nextContentIndex, minimumIndex);\n nextContentIndex = contentIndex + 1;\n return contentIndex;\n };\n const resolveSourceContentIndex = (sourceIndex: number): number => {\n const existingIndex = sourceContentIndexMap.get(sourceIndex);\n if (existingIndex != null) {\n return existingIndex;\n }\n const contentIndex = allocateContentIndex(sourceIndex);\n sourceContentIndexMap.set(sourceIndex, contentIndex);\n return contentIndex;\n };\n const createToolStepContentState = (\n contentIndex: number\n ): ToolStepContentState => ({\n indices: new Set<number>([contentIndex]),\n chunkIndices: new Map<number, number>(),\n unclaimedIndices: new Set<number>([contentIndex]),\n unboundIndices: new Set<number>([contentIndex]),\n callIdsByIndex: new Map<number, string>(),\n });\n const registerToolContentIndex = (\n state: ToolStepContentState,\n contentIndex: number,\n toolCallId?: string\n ): void => {\n if (!state.indices.has(contentIndex)) {\n state.indices.add(contentIndex);\n state.unclaimedIndices.add(contentIndex);\n state.unboundIndices.add(contentIndex);\n }\n if (toolCallId != null && toolCallId !== '') {\n const existingToolCallId = state.callIdsByIndex.get(contentIndex);\n if (\n existingToolCallId != null &&\n existingToolCallId !== toolCallId &&\n toolCallContentIndexMap.get(existingToolCallId) === contentIndex\n ) {\n toolCallContentIndexMap.delete(existingToolCallId);\n }\n toolCallContentIndexMap.set(toolCallId, contentIndex);\n state.callIdsByIndex.set(contentIndex, toolCallId);\n state.unboundIndices.delete(contentIndex);\n }\n };\n const takeFirstIndex = (indices: Set<number>): number | undefined => {\n const contentIndex = indices.values().next().value;\n if (contentIndex != null) {\n indices.delete(contentIndex);\n }\n return contentIndex;\n };\n const setContentMeta = (index: number, runStep: t.RunStep): void => {\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (!hasAgentId && !hasGroupId) {\n return;\n }\n const existingMeta = contentMetaMap.get(index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(index, existingMeta);\n };\n const applyContentMetadata = (index: number): void => {\n const contentPart = contentParts[index];\n if (contentPart == null) {\n return;\n }\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n contentPart.agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n contentPart.groupId = meta.groupId;\n }\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 (partType === 'toolCall' || partType === 'toolResponse') {\n contentParts[index] = contentPart;\n } else if (partType === ContentTypes.SUMMARY) {\n const currentSummary = contentParts[index] as\n | t.SummaryContentBlock\n | undefined;\n const incoming = contentPart as t.SummaryContentBlock;\n contentParts[index] = {\n ...incoming,\n content: [\n ...(currentSummary?.content ?? []),\n ...(incoming.content ?? []),\n ],\n };\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 // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart & t.PartMetadata;\n })\n | undefined;\n if (!finalUpdate && existingContent?.tool_call?.progress === 1) {\n return;\n }\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (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 const existingToolCallId = existingContent?.tool_call?.id;\n if (\n existingToolCallId != null &&\n existingToolCallId !== '' &&\n existingToolCallId !== id &&\n toolCallContentIndexMap.get(existingToolCallId) === index\n ) {\n toolCallContentIndexMap.delete(existingToolCallId);\n }\n\n const newToolCall: ToolCall & t.PartMetadata & { outcome?: string } = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n const auth =\n contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;\n const expiresAt =\n contentPart.tool_call.expires_at ??\n existingContent?.tool_call?.expires_at;\n if (auth != null) {\n newToolCall.auth = auth;\n newToolCall.expires_at = expiresAt;\n }\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n const outcome = (contentPart.tool_call as t.ToolCallPart).outcome;\n if (outcome != null) {\n newToolCall.outcome = outcome;\n }\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n indexContentPart(index, contentParts[index]);\n indexedContentLength = Math.max(indexedContentLength, index + 1);\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 applyContentMetadata(index);\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.ReasoningDeltaEvent\n | t.RunStepDeltaEvent\n | t.SummarizeDeltaData\n | t.SummarizeCompleteEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_SUMMARIZE_DELTA) {\n const deltaData = data as t.SummarizeDeltaData;\n const runStep = stepMap.get(deltaData.id);\n if (!runStep) {\n console.warn('No run step found for summarize delta event');\n return;\n }\n updateContent(runStep.index, deltaData.delta.summary);\n return;\n }\n\n if (event === GraphEvents.ON_SUMMARIZE_COMPLETE) {\n const completeData = data as t.SummarizeCompleteEvent;\n const summary = completeData.summary;\n if (!summary?.boundary) {\n return;\n }\n const runStep = stepMap.get(summary.boundary.messageId);\n if (!runStep) {\n return;\n }\n // Replace accumulated delta text with the authoritative final summary.\n // Multi-stage summarization streams deltas from each chunk, which\n // concatenate in updateContent. This event carries only the correct\n // final text from the last stage.\n contentParts[runStep.index] = summary;\n applyContentMetadata(runStep.index);\n return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const incomingRunStep = data as t.RunStep;\n const toolCalls =\n incomingRunStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (incomingRunStep.stepDetails.tool_calls as ToolCall[] | undefined)\n : undefined;\n syncSeededContent();\n let runStepIndex: number;\n const toolCallIndices: number[] = [];\n if (toolCalls && toolCalls.length > 0) {\n for (let index = 0; index < toolCalls.length; index++) {\n const toolCallId = toolCalls[index].id;\n let contentIndex = getToolCallContentIndex(toolCallId);\n if (contentIndex == null) {\n contentIndex =\n index === 0\n ? resolveSourceContentIndex(incomingRunStep.index)\n : allocateContentIndex();\n } else if (index === 0) {\n sourceContentIndexMap.set(incomingRunStep.index, contentIndex);\n }\n toolCallIndices.push(contentIndex);\n }\n runStepIndex = toolCallIndices[0];\n } else {\n runStepIndex = resolveSourceContentIndex(incomingRunStep.index);\n }\n const runStep =\n runStepIndex !== incomingRunStep.index\n ? { ...incomingRunStep, index: runStepIndex }\n : incomingRunStep;\n stepMap.set(runStep.id, runStep);\n\n setContentMeta(runStep.index, runStep);\n\n if (runStep.summary != null) {\n updateContent(runStep.index, runStep.summary);\n }\n\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS) {\n const toolStepContent =\n toolStepContentMap.get(runStep.id) ??\n createToolStepContentState(runStep.index);\n registerToolContentIndex(toolStepContent, runStep.index);\n (runStep.stepDetails.tool_calls as ToolCall[] | undefined)?.forEach(\n (toolCall, toolCallIndex) => {\n const contentIndex =\n toolCallIndices[toolCallIndex] ?? runStep.index;\n const toolCallId = toolCall.id ?? '';\n registerToolContentIndex(toolStepContent, contentIndex, toolCallId);\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 setContentMeta(contentIndex, runStep);\n updateContent(contentIndex, contentPart);\n }\n );\n toolStepContentMap.set(runStep.id, toolStepContent);\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 for (const contentPart of getDeltaContentParts(\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 const contentIndex = resolveSourceContentIndex(\n contentPart.agent_update.index\n );\n updateContent(contentIndex, {\n ...contentPart,\n agent_update: {\n ...contentPart.agent_update,\n index: contentIndex,\n },\n });\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 for (const contentPart of getDeltaContentParts(\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 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 const toolStepContent =\n toolStepContentMap.get(runStepDelta.id) ??\n createToolStepContentState(runStep.index);\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const chunkIndex =\n typeof toolCallDelta.index === 'number'\n ? toolCallDelta.index\n : undefined;\n const explicitToolCallId =\n toolCallDelta.id != null && toolCallDelta.id !== ''\n ? toolCallDelta.id\n : undefined;\n let contentIndex = getToolCallContentIndex(explicitToolCallId);\n if (contentIndex == null && chunkIndex != null) {\n contentIndex = toolStepContent.chunkIndices.get(chunkIndex);\n }\n const soleContentIndex =\n toolStepContent.indices.size === 1\n ? toolStepContent.indices.values().next().value\n : undefined;\n if (\n contentIndex == null &&\n explicitToolCallId == null &&\n soleContentIndex != null &&\n (chunkIndex == null ||\n toolStepContent.callIdsByIndex.has(soleContentIndex) ||\n toolStepContent.unclaimedIndices.has(soleContentIndex))\n ) {\n contentIndex = soleContentIndex;\n }\n if (contentIndex == null) {\n if (chunkIndex == null && explicitToolCallId == null) {\n console.warn(\n 'No tool call id or chunk index found for run step delta event'\n );\n return;\n }\n contentIndex =\n explicitToolCallId == null\n ? takeFirstIndex(toolStepContent.unclaimedIndices)\n : takeFirstIndex(toolStepContent.unboundIndices);\n contentIndex ??= allocateContentIndex();\n }\n registerToolContentIndex(\n toolStepContent,\n contentIndex,\n explicitToolCallId\n );\n if (chunkIndex != null) {\n toolStepContent.chunkIndices.set(chunkIndex, contentIndex);\n toolStepContent.unclaimedIndices.delete(contentIndex);\n toolStepContent.unboundIndices.delete(contentIndex);\n }\n const toolCallId =\n explicitToolCallId ??\n toolStepContent.callIdsByIndex.get(contentIndex);\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 auth: runStepDelta.delta.auth,\n expires_at: runStepDelta.delta.expires_at,\n },\n };\n\n setContentMeta(contentIndex, runStep);\n updateContent(contentIndex, contentPart);\n });\n toolStepContentMap.set(runStepDelta.id, toolStepContent);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as {\n result:\n | t.ToolEndEvent\n | (t.SummaryCompleted & { id: string; index: number });\n };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n\n if (result.type === ContentTypes.SUMMARY && 'summary' in result) {\n if (!runStep) {\n console.warn('No run step or runId found for completed step event');\n return;\n }\n contentParts[runStep.index] = result.summary as t.MessageContentComplex;\n applyContentMetadata(runStep.index);\n } else if ('tool_call' in result) {\n let contentIndex = getToolCallContentIndex(result.tool_call.id);\n if (contentIndex == null && runStep != null) {\n const toolStepContent = toolStepContentMap.get(runStep.id);\n if (toolStepContent?.indices.size === 1) {\n contentIndex = toolStepContent.indices.values().next().value;\n } else if (toolStepContent == null) {\n const declaredToolCalls =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? runStep.stepDetails.tool_calls\n : undefined;\n if ((declaredToolCalls?.length ?? 0) <= 1) {\n contentIndex = runStep.index;\n }\n }\n }\n if (contentIndex == null) {\n console.warn(\n 'No run step or tool call found for completed step event'\n );\n return;\n }\n if (runStep != null) {\n setContentMeta(contentIndex, runStep);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: (result as t.ToolEndEvent).tool_call,\n };\n updateContent(contentIndex, contentPart, true);\n }\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+CA,MAAM,+BAAoD,IAAI,IAC5D,yBACF;;;;;;AAWA,SAAS,qBAAqB,SAG5B;CAEA,IAAI,CAAC,QAAQ,SAAS,SAAS,GAC7B,OAAO;EAAE,MAAM;EAAS,UAAU;CAAG;CAGvC,IAAI,aAAa;CACjB,MAAM,iBAA2B,CAAC;CAClC,IAAI,WAAW;CAEf,OAAO,WAAW,QAAQ,QAAQ;EAChC,MAAM,aAAa,QAAQ,QAAQ,WAAW,QAAQ;EAEtD,IAAI,eAAe,IAAI;GAErB,cAAc,QAAQ,MAAM,QAAQ;GACpC;EACF;EAGA,cAAc,QAAQ,MAAM,UAAU,UAAU;EAEhD,MAAM,WAAW,QAAQ,QAAQ,YAAY,UAAU;EACvD,IAAI,aAAa,IAAI;GAEnB,cAAc,QAAQ,MAAM,UAAU;GACtC;EACF;EAGA,MAAM,eAAe,QAAQ,MAAM,aAAa,GAAG,QAAQ;EAC3D,eAAe,KAAK,YAAY;EAGhC,WAAW,WAAW;CACxB;CAEA,OAAO;EACL,MAAM,WAAW,KAAK;EACtB,UAAU,eAAe,KAAK,IAAI,CAAC,CAAC,KAAK;CAC3C;AACF;AAEA,SAAS,iBAAiB,gBAA8C;CACtE,KAAK,MAAM,SAAS,gBAClB,IAAI,SAAS,MAAM,KAAK,MAAM,IAC5B,OAAO;AAIb;AAEA,SAAS,8BACP,OACA,UACS;;;;;;;;;;CAUT,MAAM,QACH,MAAM,QAAQ,cAAc,UAC5B,UAAU,UACX,MAAM;CACR,OACE,MAAM,cAA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,cAAc,cAAc,aAAa,IAAI;GAC/C;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
@@ -640,6 +640,11 @@ function createSummarizeNode({ agentContext, graph, generateStepId }) {
640
640
  metadata: {
641
641
  ...config.metadata,
642
642
  agent_id: request.agentId,
643
+ /** Canonical agent-identity key, overwritten by every component
644
+ * that stamps identity (graph model path, ToolNode, here) so the
645
+ * closest stamper always wins via spread order — Langfuse scope
646
+ * trust relies on it (see `isForeignScope`). */
647
+ agentId: request.agentId,
643
648
  summarization_provider: clientConfig.provider,
644
649
  summarization_model: clientConfig.modelName,
645
650
  /**