@illuma-ai/agents 1.0.84 → 1.0.85

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.
@@ -145,8 +145,8 @@ class ToolNode extends run.RunnableCallable {
145
145
  return false;
146
146
  }
147
147
  else {
148
- // Custom function - evaluate with the tool args
149
- return effectivePolicy(args);
148
+ // Custom function - evaluate with tool name and args
149
+ return effectivePolicy(toolName, args);
150
150
  }
151
151
  }
152
152
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.cjs","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 { processToolOutput } from '@/utils/toonFormat';\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/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\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 /** 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 /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\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 toolDefinitions,\n agentId,\n toolApprovalConfig,\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.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n this.toolApprovalConfig = toolApprovalConfig;\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 * Evaluates whether a tool call requires human approval.\n * Returns true if approval is needed, false otherwise.\n * Does NOT perform the actual approval flow - that's handled by requestApproval().\n */\n private requiresApproval(toolName: string, args: Record<string, unknown>): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;\n\n // Scheduled executions bypass all approval checks\n if (executionContext === 'scheduled') {\n return false;\n }\n\n // Determine the effective policy for this tool\n const toolOverride = overrides?.[toolName];\n const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';\n\n // Evaluate whether approval is required\n if (effectivePolicy === 'always') {\n return true;\n } else if (effectivePolicy === 'never') {\n return false;\n } else {\n // Custom function - evaluate with the tool args\n return effectivePolicy(args);\n }\n }\n\n /**\n * Requests human approval for a tool call via event dispatch.\n * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host\n * to resolve the promise with an approval response.\n *\n * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event\n * dispatch where the host calls resolve/reject when the human responds.\n *\n * @param call - The tool call requiring approval\n * @param config - The runnable config for event dispatch\n * @returns The approval response from the human\n */\n private async requestApproval(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<t.ToolApprovalResponse> {\n const approvalRequest: t.ToolApprovalRequest = {\n type: 'tool_approval_required',\n toolCallId: call.id ?? '',\n toolName: call.name,\n toolArgs: call.args as Record<string, unknown>,\n agentId: this.agentId,\n description: `Tool \"${call.name}\" wants to execute with the provided arguments.`,\n };\n\n return new Promise<t.ToolApprovalResponse>((resolve, reject) => {\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_APPROVAL_REQUIRED,\n {\n ...approvalRequest,\n resolve,\n reject,\n },\n config\n );\n });\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 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 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) {\n /**\n * Always inject session_id so retries reuse the same workspace.\n * Also inject file refs when files exist from previous executions.\n */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\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 = {\n ...invokeParams,\n _injected_files: fileRefs,\n };\n }\n }\n }\n\n // ========================================================================\n // HITL: Check if this tool requires human approval before execution.\n // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event\n // and waits for the host to resolve/reject with a ToolApprovalResponse.\n // ========================================================================\n if (this.requiresApproval(call.name, call.args as Record<string, unknown>)) {\n const approvalResponse = await this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n // Human denied the tool call - return a denial message\n return new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback ? ` Reason: ${approvalResponse.feedback}` : ''} Please acknowledge the denial and proceed without executing this tool.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n // Human approved - optionally use modified args\n if (approvalResponse.modifiedArgs) {\n invokeParams = { ...invokeParams, args: approvalResponse.modifiedArgs };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 * 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 requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\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\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 const outputs: ToolMessage[] = 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\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 contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\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 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 let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, 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 !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, 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 message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["Send","RunnableCallable","safeDispatchCustomEvent","GraphEvents","Constants","ToolMessage","isCommand","isBaseMessage","processToolOutput","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;AA0BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;;AAIhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC1B,MAAM,SAAS,GAAa,EAAE;AAC9B,QAAA,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE;AAC3B,YAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,gBAAA,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;;AAChB,iBAAA,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;;gBAE7C,MAAM,GAAG,GAAG,KAAgC;AAC5C,gBAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;AACvD,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;;AACnB,qBAAA,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;;AAEvC,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;;;;AAI9B,QAAA,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;AACxB,YAAA,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;;;;AAK/B,IAAA,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;AAChC;AAEA;AACM,MAAO,QAAkB,SAAQC,oBAAsB,CAAA;AACnD,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBA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,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,OAAO,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,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;;SACV;AACL,QAAA,OAAOM,aAAG;;AAEd;;;;;"}
1
+ {"version":3,"file":"ToolNode.cjs","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 { processToolOutput } from '@/utils/toonFormat';\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/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\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 /** 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 /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\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 toolDefinitions,\n agentId,\n toolApprovalConfig,\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.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n this.toolApprovalConfig = toolApprovalConfig;\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 * Evaluates whether a tool call requires human approval.\n * Returns true if approval is needed, false otherwise.\n * Does NOT perform the actual approval flow - that's handled by requestApproval().\n */\n private requiresApproval(toolName: string, args: Record<string, unknown>): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;\n\n // Scheduled executions bypass all approval checks\n if (executionContext === 'scheduled') {\n return false;\n }\n\n // Determine the effective policy for this tool\n const toolOverride = overrides?.[toolName];\n const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';\n\n // Evaluate whether approval is required\n if (effectivePolicy === 'always') {\n return true;\n } else if (effectivePolicy === 'never') {\n return false;\n } else {\n // Custom function - evaluate with tool name and args\n return effectivePolicy(toolName, args);\n }\n }\n\n /**\n * Requests human approval for a tool call via event dispatch.\n * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host\n * to resolve the promise with an approval response.\n *\n * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event\n * dispatch where the host calls resolve/reject when the human responds.\n *\n * @param call - The tool call requiring approval\n * @param config - The runnable config for event dispatch\n * @returns The approval response from the human\n */\n private async requestApproval(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<t.ToolApprovalResponse> {\n const approvalRequest: t.ToolApprovalRequest = {\n type: 'tool_approval_required',\n toolCallId: call.id ?? '',\n toolName: call.name,\n toolArgs: call.args as Record<string, unknown>,\n agentId: this.agentId,\n description: `Tool \"${call.name}\" wants to execute with the provided arguments.`,\n };\n\n return new Promise<t.ToolApprovalResponse>((resolve, reject) => {\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_APPROVAL_REQUIRED,\n {\n ...approvalRequest,\n resolve,\n reject,\n },\n config\n );\n });\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 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 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) {\n /**\n * Always inject session_id so retries reuse the same workspace.\n * Also inject file refs when files exist from previous executions.\n */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\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 = {\n ...invokeParams,\n _injected_files: fileRefs,\n };\n }\n }\n }\n\n // ========================================================================\n // HITL: Check if this tool requires human approval before execution.\n // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event\n // and waits for the host to resolve/reject with a ToolApprovalResponse.\n // ========================================================================\n if (this.requiresApproval(call.name, call.args as Record<string, unknown>)) {\n const approvalResponse = await this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n // Human denied the tool call - return a denial message\n return new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback ? ` Reason: ${approvalResponse.feedback}` : ''} Please acknowledge the denial and proceed without executing this tool.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n // Human approved - optionally use modified args\n if (approvalResponse.modifiedArgs) {\n invokeParams = { ...invokeParams, args: approvalResponse.modifiedArgs };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 * 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 requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\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\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 const outputs: ToolMessage[] = 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\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 contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\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 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 let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, 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 !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, 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 message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["Send","RunnableCallable","safeDispatchCustomEvent","GraphEvents","Constants","ToolMessage","isCommand","isBaseMessage","processToolOutput","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;AA0BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;;AAIhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC1B,MAAM,SAAS,GAAa,EAAE;AAC9B,QAAA,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE;AAC3B,YAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,gBAAA,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;;AAChB,iBAAA,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;;gBAE7C,MAAM,GAAG,GAAG,KAAgC;AAC5C,gBAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;AACvD,oBAAA,SAAS,CAAC,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143
  return false;
144
144
  }
