@librechat/agents 3.2.54 → 3.2.56

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.
@@ -0,0 +1,110 @@
1
+ import "../common/enum.mjs";
2
+ import "../common/index.mjs";
3
+ //#region src/llm/truncation.ts
4
+ /**
5
+ * Providers whose adapters deliver tool calls as complete, atomic objects
6
+ * rather than streamed argument deltas. Google/Vertex (GenAI) emit each
7
+ * `functionCall` whole and seal it on arrival, so a `MAX_TOKENS` finish does
8
+ * NOT imply the arguments were cut off — the truncation guard must skip them.
9
+ */
10
+ const ATOMIC_TOOL_CALL_ARG_PROVIDERS = new Set(["google", "vertexai"]);
11
+ const MAX_TOKEN_VALUES = new Set([
12
+ "max_tokens",
13
+ "max_token",
14
+ "maxtokens",
15
+ "max_output_tokens"
16
+ ]);
17
+ const LENGTH_VALUES = new Set(["length"]);
18
+ function normalizeStopValue(value) {
19
+ if (typeof value !== "string") return null;
20
+ const normalized = value.trim().toLowerCase();
21
+ if (MAX_TOKEN_VALUES.has(normalized)) return "max_tokens";
22
+ if (LENGTH_VALUES.has(normalized)) return "length";
23
+ return null;
24
+ }
25
+ /**
26
+ * Reads the truncation stop reason off a message, covering every provider
27
+ * shape we stream:
28
+ * - `response_metadata.stopReason` (Bedrock Converse, non-streaming)
29
+ * - `response_metadata.messageStop.stopReason` (Bedrock Converse streaming)
30
+ * - `response_metadata.stop_reason` (Anthropic, non-streaming)
31
+ * - `additional_kwargs.stop_reason` (Anthropic streaming `message_delta`)
32
+ * - `response_metadata.finish_reason` (OpenAI chat-completions / compatible)
33
+ * - `response_metadata.incomplete_details.reason` (OpenAI Responses API)
34
+ * - `response_metadata.finishReason` (Google)
35
+ *
36
+ * Returns the normalized reason when the model stopped because it hit the
37
+ * output token ceiling, otherwise `null`.
38
+ */
39
+ function getTruncationStopReason(message) {
40
+ const meta = message?.response_metadata;
41
+ const additionalKwargs = message?.additional_kwargs;
42
+ if (meta == null && additionalKwargs == null) return null;
43
+ const messageStop = meta?.messageStop;
44
+ const incompleteDetails = meta?.incomplete_details;
45
+ const candidates = [
46
+ meta?.stopReason,
47
+ meta?.stop_reason,
48
+ meta?.finish_reason,
49
+ meta?.finishReason,
50
+ messageStop?.stopReason,
51
+ incompleteDetails?.reason,
52
+ additionalKwargs?.stop_reason
53
+ ];
54
+ for (const candidate of candidates) {
55
+ const normalized = normalizeStopValue(candidate);
56
+ if (normalized != null) return normalized;
57
+ }
58
+ return null;
59
+ }
60
+ function hasOpenToolCall(message) {
61
+ const m = message;
62
+ return (m.tool_calls?.length ?? 0) > 0 || (m.tool_call_chunks?.length ?? 0) > 0 || (m.invalid_tool_calls?.length ?? 0) > 0;
63
+ }
64
+ /**
65
+ * Error raised when a model turn is cut off by the output token limit while it
66
+ * was still emitting a tool call. The arguments are necessarily incomplete, so
67
+ * executing or re-prompting the call would loop on a malformed request. Failing
68
+ * fast with this surfaces an actionable message to the caller instead.
69
+ */
70
+ var OutputTruncationError = class extends Error {
71
+ stopReason;
72
+ toolCallNames;
73
+ constructor(stopReason, toolCallNames) {
74
+ const named = toolCallNames.length > 0 ? ` (tool call: ${toolCallNames.join(", ")})` : "";
75
+ super(`The model response was truncated at the maximum output token limit before the tool call arguments were complete${named}. Increase the model's max output tokens, or have the model produce smaller arguments — for large files, write a lean main file and move bulky content into separate files.`);
76
+ this.name = "OutputTruncationError";
77
+ this.stopReason = stopReason;
78
+ this.toolCallNames = toolCallNames;
79
+ }
80
+ };
81
+ function collectToolCallNames(message) {
82
+ const m = message;
83
+ const names = [
84
+ ...m.tool_calls ?? [],
85
+ ...m.tool_call_chunks ?? [],
86
+ ...m.invalid_tool_calls ?? []
87
+ ].map((tc) => tc.name).filter((name) => typeof name === "string" && name !== "");
88
+ return [...new Set(names)];
89
+ }
90
+ /**
91
+ * Throws {@link OutputTruncationError} when `message` was truncated by the
92
+ * output token limit AND still carries a tool call. For providers that stream
93
+ * tool arguments incrementally (Anthropic, Bedrock, OpenAI), a tool call
94
+ * emitted under truncation has incomplete arguments — the tool-use block is the
95
+ * last thing the model streams — so letting it through makes the agent loop on a
96
+ * malformed call. No-ops for normal completions, truncated plain-text turns, and
97
+ * providers that deliver complete tool calls atomically (Google/Vertex), where
98
+ * `MAX_TOKENS` does not imply the arguments were cut off.
99
+ */
100
+ function assertNotTruncatedToolCall(message, provider) {
101
+ if (message == null) return;
102
+ if (provider != null && ATOMIC_TOOL_CALL_ARG_PROVIDERS.has(provider)) return;
103
+ const stopReason = getTruncationStopReason(message);
104
+ if (stopReason == null || !hasOpenToolCall(message)) return;
105
+ throw new OutputTruncationError(stopReason, collectToolCallNames(message));
106
+ }
107
+ //#endregion
108
+ export { assertNotTruncatedToolCall };
109
+
110
+ //# sourceMappingURL=truncation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"truncation.mjs","names":[],"sources":["../../../src/llm/truncation.ts"],"sourcesContent":["import type { AIMessageChunk, BaseMessage } from '@langchain/core/messages';\nimport { Providers } from '@/common';\n\n/**\n * Providers whose adapters deliver tool calls as complete, atomic objects\n * rather than streamed argument deltas. Google/Vertex (GenAI) emit each\n * `functionCall` whole and seal it on arrival, so a `MAX_TOKENS` finish does\n * NOT imply the arguments were cut off — the truncation guard must skip them.\n */\nconst ATOMIC_TOOL_CALL_ARG_PROVIDERS = new Set<Providers>([\n Providers.GOOGLE,\n Providers.VERTEXAI,\n]);\n\n/**\n * Normalized truncation reasons across providers. Providers disagree on the\n * key and the value: Anthropic/Bedrock use `max_tokens`, OpenAI uses `length`,\n * Google uses `MAX_TOKENS`.\n */\nexport type TruncationStopReason = 'max_tokens' | 'length';\n\nconst MAX_TOKEN_VALUES = new Set([\n 'max_tokens',\n 'max_token',\n 'maxtokens',\n 'max_output_tokens',\n]);\nconst LENGTH_VALUES = new Set(['length']);\n\nfunction normalizeStopValue(value: unknown): TruncationStopReason | null {\n if (typeof value !== 'string') {\n return null;\n }\n const normalized = value.trim().toLowerCase();\n if (MAX_TOKEN_VALUES.has(normalized)) {\n return 'max_tokens';\n }\n if (LENGTH_VALUES.has(normalized)) {\n return 'length';\n }\n return null;\n}\n\n/**\n * Reads the truncation stop reason off a message, covering every provider\n * shape we stream:\n * - `response_metadata.stopReason` (Bedrock Converse, non-streaming)\n * - `response_metadata.messageStop.stopReason` (Bedrock Converse streaming)\n * - `response_metadata.stop_reason` (Anthropic, non-streaming)\n * - `additional_kwargs.stop_reason` (Anthropic streaming `message_delta`)\n * - `response_metadata.finish_reason` (OpenAI chat-completions / compatible)\n * - `response_metadata.incomplete_details.reason` (OpenAI Responses API)\n * - `response_metadata.finishReason` (Google)\n *\n * Returns the normalized reason when the model stopped because it hit the\n * output token ceiling, otherwise `null`.\n */\nexport function getTruncationStopReason(\n message:\n | Pick<BaseMessage, 'response_metadata' | 'additional_kwargs'>\n | undefined\n | null\n): TruncationStopReason | null {\n const meta = message?.response_metadata as\n | Record<string, unknown>\n | undefined;\n const additionalKwargs = message?.additional_kwargs as\n | Record<string, unknown>\n | undefined;\n if (meta == null && additionalKwargs == null) {\n return null;\n }\n\n const messageStop = meta?.messageStop as { stopReason?: unknown } | undefined;\n const incompleteDetails = meta?.incomplete_details as\n | { reason?: unknown }\n | undefined;\n const candidates: unknown[] = [\n meta?.stopReason,\n meta?.stop_reason,\n meta?.finish_reason,\n meta?.finishReason,\n messageStop?.stopReason,\n incompleteDetails?.reason,\n additionalKwargs?.stop_reason,\n ];\n\n for (const candidate of candidates) {\n const normalized = normalizeStopValue(candidate);\n if (normalized != null) {\n return normalized;\n }\n }\n return null;\n}\n\nfunction hasOpenToolCall(message: AIMessageChunk | BaseMessage): boolean {\n const m = message as AIMessageChunk & {\n tool_calls?: unknown[];\n tool_call_chunks?: unknown[];\n invalid_tool_calls?: unknown[];\n };\n return (\n (m.tool_calls?.length ?? 0) > 0 ||\n (m.tool_call_chunks?.length ?? 0) > 0 ||\n (m.invalid_tool_calls?.length ?? 0) > 0\n );\n}\n\n/**\n * Error raised when a model turn is cut off by the output token limit while it\n * was still emitting a tool call. The arguments are necessarily incomplete, so\n * executing or re-prompting the call would loop on a malformed request. Failing\n * fast with this surfaces an actionable message to the caller instead.\n */\nexport class OutputTruncationError extends Error {\n readonly stopReason: TruncationStopReason;\n readonly toolCallNames: string[];\n\n constructor(stopReason: TruncationStopReason, toolCallNames: string[]) {\n const named =\n toolCallNames.length > 0\n ? ` (tool call: ${toolCallNames.join(', ')})`\n : '';\n super(\n 'The model response was truncated at the maximum output token limit before ' +\n `the tool call arguments were complete${named}. Increase the model's max ` +\n 'output tokens, or have the model produce smaller arguments — for large ' +\n 'files, write a lean main file and move bulky content into separate files.'\n );\n this.name = 'OutputTruncationError';\n this.stopReason = stopReason;\n this.toolCallNames = toolCallNames;\n }\n}\n\nfunction collectToolCallNames(message: AIMessageChunk | BaseMessage): string[] {\n const m = message as AIMessageChunk & {\n tool_calls?: Array<{ name?: string }>;\n tool_call_chunks?: Array<{ name?: string }>;\n invalid_tool_calls?: Array<{ name?: string }>;\n };\n const names = [\n ...(m.tool_calls ?? []),\n ...(m.tool_call_chunks ?? []),\n ...(m.invalid_tool_calls ?? []),\n ]\n .map((tc) => tc.name)\n .filter((name): name is string => typeof name === 'string' && name !== '');\n return [...new Set(names)];\n}\n\n/**\n * Throws {@link OutputTruncationError} when `message` was truncated by the\n * output token limit AND still carries a tool call. For providers that stream\n * tool arguments incrementally (Anthropic, Bedrock, OpenAI), a tool call\n * emitted under truncation has incomplete arguments — the tool-use block is the\n * last thing the model streams — so letting it through makes the agent loop on a\n * malformed call. No-ops for normal completions, truncated plain-text turns, and\n * providers that deliver complete tool calls atomically (Google/Vertex), where\n * `MAX_TOKENS` does not imply the arguments were cut off.\n */\nexport function assertNotTruncatedToolCall(\n message: AIMessageChunk | BaseMessage | undefined | null,\n provider?: Providers\n): void {\n if (message == null) {\n return;\n }\n if (provider != null && ATOMIC_TOOL_CALL_ARG_PROVIDERS.has(provider)) {\n return;\n }\n const stopReason = getTruncationStopReason(message);\n if (stopReason == null || !hasOpenToolCall(message)) {\n return;\n }\n throw new OutputTruncationError(stopReason, collectToolCallNames(message));\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,iCAAiC,IAAI,IAAe,CAAA,UAAA,UAG1D,CAAC;AASD,MAAM,mBAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBAAgB,IAAI,IAAI,CAAC,QAAQ,CAAC;AAExC,SAAS,mBAAmB,OAA6C;CACvE,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,MAAM,aAAa,MAAM,KAAK,CAAC,CAAC,YAAY;CAC5C,IAAI,iBAAiB,IAAI,UAAU,GACjC,OAAO;CAET,IAAI,cAAc,IAAI,UAAU,GAC9B,OAAO;CAET,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,wBACd,SAI6B;CAC7B,MAAM,OAAO,SAAS;CAGtB,MAAM,mBAAmB,SAAS;CAGlC,IAAI,QAAQ,QAAQ,oBAAoB,MACtC,OAAO;CAGT,MAAM,cAAc,MAAM;CAC1B,MAAM,oBAAoB,MAAM;CAGhC,MAAM,aAAwB;EAC5B,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,aAAa;EACb,mBAAmB;EACnB,kBAAkB;CACpB;CAEA,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,aAAa,mBAAmB,SAAS;EAC/C,IAAI,cAAc,MAChB,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,gBAAgB,SAAgD;CACvE,MAAM,IAAI;CAKV,QACG,EAAE,YAAY,UAAU,KAAK,MAC7B,EAAE,kBAAkB,UAAU,KAAK,MACnC,EAAE,oBAAoB,UAAU,KAAK;AAE1C;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C;CACA;CAEA,YAAY,YAAkC,eAAyB;EACrE,MAAM,QACJ,cAAc,SAAS,IACnB,gBAAgB,cAAc,KAAK,IAAI,EAAE,KACzC;EACN,MACE,kHAC0C,MAAM,4KAGlD;EACA,KAAK,OAAO;EACZ,KAAK,aAAa;EAClB,KAAK,gBAAgB;CACvB;AACF;AAEA,SAAS,qBAAqB,SAAiD;CAC7E,MAAM,IAAI;CAKV,MAAM,QAAQ;EACZ,GAAI,EAAE,cAAc,CAAC;EACrB,GAAI,EAAE,oBAAoB,CAAC;EAC3B,GAAI,EAAE,sBAAsB,CAAC;CAC/B,CAAC,CACE,KAAK,OAAO,GAAG,IAAI,CAAC,CACpB,QAAQ,SAAyB,OAAO,SAAS,YAAY,SAAS,EAAE;CAC3E,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC;AAC3B;;;;;;;;;;;AAYA,SAAgB,2BACd,SACA,UACM;CACN,IAAI,WAAW,MACb;CAEF,IAAI,YAAY,QAAQ,+BAA+B,IAAI,QAAQ,GACjE;CAEF,MAAM,aAAa,wBAAwB,OAAO;CAClD,IAAI,cAAc,QAAQ,CAAC,gBAAgB,OAAO,GAChD;CAEF,MAAM,IAAI,sBAAsB,YAAY,qBAAqB,OAAO,CAAC;AAC3E"}
@@ -57,6 +57,11 @@ function hasToolOutputReference(value) {
57
57
  if (value !== null && typeof value === "object") return Object.values(value).some((item) => hasToolOutputReference(item));
58
58
  return false;
59
59
  }
