@librechat/agents 3.2.56 → 3.2.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +7 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +7 -2
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/langfuseToolOutputTracing.cjs +4 -0
- package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
- package/dist/cjs/langfuseTraceShaping.cjs +172 -0
- package/dist/cjs/langfuseTraceShaping.cjs.map +1 -0
- package/dist/cjs/run.cjs +6 -2
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +3 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +19 -5
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/keenable-search.cjs +68 -0
- package/dist/cjs/tools/search/keenable-search.cjs.map +1 -0
- package/dist/cjs/tools/search/rerankers.cjs +28 -11
- package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs +30 -4
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +14 -6
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +12 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/utils/title.cjs +9 -9
- package/dist/cjs/utils/title.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +7 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +7 -2
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/langfuseToolOutputTracing.mjs +4 -0
- package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
- package/dist/esm/langfuseTraceShaping.mjs +171 -0
- package/dist/esm/langfuseTraceShaping.mjs.map +1 -0
- package/dist/esm/run.mjs +6 -2
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +3 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +19 -5
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/keenable-search.mjs +66 -0
- package/dist/esm/tools/search/keenable-search.mjs.map +1 -0
- package/dist/esm/tools/search/rerankers.mjs +28 -11
- package/dist/esm/tools/search/rerankers.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs +30 -4
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +14 -6
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +12 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/utils/title.mjs +9 -9
- package/dist/esm/utils/title.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +1 -0
- package/dist/types/langfuseTraceShaping.d.ts +20 -0
- package/dist/types/run.d.ts +1 -0
- package/dist/types/tools/ToolNode.d.ts +11 -1
- package/dist/types/tools/search/keenable-search.d.ts +4 -0
- package/dist/types/tools/search/rerankers.d.ts +7 -2
- package/dist/types/tools/search/types.d.ts +38 -1
- package/dist/types/types/graph.d.ts +22 -0
- package/dist/types/types/run.d.ts +9 -0
- package/dist/types/types/tools.d.ts +6 -0
- package/package.json +1 -1
- package/src/__tests__/stream.eagerEventExecution.test.ts +44 -0
- package/src/agents/AgentContext.ts +9 -0
- package/src/agents/__tests__/AgentContext.test.ts +40 -0
- package/src/graphs/Graph.ts +31 -3
- package/src/graphs/__tests__/composition.smoke.test.ts +53 -0
- package/src/langfuseToolOutputTracing.ts +11 -0
- package/src/langfuseTraceShaping.ts +280 -0
- package/src/llm/anthropic/inherited-stream-events.spec.ts +6 -3
- package/src/run.ts +7 -3
- package/src/specs/langfuse-routing.integration.test.ts +1 -1
- package/src/specs/langfuse-trace-shaping.test.ts +194 -0
- package/src/stream.ts +10 -2
- package/src/tools/ToolNode.ts +28 -4
- package/src/tools/__tests__/SubagentExecutor.test.ts +44 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +160 -0
- package/src/tools/__tests__/hitl.test.ts +85 -0
- package/src/tools/search/jina-reranker.test.ts +70 -1
- package/src/tools/search/keenable-search.ts +98 -0
- package/src/tools/search/keenable.test.ts +183 -0
- package/src/tools/search/rerankers.ts +41 -4
- package/src/tools/search/search.ts +58 -2
- package/src/tools/search/source-processing.test.ts +86 -0
- package/src/tools/search/tool.ts +29 -4
- package/src/tools/search/types.ts +42 -1
- package/src/tools/subagent/SubagentExecutor.ts +11 -0
- package/src/types/graph.ts +22 -0
- package/src/types/run.ts +9 -0
- package/src/types/tools.ts +6 -0
- package/src/utils/title.ts +9 -9
package/dist/cjs/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","names":["LOCAL_CODING_BUNDLE_NAMES","TOOL_OUTPUT_REF_PATTERN","CODE_EXECUTION_TOOLS","getStreamedToolCallAdapter","getStreamedToolCallSeal","getMessageId","buildToolExecutionRequestPlan","safeDispatchCustomEvent","normalizeError","calculateMaxToolResultChars","truncateToolResultContent","coerceRecordArgs","isGoogleLike","handleServerToolResult","handleToolCalls","streamedToolCallAdapterAllowsSequentialSeal","handleToolCallChunks","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 handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\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(graph: StandardGraph): boolean {\n return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;\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 return excluded != null && excluded.includes(name);\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 ) {\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)) {\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 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 const output =\n result.status === 'error'\n ? `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`\n : truncateToolResultContent(\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content),\n maxToolResultChars\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: JSON.stringify(record.request.args),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\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\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\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 const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n // Track agentId and groupId for each content index (applied to content parts)\n const contentMetaMap = new Map<\n number,\n { agentId?: string; groupId?: number }\n >();\n const getFirstContentPart = (\n content?: t.MessageDelta['content'] | t.MessageContentComplex\n ): t.MessageContentComplex | undefined => {\n if (content == null) {\n return undefined;\n }\n return Array.isArray(content) ? content[0] : content;\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\n const newToolCall: ToolCall & t.PartMetadata = {\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 }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n\n // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts\n // - agentId present → MultiAgentGraph (show agent labels)\n // - groupId present → parallel execution (render columns)\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n (contentParts[index] as t.MessageContentComplex).agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n (contentParts[index] as t.MessageContentComplex).groupId = meta.groupId;\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.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 return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately\n // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)\n // - groupId: present only for parallel execution (enables column rendering)\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(runStep.index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(runStep.index, existingMeta);\n }\n\n if (runStep.summary != null) {\n updateContent(runStep.index, runStep.summary);\n }\n\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(messageDelta.delta.content);\n if (contentPart != null) {\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(reasoningDelta.delta.content);\n if (contentPart != null) {\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 runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n auth: runStepDelta.delta.auth,\n expires_at: runStepDelta.delta.expires_at,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as {\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 if (!runStep) {\n console.warn('No run step or runId found for completed step event');\n return;\n }\n\n if (result.type === ContentTypes.SUMMARY && 'summary' in result) {\n contentParts[runStep.index] = result.summary as t.MessageContentComplex;\n } else if ('tool_call' in result) {\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: (result as t.ToolEndEvent).tool_call,\n };\n updateContent(runStep.index, contentPart, true);\n }\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,+BAAoD,IAAI,IAC5DA,aAAAA,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,8BAA8B,OAA+B;CACpE,OAAO,MAAM,gBAAgB,QAAQ,MAAM,gBAAgB,YAAY;AAC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C;GACtD,MAAM,EAAE,WAAW;GAMnB,MAAM,EAAE,IAAI,WAAW;GAEvB,MAAM,UAAU,QAAQ,IAAI,MAAM;GAClC,IAAI,CAAC,SAAS;IACZ,QAAQ,KAAK,qDAAqD;IAClE;GACF;GAEA,IAAI,OAAO,SAAA,aAAiC,aAAa,QACvD,aAAa,QAAQ,SAAS,OAAO;QAChC,IAAI,eAAe,QAAQ;IAChC,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAY,OAA0B;IACxC;IACA,cAAc,QAAQ,OAAO,aAAa,IAAI;GAChD;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","names":["LOCAL_CODING_BUNDLE_NAMES","TOOL_OUTPUT_REF_PATTERN","CODE_EXECUTION_TOOLS","getStreamedToolCallAdapter","getStreamedToolCallSeal","getMessageId","buildToolExecutionRequestPlan","safeDispatchCustomEvent","normalizeError","calculateMaxToolResultChars","truncateToolResultContent","coerceRecordArgs","isGoogleLike","handleServerToolResult","handleToolCalls","streamedToolCallAdapterAllowsSequentialSeal","handleToolCallChunks","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 handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\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(graph: StandardGraph): boolean {\n return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;\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 return graph.codeSessionToolNames?.includes(name) === true;\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)) {\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 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 const output =\n result.status === 'error'\n ? `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`\n : truncateToolResultContent(\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content),\n maxToolResultChars\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: JSON.stringify(record.request.args),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\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\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\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 const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n // Track agentId and groupId for each content index (applied to content parts)\n const contentMetaMap = new Map<\n number,\n { agentId?: string; groupId?: number }\n >();\n const getFirstContentPart = (\n content?: t.MessageDelta['content'] | t.MessageContentComplex\n ): t.MessageContentComplex | undefined => {\n if (content == null) {\n return undefined;\n }\n return Array.isArray(content) ? content[0] : content;\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\n const newToolCall: ToolCall & t.PartMetadata = {\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 }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n\n // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts\n // - agentId present → MultiAgentGraph (show agent labels)\n // - groupId present → parallel execution (render columns)\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n (contentParts[index] as t.MessageContentComplex).agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n (contentParts[index] as t.MessageContentComplex).groupId = meta.groupId;\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.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 return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately\n // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)\n // - groupId: present only for parallel execution (enables column rendering)\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(runStep.index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(runStep.index, existingMeta);\n }\n\n if (runStep.summary != null) {\n updateContent(runStep.index, runStep.summary);\n }\n\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(messageDelta.delta.content);\n if (contentPart != null) {\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(reasoningDelta.delta.content);\n if (contentPart != null) {\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 runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n auth: runStepDelta.delta.auth,\n expires_at: runStepDelta.delta.expires_at,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as {\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 if (!runStep) {\n console.warn('No run step or runId found for completed step event');\n return;\n }\n\n if (result.type === ContentTypes.SUMMARY && 'summary' in result) {\n contentParts[runStep.index] = result.summary as t.MessageContentComplex;\n } else if ('tool_call' in result) {\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: (result as t.ToolEndEvent).tool_call,\n };\n updateContent(runStep.index, contentPart, true);\n }\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,+BAAoD,IAAI,IAC5DA,aAAAA,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,8BAA8B,OAA+B;CACpE,OAAO,MAAM,gBAAgB,QAAQ,MAAM,gBAAgB,YAAY;AACzE;AAEA,SAAS,uBAAuB,OA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,cAAc,QAAQ,OAAO,WAAW;GAC1C,CAAC;EAEL,OAAO,IAAI,UAAA,yBAA6C;GACtD,MAAM,EAAE,WAAW;GAMnB,MAAM,EAAE,IAAI,WAAW;GAEvB,MAAM,UAAU,QAAQ,IAAI,MAAM;GAClC,IAAI,CAAC,SAAS;IACZ,QAAQ,KAAK,qDAAqD;IAClE;GACF;GAEA,IAAI,OAAO,SAAA,aAAiC,aAAa,QACvD,aAAa,QAAQ,SAAS,OAAO;QAChC,IAAI,eAAe,QAAQ;IAChC,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAY,OAA0B;IACxC;IACA,cAAc,QAAQ,OAAO,aAAa,IAAI;GAChD;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
|
|
@@ -231,6 +231,8 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
231
231
|
eventDrivenMode = false;
|
|
232
232
|
/** Opt-in stream-layer prestart config for event-driven tools. */
|
|
233
233
|
eagerEventToolExecution;
|
|
234
|
+
/** Host tools that write to the code sandbox and share its exec session. */
|
|
235
|
+
codeSessionToolNames;
|
|
234
236
|
/** Shared per-run prestarted tool registry populated by ChatModelStreamHandler. */
|
|
235
237
|
eagerEventToolExecutions;
|
|
236
238
|
/** Shared per-run per-tool turn counter used by eager and normal event dispatch. */
|
|
@@ -285,7 +287,7 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
285
287
|
* other's in-flight state.
|
|
286
288
|
*/
|
|
287
289
|
anonBatchCounter = 0;
|
|
288
|
-
constructor({ tools, toolMap, name, tags, trace, runLangfuse, agentLangfuse, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, eagerEventToolExecution, eagerEventToolExecutions, eagerEventToolUsageCount, agentId, executingAgentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, humanInTheLoop, toolOutputReferences, toolOutputRegistry, toolExecution, fileCheckpointer }) {
|
|
290
|
+
constructor({ tools, toolMap, name, tags, trace, runLangfuse, agentLangfuse, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, eagerEventToolExecution, eagerEventToolExecutions, eagerEventToolUsageCount, agentId, executingAgentId, directToolNames, codeSessionToolNames, maxContextTokens, maxToolResultChars, hookRegistry, humanInTheLoop, toolOutputReferences, toolOutputRegistry, toolExecution, fileCheckpointer }) {
|
|
289
291
|
super({
|
|
290
292
|
name: name ?? TOOL_NODE_RUN_NAME,
|
|
291
293
|
tags,
|
|
@@ -312,6 +314,7 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
312
314
|
this.agentId = agentId;
|
|
313
315
|
this.executingAgentId = executingAgentId ?? agentId;
|
|
314
316
|
this.directToolNames = directToolNames;
|
|
317
|
+
this.codeSessionToolNames = codeSessionToolNames != null && codeSessionToolNames.length > 0 ? new Set(codeSessionToolNames) : void 0;
|
|
315
318
|
this.maxToolResultChars = maxToolResultChars ?? require_truncation.calculateMaxToolResultChars(maxContextTokens);
|
|
316
319
|
this.hookRegistry = hookRegistry;
|
|
317
320
|
this.humanInTheLoop = humanInTheLoop;
|
|
@@ -567,7 +570,7 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
567
570
|
* still need to travel through `_injected_files`; the legacy
|
|
568
571
|
* `/files/<session_id>` fallback was removed from the executors.
|
|
569
572
|
*/
|
|
570
|
-
if (
|
|
573
|
+
if (this.participatesInCodeSession(call.name)) {
|
|
571
574
|
const codeSession = this.sessions?.get("execute_code");
|
|
572
575
|
const execSessionId = codeSession?.session_id;
|
|
573
576
|
if (execSessionId != null && execSessionId !== "") {
|
|
@@ -1046,13 +1049,24 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
1046
1049
|
* Extracts code execution session context from tool results and stores in Graph.sessions.
|
|
1047
1050
|
* Mirrors the session storage logic in handleRunToolCompletions for direct execution.
|
|
1048
1051
|
*/
|
|
1052
|
+
/**
|
|
1053
|
+
* True when a tool's successful result should fold its returned exec
|
|
1054
|
+
* `session_id` into the shared code session: built-in `CODE_EXECUTION_TOOLS`,
|
|
1055
|
+
* plus host-declared sandbox-writing tools (`codeSessionToolNames`, e.g.
|
|
1056
|
+
* create_file/edit_file). Kept name-scoped rather than a blanket artifact
|
|
1057
|
+
* opt-in so only host-declared tools can influence the shared session.
|
|
1058
|
+
*/
|
|
1059
|
+
participatesInCodeSession(name) {
|
|
1060
|
+
if (name === "") return false;
|
|
1061
|
+
return require_enum.CODE_EXECUTION_TOOLS.has(name) || this.codeSessionToolNames?.has(name) === true;
|
|
1062
|
+
}
|
|
1049
1063
|
storeCodeSessionFromResults(results, requestMap) {
|
|
1050
1064
|
if (!this.sessions) return;
|
|
1051
1065
|
for (let i = 0; i < results.length; i++) {
|
|
1052
1066
|
const result = results[i];
|
|
1053
1067
|
if (result.status !== "success" || result.artifact == null) continue;
|
|
1054
1068
|
const request = requestMap.get(result.toolCallId);
|
|
1055
|
-
if (request?.name == null || request.name === "" || !
|
|
1069
|
+
if (request?.name == null || request.name === "" || !this.participatesInCodeSession(request.name) && request.name !== "skill") continue;
|
|
1056
1070
|
const artifact = result.artifact;
|
|
1057
1071
|
const execSessionId = artifact?.session_id;
|
|
1058
1072
|
if (execSessionId == null || execSessionId === "") continue;
|
|
@@ -1081,7 +1095,7 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
1081
1095
|
const toolMessage = output;
|
|
1082
1096
|
const toolCallId = call.id ?? "";
|
|
1083
1097
|
if (toolMessage.status === "error" && this.errorHandler != null) continue;
|
|
1084
|
-
if (this.sessions &&
|
|
1098
|
+
if (this.sessions && this.participatesInCodeSession(call.name)) {
|
|
1085
1099
|
const artifact = toolMessage.artifact;
|
|
1086
1100
|
const execSessionId = artifact?.session_id;
|
|
1087
1101
|
if (execSessionId != null && execSessionId !== "") updateCodeSession(this.sessions, execSessionId, artifact?.files);
|
|
@@ -1532,7 +1546,7 @@ var ToolNode = class extends require_run.RunnableCallable {
|
|
|
1532
1546
|
if (approvedEntries.length > 0) {
|
|
1533
1547
|
const plan = require_eagerEventExecution.buildToolExecutionRequestPlan({
|
|
1534
1548
|
toolCalls: approvedEntries.map((entry) => {
|
|
1535
|
-
const codeSessionContext =
|
|
1549
|
+
const codeSessionContext = this.participatesInCodeSession(entry.call.name) || entry.call.name === "skill" || entry.call.name === "read_file" ? this.getCodeSessionContext() : void 0;
|
|
1536
1550
|
return {
|
|
1537
1551
|
id: entry.call.id,
|
|
1538
1552
|
name: entry.call.name,
|