145
145
  else {
146
- // Custom function - evaluate with the tool args
147
- return effectivePolicy(args);
146
+ // Custom function - evaluate with tool name and args
147
+ return effectivePolicy(toolName, args);
148
148
  }
149
149
  }
150
150
  /**
@@ -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 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 { processToolOutput } from '@/utils/toonFormat';\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/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\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 /** 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 /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\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 toolDefinitions,\n agentId,\n toolApprovalConfig,\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.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n this.toolApprovalConfig = toolApprovalConfig;\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 * Evaluates whether a tool call requires human approval.\n * Returns true if approval is needed, false otherwise.\n * Does NOT perform the actual approval flow - that's handled by requestApproval().\n */\n private requiresApproval(toolName: string, args: Record<string, unknown>): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;\n\n // Scheduled executions bypass all approval checks\n if (executionContext === 'scheduled') {\n return false;\n }\n\n // Determine the effective policy for this tool\n const toolOverride = overrides?.[toolName];\n const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';\n\n // Evaluate whether approval is required\n if (effectivePolicy === 'always') {\n return true;\n } else if (effectivePolicy === 'never') {\n return false;\n } else {\n // Custom function - evaluate with the tool args\n return effectivePolicy(args);\n }\n }\n\n /**\n * Requests human approval for a tool call via event dispatch.\n * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host\n * to resolve the promise with an approval response.\n *\n * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event\n * dispatch where the host calls resolve/reject when the human responds.\n *\n * @param call - The tool call requiring approval\n * @param config - The runnable config for event dispatch\n * @returns The approval response from the human\n */\n private async requestApproval(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<t.ToolApprovalResponse> {\n const approvalRequest: t.ToolApprovalRequest = {\n type: 'tool_approval_required',\n toolCallId: call.id ?? '',\n toolName: call.name,\n toolArgs: call.args as Record<string, unknown>,\n agentId: this.agentId,\n description: `Tool \"${call.name}\" wants to execute with the provided arguments.`,\n };\n\n return new Promise<t.ToolApprovalResponse>((resolve, reject) => {\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_APPROVAL_REQUIRED,\n {\n ...approvalRequest,\n resolve,\n reject,\n },\n config\n );\n });\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 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 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) {\n /**\n * Always inject session_id so retries reuse the same workspace.\n * Also inject file refs when files exist from previous executions.\n */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\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 = {\n ...invokeParams,\n _injected_files: fileRefs,\n };\n }\n }\n }\n\n // ========================================================================\n // HITL: Check if this tool requires human approval before execution.\n // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event\n // and waits for the host to resolve/reject with a ToolApprovalResponse.\n // ========================================================================\n if (this.requiresApproval(call.name, call.args as Record<string, unknown>)) {\n const approvalResponse = await this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n // Human denied the tool call - return a denial message\n return new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback ? ` Reason: ${approvalResponse.feedback}` : ''} Please acknowledge the denial and proceed without executing this tool.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n // Human approved - optionally use modified args\n if (approvalResponse.modifiedArgs) {\n invokeParams = { ...invokeParams, args: approvalResponse.modifiedArgs };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 * 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 requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\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\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 const outputs: ToolMessage[] = 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\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 contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\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 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 let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, 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 !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, 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 message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AA0BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAY,IAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,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O,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,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;;SACV;AACL,QAAA,OAAO,GAAG;;AAEd;;;;"}
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 { processToolOutput } from '@/utils/toonFormat';\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/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\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 /** 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 /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\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 toolDefinitions,\n agentId,\n toolApprovalConfig,\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.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n this.toolApprovalConfig = toolApprovalConfig;\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 * Evaluates whether a tool call requires human approval.\n * Returns true if approval is needed, false otherwise.\n * Does NOT perform the actual approval flow - that's handled by requestApproval().\n */\n private requiresApproval(toolName: string, args: Record<string, unknown>): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;\n\n // Scheduled executions bypass all approval checks\n if (executionContext === 'scheduled') {\n return false;\n }\n\n // Determine the effective policy for this tool\n const toolOverride = overrides?.[toolName];\n const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';\n\n // Evaluate whether approval is required\n if (effectivePolicy === 'always') {\n return true;\n } else if (effectivePolicy === 'never') {\n return false;\n } else {\n // Custom function - evaluate with tool name and args\n return effectivePolicy(toolName, args);\n }\n }\n\n /**\n * Requests human approval for a tool call via event dispatch.\n * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host\n * to resolve the promise with an approval response.\n *\n * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event\n * dispatch where the host calls resolve/reject when the human responds.\n *\n * @param call - The tool call requiring approval\n * @param config - The runnable config for event dispatch\n * @returns The approval response from the human\n */\n private async requestApproval(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<t.ToolApprovalResponse> {\n const approvalRequest: t.ToolApprovalRequest = {\n type: 'tool_approval_required',\n toolCallId: call.id ?? '',\n toolName: call.name,\n toolArgs: call.args as Record<string, unknown>,\n agentId: this.agentId,\n description: `Tool \"${call.name}\" wants to execute with the provided arguments.`,\n };\n\n return new Promise<t.ToolApprovalResponse>((resolve, reject) => {\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_APPROVAL_REQUIRED,\n {\n ...approvalRequest,\n resolve,\n reject,\n },\n config\n );\n });\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 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 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) {\n /**\n * Always inject session_id so retries reuse the same workspace.\n * Also inject file refs when files exist from previous executions.\n */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\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 = {\n ...invokeParams,\n _injected_files: fileRefs,\n };\n }\n }\n }\n\n // ========================================================================\n // HITL: Check if this tool requires human approval before execution.\n // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event\n // and waits for the host to resolve/reject with a ToolApprovalResponse.\n // ========================================================================\n if (this.requiresApproval(call.name, call.args as Record<string, unknown>)) {\n const approvalResponse = await this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n // Human denied the tool call - return a denial message\n return new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback ? ` Reason: ${approvalResponse.feedback}` : ''} Please acknowledge the denial and proceed without executing this tool.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n // Human approved - optionally use modified args\n if (approvalResponse.modifiedArgs) {\n invokeParams = { ...invokeParams, args: approvalResponse.modifiedArgs };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 * 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 requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\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\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 const outputs: ToolMessage[] = 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\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 contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\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 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 let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, 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 !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, 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 message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &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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,OAAO,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,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;;SACV;AACL,QAAA,OAAO,GAAG;;AAEd;;;;"}
@@ -173,9 +173,11 @@ export type ExecutionContext = 'interactive' | 'scheduled';
173
173
  * Policy for when a tool requires human approval.
