@librechat/agents 3.1.73 → 3.1.75-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -0
- package/dist/cjs/agents/AgentContext.cjs +146 -57
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +13 -3
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +145 -52
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +25 -15
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +84 -70
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +1 -1
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +213 -3
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +2 -1
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +5 -4
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +468 -647
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +1 -448
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +57 -175
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +5 -3
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +1 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +39 -4
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +7 -6
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +7 -6
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/langchain.cjs +26 -0
- package/dist/cjs/messages/langchain.cjs.map +1 -0
- package/dist/cjs/messages/prune.cjs +7 -6
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +21 -11
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +37 -10
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +147 -58
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +13 -3
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +146 -54
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +25 -15
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +84 -71
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +1 -1
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +214 -4
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs +2 -1
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +5 -4
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +469 -648
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +4 -449
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +57 -175
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +5 -3
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -1
- package/dist/esm/messages/cache.mjs +39 -4
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +7 -6
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +7 -6
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/langchain.mjs +23 -0
- package/dist/esm/messages/langchain.mjs.map +1 -0
- package/dist/esm/messages/prune.mjs +7 -6
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +22 -12
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +37 -11
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -12
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +29 -4
- package/dist/types/agents/__tests__/promptCacheLiveHelpers.d.ts +46 -0
- package/dist/types/llm/anthropic/index.d.ts +22 -9
- package/dist/types/llm/anthropic/types.d.ts +5 -1
- package/dist/types/llm/anthropic/utils/message_outputs.d.ts +13 -6
- package/dist/types/llm/anthropic/utils/output_parsers.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +21 -24
- package/dist/types/llm/openrouter/index.d.ts +11 -9
- package/dist/types/llm/vertexai/index.d.ts +1 -0
- package/dist/types/messages/cache.d.ts +4 -1
- package/dist/types/messages/langchain.d.ts +27 -0
- package/dist/types/tools/CodeExecutor.d.ts +6 -0
- package/dist/types/types/graph.d.ts +26 -38
- package/dist/types/types/llm.d.ts +3 -3
- package/dist/types/types/run.d.ts +2 -0
- package/dist/types/types/stream.d.ts +1 -1
- package/dist/types/types/tools.d.ts +9 -0
- package/package.json +17 -16
- package/src/agents/AgentContext.ts +189 -71
- package/src/agents/__tests__/AgentContext.anthropic.live.test.ts +116 -0
- package/src/agents/__tests__/AgentContext.bedrock.live.test.ts +149 -0
- package/src/agents/__tests__/AgentContext.test.ts +333 -2
- package/src/agents/__tests__/promptCacheLiveHelpers.ts +165 -0
- package/src/graphs/Graph.ts +24 -4
- package/src/graphs/__tests__/composition.smoke.test.ts +188 -0
- package/src/llm/anthropic/index.ts +252 -84
- package/src/llm/anthropic/llm.spec.ts +751 -102
- package/src/llm/anthropic/types.ts +9 -1
- package/src/llm/anthropic/utils/message_inputs.ts +43 -20
- package/src/llm/anthropic/utils/message_outputs.ts +119 -101
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +77 -0
- package/src/llm/bedrock/index.ts +2 -2
- package/src/llm/bedrock/llm.spec.ts +341 -0
- package/src/llm/bedrock/utils/message_inputs.ts +303 -4
- package/src/llm/bedrock/utils/message_outputs.ts +2 -1
- package/src/llm/custom-chat-models.smoke.test.ts +662 -0
- package/src/llm/google/llm.spec.ts +339 -57
- package/src/llm/google/utils/common.ts +53 -48
- package/src/llm/openai/contentBlocks.test.ts +346 -0
- package/src/llm/openai/index.ts +736 -837
- package/src/llm/openai/utils/index.ts +84 -64
- package/src/llm/openrouter/index.ts +124 -247
- package/src/llm/openrouter/reasoning.test.ts +8 -1
- package/src/llm/vertexai/index.ts +11 -5
- package/src/llm/vertexai/llm.spec.ts +28 -1
- package/src/messages/cache.test.ts +106 -4
- package/src/messages/cache.ts +57 -5
- package/src/messages/core.ts +16 -9
- package/src/messages/format.ts +9 -6
- package/src/messages/langchain.ts +39 -0
- package/src/messages/prune.ts +12 -8
- package/src/scripts/caching.ts +2 -3
- package/src/specs/anthropic.simple.test.ts +61 -0
- package/src/specs/summarization.test.ts +58 -61
- package/src/tools/BashExecutor.ts +37 -13
- package/src/tools/CodeExecutor.ts +55 -11
- package/src/tools/ProgrammaticToolCalling.ts +29 -14
- package/src/tools/ToolNode.ts +5 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +60 -0
- package/src/types/graph.ts +35 -88
- package/src/types/llm.ts +3 -3
- package/src/types/run.ts +2 -0
- package/src/types/stream.ts +1 -1
- package/src/types/tools.ts +9 -0
- package/src/utils/llmConfig.ts +1 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n HumanMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type {\n ToolOutputResolveView,\n PreResolvedArgsMap,\n ResolvedArgsByCallId,\n} from '@/tools/toolOutputReferences';\nimport type { HookRegistry, AggregatedHookResult } from '@/hooks';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { executeHooks } from '@/hooks';\nimport { Constants, GraphEvents, CODE_EXECUTION_TOOLS } from '@/common';\nimport {\n buildReferenceKey,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\n\n/**\n * Per-call batch context for `runTool`. Bundles every optional\n * batch-scoped value the method needs so the signature stays at\n * three positional parameters even as new context fields are added.\n */\ntype RunToolBatchContext = {\n /** Position of this call within the parent ToolNode batch. */\n batchIndex?: number;\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /** Batch-local sink for post-substitution args. */\n resolvedArgsByCallId?: ResolvedArgsByCallId;\n};\n\n/**\n * Per-batch context for `dispatchToolEvents` / `executeViaEvent`.\n * Mirrors {@link RunToolBatchContext} for the event-driven path,\n * with bulk indices and the snapshot/pre-resolved-args carriers\n * used in the mixed direct+event flow.\n */\ntype DispatchBatchContext = {\n /** Per-call batch indices, parallel to the `toolCalls` array. */\n batchIndices?: number[];\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /**\n * Pre-resolved args keyed by `toolCallId`. Populated by the mixed\n * path so event calls don't re-resolve against a registry that\n * already contains same-turn direct outputs.\n */\n preResolvedArgs?: PreResolvedArgsMap;\n /**\n * Frozen pre-batch registry view used to re-resolve placeholders\n * a `PreToolUse` hook injects via `updatedInput` — preserves the\n * same-turn isolation guarantee for hook-rewritten args.\n */\n preBatchSnapshot?: ToolOutputResolveView;\n};\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Merges code execution session context into the sessions map.\n *\n * The codeapi worker reports two distinct ids on a code-execution result:\n * - `artifact.session_id` (the `sessionId` arg here) is the EXEC session\n * — the sandbox VM that ran the code. It's transient and torn down\n * post-execution; subsequent calls cannot reuse it as a sandbox.\n * - `file.session_id` on each `artifact.files[i]` is the STORAGE\n * session — the file-server bucket prefix where the artifact actually\n * lives and is served from.\n *\n * Per-file `session_id` is preserved (not overwritten with the exec id)\n * because `_injected_files` are looked up against the file-server's\n * storage path on subsequent tool calls. Stomping the storage id with\n * the exec id silently 404s every follow-up tool call within the same\n * run — `cat /mnt/data/foo.txt` reports \"No such file or directory\"\n * because the worker can't mount a file at a path the storage doesn't\n * know about. Fall back to `sessionId` only when the per-file id is\n * absent (older worker payloads).\n */\nfunction updateCodeSession(\n sessions: t.ToolSessionMap,\n sessionId: string,\n files: t.FileRefs | undefined\n): void {\n const newFiles = files ?? [];\n const existingSession = sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: file.session_id ?? sessionId,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** Maximum characters allowed in a single tool result before truncation. */\n private maxToolResultChars: number;\n /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */\n private hookRegistry?: HookRegistry;\n /**\n * Registry of tool outputs keyed by `tool<idx>turn<turn>`.\n *\n * Populated only when `toolOutputReferences.enabled` is true. The\n * registry owns the run-scoped state (turn counter, last-seen runId,\n * warn-once memo, stored outputs), so sharing a single instance\n * across multiple ToolNodes in a run lets cross-agent `{{…}}`\n * references resolve — which is why multi-agent graphs pass the\n * *same* instance to every ToolNode they compile rather than each\n * ToolNode building its own.\n */\n private toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Monotonic counter used to mint a unique scope id for anonymous\n * batches (ones invoked without a `run_id` in\n * `config.configurable`). Each such batch gets its own registry\n * partition so concurrent anonymous invocations can't delete each\n * other's in-flight state.\n */\n private anonBatchCounter: number = 0;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n maxContextTokens,\n maxToolResultChars,\n hookRegistry,\n toolOutputReferences,\n toolOutputRegistry,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.agentId = agentId;\n this.directToolNames = directToolNames;\n this.maxToolResultChars =\n maxToolResultChars ?? calculateMaxToolResultChars(maxContextTokens);\n this.hookRegistry = hookRegistry;\n /**\n * Precedence: an explicitly passed `toolOutputRegistry` instance\n * wins over a config object so a host (`Graph`) can share one\n * registry across many ToolNodes. When only the config is\n * provided (direct ToolNode usage), build a local registry so\n * the feature still works without graph-level plumbing. Registry\n * caps are intentionally decoupled from `maxToolResultChars`:\n * the registry stores the raw untruncated output so a later\n * `{{…}}` substitution pipes the full payload into the next\n * tool, even when the LLM saw a truncated preview.\n */\n if (toolOutputRegistry != null) {\n this.toolOutputRegistry = toolOutputRegistry;\n } else if (toolOutputReferences?.enabled === true) {\n this.toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: toolOutputReferences.maxOutputSize,\n maxTotalSize: toolOutputReferences.maxTotalSize,\n });\n }\n }\n\n /**\n * Returns the run-scoped tool output registry, or `undefined` when\n * the feature is disabled.\n *\n * @internal Exposed for test observation only. Host code should rely\n * on `{{tool<i>turn<n>}}` substitution at tool-invocation time and\n * not mutate the registry directly.\n */\n public _unsafeGetToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n return this.toolOutputRegistry;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling.\n *\n * `batchIndex` is the tool's position within the current ToolNode\n * batch and, together with `this.currentTurn`, forms the key used to\n * register the output for future `{{tool<idx>turn<turn>}}`\n * substitutions. Omit when no registration should occur.\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n batchContext: RunToolBatchContext = {}\n ): Promise<BaseMessage | Command> {\n const { batchIndex, turn, batchScopeId, resolvedArgsByCallId } =\n batchContext;\n const tool = this.toolMap.get(call.name);\n const registry = this.toolOutputRegistry;\n /**\n * Precompute the reference key once per call — captured locally\n * so concurrent `invoke()` calls on the same ToolNode cannot race\n * on a shared turn field.\n */\n const refKey =\n registry != null && batchIndex != null && turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n /**\n * Hoisted outside the try so the catch branch can append\n * `[unresolved refs: …]` to error messages — otherwise the LLM\n * only sees a generic error when it references a bad key, losing\n * the self-correction signal this feature is meant to provide.\n */\n let unresolvedRefs: string[] = [];\n /**\n * Use the caller-provided `batchScopeId` when threaded from\n * `run()` (so anonymous batches get their own unique scope).\n * Fall back to the config's `run_id` when runTool is invoked\n * from a context that doesn't thread it — that still preserves\n * the runId-based partitioning for named runs.\n */\n const runId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n /**\n * `usageCount` is the per-tool-name invocation index that\n * web-search and other tools observe via `invokeParams.turn`.\n * It is intentionally distinct from the outer `turn` parameter\n * (the batch turn used for ref keys); the latter is captured\n * before the try block when constructing `refKey`.\n */\n const usageCount = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, usageCount + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, usageCount);\n }\n let args = call.args;\n if (registry != null) {\n const { resolved, unresolved } = registry.resolve(runId, args);\n args = resolved;\n unresolvedRefs = unresolved;\n /**\n * Expose the post-substitution args to downstream completion\n * events so audit logs / host-side `ON_RUN_STEP_COMPLETED`\n * handlers observe what actually ran, not the `{{…}}`\n * template. Only string/object args are worth recording.\n */\n if (\n resolvedArgsByCallId != null &&\n call.id != null &&\n call.id !== '' &&\n resolved !== call.args &&\n typeof resolved === 'object'\n ) {\n resolvedArgsByCallId.set(\n call.id,\n resolved as Record<string, unknown>\n );\n }\n }\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n // `turn` here is the per-tool usage count (matches what tools have\n // observed historically via config.toolCall.turn — e.g. web search).\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn: usageCount,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING ||\n call.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n ) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (CODE_EXECUTION_TOOLS.has(call.name)) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id != null && codeSession.session_id !== '') {\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n invokeParams._injected_files = fileRefs;\n }\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (isCommand(output)) {\n return output;\n }\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n const isError = toolMsg.status === 'error';\n if (isError) {\n /**\n * Error ToolMessages bypass registration but still stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM, letting the\n * model self-correct when its reference key caused the\n * failure. Persisted `content` stays clean.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n return toolMsg;\n }\n if (this.toolOutputRegistry != null || unresolvedRefs.length > 0) {\n if (typeof toolMsg.content === 'string') {\n const rawContent = toolMsg.content;\n const llmContent = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n toolMsg.content = llmContent;\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n if (refMeta != null) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n ...refMeta,\n };\n }\n } else {\n /**\n * Non-string content (multi-part content blocks — text +\n * image). Known limitation: we cannot register under a\n * reference key because there's no canonical serialized\n * form. Warn once per tool per run when the caller\n * intended to register. The unresolved-refs hint is still\n * stamped as metadata; the lazy transform prepends a text\n * block at request time so the LLM gets the self-correction\n * signal.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n if (\n refKey != null &&\n this.toolOutputRegistry!.claimWarnOnce(runId, call.name)\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Skipping tool output reference for \"${call.name}\": ` +\n 'ToolMessage content is not a string (further occurrences for this tool in the same run are suppressed).'\n );\n }\n }\n }\n return toolMsg;\n }\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n const truncated = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncated,\n tool_call_id: call.id!,\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n const errorContent = `Error: ${e.message}\\n Please fix your mistakes.`;\n const refMeta =\n unresolvedRefs.length > 0\n ? this.recordOutputReference(\n runId,\n errorContent,\n undefined,\n unresolvedRefs\n )\n : undefined;\n return new ToolMessage({\n status: 'error',\n content: errorContent,\n name: call.name,\n tool_call_id: call.id ?? '',\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n }\n }\n\n /**\n * Registers the full, raw output under `refKey` (when provided) and\n * builds the per-message ref metadata stamped onto the resulting\n * `ToolMessage.additional_kwargs`. The metadata is read at LLM-\n * request time by `annotateMessagesForLLM` to produce a transient\n * annotated copy of the message — the persisted `content` itself\n * stays clean.\n *\n * @param registryContent The full, untruncated output to store in\n * the registry so `{{tool<i>turn<n>}}` substitutions deliver the\n * complete payload. Ignored when `refKey` is undefined.\n * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when\n * the output is not to be registered (errors, disabled feature,\n * unavailable batch/turn).\n * @param unresolved Placeholder keys that did not resolve; surfaced\n * to the LLM lazily so it can self-correct.\n * @returns A `ToolMessageRefMetadata` object when there is anything\n * to stamp, otherwise `undefined`.\n */\n private recordOutputReference(\n runId: string | undefined,\n registryContent: string,\n refKey: string | undefined,\n unresolved: string[]\n ): t.ToolMessageRefMetadata | undefined {\n if (this.toolOutputRegistry != null && refKey != null) {\n this.toolOutputRegistry.set(runId, refKey, registryContent);\n }\n if (refKey == null && unresolved.length === 0) return undefined;\n const meta: t.ToolMessageRefMetadata = {};\n if (refKey != null) {\n meta._refKey = refKey;\n /**\n * Stamp the registry scope alongside the key so the lazy\n * annotation transform can look up the right bucket. Anonymous\n * invocations get a synthetic per-batch scope (`\\0anon-<n>`)\n * that `attemptInvoke` cannot derive from\n * `config.configurable.run_id` — without this, anonymous-run\n * refs would silently fail registry lookup and the LLM would\n * never see `[ref: …]` markers for outputs that were registered.\n */\n if (runId != null) meta._refScope = runId;\n }\n if (unresolved.length > 0) meta._unresolvedRefs = unresolved;\n return meta;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requestMap: Map<string, t.ToolCallRequest>\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requestMap.get(result.toolCallId);\n if (\n !request?.name ||\n (!CODE_EXECUTION_TOOLS.has(request.name) &&\n request.name !== Constants.SKILL_TOOL)\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n updateCodeSession(this.sessions, artifact.session_id!, artifact.files);\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n *\n * @param resolvedArgsByCallId Per-batch resolved-args sink populated\n * by `runTool`. Threaded as a local map (instead of instance state)\n * so concurrent batches cannot read each other's entries.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig,\n resolvedArgsByCallId?: ResolvedArgsByCallId\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n if (this.sessions && CODE_EXECUTION_TOOLS.has(call.name)) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n updateCodeSession(this.sessions, artifact.session_id, artifact.files);\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n /**\n * Prefer the post-substitution args when a `{{…}}` placeholder\n * was resolved in `runTool`. This keeps\n * `ON_RUN_STEP_COMPLETED.tool_call.args` consistent with what\n * the tool actually received rather than leaking the template.\n */\n const effectiveArgs = resolvedArgsByCallId?.get(toolCallId) ?? call.args;\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof effectiveArgs === 'string'\n ? (effectiveArgs as string)\n : JSON.stringify((effectiveArgs as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n *\n * Hook lifecycle (when `hookRegistry` is set):\n * 1. **PreToolUse** fires per call in parallel before dispatch. Denied\n * calls produce error ToolMessages and fire **PermissionDenied**;\n * surviving calls proceed with optional `updatedInput`.\n * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.\n * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks\n * can replace tool output via `updatedOutput`.\n * 4. Injected messages from results are collected and returned alongside\n * ToolMessages (appended AFTER to respect provider ordering).\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n batchContext: DispatchBatchContext = {}\n ): Promise<{ toolMessages: ToolMessage[]; injected: BaseMessage[] }> {\n const {\n batchIndices,\n turn,\n batchScopeId,\n preResolvedArgs,\n preBatchSnapshot,\n } = batchContext;\n const runId = (config.configurable?.run_id as string | undefined) ?? '';\n /**\n * Registry-facing scope id — prefers the caller-threaded\n * `batchScopeId` so anonymous batches target their own unique\n * bucket and don't step on concurrent anonymous invocations.\n * Hooks and event payloads keep using the empty-string coerced\n * `runId` for backward compat.\n */\n const registryRunId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n const threadId = config.configurable?.thread_id as string | undefined;\n const registry = this.toolOutputRegistry;\n const unresolvedByCallId = new Map<string, string[]>();\n\n const preToolCalls = toolCalls.map((call, i) => {\n const originalArgs = call.args as Record<string, unknown>;\n let resolvedArgs = originalArgs;\n /**\n * When the caller provided a pre-resolved map (the mixed\n * direct+event path snapshots event args synchronously before\n * awaiting directs so they can't accidentally resolve\n * same-turn direct outputs), use those entries verbatim instead\n * of re-resolving against a registry that may have changed\n * since the batch started.\n */\n const pre = call.id != null ? preResolvedArgs?.get(call.id) : undefined;\n if (pre != null) {\n resolvedArgs = pre.resolved;\n if (pre.unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, pre.unresolved);\n }\n } else if (registry != null) {\n const { resolved, unresolved } = registry.resolve(\n registryRunId,\n originalArgs\n );\n resolvedArgs = resolved as Record<string, unknown>;\n if (unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, unresolved);\n }\n }\n return {\n call,\n stepId: this.toolCallStepIds?.get(call.id!) ?? '',\n args: resolvedArgs,\n batchIndex: batchIndices?.[i],\n };\n });\n\n const messageByCallId = new Map<string, ToolMessage>();\n const approvedEntries: typeof preToolCalls = [];\n const HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n });\n\n if (this.hookRegistry?.hasHookFor('PreToolUse', runId) === true) {\n const preResults = await Promise.all(\n preToolCalls.map((entry) =>\n executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PreToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK)\n )\n );\n\n for (let i = 0; i < preToolCalls.length; i++) {\n const hookResult = preResults[i];\n const entry = preToolCalls[i];\n const isDenied =\n hookResult.decision === 'deny' || hookResult.decision === 'ask';\n if (isDenied) {\n const reason = hookResult.reason ?? 'Blocked by hook';\n const contentString = `Blocked: ${reason}`;\n messageByCallId.set(\n entry.call.id!,\n new ToolMessage({\n status: 'error',\n content: contentString,\n name: entry.call.name,\n tool_call_id: entry.call.id!,\n })\n );\n this.dispatchStepCompleted(\n entry.call.id!,\n entry.call.name,\n entry.args,\n contentString,\n config\n );\n if (this.hookRegistry.hasHookFor('PermissionDenied', runId)) {\n executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PermissionDenied',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n reason,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch(() => {\n /* PermissionDenied is observational — swallow errors */\n });\n }\n continue;\n }\n if (hookResult.updatedInput != null) {\n /**\n * Re-resolve after PreToolUse replaces the input: a hook may\n * introduce new `{{tool<i>turn<n>}}` placeholders (e.g., by\n * copying user-supplied text) that the pre-hook pass never\n * saw. Re-running the resolver on the hook-rewritten args\n * keeps substitution and the unresolved-refs record in sync\n * with what the tool will actually receive.\n */\n if (registry != null) {\n /**\n * Mixed direct+event batches must use the pre-batch\n * snapshot so a hook-introduced placeholder cannot\n * accidentally resolve to a same-turn direct output that\n * has just registered. Pure event batches don't have a\n * snapshot and resolve against the live registry — safe\n * because no event-side registrations have happened yet.\n */\n const view: ToolOutputResolveView = preBatchSnapshot ?? {\n resolve: <T>(args: T) => registry.resolve(registryRunId, args),\n };\n const { resolved, unresolved } = view.resolve(\n hookResult.updatedInput\n );\n entry.args = resolved as Record<string, unknown>;\n if (entry.call.id != null) {\n if (unresolved.length > 0) {\n unresolvedByCallId.set(entry.call.id, unresolved);\n } else {\n unresolvedByCallId.delete(entry.call.id);\n }\n }\n } else {\n entry.args = hookResult.updatedInput;\n }\n }\n approvedEntries.push(entry);\n }\n } else {\n approvedEntries.push(...preToolCalls);\n }\n\n const injected: BaseMessage[] = [];\n\n const batchIndexByCallId = new Map<string, number>();\n\n if (approvedEntries.length > 0) {\n const requests: t.ToolCallRequest[] = approvedEntries.map((entry) => {\n const turn = this.toolUsageCount.get(entry.call.name) ?? 0;\n this.toolUsageCount.set(entry.call.name, turn + 1);\n\n if (entry.batchIndex != null && entry.call.id != null) {\n batchIndexByCallId.set(entry.call.id, entry.batchIndex);\n }\n\n const request: t.ToolCallRequest = {\n id: entry.call.id!,\n name: entry.call.name,\n args: entry.args,\n stepId: entry.stepId,\n turn,\n };\n\n /**\n * Emit `codeSessionContext` for any tool whose host handler may need\n * to reach into the code-execution sandbox:\n * - `CODE_EXECUTION_TOOLS` — direct executors that POST to /exec.\n * - `SKILL_TOOL` — skill files live alongside code-env state.\n * - `READ_FILE` — when the requested path is a code-env artifact\n * (e.g. `/mnt/data/...`) the host falls back to reading via the\n * same sandbox session; without the seeded `session_id` /\n * `_injected_files` here, that fallback can't see prior-turn\n * artifacts on the very first call of a turn.\n */\n if (\n CODE_EXECUTION_TOOLS.has(entry.call.name) ||\n entry.call.name === Constants.SKILL_TOOL ||\n entry.call.name === Constants.READ_FILE\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const requestMap = new Map(requests.map((r) => [r.id, r]));\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n config\n );\n }\n );\n\n this.storeCodeSessionFromResults(results, requestMap);\n\n const hasPostHook =\n this.hookRegistry?.hasHookFor('PostToolUse', runId) === true;\n const hasFailureHook =\n this.hookRegistry?.hasHookFor('PostToolUseFailure', runId) === true;\n\n for (const result of results) {\n if (result.injectedMessages && result.injectedMessages.length > 0) {\n try {\n injected.push(\n ...this.convertInjectedMessages(result.injectedMessages)\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Failed to convert injectedMessages for toolCallId=${result.toolCallId}:`,\n e instanceof Error ? e.message : e\n );\n }\n }\n const request = requestMap.get(result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n\n let contentString: string;\n let toolMessage: ToolMessage;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n /**\n * Error results bypass registration but stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM at request\n * time, letting the model self-correct when its reference\n * key caused the failure. Persisted `content` stays clean.\n */\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const errorRefMeta =\n unresolved.length > 0\n ? this.recordOutputReference(\n registryRunId,\n contentString,\n undefined,\n unresolved\n )\n : undefined;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n ...(errorRefMeta != null && {\n additional_kwargs: errorRefMeta as Record<string, unknown>,\n }),\n });\n\n if (hasFailureHook) {\n await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUseFailure',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolUseId: result.toolCallId,\n error: result.errorMessage ?? 'Unknown error',\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch(() => {\n /* PostToolUseFailure is observational — swallow errors */\n });\n }\n } else {\n let registryRaw =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n registryRaw,\n this.maxToolResultChars\n );\n\n if (hasPostHook) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolOutput: result.content,\n toolUseId: result.toolCallId,\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch((): undefined => undefined);\n if (hookResult?.updatedOutput != null) {\n const replaced =\n typeof hookResult.updatedOutput === 'string'\n ? hookResult.updatedOutput\n : JSON.stringify(hookResult.updatedOutput);\n registryRaw = replaced;\n contentString = truncateToolResultContent(\n replaced,\n this.maxToolResultChars\n );\n }\n }\n\n const batchIndex = batchIndexByCallId.get(result.toolCallId);\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const refKey =\n this.toolOutputRegistry != null &&\n batchIndex != null &&\n turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n const successRefMeta = this.recordOutputReference(\n registryRunId,\n registryRaw,\n refKey,\n unresolved\n );\n\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n ...(successRefMeta != null && {\n additional_kwargs: successRefMeta as Record<string, unknown>,\n }),\n });\n }\n\n this.dispatchStepCompleted(\n result.toolCallId,\n toolName,\n request?.args ?? {},\n contentString,\n config,\n request?.turn\n );\n\n messageByCallId.set(result.toolCallId, toolMessage);\n }\n }\n\n const toolMessages = toolCalls\n .map((call) => messageByCallId.get(call.id!))\n .filter((m): m is ToolMessage => m != null);\n return { toolMessages, injected };\n }\n\n private dispatchStepCompleted(\n toolCallId: string,\n toolName: string,\n args: Record<string, unknown>,\n output: string,\n config: RunnableConfig,\n turn?: number\n ): void {\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn ?? this.toolUsageCount.get(toolName) ?? 0,\n type: 'tool_call' as const,\n tool_call: {\n args: JSON.stringify(args),\n name: toolName,\n id: toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n config\n );\n }\n\n /**\n * Converts InjectedMessage instances to LangChain HumanMessage objects.\n * Both 'user' and 'system' roles become HumanMessage to avoid provider\n * rejections (Anthropic/Google reject non-leading SystemMessages).\n * The original role is preserved in additional_kwargs for downstream consumers.\n */\n private convertInjectedMessages(\n messages: t.InjectedMessage[]\n ): BaseMessage[] {\n const converted: BaseMessage[] = [];\n for (const msg of messages) {\n const additional_kwargs: Record<string, unknown> = {\n role: msg.role,\n };\n if (msg.isMeta != null) additional_kwargs.isMeta = msg.isMeta;\n if (msg.source != null) additional_kwargs.source = msg.source;\n if (msg.skillName != null) additional_kwargs.skillName = msg.skillName;\n\n converted.push(\n new HumanMessage({ content: msg.content, additional_kwargs })\n );\n }\n return converted;\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Injected messages are placed AFTER ToolMessages to respect provider\n * message ordering (AIMessage tool_calls must be immediately followed\n * by their ToolMessage results).\n *\n * `batchIndices` mirrors `toolCalls` and carries each call's position\n * within the parent batch. `turn` is the per-`run()` batch index\n * captured locally by the caller. Both are threaded so concurrent\n * invocations cannot race on shared mutable state.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n batchContext: DispatchBatchContext = {}\n ): Promise<T> {\n const { toolMessages, injected } = await this.dispatchToolEvents(\n toolCalls,\n config,\n batchContext\n );\n const outputs: BaseMessage[] = [...toolMessages, ...injected];\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n /**\n * Per-batch local map for resolved (post-substitution) args.\n * Lives on the stack so concurrent `run()` calls on the same\n * ToolNode cannot read or wipe each other's entries.\n */\n const resolvedArgsByCallId = new Map<string, Record<string, unknown>>();\n /**\n * Claim this batch's turn synchronously from the registry (or\n * fall back to 0 when the feature is disabled). The registry is\n * partitioned by scope id so overlapping batches cannot\n * overwrite each other's state even under a shared registry.\n *\n * For anonymous callers (no `run_id` in config), mint a unique\n * per-batch scope id so two concurrent anonymous invocations\n * don't target the same bucket. The scope is threaded down to\n * every subsequent registry call on this batch.\n */\n const incomingRunId = config.configurable?.run_id as string | undefined;\n const batchScopeId = incomingRunId ?? `\\0anon-${this.anonBatchCounter++}`;\n const turn = this.toolOutputRegistry?.nextTurn(batchScopeId) ?? 0;\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input, {\n batchIndices: [0],\n turn,\n batchScopeId,\n });\n }\n outputs = [\n await this.runTool(input.lg_tool_call, config, {\n batchIndex: 0,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n }),\n ];\n this.handleRunToolCompletions(\n [input.lg_tool_call],\n outputs,\n config,\n resolvedArgsByCallId\n );\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(\n call.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n )\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n const filteredIndices = filteredCalls.map((_, idx) => idx);\n\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input, {\n batchIndices: filteredIndices,\n turn,\n batchScopeId,\n });\n }\n\n const directEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n const eventEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n for (let i = 0; i < filteredCalls.length; i++) {\n const call = filteredCalls[i];\n const entry = { call, batchIndex: i };\n if (this.directToolNames!.has(call.name)) {\n directEntries.push(entry);\n } else {\n eventEntries.push(entry);\n }\n }\n\n const directCalls = directEntries.map((e) => e.call);\n const directIndices = directEntries.map((e) => e.batchIndex);\n const eventCalls = eventEntries.map((e) => e.call);\n const eventIndices = eventEntries.map((e) => e.batchIndex);\n\n /**\n * Snapshot the event calls' args against the *pre-batch*\n * registry state synchronously, before any await runs. The\n * directs are then awaited first (preserving fail-fast\n * semantics — a thrown error in a direct tool, e.g. with\n * `handleToolErrors=false` or a `GraphInterrupt`, aborts\n * before we dispatch any event-driven tools to the host).\n * Because the event args were captured pre-await, they stay\n * isolated from same-turn direct outputs that register\n * during the await.\n */\n const preResolvedEventArgs = new Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n >();\n /**\n * Take a frozen snapshot of the registry state before any\n * direct registrations land. The snapshot resolves\n * placeholders against this point-in-time view, so a\n * `PreToolUse` hook later rewriting event args via\n * `updatedInput` can introduce placeholders that resolve\n * cross-batch (against prior runs) without ever picking up\n * same-turn direct outputs.\n */\n const preBatchSnapshot =\n this.toolOutputRegistry?.snapshot(batchScopeId);\n if (preBatchSnapshot != null) {\n for (const entry of eventEntries) {\n if (entry.call.id != null) {\n const { resolved, unresolved } = preBatchSnapshot.resolve(\n entry.call.args as Record<string, unknown>\n );\n preResolvedEventArgs.set(entry.call.id, {\n resolved: resolved as Record<string, unknown>,\n unresolved,\n });\n }\n }\n }\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: directIndices[i],\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(\n directCalls,\n directOutputs,\n config,\n resolvedArgsByCallId\n );\n }\n\n const eventResult =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config, {\n batchIndices: eventIndices,\n turn,\n batchScopeId,\n preResolvedArgs: preResolvedEventArgs,\n preBatchSnapshot,\n })\n : {\n toolMessages: [] as ToolMessage[],\n injected: [] as BaseMessage[],\n };\n\n outputs = [\n ...directOutputs,\n ...eventResult.toolMessages,\n ...eventResult.injected,\n ];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: i,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n );\n this.handleRunToolCompletions(\n filteredCalls,\n outputs,\n config,\n resolvedArgsByCallId\n );\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return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
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n HumanMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type {\n ToolOutputResolveView,\n PreResolvedArgsMap,\n ResolvedArgsByCallId,\n} from '@/tools/toolOutputReferences';\nimport type { HookRegistry, AggregatedHookResult } from '@/hooks';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { executeHooks } from '@/hooks';\nimport { toLangChainContent } from '@/messages/langchain';\nimport { Constants, GraphEvents, CODE_EXECUTION_TOOLS } from '@/common';\nimport {\n buildReferenceKey,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\n\n/**\n * Per-call batch context for `runTool`. Bundles every optional\n * batch-scoped value the method needs so the signature stays at\n * three positional parameters even as new context fields are added.\n */\ntype RunToolBatchContext = {\n /** Position of this call within the parent ToolNode batch. */\n batchIndex?: number;\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /** Batch-local sink for post-substitution args. */\n resolvedArgsByCallId?: ResolvedArgsByCallId;\n};\n\n/**\n * Per-batch context for `dispatchToolEvents` / `executeViaEvent`.\n * Mirrors {@link RunToolBatchContext} for the event-driven path,\n * with bulk indices and the snapshot/pre-resolved-args carriers\n * used in the mixed direct+event flow.\n */\ntype DispatchBatchContext = {\n /** Per-call batch indices, parallel to the `toolCalls` array. */\n batchIndices?: number[];\n /** Batch turn shared across every call in the batch. */\n turn?: number;\n /** Registry partition scope (run id or anonymous batch id). */\n batchScopeId?: string;\n /**\n * Pre-resolved args keyed by `toolCallId`. Populated by the mixed\n * path so event calls don't re-resolve against a registry that\n * already contains same-turn direct outputs.\n */\n preResolvedArgs?: PreResolvedArgsMap;\n /**\n * Frozen pre-batch registry view used to re-resolve placeholders\n * a `PreToolUse` hook injects via `updatedInput` — preserves the\n * same-turn isolation guarantee for hook-rewritten args.\n */\n preBatchSnapshot?: ToolOutputResolveView;\n};\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Merges code execution session context into the sessions map.\n *\n * The codeapi worker reports two distinct ids on a code-execution result:\n * - `artifact.session_id` (the `sessionId` arg here) is the EXEC session\n * — the sandbox VM that ran the code. It's transient and torn down\n * post-execution; subsequent calls cannot reuse it as a sandbox.\n * - `file.session_id` on each `artifact.files[i]` is the STORAGE\n * session — the file-server bucket prefix where the artifact actually\n * lives and is served from.\n *\n * Per-file `session_id` is preserved (not overwritten with the exec id)\n * because `_injected_files` are looked up against the file-server's\n * storage path on subsequent tool calls. Stomping the storage id with\n * the exec id silently 404s every follow-up tool call within the same\n * run — `cat /mnt/data/foo.txt` reports \"No such file or directory\"\n * because the worker can't mount a file at a path the storage doesn't\n * know about. Fall back to `sessionId` only when the per-file id is\n * absent (older worker payloads).\n */\nfunction updateCodeSession(\n sessions: t.ToolSessionMap,\n sessionId: string,\n files: t.FileRefs | undefined\n): void {\n const newFiles = files ?? [];\n const existingSession = sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: file.session_id ?? sessionId,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n sessions.set(Constants.EXECUTE_CODE, {\n session_id: sessionId,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** Maximum characters allowed in a single tool result before truncation. */\n private maxToolResultChars: number;\n /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */\n private hookRegistry?: HookRegistry;\n /**\n * Registry of tool outputs keyed by `tool<idx>turn<turn>`.\n *\n * Populated only when `toolOutputReferences.enabled` is true. The\n * registry owns the run-scoped state (turn counter, last-seen runId,\n * warn-once memo, stored outputs), so sharing a single instance\n * across multiple ToolNodes in a run lets cross-agent `{{…}}`\n * references resolve — which is why multi-agent graphs pass the\n * *same* instance to every ToolNode they compile rather than each\n * ToolNode building its own.\n */\n private toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Monotonic counter used to mint a unique scope id for anonymous\n * batches (ones invoked without a `run_id` in\n * `config.configurable`). Each such batch gets its own registry\n * partition so concurrent anonymous invocations can't delete each\n * other's in-flight state.\n */\n private anonBatchCounter: number = 0;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n maxContextTokens,\n maxToolResultChars,\n hookRegistry,\n toolOutputReferences,\n toolOutputRegistry,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.agentId = agentId;\n this.directToolNames = directToolNames;\n this.maxToolResultChars =\n maxToolResultChars ?? calculateMaxToolResultChars(maxContextTokens);\n this.hookRegistry = hookRegistry;\n /**\n * Precedence: an explicitly passed `toolOutputRegistry` instance\n * wins over a config object so a host (`Graph`) can share one\n * registry across many ToolNodes. When only the config is\n * provided (direct ToolNode usage), build a local registry so\n * the feature still works without graph-level plumbing. Registry\n * caps are intentionally decoupled from `maxToolResultChars`:\n * the registry stores the raw untruncated output so a later\n * `{{…}}` substitution pipes the full payload into the next\n * tool, even when the LLM saw a truncated preview.\n */\n if (toolOutputRegistry != null) {\n this.toolOutputRegistry = toolOutputRegistry;\n } else if (toolOutputReferences?.enabled === true) {\n this.toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: toolOutputReferences.maxOutputSize,\n maxTotalSize: toolOutputReferences.maxTotalSize,\n });\n }\n }\n\n /**\n * Returns the run-scoped tool output registry, or `undefined` when\n * the feature is disabled.\n *\n * @internal Exposed for test observation only. Host code should rely\n * on `{{tool<i>turn<n>}}` substitution at tool-invocation time and\n * not mutate the registry directly.\n */\n public _unsafeGetToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n return this.toolOutputRegistry;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling.\n *\n * `batchIndex` is the tool's position within the current ToolNode\n * batch and, together with `this.currentTurn`, forms the key used to\n * register the output for future `{{tool<idx>turn<turn>}}`\n * substitutions. Omit when no registration should occur.\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig,\n batchContext: RunToolBatchContext = {}\n ): Promise<BaseMessage | Command> {\n const { batchIndex, turn, batchScopeId, resolvedArgsByCallId } =\n batchContext;\n const tool = this.toolMap.get(call.name);\n const registry = this.toolOutputRegistry;\n /**\n * Precompute the reference key once per call — captured locally\n * so concurrent `invoke()` calls on the same ToolNode cannot race\n * on a shared turn field.\n */\n const refKey =\n registry != null && batchIndex != null && turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n /**\n * Hoisted outside the try so the catch branch can append\n * `[unresolved refs: …]` to error messages — otherwise the LLM\n * only sees a generic error when it references a bad key, losing\n * the self-correction signal this feature is meant to provide.\n */\n let unresolvedRefs: string[] = [];\n /**\n * Use the caller-provided `batchScopeId` when threaded from\n * `run()` (so anonymous batches get their own unique scope).\n * Fall back to the config's `run_id` when runTool is invoked\n * from a context that doesn't thread it — that still preserves\n * the runId-based partitioning for named runs.\n */\n const runId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n /**\n * `usageCount` is the per-tool-name invocation index that\n * web-search and other tools observe via `invokeParams.turn`.\n * It is intentionally distinct from the outer `turn` parameter\n * (the batch turn used for ref keys); the latter is captured\n * before the try block when constructing `refKey`.\n */\n const usageCount = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, usageCount + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, usageCount);\n }\n let args = call.args;\n if (registry != null) {\n const { resolved, unresolved } = registry.resolve(runId, args);\n args = resolved;\n unresolvedRefs = unresolved;\n /**\n * Expose the post-substitution args to downstream completion\n * events so audit logs / host-side `ON_RUN_STEP_COMPLETED`\n * handlers observe what actually ran, not the `{{…}}`\n * template. Only string/object args are worth recording.\n */\n if (\n resolvedArgsByCallId != null &&\n call.id != null &&\n call.id !== '' &&\n resolved !== call.args &&\n typeof resolved === 'object'\n ) {\n resolvedArgsByCallId.set(\n call.id,\n resolved as Record<string, unknown>\n );\n }\n }\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n // `turn` here is the per-tool usage count (matches what tools have\n // observed historically via config.toolCall.turn — e.g. web search).\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn: usageCount,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING ||\n call.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n ) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (CODE_EXECUTION_TOOLS.has(call.name)) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.session_id != null && codeSession.session_id !== '') {\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n invokeParams._injected_files = fileRefs;\n }\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (isCommand(output)) {\n return output;\n }\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n const isError = toolMsg.status === 'error';\n if (isError) {\n /**\n * Error ToolMessages bypass registration but still stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM, letting the\n * model self-correct when its reference key caused the\n * failure. Persisted `content` stays clean.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n return toolMsg;\n }\n if (this.toolOutputRegistry != null || unresolvedRefs.length > 0) {\n if (typeof toolMsg.content === 'string') {\n const rawContent = toolMsg.content;\n const llmContent = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n toolMsg.content = llmContent;\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n if (refMeta != null) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n ...refMeta,\n };\n }\n } else {\n /**\n * Non-string content (multi-part content blocks — text +\n * image). Known limitation: we cannot register under a\n * reference key because there's no canonical serialized\n * form. Warn once per tool per run when the caller\n * intended to register. The unresolved-refs hint is still\n * stamped as metadata; the lazy transform prepends a text\n * block at request time so the LLM gets the self-correction\n * signal.\n */\n if (unresolvedRefs.length > 0) {\n toolMsg.additional_kwargs = {\n ...toolMsg.additional_kwargs,\n _unresolvedRefs: unresolvedRefs,\n };\n }\n if (\n refKey != null &&\n this.toolOutputRegistry!.claimWarnOnce(runId, call.name)\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Skipping tool output reference for \"${call.name}\": ` +\n 'ToolMessage content is not a string (further occurrences for this tool in the same run are suppressed).'\n );\n }\n }\n }\n return toolMsg;\n }\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n const truncated = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n );\n const refMeta = this.recordOutputReference(\n runId,\n rawContent,\n refKey,\n unresolvedRefs\n );\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncated,\n tool_call_id: call.id!,\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n const errorContent = `Error: ${e.message}\\n Please fix your mistakes.`;\n const refMeta =\n unresolvedRefs.length > 0\n ? this.recordOutputReference(\n runId,\n errorContent,\n undefined,\n unresolvedRefs\n )\n : undefined;\n return new ToolMessage({\n status: 'error',\n content: errorContent,\n name: call.name,\n tool_call_id: call.id ?? '',\n ...(refMeta != null && {\n additional_kwargs: refMeta as Record<string, unknown>,\n }),\n });\n }\n }\n\n /**\n * Registers the full, raw output under `refKey` (when provided) and\n * builds the per-message ref metadata stamped onto the resulting\n * `ToolMessage.additional_kwargs`. The metadata is read at LLM-\n * request time by `annotateMessagesForLLM` to produce a transient\n * annotated copy of the message — the persisted `content` itself\n * stays clean.\n *\n * @param registryContent The full, untruncated output to store in\n * the registry so `{{tool<i>turn<n>}}` substitutions deliver the\n * complete payload. Ignored when `refKey` is undefined.\n * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when\n * the output is not to be registered (errors, disabled feature,\n * unavailable batch/turn).\n * @param unresolved Placeholder keys that did not resolve; surfaced\n * to the LLM lazily so it can self-correct.\n * @returns A `ToolMessageRefMetadata` object when there is anything\n * to stamp, otherwise `undefined`.\n */\n private recordOutputReference(\n runId: string | undefined,\n registryContent: string,\n refKey: string | undefined,\n unresolved: string[]\n ): t.ToolMessageRefMetadata | undefined {\n if (this.toolOutputRegistry != null && refKey != null) {\n this.toolOutputRegistry.set(runId, refKey, registryContent);\n }\n if (refKey == null && unresolved.length === 0) return undefined;\n const meta: t.ToolMessageRefMetadata = {};\n if (refKey != null) {\n meta._refKey = refKey;\n /**\n * Stamp the registry scope alongside the key so the lazy\n * annotation transform can look up the right bucket. Anonymous\n * invocations get a synthetic per-batch scope (`\\0anon-<n>`)\n * that `attemptInvoke` cannot derive from\n * `config.configurable.run_id` — without this, anonymous-run\n * refs would silently fail registry lookup and the LLM would\n * never see `[ref: …]` markers for outputs that were registered.\n */\n if (runId != null) meta._refScope = runId;\n }\n if (unresolved.length > 0) meta._unresolvedRefs = unresolved;\n return meta;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requestMap: Map<string, t.ToolCallRequest>\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requestMap.get(result.toolCallId);\n if (\n !request?.name ||\n (!CODE_EXECUTION_TOOLS.has(request.name) &&\n request.name !== Constants.SKILL_TOOL)\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n updateCodeSession(this.sessions, artifact.session_id!, artifact.files);\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n *\n * @param resolvedArgsByCallId Per-batch resolved-args sink populated\n * by `runTool`. Threaded as a local map (instead of instance state)\n * so concurrent batches cannot read each other's entries.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig,\n resolvedArgsByCallId?: ResolvedArgsByCallId\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n if (this.sessions && CODE_EXECUTION_TOOLS.has(call.name)) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n updateCodeSession(this.sessions, artifact.session_id, artifact.files);\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n /**\n * Prefer the post-substitution args when a `{{…}}` placeholder\n * was resolved in `runTool`. This keeps\n * `ON_RUN_STEP_COMPLETED.tool_call.args` consistent with what\n * the tool actually received rather than leaking the template.\n */\n const effectiveArgs = resolvedArgsByCallId?.get(toolCallId) ?? call.args;\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof effectiveArgs === 'string'\n ? (effectiveArgs as string)\n : JSON.stringify((effectiveArgs as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n *\n * Hook lifecycle (when `hookRegistry` is set):\n * 1. **PreToolUse** fires per call in parallel before dispatch. Denied\n * calls produce error ToolMessages and fire **PermissionDenied**;\n * surviving calls proceed with optional `updatedInput`.\n * 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.\n * 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks\n * can replace tool output via `updatedOutput`.\n * 4. Injected messages from results are collected and returned alongside\n * ToolMessages (appended AFTER to respect provider ordering).\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n batchContext: DispatchBatchContext = {}\n ): Promise<{ toolMessages: ToolMessage[]; injected: BaseMessage[] }> {\n const {\n batchIndices,\n turn,\n batchScopeId,\n preResolvedArgs,\n preBatchSnapshot,\n } = batchContext;\n const runId = (config.configurable?.run_id as string | undefined) ?? '';\n /**\n * Registry-facing scope id — prefers the caller-threaded\n * `batchScopeId` so anonymous batches target their own unique\n * bucket and don't step on concurrent anonymous invocations.\n * Hooks and event payloads keep using the empty-string coerced\n * `runId` for backward compat.\n */\n const registryRunId =\n batchScopeId ?? (config.configurable?.run_id as string | undefined);\n const threadId = config.configurable?.thread_id as string | undefined;\n const registry = this.toolOutputRegistry;\n const unresolvedByCallId = new Map<string, string[]>();\n\n const preToolCalls = toolCalls.map((call, i) => {\n const originalArgs = call.args as Record<string, unknown>;\n let resolvedArgs = originalArgs;\n /**\n * When the caller provided a pre-resolved map (the mixed\n * direct+event path snapshots event args synchronously before\n * awaiting directs so they can't accidentally resolve\n * same-turn direct outputs), use those entries verbatim instead\n * of re-resolving against a registry that may have changed\n * since the batch started.\n */\n const pre = call.id != null ? preResolvedArgs?.get(call.id) : undefined;\n if (pre != null) {\n resolvedArgs = pre.resolved;\n if (pre.unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, pre.unresolved);\n }\n } else if (registry != null) {\n const { resolved, unresolved } = registry.resolve(\n registryRunId,\n originalArgs\n );\n resolvedArgs = resolved as Record<string, unknown>;\n if (unresolved.length > 0 && call.id != null) {\n unresolvedByCallId.set(call.id, unresolved);\n }\n }\n return {\n call,\n stepId: this.toolCallStepIds?.get(call.id!) ?? '',\n args: resolvedArgs,\n batchIndex: batchIndices?.[i],\n };\n });\n\n const messageByCallId = new Map<string, ToolMessage>();\n const approvedEntries: typeof preToolCalls = [];\n const HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n });\n\n if (this.hookRegistry?.hasHookFor('PreToolUse', runId) === true) {\n const preResults = await Promise.all(\n preToolCalls.map((entry) =>\n executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PreToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n stepId: entry.stepId,\n turn: this.toolUsageCount.get(entry.call.name) ?? 0,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK)\n )\n );\n\n for (let i = 0; i < preToolCalls.length; i++) {\n const hookResult = preResults[i];\n const entry = preToolCalls[i];\n const isDenied =\n hookResult.decision === 'deny' || hookResult.decision === 'ask';\n if (isDenied) {\n const reason = hookResult.reason ?? 'Blocked by hook';\n const contentString = `Blocked: ${reason}`;\n messageByCallId.set(\n entry.call.id!,\n new ToolMessage({\n status: 'error',\n content: contentString,\n name: entry.call.name,\n tool_call_id: entry.call.id!,\n })\n );\n this.dispatchStepCompleted(\n entry.call.id!,\n entry.call.name,\n entry.args,\n contentString,\n config\n );\n if (this.hookRegistry.hasHookFor('PermissionDenied', runId)) {\n executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PermissionDenied',\n runId,\n threadId,\n agentId: this.agentId,\n toolName: entry.call.name,\n toolInput: entry.args,\n toolUseId: entry.call.id!,\n reason,\n },\n sessionId: runId,\n matchQuery: entry.call.name,\n }).catch(() => {\n /* PermissionDenied is observational — swallow errors */\n });\n }\n continue;\n }\n if (hookResult.updatedInput != null) {\n /**\n * Re-resolve after PreToolUse replaces the input: a hook may\n * introduce new `{{tool<i>turn<n>}}` placeholders (e.g., by\n * copying user-supplied text) that the pre-hook pass never\n * saw. Re-running the resolver on the hook-rewritten args\n * keeps substitution and the unresolved-refs record in sync\n * with what the tool will actually receive.\n */\n if (registry != null) {\n /**\n * Mixed direct+event batches must use the pre-batch\n * snapshot so a hook-introduced placeholder cannot\n * accidentally resolve to a same-turn direct output that\n * has just registered. Pure event batches don't have a\n * snapshot and resolve against the live registry — safe\n * because no event-side registrations have happened yet.\n */\n const view: ToolOutputResolveView = preBatchSnapshot ?? {\n resolve: <T>(args: T) => registry.resolve(registryRunId, args),\n };\n const { resolved, unresolved } = view.resolve(\n hookResult.updatedInput\n );\n entry.args = resolved as Record<string, unknown>;\n if (entry.call.id != null) {\n if (unresolved.length > 0) {\n unresolvedByCallId.set(entry.call.id, unresolved);\n } else {\n unresolvedByCallId.delete(entry.call.id);\n }\n }\n } else {\n entry.args = hookResult.updatedInput;\n }\n }\n approvedEntries.push(entry);\n }\n } else {\n approvedEntries.push(...preToolCalls);\n }\n\n const injected: BaseMessage[] = [];\n\n const batchIndexByCallId = new Map<string, number>();\n\n if (approvedEntries.length > 0) {\n const requests: t.ToolCallRequest[] = approvedEntries.map((entry) => {\n const turn = this.toolUsageCount.get(entry.call.name) ?? 0;\n this.toolUsageCount.set(entry.call.name, turn + 1);\n\n if (entry.batchIndex != null && entry.call.id != null) {\n batchIndexByCallId.set(entry.call.id, entry.batchIndex);\n }\n\n const request: t.ToolCallRequest = {\n id: entry.call.id!,\n name: entry.call.name,\n args: entry.args,\n stepId: entry.stepId,\n turn,\n };\n\n /**\n * Emit `codeSessionContext` for any tool whose host handler may need\n * to reach into the code-execution sandbox:\n * - `CODE_EXECUTION_TOOLS` — direct executors that POST to /exec.\n * - `SKILL_TOOL` — skill files live alongside code-env state.\n * - `READ_FILE` — when the requested path is a code-env artifact\n * (e.g. `/mnt/data/...`) the host falls back to reading via the\n * same sandbox session; without the seeded `session_id` /\n * `_injected_files` here, that fallback can't see prior-turn\n * artifacts on the very first call of a turn.\n */\n if (\n CODE_EXECUTION_TOOLS.has(entry.call.name) ||\n entry.call.name === Constants.SKILL_TOOL ||\n entry.call.name === Constants.READ_FILE\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const requestMap = new Map(requests.map((r) => [r.id, r]));\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const batchRequest: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_EXECUTE,\n batchRequest,\n config\n );\n }\n );\n\n this.storeCodeSessionFromResults(results, requestMap);\n\n const hasPostHook =\n this.hookRegistry?.hasHookFor('PostToolUse', runId) === true;\n const hasFailureHook =\n this.hookRegistry?.hasHookFor('PostToolUseFailure', runId) === true;\n\n for (const result of results) {\n if (result.injectedMessages && result.injectedMessages.length > 0) {\n try {\n injected.push(\n ...this.convertInjectedMessages(result.injectedMessages)\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] Failed to convert injectedMessages for toolCallId=${result.toolCallId}:`,\n e instanceof Error ? e.message : e\n );\n }\n }\n const request = requestMap.get(result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n\n let contentString: string;\n let toolMessage: ToolMessage;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n /**\n * Error results bypass registration but stamp the\n * unresolved-refs hint into `additional_kwargs` so the lazy\n * annotation transform surfaces it to the LLM at request\n * time, letting the model self-correct when its reference\n * key caused the failure. Persisted `content` stays clean.\n */\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const errorRefMeta =\n unresolved.length > 0\n ? this.recordOutputReference(\n registryRunId,\n contentString,\n undefined,\n unresolved\n )\n : undefined;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n ...(errorRefMeta != null && {\n additional_kwargs: errorRefMeta as Record<string, unknown>,\n }),\n });\n\n if (hasFailureHook) {\n await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUseFailure',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolUseId: result.toolCallId,\n error: result.errorMessage ?? 'Unknown error',\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch(() => {\n /* PostToolUseFailure is observational — swallow errors */\n });\n }\n } else {\n let registryRaw =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n registryRaw,\n this.maxToolResultChars\n );\n\n if (hasPostHook) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry!,\n input: {\n hook_event_name: 'PostToolUse',\n runId,\n threadId,\n agentId: this.agentId,\n toolName,\n toolInput: request?.args ?? {},\n toolOutput: result.content,\n toolUseId: result.toolCallId,\n stepId: request?.stepId,\n turn: request?.turn,\n },\n sessionId: runId,\n matchQuery: toolName,\n }).catch((): undefined => undefined);\n if (hookResult?.updatedOutput != null) {\n const replaced =\n typeof hookResult.updatedOutput === 'string'\n ? hookResult.updatedOutput\n : JSON.stringify(hookResult.updatedOutput);\n registryRaw = replaced;\n contentString = truncateToolResultContent(\n replaced,\n this.maxToolResultChars\n );\n }\n }\n\n const batchIndex = batchIndexByCallId.get(result.toolCallId);\n const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];\n const refKey =\n this.toolOutputRegistry != null &&\n batchIndex != null &&\n turn != null\n ? buildReferenceKey(batchIndex, turn)\n : undefined;\n const successRefMeta = this.recordOutputReference(\n registryRunId,\n registryRaw,\n refKey,\n unresolved\n );\n\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n ...(successRefMeta != null && {\n additional_kwargs: successRefMeta as Record<string, unknown>,\n }),\n });\n }\n\n this.dispatchStepCompleted(\n result.toolCallId,\n toolName,\n request?.args ?? {},\n contentString,\n config,\n request?.turn\n );\n\n messageByCallId.set(result.toolCallId, toolMessage);\n }\n }\n\n const toolMessages = toolCalls\n .map((call) => messageByCallId.get(call.id!))\n .filter((m): m is ToolMessage => m != null);\n return { toolMessages, injected };\n }\n\n private dispatchStepCompleted(\n toolCallId: string,\n toolName: string,\n args: Record<string, unknown>,\n output: string,\n config: RunnableConfig,\n turn?: number\n ): void {\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn ?? this.toolUsageCount.get(toolName) ?? 0,\n type: 'tool_call' as const,\n tool_call: {\n args: JSON.stringify(args),\n name: toolName,\n id: toolCallId,\n output,\n progress: 1,\n } as t.ProcessedToolCall,\n },\n },\n config\n );\n }\n\n /**\n * Converts InjectedMessage instances to LangChain HumanMessage objects.\n * Both 'user' and 'system' roles become HumanMessage to avoid provider\n * rejections (Anthropic/Google reject non-leading SystemMessages).\n * The original role is preserved in additional_kwargs for downstream consumers.\n */\n private convertInjectedMessages(\n messages: t.InjectedMessage[]\n ): BaseMessage[] {\n const converted: BaseMessage[] = [];\n for (const msg of messages) {\n const additional_kwargs: Record<string, unknown> = {\n role: msg.role,\n };\n if (msg.isMeta != null) additional_kwargs.isMeta = msg.isMeta;\n if (msg.source != null) additional_kwargs.source = msg.source;\n if (msg.skillName != null) additional_kwargs.skillName = msg.skillName;\n\n converted.push(\n new HumanMessage({\n content: toLangChainContent(msg.content),\n additional_kwargs,\n })\n );\n }\n return converted;\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Injected messages are placed AFTER ToolMessages to respect provider\n * message ordering (AIMessage tool_calls must be immediately followed\n * by their ToolMessage results).\n *\n * `batchIndices` mirrors `toolCalls` and carries each call's position\n * within the parent batch. `turn` is the per-`run()` batch index\n * captured locally by the caller. Both are threaded so concurrent\n * invocations cannot race on shared mutable state.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n batchContext: DispatchBatchContext = {}\n ): Promise<T> {\n const { toolMessages, injected } = await this.dispatchToolEvents(\n toolCalls,\n config,\n batchContext\n );\n const outputs: BaseMessage[] = [...toolMessages, ...injected];\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n /**\n * Per-batch local map for resolved (post-substitution) args.\n * Lives on the stack so concurrent `run()` calls on the same\n * ToolNode cannot read or wipe each other's entries.\n */\n const resolvedArgsByCallId = new Map<string, Record<string, unknown>>();\n /**\n * Claim this batch's turn synchronously from the registry (or\n * fall back to 0 when the feature is disabled). The registry is\n * partitioned by scope id so overlapping batches cannot\n * overwrite each other's state even under a shared registry.\n *\n * For anonymous callers (no `run_id` in config), mint a unique\n * per-batch scope id so two concurrent anonymous invocations\n * don't target the same bucket. The scope is threaded down to\n * every subsequent registry call on this batch.\n */\n const incomingRunId = config.configurable?.run_id as string | undefined;\n const batchScopeId = incomingRunId ?? `\\0anon-${this.anonBatchCounter++}`;\n const turn = this.toolOutputRegistry?.nextTurn(batchScopeId) ?? 0;\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input, {\n batchIndices: [0],\n turn,\n batchScopeId,\n });\n }\n outputs = [\n await this.runTool(input.lg_tool_call, config, {\n batchIndex: 0,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n }),\n ];\n this.handleRunToolCompletions(\n [input.lg_tool_call],\n outputs,\n config,\n resolvedArgsByCallId\n );\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(\n call.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n )\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n const filteredIndices = filteredCalls.map((_, idx) => idx);\n\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input, {\n batchIndices: filteredIndices,\n turn,\n batchScopeId,\n });\n }\n\n const directEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n const eventEntries: Array<{ call: ToolCall; batchIndex: number }> = [];\n for (let i = 0; i < filteredCalls.length; i++) {\n const call = filteredCalls[i];\n const entry = { call, batchIndex: i };\n if (this.directToolNames!.has(call.name)) {\n directEntries.push(entry);\n } else {\n eventEntries.push(entry);\n }\n }\n\n const directCalls = directEntries.map((e) => e.call);\n const directIndices = directEntries.map((e) => e.batchIndex);\n const eventCalls = eventEntries.map((e) => e.call);\n const eventIndices = eventEntries.map((e) => e.batchIndex);\n\n /**\n * Snapshot the event calls' args against the *pre-batch*\n * registry state synchronously, before any await runs. The\n * directs are then awaited first (preserving fail-fast\n * semantics — a thrown error in a direct tool, e.g. with\n * `handleToolErrors=false` or a `GraphInterrupt`, aborts\n * before we dispatch any event-driven tools to the host).\n * Because the event args were captured pre-await, they stay\n * isolated from same-turn direct outputs that register\n * during the await.\n */\n const preResolvedEventArgs = new Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n >();\n /**\n * Take a frozen snapshot of the registry state before any\n * direct registrations land. The snapshot resolves\n * placeholders against this point-in-time view, so a\n * `PreToolUse` hook later rewriting event args via\n * `updatedInput` can introduce placeholders that resolve\n * cross-batch (against prior runs) without ever picking up\n * same-turn direct outputs.\n */\n const preBatchSnapshot =\n this.toolOutputRegistry?.snapshot(batchScopeId);\n if (preBatchSnapshot != null) {\n for (const entry of eventEntries) {\n if (entry.call.id != null) {\n const { resolved, unresolved } = preBatchSnapshot.resolve(\n entry.call.args as Record<string, unknown>\n );\n preResolvedEventArgs.set(entry.call.id, {\n resolved: resolved as Record<string, unknown>,\n unresolved,\n });\n }\n }\n }\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: directIndices[i],\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(\n directCalls,\n directOutputs,\n config,\n resolvedArgsByCallId\n );\n }\n\n const eventResult =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config, {\n batchIndices: eventIndices,\n turn,\n batchScopeId,\n preResolvedArgs: preResolvedEventArgs,\n preBatchSnapshot,\n })\n : {\n toolMessages: [] as ToolMessage[],\n injected: [] as BaseMessage[],\n };\n\n outputs = [\n ...directOutputs,\n ...eventResult.toolMessages,\n ...eventResult.injected,\n ];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call, i) =>\n this.runTool(call, config, {\n batchIndex: i,\n turn,\n batchScopeId,\n resolvedArgsByCallId,\n })\n )\n );\n this.handleRunToolCompletions(\n filteredCalls,\n outputs,\n config,\n resolvedArgsByCallId\n );\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAqFA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAY,IAAI;AAC9B;AAEA;;;;;;;;;;;;;;;;;;;AAmBG;AACH,SAAS,iBAAiB,CACxB,QAA0B,EAC1B,SAAiB,EACjB,KAA6B,EAAA;AAE7B,IAAA,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;IAC5B,MAAM,eAAe,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,CAE9C;AACb,IAAA,MAAM,aAAa,GAAG,eAAe,EAAE,KAAK,IAAI,EAAE;AAElD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;QACvB,MAAM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,EAAA;AAE5B,IAAA,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,IAAI,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK;AAC9D,IAAA,QACE,OAAO,CAAC,UAAU,EAAE,KAAK,CACvB,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,IAAI,IAAI,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ;IAC9D,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAA0B;AAEtE,IAAA,IACE,OAAO;AACP,QAAA,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;IACjB;AACA,IAAA,OAAO,GAAG;AACZ;;;;"}
|
|
@@ -126,7 +126,7 @@ export declare class AgentContext {
|
|
|
126
126
|
private summaryTokenCount;
|
|
127
127
|
/**
|
|
128
128
|
* Where the summary should be injected:
|
|
129
|
-
* - `'system_prompt'`: cross-run summary, included in
|
|
129
|
+
* - `'system_prompt'`: cross-run summary, included in the dynamic system tail
|
|
130
130
|
* - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate
|
|
131
131
|
* - `'none'`: no summary present
|
|
132
132
|
*/
|
|
@@ -193,7 +193,8 @@ export declare class AgentContext {
|
|
|
193
193
|
private buildProgrammaticOnlyToolsInstructions;
|
|
194
194
|
/**
|
|
195
195
|
* Gets the system runnable, creating it lazily if needed.
|
|
196
|
-
* Includes instructions, additional instructions, and
|
|
196
|
+
* Includes stable instructions, dynamic additional instructions, and
|
|
197
|
+
* programmatic-only tools documentation.
|
|
197
198
|
* Only rebuilds when marked stale (via markToolsAsDiscovered).
|
|
198
199
|
*/
|
|
199
200
|
get systemRunnable(): Runnable<BaseMessage[], (BaseMessage | SystemMessage)[], RunnableConfig<Record<string, unknown>>> | undefined;
|
|
@@ -203,10 +204,16 @@ export declare class AgentContext {
|
|
|
203
204
|
*/
|
|
204
205
|
initializeSystemRunnable(): void;
|
|
205
206
|
/**
|
|
206
|
-
* Builds the
|
|
207
|
+
* Builds the cacheable instructions string (without creating SystemMessage).
|
|
207
208
|
* Includes agent identity preamble and handoff context when available.
|
|
208
209
|
*/
|
|
209
|
-
private
|
|
210
|
+
private buildStableInstructionsString;
|
|
211
|
+
/**
|
|
212
|
+
* Builds the dynamic system-tail string (without creating SystemMessage).
|
|
213
|
+
* Keep this out of prompt-cache-marked content so volatile context does not
|
|
214
|
+
* invalidate the stable prefix.
|
|
215
|
+
*/
|
|
216
|
+
private buildDynamicInstructionsString;
|
|
210
217
|
/**
|
|
211
218
|
* Builds the agent identity preamble including handoff context if present.
|
|
212
219
|
* This helps the agent understand its role in the multi-agent workflow.
|
|
@@ -217,6 +224,9 @@ export declare class AgentContext {
|
|
|
217
224
|
* Only called when content has actually changed.
|
|
218
225
|
*/
|
|
219
226
|
private buildSystemRunnable;
|
|
227
|
+
private hasAnthropicPromptCache;
|
|
228
|
+
private hasBedrockPromptCache;
|
|
229
|
+
private buildSystemMessage;
|
|
220
230
|
/**
|
|
221
231
|
* Reset context for a new run
|
|
222
232
|
*/
|
|
@@ -238,6 +248,21 @@ export declare class AgentContext {
|
|
|
238
248
|
updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void;
|
|
239
249
|
/** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
|
|
240
250
|
private getActiveToolDefinitions;
|
|
251
|
+
/**
|
|
252
|
+
* Single source of truth for "which entries of `this.tools` should be
|
|
253
|
+
* treated as actually bound". Callers:
|
|
254
|
+
* - `getToolsForBinding` (non-event-driven branch)
|
|
255
|
+
* - `getEventDrivenToolsForBinding` (appends instance tools alongside
|
|
256
|
+
* schema-only definitions)
|
|
257
|
+
* - `calculateInstructionTokens` (counts schema bytes for accounting)
|
|
258
|
+
*
|
|
259
|
+
* In event-driven mode (`toolDefinitions` present) instance tools are
|
|
260
|
+
* appended unfiltered; outside event-driven mode they pass through
|
|
261
|
+
* `filterToolsForBinding`. Centralizing the decision here prevents the
|
|
262
|
+
* accounting/binding paths from drifting apart, which was the root
|
|
263
|
+
* cause of the original miscount.
|
|
264
|
+
*/
|
|
265
|
+
private getEffectiveInstanceTools;
|
|
241
266
|
/**
|
|
242
267
|
* Calculate tool tokens and add to instruction tokens
|
|
243
268
|
* Note: System message tokens are calculated during systemRunnable creation
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { UsageMetadata } from '@langchain/core/messages';
|
|
2
|
+
import type * as t from '@/types';
|
|
3
|
+
import { Providers } from '@/common';
|
|
4
|
+
type LivePromptCacheProvider = Providers.ANTHROPIC | Providers.BEDROCK;
|
|
5
|
+
type PromptCacheExpectedSystemBlock = {
|
|
6
|
+
type: 'text';
|
|
7
|
+
text: string;
|
|
8
|
+
cache_control?: {
|
|
9
|
+
type: 'ephemeral';
|
|
10
|
+
};
|
|
11
|
+
} | {
|
|
12
|
+
cachePoint: {
|
|
13
|
+
type: 'default';
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
type LivePromptCacheClientOptions = t.ClientOptions | t.BedrockAnthropicClientOptions;
|
|
17
|
+
export declare function buildStableInstructions({ nonce, providerLabel, }: {
|
|
18
|
+
nonce: string;
|
|
19
|
+
providerLabel: string;
|
|
20
|
+
}): string;
|
|
21
|
+
export declare function buildDynamicInstructions({ marker, tailDescription, }: {
|
|
22
|
+
marker: string;
|
|
23
|
+
tailDescription: string;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function waitForCachePropagation(): Promise<void>;
|
|
26
|
+
export declare function assertSystemPayloadShape({ agentId, provider, clientOptions, stableInstructions, dynamicInstructions, expectedContent, }: {
|
|
27
|
+
agentId: string;
|
|
28
|
+
provider: LivePromptCacheProvider;
|
|
29
|
+
clientOptions: LivePromptCacheClientOptions;
|
|
30
|
+
stableInstructions: string;
|
|
31
|
+
dynamicInstructions: string;
|
|
32
|
+
expectedContent: PromptCacheExpectedSystemBlock[];
|
|
33
|
+
}): Promise<void>;
|
|
34
|
+
export declare function runLiveTurn({ provider, providerLabel, clientOptions, runId, threadId, stableInstructions, dynamicInstructions, }: {
|
|
35
|
+
provider: LivePromptCacheProvider;
|
|
36
|
+
providerLabel: string;
|
|
37
|
+
clientOptions: LivePromptCacheClientOptions;
|
|
38
|
+
runId: string;
|
|
39
|
+
threadId: string;
|
|
40
|
+
stableInstructions: string;
|
|
41
|
+
dynamicInstructions: string;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
text: string;
|
|
44
|
+
usage: UsageMetadata;
|
|
45
|
+
}>;
|
|
46
|
+
export {};
|