@librechat/agents 3.1.88 → 3.1.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/cjs/graphs/Graph.cjs +25 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/hooks/executeHooks.cjs +14 -7
  4. package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/index.cjs +8 -2
  6. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  7. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +34 -0
  8. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  9. package/dist/cjs/main.cjs +9 -0
  10. package/dist/cjs/main.cjs.map +1 -1
  11. package/dist/cjs/stream.cjs +115 -8
  12. package/dist/cjs/stream.cjs.map +1 -1
  13. package/dist/cjs/tools/BashExecutor.cjs +10 -9
  14. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  15. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +12 -8
  16. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  17. package/dist/cjs/tools/CodeExecutor.cjs +35 -11
  18. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  19. package/dist/cjs/tools/CodeSessionFileSummary.cjs +63 -0
  20. package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -0
  21. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -12
  22. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  23. package/dist/cjs/tools/ToolNode.cjs +32 -12
  24. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  25. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +319 -29
  26. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  27. package/dist/cjs/tools/toolOutputReferences.cjs +8 -0
  28. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  29. package/dist/cjs/utils/events.cjs +3 -1
  30. package/dist/cjs/utils/events.cjs.map +1 -1
  31. package/dist/esm/graphs/Graph.mjs +25 -1
  32. package/dist/esm/graphs/Graph.mjs.map +1 -1
  33. package/dist/esm/hooks/executeHooks.mjs +14 -7
  34. package/dist/esm/hooks/executeHooks.mjs.map +1 -1
  35. package/dist/esm/llm/anthropic/index.mjs +9 -3
  36. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  37. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +33 -1
  38. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  39. package/dist/esm/main.mjs +2 -1
  40. package/dist/esm/main.mjs.map +1 -1
  41. package/dist/esm/stream.mjs +115 -8
  42. package/dist/esm/stream.mjs.map +1 -1
  43. package/dist/esm/tools/BashExecutor.mjs +11 -10
  44. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  45. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +13 -9
  46. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  47. package/dist/esm/tools/CodeExecutor.mjs +29 -12
  48. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  49. package/dist/esm/tools/CodeSessionFileSummary.mjs +60 -0
  50. package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -0
  51. package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -13
  52. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  53. package/dist/esm/tools/ToolNode.mjs +32 -12
  54. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  55. package/dist/esm/tools/subagent/SubagentExecutor.mjs +320 -31
  56. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  57. package/dist/esm/tools/toolOutputReferences.mjs +8 -1
  58. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  59. package/dist/esm/utils/events.mjs +3 -1
  60. package/dist/esm/utils/events.mjs.map +1 -1
  61. package/dist/types/graphs/Graph.d.ts +8 -0
  62. package/dist/types/llm/anthropic/index.d.ts +3 -1
  63. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +4 -0
  64. package/dist/types/tools/BashExecutor.d.ts +3 -3
  65. package/dist/types/tools/CodeExecutor.d.ts +10 -3
  66. package/dist/types/tools/CodeSessionFileSummary.d.ts +3 -0
  67. package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -4
  68. package/dist/types/tools/subagent/SubagentExecutor.d.ts +8 -5
  69. package/dist/types/types/tools.d.ts +11 -3
  70. package/dist/types/utils/events.d.ts +1 -1
  71. package/package.json +1 -1
  72. package/src/__tests__/stream.eagerEventExecution.test.ts +1073 -221
  73. package/src/graphs/Graph.ts +27 -5
  74. package/src/hooks/__tests__/executeHooks.test.ts +38 -0
  75. package/src/hooks/executeHooks.ts +27 -7
  76. package/src/llm/anthropic/index.ts +27 -3
  77. package/src/llm/anthropic/llm.spec.ts +60 -1
  78. package/src/llm/anthropic/utils/message_inputs.ts +46 -0
  79. package/src/specs/subagent.test.ts +87 -1
  80. package/src/stream.ts +163 -12
  81. package/src/tools/BashExecutor.ts +21 -10
  82. package/src/tools/BashProgrammaticToolCalling.ts +21 -9
  83. package/src/tools/CodeExecutor.ts +55 -12
  84. package/src/tools/CodeSessionFileSummary.ts +80 -0
  85. package/src/tools/ProgrammaticToolCalling.ts +25 -12
  86. package/src/tools/ToolNode.ts +142 -116
  87. package/src/tools/__tests__/BashExecutor.test.ts +9 -0
  88. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +43 -0
  89. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +100 -16
  90. package/src/tools/__tests__/SubagentExecutor.test.ts +540 -6
  91. package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +278 -14
  92. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +52 -0
  93. package/src/tools/__tests__/subagentHooks.test.ts +237 -0
  94. package/src/tools/subagent/SubagentExecutor.ts +514 -36
  95. package/src/types/tools.ts +11 -3
  96. package/src/utils/events.ts +4 -2
