@librechat/agents 3.2.58 → 3.2.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs +31 -7
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +7 -0
- package/dist/cjs/run.cjs +4 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +2 -1
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +58 -9
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +4 -2
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +57 -7
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +9 -3
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +114 -11
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/eagerEventExecution.cjs +18 -1
- package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +31 -7
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -3
- package/dist/esm/run.mjs +4 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +2 -1
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +56 -10
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +4 -2
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +54 -8
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +9 -3
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +115 -12
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/eagerEventExecution.mjs +18 -2
- package/dist/esm/tools/eagerEventExecution.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +21 -3
- package/dist/types/run.d.ts +1 -0
- package/dist/types/tools/BashExecutor.d.ts +13 -0
- package/dist/types/tools/CodeExecutor.d.ts +14 -0
- package/dist/types/tools/ToolNode.d.ts +60 -1
- package/dist/types/tools/eagerEventExecution.d.ts +8 -0
- package/dist/types/types/hitl.d.ts +49 -3
- package/dist/types/types/run.d.ts +21 -0
- package/dist/types/types/tools.d.ts +95 -1
- package/package.json +1 -1
- package/src/graphs/Graph.ts +74 -28
- package/src/run.ts +4 -0
- package/src/specs/ask-user-question-batch.test.ts +289 -0
- package/src/specs/tool-error-resume.test.ts +194 -0
- package/src/stream.ts +17 -1
- package/src/tools/BashExecutor.ts +107 -14
- package/src/tools/BashProgrammaticToolCalling.ts +20 -1
- package/src/tools/CodeExecutor.ts +113 -9
- package/src/tools/ProgrammaticToolCalling.ts +27 -1
- package/src/tools/ToolNode.ts +208 -31
- package/src/tools/__tests__/BashExecutor.test.ts +39 -0
- package/src/tools/__tests__/CodeExecutor.stateful.test.ts +113 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +86 -0
- package/src/tools/__tests__/eagerEventExecution.session.test.ts +92 -0
- package/src/tools/__tests__/hitl.test.ts +48 -0
- package/src/tools/eagerEventExecution.ts +32 -5
- package/src/types/hitl.ts +49 -3
- package/src/types/run.ts +21 -0
- package/src/types/tools.ts +102 -1
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -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 isEagerExecutionExcludedTool(\n name: string,\n graph: StandardGraph\n): boolean {\n if (name === '') {\n return false;\n }\n const excluded = graph.eagerEventToolExecution?.excludeToolNames;\n if (excluded != null && excluded.includes(name)) {\n return true;\n }\n // A code-session participant writes to the shared sandbox, so it is\n // side-effecting: never prestart it speculatively (a revised/superseded turn\n // would leave the write applied). Implies exclusion without the host having\n // to also list the name in excludeToolNames.\n return graph.codeSessionToolNames?.includes(name) === true;\n}\n\nfunction isDirectGraphTool(\n name: string,\n agentContext: AgentContext | undefined\n): boolean {\n if (name.startsWith(Constants.LC_TRANSFER_TO_)) {\n return true;\n }\n return (\n (agentContext?.graphTools as t.GenericTool[] | undefined)?.some(\n (tool) => 'name' in tool && tool.name === name\n ) === true\n );\n}\n\nfunction isDirectLocalTool(name: string, graph: StandardGraph): boolean {\n const toolExecution = graph.toolExecution;\n const engine = toolExecution?.engine;\n if (\n toolExecution == null ||\n (engine !== 'local' && engine !== 'cloudflare-sandbox')\n ) {\n return false;\n }\n const includeCodingTools =\n engine === 'cloudflare-sandbox'\n ? toolExecution.cloudflare?.includeCodingTools\n : toolExecution.local?.includeCodingTools;\n if (includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE &&\n graph.codeSessionToolNames?.includes(name) !== true\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (\n graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&\n graph.eventToolExecutionAvailable !== true\n ) {\n return false;\n }\n return true;\n}\n\nfunction hasFinalToolCallSignal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n const finishReason =\n metadata?.finish_reason ??\n metadata?.finishReason ??\n metadata?.stop_reason ??\n metadata?.stopReason;\n return finishReason === 'tool_calls' || finishReason === 'tool_use';\n}\n\nfunction canPrestartSequentialStreamedToolChunks(\n agentContext: AgentContext | undefined\n): boolean {\n // Anthropic seals each prior streamed tool-use block when the next indexed\n // tool-use block begins. Live Kimi/Moonshot streams can still revise prior\n // args after advancing to the next index, so keep those on the final\n // tool-call path unless they grow an explicit adapter seal.\n return agentContext?.provider === Providers.ANTHROPIC;\n}\n\nfunction hasExplicitStreamedToolCallSeals(\n chunk: Partial<AIMessageChunk>\n): boolean {\n return (\n getStreamedToolCallAdapter(\n chunk.response_metadata as Record<string, unknown> | undefined\n ) != null\n );\n}\n\n/**\n * True when a provider adapter marked every tool call on this chunk as\n * complete on arrival (seal kind `all`), e.g. Google GenAI / Vertex AI, whose\n * protocol delivers function calls as whole objects rather than arg deltas.\n */\nfunction hasOnArrivalToolCallSeal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n return (\n getStreamedToolCallAdapter(metadata) != null &&\n getStreamedToolCallSeal(metadata)?.kind === 'all'\n );\n}\n\nfunction hasDirectToolCallInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n}): boolean {\n const { graph, agentContext, toolCalls } = args;\n return toolCalls.some(\n (toolCall) =>\n toolCall.name !== '' &&\n (isDirectGraphTool(toolCall.name, agentContext) ||\n isDirectLocalTool(toolCall.name, graph))\n );\n}\n\nfunction hasPotentialDirectToolInStreamContext(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, agentContext } = args;\n const engine = graph.toolExecution?.engine;\n if (engine === 'local' || engine === 'cloudflare-sandbox') {\n return true;\n }\n if ((agentContext?.graphTools?.length ?? 0) > 0) {\n return true;\n }\n return false;\n}\n\nfunction hasDirectToolCallChunkInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCallChunks?: ToolCallChunk[];\n}): boolean {\n const { graph, agentContext, toolCallChunks } = args;\n return (\n toolCallChunks?.some(\n (toolCallChunk) =>\n toolCallChunk.name != null &&\n toolCallChunk.name !== '' &&\n (isDirectGraphTool(toolCallChunk.name, agentContext) ||\n isDirectLocalTool(toolCallChunk.name, graph))\n ) === true\n );\n}\n\nfunction hasDirectToolCallChunkStateInStep(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n stepKey: string;\n}): boolean {\n const { graph, agentContext, stepKey } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n const name = state.name;\n if (\n name != null &&\n name !== '' &&\n (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction isGoogleServerSideToolContentPart(\n contentPart: t.MessageContentComplex\n): boolean {\n return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';\n}\n\nfunction isTextContentPart(contentPart: t.MessageContentComplex): boolean {\n return contentPart.type?.startsWith(ContentTypes.TEXT) ?? false;\n}\n\nfunction isReasoningContentPart(contentPart: t.MessageContentComplex): boolean {\n return (\n (contentPart.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n contentPart.type === 'redacted_thinking'\n );\n}\n\nfunction getReasoningTextFromContentPart(\n contentPart: t.MessageContentComplex\n): string {\n return (\n (contentPart as t.ThinkingContentText).thinking ??\n (contentPart as Partial<t.GoogleReasoningContentText>).reasoning ??\n (contentPart as Partial<t.BedrockReasoningContentText>).reasoningText\n ?.text ??\n ''\n );\n}\n\nfunction getReasoningTextFromChunk(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n): string {\n const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (typeof reasoning === 'string') {\n return reasoning;\n }\n return reasoning?.summary?.[0]?.text ?? '';\n}\n\nconst googleServerSideToolStepIdsByGraph = new WeakMap<\n StandardGraph,\n Set<string>\n>();\n\nfunction markGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): void {\n const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();\n stepIds.add(stepId);\n googleServerSideToolStepIdsByGraph.set(graph, stepIds);\n}\n\nfunction isGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): boolean {\n return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;\n}\n\nfunction shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n}: {\n graph: StandardGraph;\n stepId: string;\n runStep?: t.RunStep;\n content: string | t.MessageContentComplex[];\n}): boolean {\n if (\n runStep?.type !== StepTypes.MESSAGE_CREATION ||\n !isGoogleServerSideToolMessageStep(graph, stepId)\n ) {\n return false;\n }\n if (typeof content === 'string') {\n return true;\n }\n return (\n content.every((c) => isTextContentPart(c)) ||\n content.every((c) => isReasoningContentPart(c))\n );\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n metadata?: Record<string, unknown>;\n}): Promise<string> {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n return graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n}\n\nasync function dispatchMessageContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n for (const contentPart of content) {\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n if (isGoogleServerSideToolContentPart(contentPart)) {\n markGoogleServerSideToolMessageStep(graph, currentStepId);\n }\n await graph.dispatchMessageDelta(\n currentStepId,\n {\n content: [contentPart],\n },\n metadata\n );\n }\n}\n\nasync function dispatchReasoningContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n if (content.length === 0) {\n return;\n }\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n await graph.dispatchReasoningDelta(\n currentStepId,\n {\n content,\n },\n metadata\n );\n}\n\nasync function dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n const reasoningContent: t.MessageContentComplex[] = [];\n const reasoningText = getReasoningTextFromChunk(chunk, agentContext);\n if (reasoningText !== '') {\n reasoningContent.push({\n type: ContentTypes.THINK,\n think: reasoningText,\n });\n }\n reasoningContent.push(\n ...content\n .filter((contentPart) => isReasoningContentPart(contentPart))\n .map((contentPart) => ({\n type: ContentTypes.THINK,\n think: getReasoningTextFromContentPart(contentPart),\n }))\n .filter((contentPart) => contentPart.think !== '')\n );\n await dispatchReasoningContentParts({\n graph,\n stepKey,\n content: reasoningContent,\n metadata,\n });\n\n const messageContent = content.filter(\n (contentPart) =>\n isTextContentPart(contentPart) ||\n isGoogleServerSideToolContentPart(contentPart)\n );\n await dispatchMessageContentParts({\n graph,\n stepKey,\n content: messageContent,\n metadata,\n });\n}\n\ntype EagerToolExecutionEntry = {\n id: string;\n toolName: string;\n coercedArgs: Record<string, unknown>;\n request: t.ToolCallRequest;\n};\n\nfunction createEagerToolExecutionPlan(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): EagerToolExecutionEntry[] | undefined {\n const {\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting = false,\n } = args;\n if (\n !isEagerToolExecutionEnabledForBatch({\n graph,\n metadata,\n agentContext,\n })\n ) {\n return undefined;\n }\n\n if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {\n return undefined;\n }\n if (\n graph.toolOutputReferences?.enabled === true &&\n toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))\n ) {\n return undefined;\n }\n\n const unstartedToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n // Drop host-excluded tools only AFTER the batch-level guards above have run\n // against the full batch, so excluding a call never hides a sibling direct\n // tool from `hasDirectToolCallInBatch`. Excluded calls fall through to normal\n // ToolNode execution; siblings may still eager-execute.\n const candidateToolCalls = unstartedToolCalls.filter(\n (toolCall) => !isEagerExecutionExcludedTool(toolCall.name, graph)\n );\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const records: t.EagerEventToolExecution[] = [];\n const promise: Promise<t.EagerEventToolExecutionOutcome> = new Promise<\n t.ToolExecuteResult[]\n >((resolve, reject) => {\n let dispatchSettled = false;\n let resultSettled = false;\n let settledResults: t.ToolExecuteResult[] | undefined;\n const maybeResolve = (): void => {\n if (dispatchSettled && resultSettled) {\n resolve(settledResults ?? []);\n }\n };\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: entries.map((entry) => entry.request),\n userId: graph.config?.configurable?.user_id as string | undefined,\n agentId: agentContext?.agentId,\n configurable: graph.config?.configurable as\n | Record<string, unknown>\n | undefined,\n metadata,\n resolve: (results): void => {\n resultSettled = true;\n settledResults = results;\n maybeResolve();\n },\n reject,\n };\n\n void safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n graph.config\n )\n .then(() => {\n dispatchSettled = true;\n maybeResolve();\n })\n .catch(reject);\n }).then(\n async (results): Promise<t.EagerEventToolExecutionOutcome> => {\n await dispatchEagerToolCompletions({\n graph,\n agentContext,\n records,\n results,\n });\n return { results };\n },\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n const record: t.EagerEventToolExecution = {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\n };\n records.push(record);\n graph.eagerEventToolExecutions.set(entry.id, record);\n }\n}\n\nasync function dispatchEagerToolCompletions(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n records: t.EagerEventToolExecution[];\n results: t.ToolExecuteResult[];\n}): Promise<void> {\n const { graph, agentContext, records, results } = args;\n const recordById = new Map(\n records.map((record) => [record.toolCallId, record])\n );\n const maxToolResultChars =\n agentContext?.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext?.maxContextTokens);\n\n for (const result of results) {\n const record = recordById.get(result.toolCallId);\n if (record == null) {\n continue;\n }\n if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {\n continue;\n }\n const stepId =\n record.request.stepId ??\n graph.toolCallStepIds.get(result.toolCallId) ??\n '';\n if (stepId === '') {\n continue;\n }\n const output =\n result.status === 'error'\n ? `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`\n : truncateToolResultContent(\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content),\n maxToolResultChars\n );\n\n try {\n const dispatched = await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: record.request.turn ?? 0,\n type: 'tool_call' as const,\n eager: true,\n tool_call: {\n args: JSON.stringify(record.request.args),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n graph.config\n );\n if (dispatched === false) {\n continue;\n }\n record.completionDispatched = true;\n } catch (error) {\n // Let ToolNode dispatch the completion through the normal path later.\n\n console.warn(\n `[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`,\n error instanceof Error ? error.message : error\n );\n }\n }\n}\n\nfunction getEagerToolChunkKey(\n stepKey: string,\n toolCallChunk: ToolCallChunk\n): string | undefined {\n let chunkKey: string | undefined;\n if (typeof toolCallChunk.index === 'number') {\n chunkKey = String(toolCallChunk.index);\n } else if (toolCallChunk.id != null && toolCallChunk.id !== '') {\n chunkKey = toolCallChunk.id;\n }\n if (chunkKey == null) {\n return undefined;\n }\n return `${stepKey}\\u0000${chunkKey}`;\n}\n\nfunction getEagerToolChunkIndex(\n toolCallChunk: ToolCallChunk\n): number | undefined {\n return typeof toolCallChunk.index === 'number'\n ? toolCallChunk.index\n : undefined;\n}\n\nfunction pruneEagerToolCallChunkStates(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallIds?: ReadonlySet<string>;\n clearStep?: boolean;\n}): void {\n const { graph, stepKey, toolCallIds, clearStep = false } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (\n clearStep ||\n (state.id != null && toolCallIds?.has(state.id) === true)\n ) {\n graph.eagerEventToolCallChunks.delete(key);\n }\n }\n}\n\nfunction isEagerToolChunkStateComplete(\n state: t.EagerEventToolCallChunkState\n): boolean {\n return (\n state.id != null &&\n state.id !== '' &&\n state.name != null &&\n state.name !== '' &&\n coerceRecordArgs(state.argsText) != null\n );\n}\n\nfunction mergeToolCallArgsText(existing: string, incoming: string): string {\n if (incoming === '') {\n return existing;\n }\n if (existing === '') {\n return incoming;\n }\n if (incoming === existing) {\n try {\n JSON.parse(incoming);\n return incoming;\n } catch {\n return `${existing}${incoming}`;\n }\n }\n if (incoming.startsWith(existing)) {\n return incoming;\n }\n if (existing.startsWith(incoming)) {\n return existing;\n }\n try {\n JSON.parse(existing);\n JSON.parse(incoming);\n return incoming;\n } catch {\n // Fall through to delta concatenation.\n }\n for (\n let overlap = Math.min(existing.length, incoming.length);\n overlap >= 8;\n overlap -= 1\n ) {\n if (existing.endsWith(incoming.slice(0, overlap))) {\n return `${existing}${incoming.slice(overlap)}`;\n }\n }\n return `${existing}${incoming}`;\n}\n\nfunction recordEagerToolCallChunks(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n}): void {\n const { graph, stepKey, toolCallChunks } = args;\n if (toolCallChunks == null || toolCallChunks.length === 0) {\n return;\n }\n\n // Streamed args can be cumulative and parseable before the provider has\n // sealed the call. Recording stays separate from dispatch so the boundary\n // logic can wait for either a later tool index or the final tool-call signal.\n for (const toolCallChunk of toolCallChunks) {\n const key = getEagerToolChunkKey(stepKey, toolCallChunk);\n if (key == null) {\n continue;\n }\n\n const incomingId =\n toolCallChunk.id != null && toolCallChunk.id !== ''\n ? toolCallChunk.id\n : undefined;\n const incomingName =\n toolCallChunk.name != null && toolCallChunk.name !== ''\n ? toolCallChunk.name\n : undefined;\n const previous = graph.eagerEventToolCallChunks.get(key);\n const shouldReset =\n previous != null &&\n ((incomingId != null &&\n previous.id != null &&\n incomingId !== previous.id) ||\n (incomingName != null &&\n previous.name != null &&\n incomingName !== previous.name));\n const existing =\n previous == null || shouldReset\n ? {\n argsText: '',\n }\n : previous;\n const id = incomingId ?? existing.id;\n const name = incomingName ?? existing.name;\n const incomingArgs = toolCallChunk.args ?? '';\n const isRepeatedObservedFragment =\n incomingArgs !== '' &&\n incomingArgs.length > 1 &&\n incomingArgs === existing.lastArgsFragment;\n const argsText = isRepeatedObservedFragment\n ? existing.argsText\n : mergeToolCallArgsText(existing.argsText, incomingArgs);\n const next = {\n id,\n name,\n argsText,\n index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,\n lastArgsFragment:\n incomingArgs !== '' ? incomingArgs : existing.lastArgsFragment,\n };\n graph.eagerEventToolCallChunks.set(key, next);\n }\n}\n\nfunction getStreamedReadyToolCalls(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): ToolCall[] {\n const {\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal = false,\n sealAll = false,\n } = args;\n const currentIndices = new Set<number>();\n for (const toolCallChunk of toolCallChunks ?? []) {\n const index = getEagerToolChunkIndex(toolCallChunk);\n if (index != null) {\n currentIndices.add(index);\n }\n }\n const highestCurrentIndex =\n currentIndices.size > 0 ? Math.max(...currentIndices) : undefined;\n const prefix = `${stepKey}\\u0000`;\n const readyEntries: Array<{\n key: string;\n state: t.EagerEventToolCallChunkState;\n }> = [];\n\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {\n graph.eagerEventToolCallChunks.delete(key);\n continue;\n }\n if (!isEagerToolChunkStateComplete(state)) {\n continue;\n }\n const isSealedByLaterChunk =\n allowSequentialSeal &&\n highestCurrentIndex != null &&\n state.index != null &&\n state.index < highestCurrentIndex &&\n !currentIndices.has(state.index);\n const isSealedExplicitly =\n seal?.kind === 'single' &&\n ((seal.id != null && state.id === seal.id) ||\n (seal.index != null && state.index === seal.index));\n if (\n sealAll ||\n seal?.kind === 'all' ||\n isSealedByLaterChunk ||\n isSealedExplicitly\n ) {\n readyEntries.push({ key, state });\n }\n }\n\n pruneEagerToolCallChunkStates({\n graph,\n stepKey,\n toolCallIds: new Set(\n readyEntries\n .map(({ state }) => state.id)\n .filter((id): id is string => id != null && id !== '')\n ),\n });\n if (sealAll) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n\n return readyEntries\n .sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0))\n .flatMap(({ state }) => {\n const args = coerceRecordArgs(state.argsText);\n if (args == null) {\n return [];\n }\n return [\n {\n id: state.id,\n name: state.name ?? '',\n args,\n },\n ];\n });\n}\n\nfunction startReadyStreamedEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): void {\n const {\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n } = args;\n if (\n hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||\n hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||\n hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||\n !isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })\n ) {\n return;\n }\n const toolCalls = getStreamedReadyToolCalls({\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n });\n if (toolCalls.length === 0) {\n return;\n }\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting: true,\n });\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n isGoogleLike(provider) &&\n Array.isArray(chunk?.content) &&\n chunk.content.some((c) => isGoogleServerSideToolContentPart(c))\n ) {\n return chunk.content;\n }\n\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n if (provider === Providers.OPENROUTER) {\n // Content presence signals end of reasoning phase - prefer content over reasoning\n // This handles transitional chunks that may have both reasoning and content\n if (typeof chunk?.content === 'string' && chunk.content !== '') {\n return chunk.content;\n }\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n const reasoningContent = chunk?.additional_kwargs?.reasoning_content as\n | string\n | undefined;\n if (reasoningContent != null && reasoningContent !== '') {\n return reasoningContent;\n }\n return chunk?.content;\n }\n const keyedReasoning = chunk?.additional_kwargs?.[reasoningKey] as\n | string\n | undefined;\n if (\n typeof chunk?.content === 'string' &&\n chunk.content !== '' &&\n keyedReasoning != null &&\n keyedReasoning !== ''\n ) {\n return chunk.content;\n }\n return ((keyedReasoning as string | undefined) ?? '') || chunk?.content;\n}\n\nfunction isDisableStreamingEnabled(\n clientOptions: t.ClientOptions | undefined\n): boolean {\n return (\n clientOptions != null &&\n 'disableStreaming' in clientOptions &&\n clientOptions.disableStreaming === true\n );\n}\n\nfunction hasReasoningContent(\n value: string | ReasoningSummaryLike | object[] | null | undefined\n): boolean {\n if (typeof value === 'string') {\n return value !== '';\n }\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n if (value == null) {\n return false;\n }\n return (\n value.summary?.some(\n (summary) => summary.text != null && summary.text.length > 0\n ) === true\n );\n}\n\nfunction shouldDeferMixedFinalReasoningChunk({\n chunk,\n agentContext,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n}): boolean {\n if (\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n typeof chunk.content !== 'string' ||\n chunk.content === ''\n ) {\n return false;\n }\n const additionalKwargs = chunk.additional_kwargs;\n if (\n agentContext.provider === Providers.OPENROUTER &&\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n ) {\n return true;\n }\n if (!isDisableStreamingEnabled(agentContext.clientOptions)) {\n return false;\n }\n return (\n hasReasoningContent(\n additionalKwargs?.[agentContext.reasoningKey] as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning_content as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(\n additionalKwargs?.reasoning as\n | string\n | ReasoningSummaryLike\n | null\n | undefined\n ) ||\n hasReasoningContent(additionalKwargs?.reasoning_details as object[])\n );\n}\n\nfunction hasCurrentTextDeltaStep({\n graph,\n metadata,\n}: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (metadata == null) {\n return false;\n }\n const baseStepKey = graph.getStepBaseKey(metadata);\n for (const [stepKey, stepIds] of graph.stepKeyIds) {\n if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {\n continue;\n }\n if (stepIds.some((stepId) => graph.messageStepHasTextDeltas.has(stepId))) {\n return true;\n }\n }\n return false;\n}\n\nfunction shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n}: {\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n}): boolean {\n if (\n agentContext.provider !== Providers.OPENROUTER ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n (chunk.content != null && chunk.content !== '')\n ) {\n return false;\n }\n return (\n (hasReasoningContent(chunk.additional_kwargs?.reasoning as string) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_content as string\n ) ||\n hasReasoningContent(\n chunk.additional_kwargs?.reasoning_details as object[]\n )) &&\n hasCurrentTextDeltaStep({ graph, metadata })\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n if (shouldDeferMixedFinalReasoningChunk({ chunk, agentContext })) {\n return;\n }\n if (\n shouldSkipLateOpenRouterReasoningChunk({\n chunk,\n agentContext,\n graph,\n metadata,\n })\n ) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n const stepKey = graph.getStepKey(metadata);\n let hasToolCalls = false;\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const hasGoogleServerSideToolContent =\n isGoogleLike(agentContext.provider) &&\n Array.isArray(content) &&\n content.some((c) => isGoogleServerSideToolContentPart(c));\n if (hasGoogleServerSideToolContent && Array.isArray(content)) {\n await dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n });\n }\n\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n if (hasFinalToolCallSignal(chunk)) {\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n if (!hasToolCallChunks) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n } else if (\n hasOnArrivalToolCallSeal(chunk) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext })\n ) {\n // Providers like Google never signal `tool_calls`/`tool_use` as the\n // finish reason, but their adapters seal calls on arrival — prestart\n // these mid-stream under the same direct-tool guard as streamed\n // chunk sealing.\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls: chunk.tool_calls,\n skipExisting: true,\n });\n }\n }\n\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n const streamedToolCallSeal = getStreamedToolCallSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const allowSequentialSeal =\n canPrestartSequentialStreamedToolChunks(agentContext) ||\n streamedToolCallAdapterAllowsSequentialSeal(\n chunk.response_metadata as Record<string, unknown> | undefined\n );\n const canStreamEager =\n (allowSequentialSeal || hasExplicitStreamedToolCallSeals(chunk)) &&\n !hasPotentialDirectToolInStreamContext({ graph, agentContext }) &&\n isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext });\n if (canStreamEager) {\n recordEagerToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n if (canStreamEager) {\n startReadyStreamedEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n seal: streamedToolCallSeal,\n allowSequentialSeal,\n sealAll: hasFinalToolCallSignal(chunk),\n });\n }\n }\n\n if (isEmptyContent) {\n return;\n }\n\n if (hasGoogleServerSideToolContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n let stepId = graph.getStepIdByKey(stepKey);\n let runStep = graph.getRunStep(stepId);\n if (\n shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n })\n ) {\n stepId = await dispatchMessageCreationStep({ graph, stepKey, metadata });\n runStep = graph.getRunStep(stepId);\n }\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n },\n metadata\n );\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n },\n metadata\n );\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(\n newStepId,\n {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n },\n metadata\n );\n }\n } else {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n },\n metadata\n );\n }\n } else if (content.every((c) => isTextContentPart(c))) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content,\n },\n metadata\n );\n } else if (content.every((c) => isReasoningContentPart(c))) {\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText\n ?.text ??\n '',\n })),\n },\n metadata\n );\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT ||\n chunk.content[0]?.type === 'redacted_thinking')\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Only set reasoning as valid if content is NOT present (content signals end of reasoning)\n (chunk.content == null || chunk.content === '') &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== '') ||\n (typeof chunk.additional_kwargs?.reasoning_content === 'string' &&\n chunk.additional_kwargs.reasoning_content !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n agentContext.reasoningTransitionCount++;\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n // Track agentId and groupId for each content index (applied to content parts)\n const contentMetaMap = new Map<\n number,\n { agentId?: string; groupId?: number }\n >();\n const getFirstContentPart = (\n content?: t.MessageDelta['content'] | t.MessageContentComplex\n ): t.MessageContentComplex | undefined => {\n if (content == null) {\n return undefined;\n }\n return Array.isArray(content) ? content[0] : content;\n };\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index] && partType !== ContentTypes.TOOL_CALL) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (partType === 'toolCall' || partType === 'toolResponse') {\n contentParts[index] = contentPart;\n } else if (partType === ContentTypes.SUMMARY) {\n const currentSummary = contentParts[index] as\n | t.SummaryContentBlock\n | undefined;\n const incoming = contentPart as t.SummaryContentBlock;\n contentParts[index] = {\n ...incoming,\n content: [\n ...(currentSummary?.content ?? []),\n ...(incoming.content ?? []),\n ],\n };\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart & t.PartMetadata;\n })\n | undefined;\n if (!finalUpdate && existingContent?.tool_call?.progress === 1) {\n return;\n }\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n const auth =\n contentPart.tool_call.auth ?? existingContent?.tool_call?.auth;\n const expiresAt =\n contentPart.tool_call.expires_at ??\n existingContent?.tool_call?.expires_at;\n if (auth != null) {\n newToolCall.auth = auth;\n newToolCall.expires_at = expiresAt;\n }\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n\n // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts\n // - agentId present → MultiAgentGraph (show agent labels)\n // - groupId present → parallel execution (render columns)\n const meta = contentMetaMap.get(index);\n if (meta?.agentId != null) {\n (contentParts[index] as t.MessageContentComplex).agentId = meta.agentId;\n }\n if (meta?.groupId != null) {\n (contentParts[index] as t.MessageContentComplex).groupId = meta.groupId;\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.ReasoningDeltaEvent\n | t.RunStepDeltaEvent\n | t.SummarizeDeltaData\n | t.SummarizeCompleteEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_SUMMARIZE_DELTA) {\n const deltaData = data as t.SummarizeDeltaData;\n const runStep = stepMap.get(deltaData.id);\n if (!runStep) {\n console.warn('No run step found for summarize delta event');\n return;\n }\n updateContent(runStep.index, deltaData.delta.summary);\n return;\n }\n\n if (event === GraphEvents.ON_SUMMARIZE_COMPLETE) {\n const completeData = data as t.SummarizeCompleteEvent;\n const summary = completeData.summary;\n if (!summary?.boundary) {\n return;\n }\n const runStep = stepMap.get(summary.boundary.messageId);\n if (!runStep) {\n return;\n }\n // Replace accumulated delta text with the authoritative final summary.\n // Multi-stage summarization streams deltas from each chunk, which\n // concatenate in updateContent. This event carries only the correct\n // final text from the last stage.\n contentParts[runStep.index] = summary;\n return;\n }\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately\n // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)\n // - groupId: present only for parallel execution (enables column rendering)\n const hasAgentId = runStep.agentId != null && runStep.agentId !== '';\n const hasGroupId = runStep.groupId != null;\n if (hasAgentId || hasGroupId) {\n const existingMeta = contentMetaMap.get(runStep.index) ?? {};\n if (hasAgentId) {\n existingMeta.agentId = runStep.agentId;\n }\n if (hasGroupId) {\n existingMeta.groupId = runStep.groupId;\n }\n contentMetaMap.set(runStep.index, existingMeta);\n }\n\n if (runStep.summary != null) {\n updateContent(runStep.index, runStep.summary);\n }\n\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(messageDelta.delta.content);\n if (contentPart != null) {\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n const contentPart = getFirstContentPart(reasoningDelta.delta.content);\n if (contentPart != null) {\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n auth: runStepDelta.delta.auth,\n expires_at: runStepDelta.delta.expires_at,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as {\n result:\n | t.ToolEndEvent\n | (t.SummaryCompleted & { id: string; index: number });\n };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn('No run step or runId found for completed step event');\n return;\n }\n\n if (result.type === ContentTypes.SUMMARY && 'summary' in result) {\n contentParts[runStep.index] = result.summary as t.MessageContentComplex;\n } else if ('tool_call' in result) {\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: (result as t.ToolEndEvent).tool_call,\n };\n updateContent(runStep.index, contentPart, true);\n }\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,+BAAoD,IAAI,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;EAC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Ac,IAAI,aAAa,EAAE;IAEpD,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAW;MACT,MAAM,cAAc,QAAQ;MAC5B,MAAM,cAAc;MACpB,IAAI;MACJ,MAAM,aAAa,MAAM;MACzB,YAAY,aAAa,MAAM;KACjC;IACF;IAEA,cAAc,QAAQ,OAAO,WAAW;GAC1C,CAAC;EAEL,OAAO,IAAI,UAAA,yBAA6C;GACtD,MAAM,EAAE,WAAW;GAMnB,MAAM,EAAE,IAAI,WAAW;GAEvB,MAAM,UAAU,QAAQ,IAAI,MAAM;GAClC,IAAI,CAAC,SAAS;IACZ,QAAQ,KAAK,qDAAqD;IAClE;GACF;GAEA,IAAI,OAAO,SAAA,aAAiC,aAAa,QACvD,aAAa,QAAQ,SAAS,OAAO;QAChC,IAAI,eAAe,QAAQ;IAChC,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAY,OAA0B;IACxC;IACA,cAAc,QAAQ,OAAO,aAAa,IAAI;GAChD;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
|
|
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 if (excluded != null && excluded.includes(name)) {\n return true;\n }\n // A code-session participant writes to the shared sandbox, so it is\n // side-effecting: never prestart it speculatively (a revised/superseded turn\n // would leave the write applied). Implies exclusion without the host having\n // to also list the name in excludeToolNames.\n if (graph.codeSessionToolNames?.includes(name) === true) {\n return true;\n }\n // With stateful sessions on, execute_code/bash run against a DURABLE warm\n // runtime. Speculative prestart there is unsafe: if the model revises the\n // args, ToolNode discards the eager result but the mutation has already\n // landed in the session workspace, corrupting later runs. Stateless mode\n // uses a throwaway VM per call, so eager prestart stays safe there.\n return (\n graph.toolExecution?.sandbox?.statefulSessions === true &&\n CODE_EXECUTION_TOOLS.has(name)\n );\n}\n\nfunction isDirectGraphTool(\n name: string,\n agentContext: AgentContext | undefined\n): boolean {\n if (name.startsWith(Constants.LC_TRANSFER_TO_)) {\n return true;\n }\n return (\n (agentContext?.graphTools as t.GenericTool[] | undefined)?.some(\n (tool) => 'name' in tool && tool.name === name\n ) === true\n );\n}\n\nfunction isDirectLocalTool(name: string, graph: StandardGraph): boolean {\n const toolExecution = graph.toolExecution;\n const engine = toolExecution?.engine;\n if (\n toolExecution == null ||\n (engine !== 'local' && engine !== 'cloudflare-sandbox')\n ) {\n return false;\n }\n const includeCodingTools =\n engine === 'cloudflare-sandbox'\n ? toolExecution.cloudflare?.includeCodingTools\n : toolExecution.local?.includeCodingTools;\n if (includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE &&\n graph.codeSessionToolNames?.includes(name) !== true\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (\n graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&\n graph.eventToolExecutionAvailable !== true\n ) {\n return false;\n }\n return true;\n}\n\nfunction hasFinalToolCallSignal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n const finishReason =\n metadata?.finish_reason ??\n metadata?.finishReason ??\n metadata?.stop_reason ??\n metadata?.stopReason;\n return finishReason === 'tool_calls' || finishReason === 'tool_use';\n}\n\nfunction canPrestartSequentialStreamedToolChunks(\n agentContext: AgentContext | undefined\n): boolean {\n // Anthropic seals each prior streamed tool-use block when the next indexed\n // tool-use block begins. Live Kimi/Moonshot streams can still revise prior\n // args after advancing to the next index, so keep those on the final\n // tool-call path unless they grow an explicit adapter seal.\n return agentContext?.provider === Providers.ANTHROPIC;\n}\n\nfunction hasExplicitStreamedToolCallSeals(\n chunk: Partial<AIMessageChunk>\n): boolean {\n return (\n getStreamedToolCallAdapter(\n chunk.response_metadata as Record<string, unknown> | undefined\n ) != null\n );\n}\n\n/**\n * True when a provider adapter marked every tool call on this chunk as\n * complete on arrival (seal kind `all`), e.g. Google GenAI / Vertex AI, whose\n * protocol delivers function calls as whole objects rather than arg deltas.\n */\nfunction hasOnArrivalToolCallSeal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n return (\n getStreamedToolCallAdapter(metadata) != null &&\n getStreamedToolCallSeal(metadata)?.kind === 'all'\n );\n}\n\nfunction hasDirectToolCallInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n}): boolean {\n const { graph, agentContext, toolCalls } = args;\n return toolCalls.some(\n (toolCall) =>\n toolCall.name !== '' &&\n (isDirectGraphTool(toolCall.name, agentContext) ||\n isDirectLocalTool(toolCall.name, graph))\n );\n}\n\nfunction hasPotentialDirectToolInStreamContext(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, agentContext } = args;\n const engine = graph.toolExecution?.engine;\n if (engine === 'local' || engine === 'cloudflare-sandbox') {\n return true;\n }\n if ((agentContext?.graphTools?.length ?? 0) > 0) {\n return true;\n }\n return false;\n}\n\nfunction hasDirectToolCallChunkInBatch(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n toolCallChunks?: ToolCallChunk[];\n}): boolean {\n const { graph, agentContext, toolCallChunks } = args;\n return (\n toolCallChunks?.some(\n (toolCallChunk) =>\n toolCallChunk.name != null &&\n toolCallChunk.name !== '' &&\n (isDirectGraphTool(toolCallChunk.name, agentContext) ||\n isDirectLocalTool(toolCallChunk.name, graph))\n ) === true\n );\n}\n\nfunction hasDirectToolCallChunkStateInStep(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n stepKey: string;\n}): boolean {\n const { graph, agentContext, stepKey } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n const name = state.name;\n if (\n name != null &&\n name !== '' &&\n (isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction isGoogleServerSideToolContentPart(\n contentPart: t.MessageContentComplex\n): boolean {\n return contentPart.type === 'toolCall' || contentPart.type === 'toolResponse';\n}\n\nfunction isTextContentPart(contentPart: t.MessageContentComplex): boolean {\n return contentPart.type?.startsWith(ContentTypes.TEXT) ?? false;\n}\n\nfunction isReasoningContentPart(contentPart: t.MessageContentComplex): boolean {\n return (\n (contentPart.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (contentPart.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n contentPart.type === 'redacted_thinking'\n );\n}\n\nfunction getReasoningTextFromContentPart(\n contentPart: t.MessageContentComplex\n): string {\n return (\n (contentPart as t.ThinkingContentText).thinking ??\n (contentPart as Partial<t.GoogleReasoningContentText>).reasoning ??\n (contentPart as Partial<t.BedrockReasoningContentText>).reasoningText\n ?.text ??\n ''\n );\n}\n\nfunction getReasoningTextFromChunk(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n): string {\n const reasoning = chunk.additional_kwargs?.[agentContext.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (typeof reasoning === 'string') {\n return reasoning;\n }\n return reasoning?.summary?.[0]?.text ?? '';\n}\n\nconst googleServerSideToolStepIdsByGraph = new WeakMap<\n StandardGraph,\n Set<string>\n>();\n\nfunction markGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): void {\n const stepIds = googleServerSideToolStepIdsByGraph.get(graph) ?? new Set();\n stepIds.add(stepId);\n googleServerSideToolStepIdsByGraph.set(graph, stepIds);\n}\n\nfunction isGoogleServerSideToolMessageStep(\n graph: StandardGraph,\n stepId: string\n): boolean {\n return googleServerSideToolStepIdsByGraph.get(graph)?.has(stepId) === true;\n}\n\nfunction shouldStartFreshMessageStepAfterGoogleServerSideTool({\n graph,\n stepId,\n runStep,\n content,\n}: {\n graph: StandardGraph;\n stepId: string;\n runStep?: t.RunStep;\n content: string | t.MessageContentComplex[];\n}): boolean {\n if (\n runStep?.type !== StepTypes.MESSAGE_CREATION ||\n !isGoogleServerSideToolMessageStep(graph, stepId)\n ) {\n return false;\n }\n if (typeof content === 'string') {\n return true;\n }\n return (\n content.every((c) => isTextContentPart(c)) ||\n content.every((c) => isReasoningContentPart(c))\n );\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n metadata?: Record<string, unknown>;\n}): Promise<string> {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n return graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n },\n metadata\n );\n}\n\nasync function dispatchMessageContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n for (const contentPart of content) {\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n if (isGoogleServerSideToolContentPart(contentPart)) {\n markGoogleServerSideToolMessageStep(graph, currentStepId);\n }\n await graph.dispatchMessageDelta(\n currentStepId,\n {\n content: [contentPart],\n },\n metadata\n );\n }\n}\n\nasync function dispatchReasoningContentParts({\n graph,\n stepKey,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n if (content.length === 0) {\n return;\n }\n const currentStepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n metadata,\n });\n await graph.dispatchReasoningDelta(\n currentStepId,\n {\n content,\n },\n metadata\n );\n}\n\nasync function dispatchGoogleServerSideToolStreamContent({\n graph,\n stepKey,\n chunk,\n agentContext,\n content,\n metadata,\n}: {\n graph: StandardGraph;\n stepKey: string;\n chunk: Partial<AIMessageChunk>;\n agentContext: AgentContext;\n content: t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n}): Promise<void> {\n const reasoningContent: t.MessageContentComplex[] = [];\n const reasoningText = getReasoningTextFromChunk(chunk, agentContext);\n if (reasoningText !== '') {\n reasoningContent.push({\n type: ContentTypes.THINK,\n think: reasoningText,\n });\n }\n reasoningContent.push(\n ...content\n .filter((contentPart) => isReasoningContentPart(contentPart))\n .map((contentPart) => ({\n type: ContentTypes.THINK,\n think: getReasoningTextFromContentPart(contentPart),\n }))\n .filter((contentPart) => contentPart.think !== '')\n );\n await dispatchReasoningContentParts({\n graph,\n stepKey,\n content: reasoningContent,\n metadata,\n });\n\n const messageContent = content.filter(\n (contentPart) =>\n isTextContentPart(contentPart) ||\n isGoogleServerSideToolContentPart(contentPart)\n );\n await dispatchMessageContentParts({\n graph,\n stepKey,\n content: messageContent,\n metadata,\n });\n}\n\ntype EagerToolExecutionEntry = {\n id: string;\n toolName: string;\n coercedArgs: Record<string, unknown>;\n request: t.ToolCallRequest;\n};\n\nfunction createEagerToolExecutionPlan(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): EagerToolExecutionEntry[] | undefined {\n const {\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting = false,\n } = args;\n if (\n !isEagerToolExecutionEnabledForBatch({\n graph,\n metadata,\n agentContext,\n })\n ) {\n return undefined;\n }\n\n if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {\n return undefined;\n }\n if (\n graph.toolOutputReferences?.enabled === true &&\n toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))\n ) {\n return undefined;\n }\n\n const unstartedToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n // Drop host-excluded tools only AFTER the batch-level guards above have run\n // against the full batch, so excluding a call never hides a sibling direct\n // tool from `hasDirectToolCallInBatch`. Excluded calls fall through to normal\n // ToolNode execution; siblings may still eager-execute.\n const candidateToolCalls = unstartedToolCalls.filter(\n (toolCall) => !isEagerExecutionExcludedTool(toolCall.name, graph)\n );\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n /* No runtimeSessionHint here on purpose: the eager path is speculative, and\n * code-session tools (the only ones that carry a hint) are excluded from\n * eager prestart entirely when stateful sessions are on — see\n * isEagerExecutionExcludedTool. The durable runtime is only ever touched by\n * the committed ToolNode path. */\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const records: t.EagerEventToolExecution[] = [];\n const promise: Promise<t.EagerEventToolExecutionOutcome> = new Promise<\n t.ToolExecuteResult[]\n >((resolve, reject) => {\n let dispatchSettled = false;\n let resultSettled = false;\n let settledResults: t.ToolExecuteResult[] | undefined;\n const maybeResolve = (): void => {\n if (dispatchSettled && resultSettled) {\n resolve(settledResults ?? []);\n }\n };\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: entries.map((entry) => entry.request),\n userId: graph.config?.configurable?.user_id as string | undefined,\n agentId: agentContext?.agentId,\n configurable: graph.config?.configurable as\n | Record<string, unknown>\n | undefined,\n metadata,\n resolve: (results): void => {\n resultSettled = true;\n settledResults = results;\n maybeResolve();\n },\n reject,\n };\n\n void safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n graph.config\n )\n .then(() => {\n dispatchSettled = true;\n maybeResolve();\n })\n .catch(reject);\n }).then(\n async (results): Promise<t.EagerEventToolExecutionOutcome> => {\n await dispatchEagerToolCompletions({\n graph,\n agentContext,\n records,\n results,\n });\n return { results };\n },\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n const record: t.EagerEventToolExecution = {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\n };\n records.push(record);\n graph.eagerEventToolExecutions.set(entry.id, record);\n }\n}\n\nasync function dispatchEagerToolCompletions(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n records: t.EagerEventToolExecution[];\n results: t.ToolExecuteResult[];\n}): Promise<void> {\n const { graph, agentContext, records, results } = args;\n const recordById = new Map(\n records.map((record) => [record.toolCallId, record])\n );\n const maxToolResultChars =\n agentContext?.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext?.maxContextTokens);\n\n for (const result of results) {\n const record = recordById.get(result.toolCallId);\n if (record == null) {\n continue;\n }\n if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {\n continue;\n }\n const stepId =\n record.request.stepId ??\n graph.toolCallStepIds.get(result.toolCallId) ??\n '';\n if (stepId === '') {\n continue;\n }\n 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,Q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,kBAAkB;IACvD,MAAM,aAAa,cAAc,IAAI,aAAa,EAAE;IAEpD,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAW;MACT,MAAM,cAAc,QAAQ;MAC5B,MAAM,cAAc;MACpB,IAAI;MACJ,MAAM,aAAa,MAAM;MACzB,YAAY,aAAa,MAAM;KACjC;IACF;IAEA,cAAc,QAAQ,OAAO,WAAW;GAC1C,CAAC;EAEL,OAAO,IAAI,UAAA,yBAA6C;GACtD,MAAM,EAAE,WAAW;GAMnB,MAAM,EAAE,IAAI,WAAW;GAEvB,MAAM,UAAU,QAAQ,IAAI,MAAM;GAClC,IAAI,CAAC,SAAS;IACZ,QAAQ,KAAK,qDAAqD;IAClE;GACF;GAEA,IAAI,OAAO,SAAA,aAAiC,aAAa,QACvD,aAAa,QAAQ,SAAS,OAAO;QAChC,IAAI,eAAe,QAAQ;IAChC,MAAM,cAAuC;KAC3C,MAAA;KACA,WAAY,OAA0B;IACxC;IACA,cAAc,QAAQ,OAAO,aAAa,IAAI;GAChD;EACF;CACF;CAEA,OAAO;EAAE;EAAc;EAAkB;CAAQ;AACnD"}
|
|
@@ -35,6 +35,26 @@ const BashExecutionToolSchema = {
|
|
|
35
35
|
const BashExecutionToolDescription = `
|
|
36
36
|
Runs bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
|
|
37
37
|
|
|
38
|
+
Usage:
|
|
39
|
+
- No network access available.
|
|
40
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
41
|
+
- ${CODE_ARTIFACT_PATH_GUIDANCE}
|
|
42
|
+
- ${BASH_SHELL_GUIDANCE}
|
|
43
|
+
- NEVER use this tool to execute malicious commands.
|
|
44
|
+
`.trim();
|
|
45
|
+
/**
|
|
46
|
+
* Bash statefulness is filesystem-tier: on a warm session the machine (files
|
|
47
|
+
* including /tmp, installed packages, background processes) persists between
|
|
48
|
+
* calls, but each call may start a fresh shell — so shell variables and cwd
|
|
49
|
+
* are NOT reliable, and the machine can be reset at any time. Only /mnt/data
|
|
50
|
+
* is durable.
|
|
51
|
+
*/
|
|
52
|
+
const STATEFUL_BASH_NOTE = "Session state (best-effort): commands in this conversation usually run on the same machine, so files (including /tmp), installed packages, and running background processes from earlier calls typically persist. Each call may still start a fresh shell — do not rely on shell variables or the working directory carrying over — and the machine may be reset at any time. Only /mnt/data is durable.";
|
|
53
|
+
const StatefulBashExecutionToolDescription = `
|
|
54
|
+
Runs bash commands and returns stdout/stderr output from a session-based execution environment, similar to a long-running machine.
|
|
55
|
+
|
|
56
|
+
${STATEFUL_BASH_NOTE}
|
|
57
|
+
|
|
38
58
|
Usage:
|
|
39
59
|
- No network access available.
|
|
40
60
|
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
@@ -70,8 +90,25 @@ Referencing previous tool outputs:
|
|
|
70
90
|
* will actually be able to use.
|
|
71
91
|
*/
|
|
72
92
|
function buildBashExecutionToolDescription(options) {
|
|
73
|
-
|
|
74
|
-
return
|
|
93
|
+
const base = options?.statefulSessions === true ? StatefulBashExecutionToolDescription : BashExecutionToolDescription;
|
|
94
|
+
if (options?.enableToolOutputReferences === true) return `${base}\n\n${BashToolOutputReferencesGuide}`;
|
|
95
|
+
return base;
|
|
96
|
+
}
|
|
97
|
+
const STATELESS_BASH_PARAM_NOTE = "The environment is stateless; variables and state don't persist between executions.";
|
|
98
|
+
const STATEFUL_BASH_PARAM_NOTE = "Files, installed packages, and background processes usually persist between calls, but each call may start a fresh shell (do not rely on shell variables or cwd) and the machine may reset. Only /mnt/data is durable.";
|
|
99
|
+
function buildBashExecutionToolSchema(opts) {
|
|
100
|
+
const note = opts?.statefulSessions === true ? STATEFUL_BASH_PARAM_NOTE : STATELESS_BASH_PARAM_NOTE;
|
|
101
|
+
const commandDescription = BashExecutionToolSchema.properties.command.description.replace(STATELESS_BASH_PARAM_NOTE, note);
|
|
102
|
+
return {
|
|
103
|
+
...BashExecutionToolSchema,
|
|
104
|
+
properties: {
|
|
105
|
+
...BashExecutionToolSchema.properties,
|
|
106
|
+
command: {
|
|
107
|
+
...BashExecutionToolSchema.properties.command,
|
|
108
|
+
description: commandDescription
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
75
112
|
}
|
|
76
113
|
const BashExecutionToolName = "bash_tool";
|
|
77
114
|
/**
|
|
@@ -91,15 +128,16 @@ const BashExecutionToolDefinition = {
|
|
|
91
128
|
};
|
|
92
129
|
function createBashExecutionTool(params = {}) {
|
|
93
130
|
return tool(async (rawInput, config) => {
|
|
94
|
-
const { authHeaders, ...executionParams } = params ?? {};
|
|
95
|
-
const { command, ...rest } = rawInput;
|
|
96
|
-
const { session_id, _injected_files } = config.toolCall ?? {};
|
|
131
|
+
const { authHeaders, statefulSessions: _statefulSessions, ...executionParams } = params ?? {};
|
|
132
|
+
const { command, runtime_session_hint: _ignoredModelHint, ...rest } = rawInput;
|
|
133
|
+
const { session_id, _injected_files, _runtime_session_hint } = config.toolCall ?? {};
|
|
97
134
|
const postData = {
|
|
98
135
|
lang: "bash",
|
|
99
136
|
code: command,
|
|
100
137
|
...rest,
|
|
101
138
|
...executionParams
|
|
102
139
|
};
|
|
140
|
+
if (typeof _runtime_session_hint === "string" && _runtime_session_hint !== "") postData.runtime_session_hint = _runtime_session_hint;
|
|
103
141
|
if (_injected_files && _injected_files.length > 0) postData.files = _injected_files;
|
|
104
142
|
else if (session_id != null && session_id.length > 0 && !Array.isArray(postData.files)) console.debug(`[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`);
|
|
105
143
|
try {
|
|
@@ -122,22 +160,30 @@ function createBashExecutionTool(params = {}) {
|
|
|
122
160
|
if (result.stderr) formattedOutput += `stderr:\n${result.stderr}\n`;
|
|
123
161
|
const outputWithReminder = appendTmpScratchReminder(formattedOutput, command);
|
|
124
162
|
const hasFiles = result.files != null && result.files.length > 0;
|
|
163
|
+
const runtimeEcho = result.runtime_session_id != null ? {
|
|
164
|
+
runtime_session_id: result.runtime_session_id,
|
|
165
|
+
runtime_status: result.runtime_status
|
|
166
|
+
} : {};
|
|
125
167
|
return [appendCodeSessionFileSummary(outputWithReminder, result.files), hasFiles ? {
|
|
126
168
|
session_id: result.session_id,
|
|
127
|
-
files: result.files
|
|
128
|
-
|
|
169
|
+
files: result.files,
|
|
170
|
+
...runtimeEcho
|
|
171
|
+
} : {
|
|
172
|
+
session_id: result.session_id,
|
|
173
|
+
...runtimeEcho
|
|
174
|
+
}];
|
|
129
175
|
} catch (error) {
|
|
130
176
|
const messageWithReminder = appendFailedExecutionFileReminder(error?.message ?? "", command);
|
|
131
177
|
throw new Error(`Execution error:\n\n${messageWithReminder}`);
|
|
132
178
|
}
|
|
133
179
|
}, {
|
|
134
180
|
name: BashExecutionToolName,
|
|
135
|
-
description:
|
|
136
|
-
schema:
|
|
181
|
+
description: buildBashExecutionToolDescription({ statefulSessions: params?.statefulSessions }),
|
|
182
|
+
schema: buildBashExecutionToolSchema(params ?? void 0),
|
|
137
183
|
responseFormat: "content_and_artifact"
|
|
138
184
|
});
|
|
139
185
|
}
|
|
140
186
|
//#endregion
|
|
141
|
-
export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashToolOutputReferencesGuide, buildBashExecutionToolDescription, createBashExecutionTool };
|
|
187
|
+
export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashToolOutputReferencesGuide, STATEFUL_BASH_NOTE, StatefulBashExecutionToolDescription, buildBashExecutionToolDescription, buildBashExecutionToolSchema, createBashExecutionTool };
|
|
142
188
|
|
|
143
189
|
//# sourceMappingURL=BashExecutor.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BashExecutor.mjs","names":[],"sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n getCodeBaseURL,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { authHeaders, ...executionParams } = params ?? {};\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n command\n );\n const hasFiles = result.files != null && result.files.length > 0;\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error | undefined)?.message ?? '',\n command\n );\n throw new Error(\n `Execution error:\\n\\n${messageWithReminder}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"mappings":";;;;;;;;;AAkBA,OAAO;AAGP,MAAM,gBAAgB,GADD,eACe,EAAE;AAEtC,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aAAa;;;IAGf,4BAA4B;IAC5B,oBAAoB;;;;;EAKpB;EACA,MAAM;GACJ,MAAM;GACN,OAAO,EAAE,MAAM,SAAS;GACxB,aACE;EACJ;CACF;CACA,UAAU,CAAC,SAAS;AACtB;AAEA,MAAa,+BAA+B;;;;;;IAMxC,4BAA4B;IAC5B,oBAAoB;;EAEtB,KAAK;;;;;;;;;;;AAYP,MAAa,gCAAgC;;;;;;;;;EAS3C,KAAK;;;;;;;;AASP,SAAgB,kCAAkC,SAEvC;CACT,IAAI,SAAS,+BAA+B,MAC1C,OAAO,GAAG,6BAA6B,MAAM;CAE/C,OAAO;AACT;AAEA,MAAa,wBAAA;;;;;;;;;;;AAYb,MAAa,8BAA8B;CACzC,MAAM;CACN,aAAa;CACb,QAAQ;AACV;AAEA,SAAS,wBACP,SAA2C,CAAC,GACrB;CACvB,OAAO,KACL,OAAO,UAAU,WAAW;EAC1B,MAAM,EAAE,aAAa,GAAG,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ACR,uBAAuB,qBACzB;EACF;CACF,GACA;EACE,MAAM;EACN,aAAa;EACb,QAAQ;EACR,gBAAA;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"BashExecutor.mjs","names":[],"sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n getCodeBaseURL,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Bash statefulness is filesystem-tier: on a warm session the machine (files\n * including /tmp, installed packages, background processes) persists between\n * calls, but each call may start a fresh shell — so shell variables and cwd\n * are NOT reliable, and the machine can be reset at any time. Only /mnt/data\n * is durable.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state (best-effort): commands in this conversation usually run on the same machine, so files (including /tmp), installed packages, and running background processes from earlier calls typically persist. Each call may still start a fresh shell — do not rely on shell variables or the working directory carrying over — and the machine may be reset at any time. Only /mnt/data is durable.';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a session-based execution environment, similar to a long-running machine.\n\n${STATEFUL_BASH_NOTE}\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n statefulSessions?: boolean;\n}): string {\n const base =\n options?.statefulSessions === true\n ? StatefulBashExecutionToolDescription\n : BashExecutionToolDescription;\n if (options?.enableToolOutputReferences === true) {\n return `${base}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return base;\n}\n\nconst STATELESS_BASH_PARAM_NOTE =\n 'The environment is stateless; variables and state don\\'t persist between executions.';\nconst STATEFUL_BASH_PARAM_NOTE =\n 'Files, installed packages, and background processes usually persist between calls, but each call may start a fresh shell (do not rely on shell variables or cwd) and the machine may reset. Only /mnt/data is durable.';\n\nexport function buildBashExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof BashExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_BASH_PARAM_NOTE\n : STATELESS_BASH_PARAM_NOTE;\n const commandDescription =\n BashExecutionToolSchema.properties.command.description.replace(\n STATELESS_BASH_PARAM_NOTE,\n note\n );\n return {\n ...BashExecutionToolSchema,\n properties: {\n ...BashExecutionToolSchema.properties,\n command: {\n ...BashExecutionToolSchema.properties.command,\n description: commandDescription,\n },\n },\n } as typeof BashExecutionToolSchema;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is prompt-only — keep it out of the wire body. */\n const {\n authHeaders,\n statefulSessions: _statefulSessions,\n ...executionParams\n } = params ?? {};\n void _statefulSessions;\n /* Drop any model-supplied `runtime_session_hint` from the raw args: the\n * hint must only come from ToolNode's injected `_runtime_session_hint`\n * (below), never from the tool call itself. */\n const {\n command,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n command: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n const { session_id, _injected_files, _runtime_session_hint } =\n (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n command\n );\n const hasFiles = result.files != null && result.files.length > 0;\n const runtimeEcho =\n result.runtime_session_id != null\n ? {\n runtime_session_id: result.runtime_session_id,\n runtime_status: result.runtime_status,\n }\n : {};\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? {\n session_id: result.session_id,\n files: result.files,\n ...runtimeEcho,\n }\n : {\n session_id: result.session_id,\n ...runtimeEcho,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error | undefined)?.message ?? '',\n command\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: BashExecutionToolName,\n description: buildBashExecutionToolDescription({\n statefulSessions: params?.statefulSessions,\n }),\n schema: buildBashExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],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