60
+ function isEagerExecutionExcludedTool(name, graph) {
61
+ if (name === "") return false;
62
+ const excluded = graph.eagerEventToolExecution?.excludeToolNames;
63
+ return excluded != null && excluded.includes(name);
64
+ }
60
65
  function isDirectGraphTool(name, agentContext) {
61
66
  if (name.startsWith("lc_transfer_to_")) return true;
62
67
  return (agentContext?.graphTools)?.some((tool) => "name" in tool && tool.name === name) === true;
@@ -248,10 +253,10 @@ function createEagerToolExecutionPlan(args) {
248
253
  toolCalls
249
254
  })) return;
250
255
  if (graph.toolOutputReferences?.enabled === true && toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))) return;
251
- const candidateToolCalls = skipExisting ? toolCalls.filter((toolCall) => {
256
+ const candidateToolCalls = (skipExisting ? toolCalls.filter((toolCall) => {
252
257
  if (toolCall.id == null || toolCall.id === "") return true;
253
258
  return !graph.eagerEventToolExecutions.has(toolCall.id);
254
- }) : toolCalls;
259
+ }) : toolCalls).filter((toolCall) => !isEagerExecutionExcludedTool(toolCall.name, graph));
255
260
  if (candidateToolCalls.length === 0) return [];