@@ -1 +1 @@
1
- {"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\n\nconst LOCAL_CODING_BUNDLE_NAME_SET: ReadonlySet<string> = new Set(\n LOCAL_CODING_BUNDLE_NAMES\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 (\n graph.hookRegistry != null ||\n graph.humanInTheLoop?.enabled === true ||\n graph.toolOutputReferences?.enabled === true\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 if (graph.toolExecution?.engine !== 'local') {\n return false;\n }\n if (graph.toolExecution.local?.includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null) {\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\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 if (graph.toolExecution?.engine === 'local') {\n return true;\n }\n if ((agentContext?.graphTools?.length ?? 0) > 0) {\n return true;\n }\n return (\n agentContext?.toolDefinitions?.some((toolDefinition) =>\n toolDefinition.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) === true\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\n const candidateToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const 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 (results): t.EagerEventToolExecutionOutcome => ({ results }),\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n graph.eagerEventToolExecutions.set(entry.id, {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\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 !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 (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n // Content presence signals end of reasoning phase - prefer content over reasoning\n // This handles transitional chunks that may have both reasoning and content\n if (typeof chunk?.content === 'string' && chunk.content !== '') {\n return chunk.content;\n }\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\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 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 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 }\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 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 const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(\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 (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content,\n },\n metadata\n );\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n c.type === 'redacted_thinking'\n )\n ) {\n await graph.dispatchReasoningDelta(\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 ) {\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\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 === 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;\n })\n | undefined;\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 if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n 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"],"names":[],"mappings":";;;;;;;;;;AAmCA,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAC/D,yBAAyB,CAC1B;AAED;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;IACxC;IAEA,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;QACF;;QAGA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ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nC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,qDAAqD,CAAC;gBACnE;YACF;AAEA,YAAA,IAAI,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC,OAAO,IAAI,SAAS,IAAI,MAAM,EAAE;gBAC/D,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,OAAkC;YACzE;AAAO,iBAAA,IAAI,WAAW,IAAI,MAAM,EAAE;AAChC,gBAAA,MAAM,WAAW,GAA4B;oBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;oBAC5B,SAAS,EAAG,MAAyB,CAAC,SAAS;iBAChD;gBACD,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;YACjD;QACF;AACF,IAAA,CAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
1
+ {"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n CODE_EXECUTION_TOOLS,\n LOCAL_CODING_BUNDLE_NAMES,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport {\n buildToolExecutionRequestPlan,\n coerceRecordArgs,\n normalizeError,\n} from '@/tools/eagerEventExecution';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport {\n getStreamedToolCallSeal,\n getStreamedToolCallAdapter,\n type StreamedToolCallSeal,\n} from '@/tools/streamedToolCallSeals';\nimport { TOOL_OUTPUT_REF_PATTERN } from '@/tools/toolOutputReferences';\n\nconst LOCAL_CODING_BUNDLE_NAME_SET: ReadonlySet<string> = new Set(\n LOCAL_CODING_BUNDLE_NAMES\n);\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nfunction isBatchSensitiveToolExecution(graph: StandardGraph): boolean {\n return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;\n}\n\nfunction hasToolOutputReference(value: unknown): boolean {\n if (typeof value === 'string') {\n return TOOL_OUTPUT_REF_PATTERN.test(value);\n }\n if (Array.isArray(value)) {\n return value.some((item) => hasToolOutputReference(item));\n }\n if (value !== null && typeof value === 'object') {\n return Object.values(value as Record<string, unknown>).some((item) =>\n hasToolOutputReference(item)\n );\n }\n return false;\n}\n\nfunction isDirectGraphTool(\n name: string,\n agentContext: AgentContext | undefined\n): boolean {\n if (name.startsWith(Constants.LC_TRANSFER_TO_)) {\n return true;\n }\n return (\n (agentContext?.graphTools as t.GenericTool[] | undefined)?.some(\n (tool) => 'name' in tool && tool.name === name\n ) === true\n );\n}\n\nfunction isDirectLocalTool(name: string, graph: StandardGraph): boolean {\n if (graph.toolExecution?.engine !== 'local') {\n return false;\n }\n if (graph.toolExecution.local?.includeCodingTools === false) {\n return CODE_EXECUTION_TOOLS.has(name);\n }\n return LOCAL_CODING_BUNDLE_NAME_SET.has(name);\n}\n\nfunction toCodeEnvFile(file: t.FileRef, execSessionId: string): t.CodeEnvFile {\n const base = {\n id: file.id,\n resource_id: file.resource_id ?? file.id,\n name: file.name,\n storage_session_id: file.storage_session_id ?? execSessionId,\n };\n const kind = file.kind ?? 'user';\n if (kind === 'skill' && file.version != null) {\n return { ...base, kind: 'skill', version: file.version };\n }\n if (kind === 'agent') {\n return { ...base, kind: 'agent' };\n }\n return { ...base, kind: 'user' };\n}\n\nfunction getCodeSessionContext(\n graph: StandardGraph,\n name: string\n): t.ToolCallRequest['codeSessionContext'] | undefined {\n if (\n !CODE_EXECUTION_TOOLS.has(name) &&\n name !== Constants.SKILL_TOOL &&\n name !== Constants.READ_FILE\n ) {\n return undefined;\n }\n\n const codeSession = graph.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id == null || codeSession.session_id === '') {\n return undefined;\n }\n\n return {\n session_id: codeSession.session_id,\n files: codeSession.files?.map((file) =>\n toCodeEnvFile(file, codeSession.session_id)\n ),\n };\n}\n\nfunction isEagerToolExecutionEnabledForBatch(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): boolean {\n const { graph, metadata, agentContext } = args;\n if (graph.eagerEventToolExecution?.enabled !== true) {\n return false;\n }\n if ((agentContext?.toolDefinitions?.length ?? 0) === 0) {\n return false;\n }\n if (isBatchSensitiveToolExecution(graph)) {\n return false;\n }\n if (\n metadata?.[Constants.PROGRAMMATIC_TOOL_CALLING] === true ||\n metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true\n ) {\n return false;\n }\n if (\n graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&\n graph.eventToolExecutionAvailable !== true\n ) {\n return false;\n }\n return true;\n}\n\nfunction hasFinalToolCallSignal(chunk: Partial<AIMessageChunk>): boolean {\n const metadata = chunk.response_metadata as\n | Record<string, unknown>\n | undefined;\n const finishReason =\n metadata?.finish_reason ??\n metadata?.finishReason ??\n metadata?.stop_reason ??\n metadata?.stopReason;\n return finishReason === 'tool_calls' || finishReason === 'tool_use';\n}\n\nfunction canPrestartSequentialStreamedToolChunks(\n agentContext: AgentContext | undefined\n): boolean {\n // Anthropic seals each prior streamed tool-use block when the next indexed\n // tool-use block begins. Live Kimi/Moonshot streams can still revise prior\n // args after advancing to the next index, so keep those on the final\n // tool-call path unless they grow an explicit adapter seal.\n return agentContext?.provider === Providers.ANTHROPIC;\n}\n\nfunction hasExplicitStreamedToolCallSeals(\n chunk: Partial<AIMessageChunk>\n): boolean {\n return (\n getStreamedToolCallAdapter(\n chunk.response_metadata as Record<string, unknown> | undefined\n ) != null\n );\n}\n\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 if (graph.toolExecution?.engine === 'local') {\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\ntype EagerToolExecutionEntry = {\n id: string;\n toolName: string;\n coercedArgs: Record<string, unknown>;\n request: t.ToolCallRequest;\n};\n\nfunction createEagerToolExecutionPlan(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): EagerToolExecutionEntry[] | undefined {\n const {\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting = false,\n } = args;\n if (\n !isEagerToolExecutionEnabledForBatch({\n graph,\n metadata,\n agentContext,\n })\n ) {\n return undefined;\n }\n\n if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {\n return undefined;\n }\n if (\n graph.toolOutputReferences?.enabled === true &&\n toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))\n ) {\n return undefined;\n }\n\n const candidateToolCalls = skipExisting\n ? toolCalls.filter((toolCall) => {\n if (toolCall.id == null || toolCall.id === '') {\n return true;\n }\n return !graph.eagerEventToolExecutions.has(toolCall.id);\n })\n : toolCalls;\n if (candidateToolCalls.length === 0) {\n return [];\n }\n\n // Eager execution must preserve ToolNode batch semantics exactly for every\n // unstarted call. If any candidate cannot be planned, fall back for that\n // candidate set.\n if (\n candidateToolCalls.some(\n (toolCall) =>\n toolCall.id == null ||\n toolCall.id === '' ||\n toolCall.name === '' ||\n (!skipExisting && graph.eagerEventToolExecutions.has(toolCall.id))\n )\n ) {\n return undefined;\n }\n\n const plan = buildToolExecutionRequestPlan({\n toolCalls: candidateToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n stepId: graph.toolCallStepIds.get(toolCall.id!) ?? '',\n codeSessionContext: getCodeSessionContext(graph, toolCall.name),\n })),\n usageCount: graph.getEagerEventToolUsageCount(agentContext?.agentId),\n });\n if (plan == null) {\n return undefined;\n }\n\n return plan.requests.map(\n (request): EagerToolExecutionEntry => ({\n id: request.id,\n toolName: request.name,\n coercedArgs: request.args,\n request,\n })\n );\n}\n\nfunction startEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n toolCalls: ToolCall[];\n skipExisting?: boolean;\n}): void {\n const { graph, metadata, agentContext, toolCalls, skipExisting } = args;\n const entries = createEagerToolExecutionPlan({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting,\n });\n if (entries == null || entries.length === 0) {\n return;\n }\n\n const records: t.EagerEventToolExecution[] = [];\n const promise: Promise<t.EagerEventToolExecutionOutcome> = new Promise<\n t.ToolExecuteResult[]\n >((resolve, reject) => {\n let dispatchSettled = false;\n let resultSettled = false;\n let settledResults: t.ToolExecuteResult[] | undefined;\n const maybeResolve = (): void => {\n if (dispatchSettled && resultSettled) {\n resolve(settledResults ?? []);\n }\n };\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: entries.map((entry) => entry.request),\n userId: graph.config?.configurable?.user_id as string | undefined,\n agentId: agentContext?.agentId,\n configurable: graph.config?.configurable as\n | Record<string, unknown>\n | undefined,\n metadata,\n resolve: (results): void => {\n resultSettled = true;\n settledResults = results;\n maybeResolve();\n },\n reject,\n };\n\n void safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n graph.config\n )\n .then(() => {\n dispatchSettled = true;\n maybeResolve();\n })\n .catch(reject);\n }).then(\n async (results): Promise<t.EagerEventToolExecutionOutcome> => {\n await dispatchEagerToolCompletions({\n graph,\n agentContext,\n records,\n results,\n });\n return { results };\n },\n (error): t.EagerEventToolExecutionOutcome => ({\n error: normalizeError(error),\n })\n );\n\n for (const entry of entries) {\n const record: t.EagerEventToolExecution = {\n toolCallId: entry.id,\n toolName: entry.toolName,\n args: entry.coercedArgs,\n request: entry.request,\n promise,\n };\n records.push(record);\n graph.eagerEventToolExecutions.set(entry.id, record);\n }\n}\n\nasync function dispatchEagerToolCompletions(args: {\n graph: StandardGraph;\n agentContext?: AgentContext;\n records: t.EagerEventToolExecution[];\n results: t.ToolExecuteResult[];\n}): Promise<void> {\n const { graph, agentContext, records, results } = args;\n const recordById = new Map(\n records.map((record) => [record.toolCallId, record])\n );\n const maxToolResultChars =\n agentContext?.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext?.maxContextTokens);\n\n for (const result of results) {\n const record = recordById.get(result.toolCallId);\n if (record == null) {\n continue;\n }\n if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {\n continue;\n }\n const stepId =\n record.request.stepId ??\n graph.toolCallStepIds.get(result.toolCallId) ??\n '';\n if (stepId === '') {\n continue;\n }\n const output =\n result.status === 'error'\n ? `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`\n : truncateToolResultContent(\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content),\n maxToolResultChars\n );\n\n try {\n const dispatched = await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: record.request.turn ?? 0,\n type: 'tool_call' as const,\n eager: true,\n tool_call: {\n args: JSON.stringify(record.request.args),\n name: record.toolName,\n id: result.toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n graph.config\n );\n if (dispatched === false) {\n continue;\n }\n record.completionDispatched = true;\n } catch (error) {\n // Let ToolNode dispatch the completion through the normal path later.\n\n console.warn(\n `[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`,\n error instanceof Error ? error.message : error\n );\n }\n }\n}\n\nfunction getEagerToolChunkKey(\n stepKey: string,\n toolCallChunk: ToolCallChunk\n): string | undefined {\n let chunkKey: string | undefined;\n if (typeof toolCallChunk.index === 'number') {\n chunkKey = String(toolCallChunk.index);\n } else if (toolCallChunk.id != null && toolCallChunk.id !== '') {\n chunkKey = toolCallChunk.id;\n }\n if (chunkKey == null) {\n return undefined;\n }\n return `${stepKey}\\u0000${chunkKey}`;\n}\n\nfunction getEagerToolChunkIndex(\n toolCallChunk: ToolCallChunk\n): number | undefined {\n return typeof toolCallChunk.index === 'number'\n ? toolCallChunk.index\n : undefined;\n}\n\nfunction pruneEagerToolCallChunkStates(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallIds?: ReadonlySet<string>;\n clearStep?: boolean;\n}): void {\n const { graph, stepKey, toolCallIds, clearStep = false } = args;\n const prefix = `${stepKey}\\u0000`;\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (\n clearStep ||\n (state.id != null && toolCallIds?.has(state.id) === true)\n ) {\n graph.eagerEventToolCallChunks.delete(key);\n }\n }\n}\n\nfunction isEagerToolChunkStateComplete(\n state: t.EagerEventToolCallChunkState\n): boolean {\n return (\n state.id != null &&\n state.id !== '' &&\n state.name != null &&\n state.name !== '' &&\n coerceRecordArgs(state.argsText) != null\n );\n}\n\nfunction mergeToolCallArgsText(existing: string, incoming: string): string {\n if (incoming === '') {\n return existing;\n }\n if (existing === '') {\n return incoming;\n }\n if (incoming === existing) {\n try {\n JSON.parse(incoming);\n return incoming;\n } catch {\n return `${existing}${incoming}`;\n }\n }\n if (incoming.startsWith(existing)) {\n return incoming;\n }\n if (existing.startsWith(incoming)) {\n return existing;\n }\n try {\n JSON.parse(existing);\n JSON.parse(incoming);\n return incoming;\n } catch {\n // Fall through to delta concatenation.\n }\n for (\n let overlap = Math.min(existing.length, incoming.length);\n overlap >= 8;\n overlap -= 1\n ) {\n if (existing.endsWith(incoming.slice(0, overlap))) {\n return `${existing}${incoming.slice(overlap)}`;\n }\n }\n return `${existing}${incoming}`;\n}\n\nfunction recordEagerToolCallChunks(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n}): void {\n const { graph, stepKey, toolCallChunks } = args;\n if (toolCallChunks == null || toolCallChunks.length === 0) {\n return;\n }\n\n // Streamed args can be cumulative and parseable before the provider has\n // sealed the call. Recording stays separate from dispatch so the boundary\n // logic can wait for either a later tool index or the final tool-call signal.\n for (const toolCallChunk of toolCallChunks) {\n const key = getEagerToolChunkKey(stepKey, toolCallChunk);\n if (key == null) {\n continue;\n }\n\n const incomingId =\n toolCallChunk.id != null && toolCallChunk.id !== ''\n ? toolCallChunk.id\n : undefined;\n const incomingName =\n toolCallChunk.name != null && toolCallChunk.name !== ''\n ? toolCallChunk.name\n : undefined;\n const previous = graph.eagerEventToolCallChunks.get(key);\n const shouldReset =\n previous != null &&\n ((incomingId != null &&\n previous.id != null &&\n incomingId !== previous.id) ||\n (incomingName != null &&\n previous.name != null &&\n incomingName !== previous.name));\n const existing =\n previous == null || shouldReset\n ? {\n argsText: '',\n }\n : previous;\n const id = incomingId ?? existing.id;\n const name = incomingName ?? existing.name;\n const incomingArgs = toolCallChunk.args ?? '';\n const isRepeatedObservedFragment =\n incomingArgs !== '' &&\n incomingArgs.length > 1 &&\n incomingArgs === existing.lastArgsFragment;\n const argsText = isRepeatedObservedFragment\n ? existing.argsText\n : mergeToolCallArgsText(existing.argsText, incomingArgs);\n const next = {\n id,\n name,\n argsText,\n index: getEagerToolChunkIndex(toolCallChunk) ?? existing.index,\n lastArgsFragment:\n incomingArgs !== '' ? incomingArgs : existing.lastArgsFragment,\n };\n graph.eagerEventToolCallChunks.set(key, next);\n }\n}\n\nfunction getStreamedReadyToolCalls(args: {\n graph: StandardGraph;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): ToolCall[] {\n const {\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal = false,\n sealAll = false,\n } = args;\n const currentIndices = new Set<number>();\n for (const toolCallChunk of toolCallChunks ?? []) {\n const index = getEagerToolChunkIndex(toolCallChunk);\n if (index != null) {\n currentIndices.add(index);\n }\n }\n const highestCurrentIndex =\n currentIndices.size > 0 ? Math.max(...currentIndices) : undefined;\n const prefix = `${stepKey}\\u0000`;\n const readyEntries: Array<{\n key: string;\n state: t.EagerEventToolCallChunkState;\n }> = [];\n\n for (const [key, state] of graph.eagerEventToolCallChunks) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (state.id != null && graph.eagerEventToolExecutions.has(state.id)) {\n graph.eagerEventToolCallChunks.delete(key);\n continue;\n }\n if (!isEagerToolChunkStateComplete(state)) {\n continue;\n }\n const isSealedByLaterChunk =\n allowSequentialSeal &&\n highestCurrentIndex != null &&\n state.index != null &&\n state.index < highestCurrentIndex &&\n !currentIndices.has(state.index);\n const isSealedExplicitly =\n seal?.kind === 'single' &&\n ((seal.id != null && state.id === seal.id) ||\n (seal.index != null && state.index === seal.index));\n if (\n sealAll ||\n seal?.kind === 'all' ||\n isSealedByLaterChunk ||\n isSealedExplicitly\n ) {\n readyEntries.push({ key, state });\n }\n }\n\n pruneEagerToolCallChunkStates({\n graph,\n stepKey,\n toolCallIds: new Set(\n readyEntries\n .map(({ state }) => state.id)\n .filter((id): id is string => id != null && id !== '')\n ),\n });\n if (sealAll) {\n pruneEagerToolCallChunkStates({ graph, stepKey, clearStep: true });\n }\n\n return readyEntries\n .sort((left, right) => (left.state.index ?? 0) - (right.state.index ?? 0))\n .flatMap(({ state }) => {\n const args = coerceRecordArgs(state.argsText);\n if (args == null) {\n return [];\n }\n return [\n {\n id: state.id,\n name: state.name ?? '',\n args,\n },\n ];\n });\n}\n\nfunction startReadyStreamedEagerToolExecutions(args: {\n graph: StandardGraph;\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n stepKey: string;\n toolCallChunks?: ToolCallChunk[];\n seal?: StreamedToolCallSeal;\n allowSequentialSeal?: boolean;\n sealAll?: boolean;\n}): void {\n const {\n graph,\n metadata,\n agentContext,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n } = args;\n if (\n hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||\n hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||\n hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||\n !isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })\n ) {\n return;\n }\n const toolCalls = getStreamedReadyToolCalls({\n graph,\n stepKey,\n toolCallChunks,\n seal,\n allowSequentialSeal,\n sealAll,\n });\n if (toolCalls.length === 0) {\n return;\n }\n startEagerToolExecutions({\n graph,\n metadata,\n agentContext,\n toolCalls,\n skipExisting: true,\n });\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n // Content presence signals end of reasoning phase - prefer content over reasoning\n // This handles transitional chunks that may have both reasoning and content\n if (typeof chunk?.content === 'string' && chunk.content !== '') {\n return chunk.content;\n }\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\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 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 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 }\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 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 const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(\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 (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(\n stepId,\n {\n content,\n },\n metadata\n );\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||\n c.type === 'redacted_thinking'\n )\n ) {\n await graph.dispatchReasoningDelta(\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 ) {\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\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 === 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 if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n 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"],"names":[],"mappings":";;;;;;;;;;;;AAwCA,MAAM,4BAA4B,GAAwB,IAAI,GAAG,CAC/D,yBAAyB,CAC1B;AAED;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;IACxC;IAEA,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAA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
4
  import { tool } from '@langchain/core/tools';