174
174
  * - 'always': Always require approval (default for interactive context).
175
175
  * - 'never': Never require approval (used for safe read-only tools).
176
- * - A function: Custom logic based on tool args (e.g., approve writes but not reads).
176
+ * - A function: Custom logic based on tool name and args.
177
+ * Receives the tool name as first arg so the host can classify tools dynamically
178
+ * (e.g., only require approval for tools whose name includes "send", "create", "delete").
177
179
  */
178
- export type ToolApprovalRule = 'always' | 'never' | ((args: Record<string, unknown>) => boolean);
180
+ export type ToolApprovalRule = 'always' | 'never' | ((toolName: string, args: Record<string, unknown>) => boolean);
179
181
  /**
180
182
  * Per-tool approval overrides. Keys are tool names (or glob patterns).
181
183
  * When a tool is not listed, it falls back to the default policy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@illuma-ai/agents",
3
- "version": "1.0.84",
3
+ "version": "1.0.85",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -184,8 +184,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
184
184
  } else if (effectivePolicy === 'never') {
185
185
  return false;
186
186
  } else {
187
- // Custom function - evaluate with the tool args
188
- return effectivePolicy(args);
187
+ // Custom function - evaluate with tool name and args
188
+ return effectivePolicy(toolName, args);
189
189
  }
190
190
  }
191
191
 
@@ -371,7 +371,7 @@ describe('HITL Tool Approval - Event-Driven Flow', () => {
371
371
  defaultPolicy: 'never',
372
372
  executionContext: 'interactive',
373
373
  overrides: {
374
- send_email: (args: Record<string, unknown>) => {
374
+ send_email: (_toolName: string, args: Record<string, unknown>) => {
375
375
  const to = (args.to as string) ?? '';
376
376
  return !to.endsWith('@internal.com');
377
377
  },
@@ -421,7 +421,7 @@ describe('HITL Tool Approval - Event-Driven Flow', () => {
421
421
  defaultPolicy: 'never',
422
422
  executionContext: 'interactive',
423
423
  overrides: {
424
- send_email: (args: Record<string, unknown>) => {
424
+ send_email: (_toolName: string, args: Record<string, unknown>) => {
425
425
  const to = (args.to as string) ?? '';
426
426
  return !to.endsWith('@internal.com');
427
427
  },
@@ -660,7 +660,7 @@ describe('HITL Types', () => {
660
660
  overrides: {
661
661
  search: 'never',
662
662
  send_email: 'always',
663
- custom_tool: (args) => (args.dangerous as boolean) === true,
663
+ custom_tool: (_toolName, args) => (args.dangerous as boolean) === true,
664
664
  },
665
665
  };
666
666
  expect(config3.overrides).toBeDefined();
@@ -696,4 +696,30 @@ describe('HITL Types', () => {
696
696
  };
697
697
  expect(edited.modifiedArgs).toBeDefined();
698
698
  });
699
+
700
+ test('ToolApprovalRule function receives toolName as first argument', () => {
701
+ // Verify the function-based policy can use toolName for classification
702
+ const actionPrefixes = ['send', 'create', 'delete', 'post'];
703
+ const policy: t.ToolApprovalRule = (toolName: string, _args: Record<string, unknown>) => {
704
+ const lower = toolName.toLowerCase();
705
+ return actionPrefixes.some((prefix) => lower.includes(prefix));
706
+ };
707
+
708
+ // Action tools should require approval
709
+ expect(policy('send_email', { to: 'a@b.com' })).toBe(true);
710
+ expect(policy('create_document', {})).toBe(true);
711
+ expect(policy('delete_file', {})).toBe(true);
712
+ expect(policy('post_message', {})).toBe(true);
713
+
714
+ // Read-only tools should not
715
+ expect(policy('search', { query: 'test' })).toBe(false);
716
+ expect(policy('list_emails', {})).toBe(false);
717
+ expect(policy('get_calendar', {})).toBe(false);
718
+
719
+ const config: t.ToolApprovalConfig = {
720
+ defaultPolicy: policy,
721
+ executionContext: 'interactive',
722
+ };
723
+ expect(typeof config.defaultPolicy).toBe('function');
724
+ });
699
725
  });
@@ -210,12 +210,14 @@ export type ExecutionContext = 'interactive' | 'scheduled';
210
210
  * Policy for when a tool requires human approval.
211
211
  * - 'always': Always require approval (default for interactive context).
212
212
  * - 'never': Never require approval (used for safe read-only tools).
213
- * - A function: Custom logic based on tool args (e.g., approve writes but not reads).
213
+ * - A function: Custom logic based on tool name and args.
214
+ * Receives the tool name as first arg so the host can classify tools dynamically
215
+ * (e.g., only require approval for tools whose name includes "send", "create", "delete").
214
216
  */
215
217
  export type ToolApprovalRule =
216
218
  | 'always'
217
219
  | 'never'
218
- | ((args: Record<string, unknown>) => boolean);
220
+ | ((toolName: string, args: Record<string, unknown>) => boolean);
219
221
 
220
222
  /**
221
223
  * Per-tool approval overrides. Keys are tool names (or glob patterns).