256
261
  if (candidateToolCalls.some((toolCall) => toolCall.id == null || toolCall.id === "" || toolCall.name === "" || !skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))) return;
257
262
  const plan = buildToolExecutionRequestPlan({
@@ -1 +1 @@
1
- {"version":3,"file":"stream.mjs","names":["completeData"],"sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n streamedToolCallAdapterAllowsSequentialSeal,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n 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 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 candidateToolCalls = 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 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,IAC5D,yBACF;;;;;;AAWA,SAAS,qBAAqB,SAG5B;CAEA,IAAI,CAAC,QAAQ,SAAS,SAAS,GAC7B,OAAO;EAAE,MAAM;EAAS,UAAU;CAAG;CAGvC,IAAI,aAAa;CACjB,MAAM,iBAA2B,CAAC;CAClC,IAAI,WAAW;CAEf,OAAO,WAAW,QAAQ,QAAQ;EAChC,MAAM,aAAa,QAAQ,QAAQ,WAAW,QAAQ;EAEtD,IAAI,eAAe,IAAI;GAErB,cAAc,QAAQ,MAAM,QAAQ;GACpC;EACF;EAGA,cAAc,QAAQ,MAAM,UAAU,UAAU;EAEhD,MAAM,WAAW,QAAQ,QAAQ,YAAY,UAAU;EACvD,IAAI,aAAa,IAAI;GAEnB,cAAc,QAAQ,MAAM,UAAU;GACtC;EACF;EAGA,MAAM,eAAe,QAAQ,MAAM,aAAa,GAAG,QAAQ;EAC3D,eAAe,KAAK,YAAY;EA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ACZ,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.mjs","names":["completeData"],"sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n streamedToolCallAdapterAllowsSequentialSeal,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n 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,IAC5D,yBACF;;;;;;AAWA,SAAS,qBAAqB,SAG5B;CAEA,IAAI,CAAC,QAAQ,SAAS,SAAS,GAC7B,OAAO;EAAE,MAAM;EAAS,UAAU;CAAG;CAGvC,IAAI,aAAa;CACjB,MAAM,iBAA2B,CAAC;CAClC,IAAI,WAAW;CAEf,OAAO,WAAW,QAAQ,QAAQ;EAChC,MAAM,aAAa,QAAQ,QAAQ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