5
- import { getCodeBaseURL, resolveCodeApiAuthHeaders, buildCodeApiHttpErrorMessage, emptyOutputMessage } from './CodeExecutor.mjs';
5
+ import { getCodeBaseURL, CODE_ARTIFACT_PATH_GUIDANCE, BASH_SHELL_GUIDANCE, resolveCodeApiAuthHeaders, buildCodeApiHttpErrorMessage, emptyOutputMessage, appendTmpScratchReminder, appendFailedExecutionFileReminder } from './CodeExecutor.mjs';
6
6
  import { Constants } from '../common/enum.mjs';
7
+ import { appendCodeSessionFileSummary } from './CodeSessionFileSummary.mjs';
7
8
 
8
9
  config();
9
10
  const baseEndpoint = getCodeBaseURL();
@@ -15,8 +16,9 @@ const BashExecutionToolSchema = {
15
16
  type: 'string',
16
17
  description: `The bash command or script to execute.
17
18
  - The environment is stateless; variables and state don't persist between executions.
18
- - Generated files from previous executions are automatically available in "/mnt/data/".
19
- - Files from previous executions are automatically available and can be modified in place.
19
+ - Prior /mnt/data files are available and can be modified in place.
20
+ - ${CODE_ARTIFACT_PATH_GUIDANCE}
21
+ - ${BASH_SHELL_GUIDANCE}
20
22
  - Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
21
23
  - Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
22
24
  - IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
@@ -36,6 +38,8 @@ Runs bash commands and returns stdout/stderr output from a stateless execution e
36
38
  Usage:
37
39
  - No network access available.
38
40
  - Generated files are automatically delivered; **DO NOT** provide download links.
41
+ - ${CODE_ARTIFACT_PATH_GUIDANCE}
42
+ - ${BASH_SHELL_GUIDANCE}
39
43
  - NEVER use this tool to execute malicious commands.
40
44
  `.trim();
41
45
  /**
@@ -129,11 +133,6 @@ function createBashExecutionTool(params = {}) {
129
133
  throw new Error(await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response));
130
134
  }
131
135
  const result = await response.json();
132
- /* See `CodeExecutor.ts` — file listings were removed from the
133
- * LLM-facing tool result. Bash especially benefits: models
134
- * naturally `ls /mnt/data/` to discover what's available
135
- * rather than relying on a prescriptive summary that
136
- * misleads as often as it helps. */
137
136
  let formattedOutput = '';
138
137
  if (result.stdout) {
139
138
  formattedOutput += `stdout:\n${result.stdout}\n`;
@@ -143,9 +142,10 @@ function createBashExecutionTool(params = {}) {
143
142
  }
144
143
  if (result.stderr)
145
144
  formattedOutput += `stderr:\n${result.stderr}\n`;
145
+ const outputWithReminder = appendTmpScratchReminder(formattedOutput, command);
146
146
  const hasFiles = result.files != null && result.files.length > 0;
147
147
  return [
148
- formattedOutput.trim(),
148
+ appendCodeSessionFileSummary(outputWithReminder, result.files),
149
149
  (hasFiles
150
150
  ? { session_id: result.session_id, files: result.files }
151
151
  : {
@@ -154,7 +154,8 @@ function createBashExecutionTool(params = {}) {
154
154
  ];
155
155
  }
156
156
  catch (error) {
157
- throw new Error(`Execution error:\n\n${error?.message}`);
157
+ const messageWithReminder = appendFailedExecutionFileReminder(error?.message ?? '', command);
158
+ throw new Error(`Execution error:\n\n${messageWithReminder}`);
158
159
  }
159
160
  }, {
160
161
  name: BashExecutionToolName,
@@ -1 +1 @@
1
- {"version":3,"file":"BashExecutor.mjs","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 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- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\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- 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 = {}\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 /* See `CodeExecutor.ts` — file listings were removed from the\n * LLM-facing tool result. Bash especially benefits: models\n * naturally `ls /mnt/data/` to discover what's available\n * rather than relying on a prescriptive summary that\n * misleads as often as it helps. */\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 hasFiles = result.files != null && result.files.length > 0;\n return [\n formattedOutput.trim(),\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 throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\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"],"names":[],"mappings":";;;;;;;AAaA,MAA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C;AACzD,YAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;AAChB,gBAAA,MAAM,IAAI,KAAK,CACb,MAAM,4BAA4B,CAAC,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,CACpE;YACH;AAEA,YAAA,MAAM,MAAM,GAAoB,MAAM,QAAQ,CAAC,IAAI,EAAE;AACrD;;;;AAIoC;YACpC,IAAI,eAAe,GAAG,EAAE;AACxB,YAAA,IAAI,MAAM,CAAC,MAAM,EAAE;AACjB,gBAAA,eAAe,IAAI,CAAA,SAAA,EAAY,MAAM,CAAC,MAAM,IAAI;YAClD;iBAAO;gBACL,eAAe,IAAI,kBAAkB;YACvC;YACA,IAAI,MAAM,CAAC,MAAM;AAAE,gBAAA,eAAe,IAAI,CAAA,SAAA,EAAY,MAAM,CAAC,MAAM,IAAI;AAEnE,YAAA,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;YAChE,OAAO;gBACL,eAAe,CAAC,IAAI,EAAE;AACtB,iBAAC;AACC,sBAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK;AACtD,sBAAE;wBACA,UAAU,EAAE,MAAM,CAAC,UAAU;qBAC9B;aACJ;QACH;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
1
+ {"version":3,"file":"BashExecutor.mjs","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"],"names":[],"mappings":";;;;;;;;AAkBA,MAAM,EAAE;AAER,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;IAGf,2BAA2B;IAC3B,mBAAmB;;;;AAIiC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,uIAAuI;AAC1I,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;;AAGhB,MAAM,4BAA4B,GAAG;;;;;;IAMxC,2BAA2B;IAC3B,mBAAmB;;CAEtB,CAAC,IAAI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e,EACf,OAAO,CACR;AACD,YAAA,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;YAChE,OAAO;AACL,gBAAA,4BAA4B,CAAC,kBAAkB,EAAE,MAAM,CAAC,KAAK,CAAC;AAC9D,iBAAC;AACC,sBAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK;AACtD,sBAAE;wBACA,UAAU,EAAE,MAAM,CAAC,UAAU;qBAC9B;aACJ;QACH;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,MAAM,mBAAmB,GAAG,iCAAiC,CAC1D,KAA2B,EAAE,OAAO,IAAI,EAAE,EAC3C,OAAO,CACR;AACD,YAAA,MAAM,IAAI,KAAK,CACb,uBAAuB,mBAAmB,CAAA,CAAE,CAC7C;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -1,7 +1,7 @@
1
1
  import { config } from 'dotenv';
2
2
  import { tool } from '@langchain/core/tools';
3
3
  import { makeRequest, executeTools, formatCompletedResponse } from './ProgrammaticToolCalling.mjs';
4
- import { getCodeBaseURL } from './CodeExecutor.mjs';
4
+ import { CODE_ARTIFACT_PATH_GUIDANCE, BASH_SHELL_GUIDANCE, getCodeBaseURL, appendFailedExecutionFileReminder } from './CodeExecutor.mjs';
5
5
  import { resolveCodeApiRunTimeoutMs, createCodeApiRunTimeoutSchema, clampCodeApiRunTimeoutMs } from './ptcTimeout.mjs';
6
6
  import { Constants } from '../common/enum.mjs';
7
7
 
@@ -45,11 +45,14 @@ Each call is a fresh bash shell. Variables and state do NOT persist between call
45
45
  You MUST complete your entire workflow in ONE code block.
46
46
  DO NOT split work across multiple calls expecting to reuse variables.`;
47
47
  const CORE_RULES = `Rules:
48
- - EVERYTHING in one call—no state persists between executions
48
+ - One call: state does not persist
49
49
  - Tools are pre-defined as bash functions—DO NOT redefine them
50
50
  - Each tool function accepts a JSON string argument
51
+ - Save tool output with raw=$(tool '{}'); printf '%s\n' "$raw" > /mnt/data/file.json; direct tool > file may be empty
52
+ - jq: use fromjson? // . on saved tool stdout and again on JSON-string fields; check types since arrays may contain strings
51
53
  - Only echo/printf output returns to the model
52
- - Generated files are automatically available in /mnt/data/ for subsequent executions
54
+ - ${CODE_ARTIFACT_PATH_GUIDANCE}
55
+ - ${BASH_SHELL_GUIDANCE}
53
56
  - timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;
54
57
  const ADDITIONAL_RULES = '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';
55
58
  const EXAMPLES = `Example (Complete workflow in one call):
@@ -58,11 +61,11 @@ const EXAMPLES = `Example (Complete workflow in one call):
58
61
  echo "$data" | jq '.[] | .name'
59
62
 
60
63
  Example (Parallel calls):
61
- web_search '{"query": "SF weather"}' > /tmp/sf.txt &
62
- web_search '{"query": "NY weather"}' > /tmp/ny.txt &
64
+ { sf=$(web_search '{"query": "SF weather"}'); printf '%s\n' "$sf" > /mnt/data/sf.json; } &
65
+ { ny=$(web_search '{"query": "NY weather"}'); printf '%s\n' "$ny" > /mnt/data/ny.json; } &
63
66
  wait
64
- echo "SF: $(cat /tmp/sf.txt)"
65
- echo "NY: $(cat /tmp/ny.txt)"`;
67
+ echo "SF: $(jq -r . /mnt/data/sf.json)"
68
+ echo "NY: $(jq -r . /mnt/data/ny.json)"`;
66
69
  const CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.
67
70
 
68
71
  ${STATELESS_WARNING}
@@ -259,7 +262,7 @@ function createBashProgrammaticToolCallingTool(initParams = {}) {
259
262
  // Phase 3: Handle final state
260
263
  // ====================================================================
261
264
  if (response.status === 'completed') {
262
- return formatCompletedResponse(response);
265
+ return formatCompletedResponse(response, code);
263
266
  }
264
267
  if (response.status === 'error') {
265
268
  throw new Error(`Execution error: ${response.error}` +
@@ -270,7 +273,8 @@ function createBashProgrammaticToolCallingTool(initParams = {}) {
270
273
  throw new Error(`Unexpected response status: ${response.status}`);
271
274
  }
272
275
  catch (error) {
273
- throw new Error(`Bash programmatic execution failed: ${error.message}`);
276
+ const messageWithReminder = appendFailedExecutionFileReminder(error.message, code);
277
+ throw new Error(`Bash programmatic execution failed: ${messageWithReminder}`);
274
278
  }
275
279
  }, {
276
280
  name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,