@librechat/agents 3.1.66-dev.0 → 3.1.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +24 -15
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +0 -13
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +0 -3
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +0 -40
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +12 -74
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +0 -111
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +140 -304
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +24 -15
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -12
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +0 -3
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -10
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +4 -66
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +0 -111
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +142 -306
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +1 -7
- package/dist/types/graphs/Graph.d.ts +0 -2
- package/dist/types/index.d.ts +0 -6
- package/dist/types/messages/format.d.ts +1 -2
- package/dist/types/run.d.ts +0 -1
- package/dist/types/tools/ToolNode.d.ts +2 -24
- package/dist/types/types/index.d.ts +0 -1
- package/dist/types/types/llm.d.ts +14 -2
- package/dist/types/types/run.d.ts +0 -20
- package/dist/types/types/tools.d.ts +1 -38
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +28 -15
- package/src/agents/__tests__/AgentContext.test.ts +110 -0
- package/src/common/enum.ts +0 -12
- package/src/graphs/Graph.ts +0 -4
- package/src/index.ts +0 -8
- package/src/messages/format.ts +4 -74
- package/src/run.ts +0 -126
- package/src/tools/ToolNode.ts +169 -391
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/types/index.ts +0 -1
- package/src/types/llm.ts +16 -2
- package/src/types/run.ts +0 -20
- package/src/types/tools.ts +1 -41
- package/dist/cjs/hooks/HookRegistry.cjs +0 -162
- package/dist/cjs/hooks/HookRegistry.cjs.map +0 -1
- package/dist/cjs/hooks/executeHooks.cjs +0 -276
- package/dist/cjs/hooks/executeHooks.cjs.map +0 -1
- package/dist/cjs/hooks/matchers.cjs +0 -256
- package/dist/cjs/hooks/matchers.cjs.map +0 -1
- package/dist/cjs/hooks/types.cjs +0 -27
- package/dist/cjs/hooks/types.cjs.map +0 -1
- package/dist/cjs/tools/BashExecutor.cjs +0 -175
- package/dist/cjs/tools/BashExecutor.cjs.map +0 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -296
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +0 -1
- package/dist/cjs/tools/ReadFile.cjs +0 -43
- package/dist/cjs/tools/ReadFile.cjs.map +0 -1
- package/dist/cjs/tools/SkillTool.cjs +0 -50
- package/dist/cjs/tools/SkillTool.cjs.map +0 -1
- package/dist/cjs/tools/skillCatalog.cjs +0 -84
- package/dist/cjs/tools/skillCatalog.cjs.map +0 -1
- package/dist/esm/hooks/HookRegistry.mjs +0 -160
- package/dist/esm/hooks/HookRegistry.mjs.map +0 -1
- package/dist/esm/hooks/executeHooks.mjs +0 -273
- package/dist/esm/hooks/executeHooks.mjs.map +0 -1
- package/dist/esm/hooks/matchers.mjs +0 -251
- package/dist/esm/hooks/matchers.mjs.map +0 -1
- package/dist/esm/hooks/types.mjs +0 -25
- package/dist/esm/hooks/types.mjs.map +0 -1
- package/dist/esm/tools/BashExecutor.mjs +0 -169
- package/dist/esm/tools/BashExecutor.mjs.map +0 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -287
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +0 -1
- package/dist/esm/tools/ReadFile.mjs +0 -38
- package/dist/esm/tools/ReadFile.mjs.map +0 -1
- package/dist/esm/tools/SkillTool.mjs +0 -45
- package/dist/esm/tools/SkillTool.mjs.map +0 -1
- package/dist/esm/tools/skillCatalog.mjs +0 -82
- package/dist/esm/tools/skillCatalog.mjs.map +0 -1
- package/dist/types/hooks/HookRegistry.d.ts +0 -56
- package/dist/types/hooks/executeHooks.d.ts +0 -79
- package/dist/types/hooks/index.d.ts +0 -6
- package/dist/types/hooks/matchers.d.ts +0 -95
- package/dist/types/hooks/types.d.ts +0 -309
- package/dist/types/tools/BashExecutor.d.ts +0 -45
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +0 -72
- package/dist/types/tools/ReadFile.d.ts +0 -28
- package/dist/types/tools/SkillTool.d.ts +0 -40
- package/dist/types/tools/skillCatalog.d.ts +0 -19
- package/dist/types/types/skill.d.ts +0 -9
- package/src/hooks/HookRegistry.ts +0 -208
- package/src/hooks/__tests__/HookRegistry.test.ts +0 -190
- package/src/hooks/__tests__/executeHooks.test.ts +0 -1013
- package/src/hooks/__tests__/integration.test.ts +0 -337
- package/src/hooks/__tests__/matchers.test.ts +0 -238
- package/src/hooks/__tests__/toolHooks.test.ts +0 -669
- package/src/hooks/executeHooks.ts +0 -375
- package/src/hooks/index.ts +0 -55
- package/src/hooks/matchers.ts +0 -280
- package/src/hooks/types.ts +0 -388
- package/src/messages/formatAgentMessages.skills.test.ts +0 -334
- package/src/tools/BashExecutor.ts +0 -205
- package/src/tools/BashProgrammaticToolCalling.ts +0 -397
- package/src/tools/ReadFile.ts +0 -39
- package/src/tools/SkillTool.ts +0 -46
- package/src/tools/__tests__/ReadFile.test.ts +0 -44
- package/src/tools/__tests__/SkillTool.test.ts +0 -442
- package/src/tools/__tests__/skillCatalog.test.ts +0 -161
- package/src/tools/skillCatalog.ts +0 -126
- package/src/types/skill.ts +0 -11
|
@@ -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 * as t from '@/types';\nimport type { HookRegistry, AggregatedHookResult } from '@/hooks';\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';\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/** Merges code execution session context into the sessions map. */\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: 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 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 }: 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\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 protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, turn);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\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 (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n ),\n tool_call_id: call.id!,\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 return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\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 private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig\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 const tool_call: t.ProcessedToolCall = {\n args:\n typeof call.args === 'string'\n ? (call.args as string)\n : JSON.stringify((call.args 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 ): Promise<{ toolMessages: ToolMessage[]; injected: BaseMessage[] }> {\n const runId = (config.configurable?.run_id as string | undefined) ?? '';\n const threadId = config.configurable?.thread_id as string | undefined;\n\n const preToolCalls = toolCalls.map((call) => ({\n call,\n stepId: this.toolCallStepIds?.get(call.id!) ?? '',\n args: call.args as Record<string, unknown>,\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 entry.args = hookResult.updatedInput;\n }\n approvedEntries.push(entry);\n }\n } else {\n approvedEntries.push(...preToolCalls);\n }\n\n const injected: BaseMessage[] = [];\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 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 if (\n CODE_EXECUTION_TOOLS.has(entry.call.name) ||\n entry.call.name === Constants.SKILL_TOOL\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 toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\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 const rawContent =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n rawContent,\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 contentString = truncateToolResultContent(\n replaced,\n this.maxToolResultChars\n );\n }\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 });\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 private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const { toolMessages, injected } = await this.dispatchToolEvents(\n toolCalls,\n config\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 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 }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n this.handleRunToolCompletions([input.lg_tool_call], outputs, config);\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 if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n const directCalls = filteredCalls.filter((c) =>\n this.directToolNames!.has(c.name)\n );\n const eventCalls = filteredCalls.filter(\n (c) => !this.directToolNames!.has(c.name)\n );\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call) => this.runTool(call, config))\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(directCalls, directOutputs, config);\n }\n\n const eventResult =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config)\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) => this.runTool(call, config))\n );\n this.handleRunToolCompletions(filteredCalls, outputs, config);\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":";;;;;;;;;;;;;AAgCA;;AAEG;A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C,EAC7C;AACA,QAAA,OAAO,QAAQ;IACjB;AACA,IAAA,OAAO,GAAG;AACZ;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\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 * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport {\n calculateMaxToolResultChars,\n truncateToolResultContent,\n} from '@/utils/truncation';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\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// 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\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 }: 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 }\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 protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, turn);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\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 (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\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 (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n const rawContent =\n typeof output === 'string' ? output : JSON.stringify(output);\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\n ),\n tool_call_id: call.id!,\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 return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\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 requests: 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 = requests.find((r) => r.id === result.toolCallId);\n if (\n request?.name !== Constants.EXECUTE_CODE &&\n request?.name !== Constants.PROGRAMMATIC_TOOL_CALLING\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 const newFiles = artifact.files ?? [];\n const existingSession = this.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: artifact.session_id,\n }));\n\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\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 private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig\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 // Store code session context from tool results\n if (\n this.sessions &&\n (call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING)\n ) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n const newFiles = artifact.files ?? [];\n const existingSession = this.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: artifact.session_id,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\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 const tool_call: t.ProcessedToolCall = {\n args:\n typeof call.args === 'string'\n ? (call.args as string)\n : JSON.stringify((call.args 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 private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig\n ): Promise<ToolMessage[]> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n\n const request: t.ToolCallRequest = {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: 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(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n this.storeCodeSessionFromResults(results, requests);\n\n return results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${result.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 let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n const rawContent =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n contentString = truncateToolResultContent(\n rawContent,\n this.maxToolResultChars\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 });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\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 ): Promise<T> {\n const outputs = await this.dispatchToolEvents(toolCalls, config);\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 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 }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n this.handleRunToolCompletions([input.lg_tool_call], outputs, config);\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 if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n const directCalls = filteredCalls.filter((c) =>\n this.directToolNames!.has(c.name)\n );\n const eventCalls = filteredCalls.filter(\n (c) => !this.directToolNames!.has(c.name)\n );\n\n const directOutputs: (BaseMessage | Command)[] =\n directCalls.length > 0\n ? await Promise.all(\n directCalls.map((call) => this.runTool(call, config))\n )\n : [];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(directCalls, directOutputs, config);\n }\n\n const eventOutputs: ToolMessage[] =\n eventCalls.length > 0\n ? await this.dispatchToolEvents(eventCalls, config)\n : [];\n\n outputs = [...directOutputs, ...eventOutputs];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n this.handleRunToolCompletions(filteredCalls, outputs, config);\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":";;;;;;;;;;;;AA6BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAY,IAAI;AAC9B;AAEA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AACnD,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;IACvB,KAAK,GAAG,KAAK;AACb,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;;AAEd,IAAA,aAAa,GAAwB,IAAI,GAAG,EAAE;;AAE9C,IAAA,YAAY;;AAEZ,IAAA,iBAAiB;;AAEjB,IAAA,QAAQ;;IAER,eAAe,GAAY,KAAK;;AAEhC,IAAA,OAAO;;AAEP,IAAA,eAAe;;AAEf,IAAA,kBAAkB;AAE1B,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,QAAQ,EACR,eAAe,EACf,OAAO,EACP,eAAe,EACf,gBAAgB,EAChB,kBAAkB,GACU,EAAA;QAC5B,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC;QACvE,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AACzE,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe;QAC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C,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;;;;"}
|
|
@@ -230,6 +230,8 @@ export declare class AgentContext {
|
|
|
230
230
|
* token counts.
|
|
231
231
|
*/
|
|
232
232
|
updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void;
|
|
233
|
+
/** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
|
|
234
|
+
private getActiveToolDefinitions;
|
|
233
235
|
/**
|
|
234
236
|
* Calculate tool tokens and add to instruction tokens
|
|
235
237
|
* Note: System message tokens are calculated during systemRunnable creation
|
|
@@ -284,6 +286,10 @@ export declare class AgentContext {
|
|
|
284
286
|
/**
|
|
285
287
|
* Returns a structured breakdown of how the context token budget is consumed.
|
|
286
288
|
* Useful for diagnostics when context overflow or pruning issues occur.
|
|
289
|
+
*
|
|
290
|
+
* Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`
|
|
291
|
+
* is a snapshot taken during `calculateInstructionTokens` and is not
|
|
292
|
+
* recomputed when `markToolsAsDiscovered` is called mid-run.
|
|
287
293
|
*/
|
|
288
294
|
getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown;
|
|
289
295
|
/**
|
|
@@ -136,14 +136,8 @@ export declare enum Constants {
|
|
|
136
136
|
/** Delimiter for MCP tools: toolName_mcp_serverName */
|
|
137
137
|
MCP_DELIMITER = "_mcp_",
|
|
138
138
|
/** Anthropic server tool ID prefix (web_search, code_execution, etc.) */
|
|
139
|
-
ANTHROPIC_SERVER_TOOL_PREFIX = "srvtoolu_"
|
|
140
|
-
SKILL_TOOL = "skill",
|
|
141
|
-
READ_FILE = "read_file",
|
|
142
|
-
BASH_TOOL = "bash_tool",
|
|
143
|
-
BASH_PROGRAMMATIC_TOOL_CALLING = "run_tools_with_bash"
|
|
139
|
+
ANTHROPIC_SERVER_TOOL_PREFIX = "srvtoolu_"
|
|
144
140
|
}
|
|
145
|
-
/** Tool names that use the code execution environment (shared session, file tracking). */
|
|
146
|
-
export declare const CODE_EXECUTION_TOOLS: ReadonlySet<string>;
|
|
147
141
|
export declare enum TitleMethod {
|
|
148
142
|
STRUCTURED = "structured",
|
|
149
143
|
FUNCTIONS = "functions",
|
|
@@ -6,7 +6,6 @@ import type * as t from '@/types';
|
|
|
6
6
|
import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
|
|
7
7
|
import { AgentContext } from '@/agents/AgentContext';
|
|
8
8
|
import { HandlerRegistry } from '@/events';
|
|
9
|
-
import type { HookRegistry } from '@/hooks';
|
|
10
9
|
export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphState, _TNodeName extends string = string> {
|
|
11
10
|
abstract resetValues(): void;
|
|
12
11
|
abstract initializeTools({ currentTools, currentToolMap, }: {
|
|
@@ -44,7 +43,6 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
44
43
|
/** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
|
|
45
44
|
invokedToolIds?: Set<string>;
|
|
46
45
|
handlerRegistry: HandlerRegistry | undefined;
|
|
47
|
-
hookRegistry: HookRegistry | undefined;
|
|
48
46
|
/**
|
|
49
47
|
* Tool session contexts for automatic state persistence across tool invocations.
|
|
50
48
|
* Keyed by tool name (e.g., Constants.EXECUTE_CODE).
|
package/dist/types/index.d.ts
CHANGED
|
@@ -7,12 +7,7 @@ export * from './graphs';
|
|
|
7
7
|
export * from './summarization';
|
|
8
8
|
export * from './tools/Calculator';
|
|
9
9
|
export * from './tools/CodeExecutor';
|
|
10
|
-
export * from './tools/BashExecutor';
|
|
11
10
|
export * from './tools/ProgrammaticToolCalling';
|
|
12
|
-
export * from './tools/BashProgrammaticToolCalling';
|
|
13
|
-
export * from './tools/SkillTool';
|
|
14
|
-
export * from './tools/ReadFile';
|
|
15
|
-
export * from './tools/skillCatalog';
|
|
16
11
|
export * from './tools/ToolSearch';
|
|
17
12
|
export * from './tools/ToolNode';
|
|
18
13
|
export * from './tools/schema';
|
|
@@ -20,7 +15,6 @@ export * from './tools/handlers';
|
|
|
20
15
|
export * from './tools/search';
|
|
21
16
|
export * from './common';
|
|
22
17
|
export * from './utils';
|
|
23
|
-
export * from './hooks';
|
|
24
18
|
export type * from './types';
|
|
25
19
|
export { CustomOpenAIClient } from './llm/openai';
|
|
26
20
|
export { ChatOpenRouter } from './llm/openrouter';
|
|
@@ -104,10 +104,9 @@ export declare const labelContentByAgent: (contentParts: MessageContentComplex[]
|
|
|
104
104
|
* @param payload - The array of messages to format.
|
|
105
105
|
* @param indexTokenCountMap - Optional map of message indices to token counts.
|
|
106
106
|
* @param tools - Optional set of tool names that are allowed in the request.
|
|
107
|
-
* @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.
|
|
108
107
|
* @returns - Object containing formatted messages and updated indexTokenCountMap if provided.
|
|
109
108
|
*/
|
|
110
|
-
export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap?: Record<number, number | undefined>, tools?: Set<string
|
|
109
|
+
export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap?: Record<number, number | undefined>, tools?: Set<string>) => {
|
|
111
110
|
messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;
|
|
112
111
|
indexTokenCountMap?: Record<number, number>;
|
|
113
112
|
/** Cross-run summary extracted from the payload. Should be forwarded to the
|
package/dist/types/run.d.ts
CHANGED
|
@@ -28,9 +28,7 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
28
28
|
private directToolNames?;
|
|
29
29
|
/** Maximum characters allowed in a single tool result before truncation. */
|
|
30
30
|
private maxToolResultChars;
|
|
31
|
-
|
|
32
|
-
private hookRegistry?;
|
|
33
|
-
constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, }: t.ToolNodeConstructorParams);
|
|
31
|
+
constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, }: t.ToolNodeConstructorParams);
|
|
34
32
|
/**
|
|
35
33
|
* Returns cached programmatic tools, computing once on first access.
|
|
36
34
|
* Single iteration builds both toolMap and toolDefs simultaneously.
|
|
@@ -68,31 +66,11 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
68
66
|
/**
|
|
69
67
|
* Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.
|
|
70
68
|
* Core logic for event-driven execution, separated from output shaping.
|
|
71
|
-
*
|
|
72
|
-
* Hook lifecycle (when `hookRegistry` is set):
|
|
73
|
-
* 1. **PreToolUse** fires per call in parallel before dispatch. Denied
|
|
74
|
-
* calls produce error ToolMessages and fire **PermissionDenied**;
|
|
75
|
-
* surviving calls proceed with optional `updatedInput`.
|
|
76
|
-
* 2. Surviving calls are dispatched to the host via `ON_TOOL_EXECUTE`.
|
|
77
|
-
* 3. **PostToolUse** / **PostToolUseFailure** fire per result. Post hooks
|
|
78
|
-
* can replace tool output via `updatedOutput`.
|
|
79
|
-
* 4. Injected messages from results are collected and returned alongside
|
|
80
|
-
* ToolMessages (appended AFTER to respect provider ordering).
|
|
81
69
|
*/
|
|
82
70
|
private dispatchToolEvents;
|
|
83
|
-
private dispatchStepCompleted;
|
|
84
|
-
/**
|
|
85
|
-
* Converts InjectedMessage instances to LangChain HumanMessage objects.
|
|
86
|
-
* Both 'user' and 'system' roles become HumanMessage to avoid provider
|
|
87
|
-
* rejections (Anthropic/Google reject non-leading SystemMessages).
|
|
88
|
-
* The original role is preserved in additional_kwargs for downstream consumers.
|
|
89
|
-
*/
|
|
90
|
-
private convertInjectedMessages;
|
|
91
71
|
/**
|
|
92
72
|
* Execute all tool calls via ON_TOOL_EXECUTE event dispatch.
|
|
93
|
-
*
|
|
94
|
-
* message ordering (AIMessage tool_calls must be immediately followed
|
|
95
|
-
* by their ToolMessage results).
|
|
73
|
+
* Used in event-driven mode where the host handles actual tool execution.
|
|
96
74
|
*/
|
|
97
75
|
private executeViaEvent;
|
|
98
76
|
protected run(input: any, config: RunnableConfig): Promise<T>;
|
|
@@ -28,7 +28,18 @@ export type AzureClientOptions = Partial<OpenAIChatInput> & Partial<AzureOpenAII
|
|
|
28
28
|
} & BaseChatModelParams & {
|
|
29
29
|
configuration?: OAIClientOptions;
|
|
30
30
|
};
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Controls whether Claude's reasoning content is returned in adaptive
|
|
33
|
+
* thinking responses. Added for Claude Opus 4.7, which omits thinking by
|
|
34
|
+
* default unless the caller opts in with `'summarized'`.
|
|
35
|
+
* @see https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7#thinking-content-omitted-by-default
|
|
36
|
+
*/
|
|
37
|
+
export type ThinkingDisplay = 'summarized' | 'omitted';
|
|
38
|
+
export type ThinkingConfigAdaptive = {
|
|
39
|
+
type: 'adaptive';
|
|
40
|
+
display?: ThinkingDisplay;
|
|
41
|
+
};
|
|
42
|
+
export type ThinkingConfig = NonNullable<AnthropicInput['thinking']> | ThinkingConfigAdaptive;
|
|
32
43
|
export type ChatOpenAIToolType = BindToolsInput | OpenAIClient.ChatCompletionTool;
|
|
33
44
|
export type CommonToolType = StructuredTool | ChatOpenAIToolType;
|
|
34
45
|
export type AnthropicReasoning = {
|
|
@@ -41,7 +52,8 @@ export type GoogleThinkingConfig = {
|
|
|
41
52
|
thinkingLevel?: string;
|
|
42
53
|
};
|
|
43
54
|
export type OpenAIClientOptions = ChatOpenAIFields;
|
|
44
|
-
export type AnthropicClientOptions = AnthropicInput & {
|
|
55
|
+
export type AnthropicClientOptions = Omit<AnthropicInput, 'thinking'> & {
|
|
56
|
+
thinking?: ThinkingConfig;
|
|
45
57
|
promptCache?: boolean;
|
|
46
58
|
};
|
|
47
59
|
export type MistralAIClientOptions = ChatMistralAIInput;
|
|
@@ -7,8 +7,6 @@ import type * as s from '@/types/stream';
|
|
|
7
7
|
import type * as e from '@/common/enum';
|
|
8
8
|
import type * as g from '@/types/graph';
|
|
9
9
|
import type * as l from '@/types/llm';
|
|
10
|
-
import type { ToolSessionMap } from '@/types/tools';
|
|
11
|
-
import type { HookRegistry } from '@/hooks';
|
|
12
10
|
export type ZodObjectAny = z.ZodObject<any, any, any, any>;
|
|
13
11
|
export type BaseGraphConfig = {
|
|
14
12
|
llmConfig: l.LLMConfig;
|
|
@@ -102,18 +100,6 @@ export type RunConfig = {
|
|
|
102
100
|
runId: string;
|
|
103
101
|
graphConfig: LegacyGraphConfig | StandardGraphConfig | MultiAgentGraphConfig;
|
|
104
102
|
customHandlers?: Record<string, g.EventHandler>;
|
|
105
|
-
/**
|
|
106
|
-
* Pre-constructed hook registry for this run. Hooks fire at lifecycle
|
|
107
|
-
* points in `processStream` (RunStart, UserPromptSubmit, Stop,
|
|
108
|
-
* StopFailure) and around tool calls (PreToolUse, PostToolUse,
|
|
109
|
-
* PostToolUseFailure, PermissionDenied).
|
|
110
|
-
*
|
|
111
|
-
* Pass `undefined` (the default) to skip all hook dispatch. When a
|
|
112
|
-
* registry is provided, the run attaches it to the `Graph` so internal
|
|
113
|
-
* nodes can fire hooks too, and clears the session in the `finally`
|
|
114
|
-
* block to prevent leaks.
|
|
115
|
-
*/
|
|
116
|
-
hooks?: HookRegistry;
|
|
117
103
|
returnContent?: boolean;
|
|
118
104
|
tokenCounter?: TokenCounter;
|
|
119
105
|
indexTokenCountMap?: Record<string, number>;
|
|
@@ -128,12 +114,6 @@ export type RunConfig = {
|
|
|
128
114
|
calibrationRatio?: number;
|
|
129
115
|
/** Skip post-stream cleanup (clearHeavyState) — useful for tests that inspect graph state after processStream */
|
|
130
116
|
skipCleanup?: boolean;
|
|
131
|
-
/**
|
|
132
|
-
* Initial session state to seed the Graph's ToolSessionMap.
|
|
133
|
-
* Used to carry over code environment sessions from skill file priming
|
|
134
|
-
* at run start, so ToolNode can inject session_id + files into tool calls.
|
|
135
|
-
*/
|
|
136
|
-
initialSessions?: ToolSessionMap;
|
|
137
117
|
};
|
|
138
118
|
export type ProvidedCallbacks = (BaseCallbackHandler | CallbackHandlerMethods)[] | undefined;
|
|
139
119
|
export type TokenCounter = (message: BaseMessage) => number;
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import type { StructuredToolInterface } from '@langchain/core/tools';
|
|
2
2
|
import type { RunnableToolLike } from '@langchain/core/runnables';
|
|
3
3
|
import type { ToolCall } from '@langchain/core/messages/tool';
|
|
4
|
-
import type {
|
|
5
|
-
import type { MessageContentComplex, ToolErrorData } from './stream';
|
|
4
|
+
import type { ToolErrorData } from './stream';
|
|
6
5
|
import { EnvVar } from '@/common';
|
|
7
6
|
/** Replacement type for `import type { ToolCall } from '@langchain/core/messages/tool'` in order to have stringified args typed */
|
|
8
7
|
export type CustomToolCall = {
|
|
@@ -40,12 +39,6 @@ export type ToolNodeOptions = {
|
|
|
40
39
|
agentId?: string;
|
|
41
40
|
/** Tool names that must be executed directly (via runTool) even in event-driven mode (e.g., graph-managed handoff tools) */
|
|
42
41
|
directToolNames?: Set<string>;
|
|
43
|
-
/**
|
|
44
|
-
* Hook registry for PreToolUse/PostToolUse lifecycle hooks.
|
|
45
|
-
* Only fires for event-driven tool calls (`dispatchToolEvents`). Tools
|
|
46
|
-
* routed through `directToolNames` bypass hook dispatch entirely.
|
|
47
|
-
*/
|
|
48
|
-
hookRegistry?: HookRegistry;
|
|
49
42
|
/** Max context tokens for the agent — used to compute tool result truncation limits. */
|
|
50
43
|
maxContextTokens?: number;
|
|
51
44
|
/**
|
|
@@ -161,25 +154,6 @@ export type ToolExecuteBatchRequest = {
|
|
|
161
154
|
/** Promise rejector - handler calls this on fatal error */
|
|
162
155
|
reject: (error: Error) => void;
|
|
163
156
|
};
|
|
164
|
-
/**
|
|
165
|
-
* A message injected into graph state by any tool execution handler.
|
|
166
|
-
* Generic mechanism: any tool returning `injectedMessages` in its `ToolExecuteResult`
|
|
167
|
-
* will have these appended to state after the ToolMessage for this call.
|
|
168
|
-
*/
|
|
169
|
-
export type InjectedMessage = {
|
|
170
|
-
/** 'user' for skill body injection, 'system' for context hints.
|
|
171
|
-
* Both are converted to HumanMessage at runtime; the original role
|
|
172
|
-
* is preserved in additional_kwargs.role. */
|
|
173
|
-
role: 'user' | 'system';
|
|
174
|
-
/** Message content: string for simple text, array for complex multi-part content */
|
|
175
|
-
content: string | MessageContentComplex[];
|
|
176
|
-
/** When true, the message is framework-internal: not shown in UI, not counted as a user turn */
|
|
177
|
-
isMeta?: boolean;
|
|
178
|
-
/** Origin tag for downstream consumers (UI, pruner, compaction) */
|
|
179
|
-
source?: 'skill' | 'hook' | 'system';
|
|
180
|
-
/** Only set when source is 'skill', for compaction preservation */
|
|
181
|
-
skillName?: string;
|
|
182
|
-
};
|
|
183
157
|
/** Result for a single tool call in event-driven execution */
|
|
184
158
|
export type ToolExecuteResult = {
|
|
185
159
|
/** Matches ToolCallRequest.id */
|
|
@@ -192,13 +166,6 @@ export type ToolExecuteResult = {
|
|
|
192
166
|
status: 'success' | 'error';
|
|
193
167
|
/** Error message if status is 'error' */
|
|
194
168
|
errorMessage?: string;
|
|
195
|
-
/**
|
|
196
|
-
* Messages to inject into graph state after the ToolMessage for this call.
|
|
197
|
-
* Placed after tool results to respect provider message ordering (tool_call -> tool_result adjacency).
|
|
198
|
-
* The host's message formatter may merge injected user messages with the preceding tool_result turn.
|
|
199
|
-
* Generic mechanism: any tool execution handler can use this.
|
|
200
|
-
*/
|
|
201
|
-
injectedMessages?: InjectedMessage[];
|
|
202
169
|
};
|
|
203
170
|
/** Map of tool names to tool definitions */
|
|
204
171
|
export type LCToolRegistry = Map<string, LCTool>;
|
|
@@ -299,10 +266,6 @@ export type ProgrammaticExecutionArtifact = {
|
|
|
299
266
|
session_id?: string;
|
|
300
267
|
files?: FileRefs;
|
|
301
268
|
};
|
|
302
|
-
/** Parameters for creating a bash execution tool (same API as CodeExecutor, bash-only) */
|
|
303
|
-
export type BashExecutionToolParams = CodeExecutionToolParams;
|
|
304
|
-
/** Parameters for creating a bash programmatic tool calling tool (same API as PTC, bash-only) */
|
|
305
|
-
export type BashProgrammaticToolCallingParams = ProgrammaticToolCallingParams;
|
|
306
269
|
/**
|
|
307
270
|
* Initialization parameters for the PTC tool
|
|
308
271
|
*/
|