@illuma-ai/agents 1.0.83 → 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.
@@ -1,6 +1,6 @@
1
- import { isBaseMessage, ToolMessage, isAIMessage } from '@langchain/core/messages';
1
+ import { ToolMessage, isBaseMessage, isAIMessage } from '@langchain/core/messages';
2
2
  import { isCommand, isGraphInterrupt, Command, Send, END } from '@langchain/langgraph';
3
- import { Constants, GraphEvents } from '../common/enum.mjs';
3
+ import { GraphEvents, Constants } from '../common/enum.mjs';
4
4
  import 'nanoid';
5
5
  import '../messages/core.mjs';
6
6
  import { processToolOutput } from '../utils/toonFormat.mjs';
@@ -72,7 +72,9 @@ class ToolNode extends RunnableCallable {
72
72
  toolDefinitions;
73
73
  /** Agent ID for event-driven mode */
74
74
  agentId;
75
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, toolDefinitions, agentId, }) {
75
+ /** HITL tool approval configuration */
76
+ toolApprovalConfig;
77
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, toolDefinitions, agentId, toolApprovalConfig, }) {
76
78
  super({ name, tags, func: (input, config) => this.run(input, config) });
77
79
  this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));
78
80
  this.toolCallStepIds = toolCallStepIds;
@@ -85,6 +87,7 @@ class ToolNode extends RunnableCallable {
85
87
  this.eventDrivenMode = eventDrivenMode ?? false;
86
88
  this.toolDefinitions = toolDefinitions;
87
89
  this.agentId = agentId;
90
+ this.toolApprovalConfig = toolApprovalConfig;
88
91
  }
89
92
  /**
90
93
  * Returns cached programmatic tools, computing once on first access.
@@ -115,6 +118,64 @@ class ToolNode extends RunnableCallable {
115
118
  getToolUsageCounts() {
116
119
  return new Map(this.toolUsageCount); // Return a copy
117
120
  }
121
+ /**
122
+ * Evaluates whether a tool call requires human approval.
123
+ * Returns true if approval is needed, false otherwise.
124
+ * Does NOT perform the actual approval flow - that's handled by requestApproval().
125
+ */
126
+ requiresApproval(toolName, args) {
127
+ if (!this.toolApprovalConfig) {
128
+ return false;
129
+ }
130
+ const { defaultPolicy, overrides, executionContext } = this.toolApprovalConfig;
131
+ // Scheduled executions bypass all approval checks
132
+ if (executionContext === 'scheduled') {
133
+ return false;
134
+ }
135
+ // Determine the effective policy for this tool
136
+ const toolOverride = overrides?.[toolName];
137
+ const effectivePolicy = toolOverride ?? defaultPolicy ?? 'always';
138
+ // Evaluate whether approval is required
139
+ if (effectivePolicy === 'always') {
140
+ return true;
141
+ }
142
+ else if (effectivePolicy === 'never') {
143
+ return false;
144
+ }
145
+ else {
146
+ // Custom function - evaluate with tool name and args
147
+ return effectivePolicy(toolName, args);
148
+ }
149
+ }
150
+ /**
151
+ * Requests human approval for a tool call via event dispatch.
152
+ * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host
153
+ * to resolve the promise with an approval response.
154
+ *
155
+ * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event
156
+ * dispatch where the host calls resolve/reject when the human responds.
157
+ *
158
+ * @param call - The tool call requiring approval
159
+ * @param config - The runnable config for event dispatch
160
+ * @returns The approval response from the human
161
+ */
162
+ async requestApproval(call, config) {
163
+ const approvalRequest = {
164
+ type: 'tool_approval_required',
165
+ toolCallId: call.id ?? '',
166
+ toolName: call.name,
167
+ toolArgs: call.args,
168
+ agentId: this.agentId,
169
+ description: `Tool "${call.name}" wants to execute with the provided arguments.`,
170
+ };
171
+ return new Promise((resolve, reject) => {
172
+ safeDispatchCustomEvent(GraphEvents.ON_TOOL_APPROVAL_REQUIRED, {
173
+ ...approvalRequest,
174
+ resolve,
175
+ reject,
176
+ }, config);
177
+ });
178
+ }
118
179
  /**
119
180
  * Runs a single tool call with error handling
120
181
  */
@@ -187,6 +248,27 @@ class ToolNode extends RunnableCallable {
187
248
  }
188
249
  }
189
250
  }
251
+ // ========================================================================
252
+ // HITL: Check if this tool requires human approval before execution.
253
+ // Uses event-driven pattern: dispatches ON_TOOL_APPROVAL_REQUIRED event
254
+ // and waits for the host to resolve/reject with a ToolApprovalResponse.
255
+ // ========================================================================
256
+ if (this.requiresApproval(call.name, call.args)) {
257
+ const approvalResponse = await this.requestApproval(call, config);
258
+ if (!approvalResponse.approved) {
259
+ // Human denied the tool call - return a denial message
260
+ return new ToolMessage({
261
+ status: 'error',
262
+ 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.`,
263
+ name: call.name,
264
+ tool_call_id: call.id ?? '',
265
+ });
266
+ }
267
+ // Human approved - optionally use modified args
268
+ if (approvalResponse.modifiedArgs) {
269
+ invokeParams = { ...invokeParams, args: approvalResponse.modifiedArgs };
270
+ }
271
+ }
190
272
  const output = await tool.invoke(invokeParams, config);
191
273
  // Handle Command outputs directly
192
274
  if (isCommand(output)) {
@@ -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\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 }: 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 }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n 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 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;A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AAC,OAAO,CAAE,KAA+B,CAAC,QAAQ,CAAC;YACvD,KAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC;;AAGrE;AAED,SAAS,mBAAmB,CAC1B,OAAkB,EAClB,cAA4B,EAAA;AAE5B,IAAA,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,IAAI,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK;AAC9D,IAAA,QACE,OAAO,CAAC,UAAU,EAAE,KAAK,CACvB,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,IAAI,IAAI,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,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;;;;"}
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 &&\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,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,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/types/graph.ts"],"sourcesContent":["// src/types/graph.ts\nimport type {\n START,\n StateType,\n UpdateType,\n StateGraph,\n StateGraphArgs,\n StateDefinition,\n CompiledStateGraph,\n BinaryOperatorAggregate,\n} from '@langchain/langgraph';\nimport type { BindToolsInput } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n AIMessageChunk,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleAIToolType } from '@langchain/google-common';\nimport type { ToolMap, ToolEndEvent, GenericTool, LCTool } from '@/types/tools';\nimport type { Providers, Callback, GraphNodeKeys } from '@/common';\nimport type { StandardGraph, MultiAgentGraph } from '@/graphs';\nimport type { ClientOptions } from '@/types/llm';\nimport type {\n RunStep,\n RunStepDeltaEvent,\n MessageDeltaEvent,\n ReasoningDeltaEvent,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\n\n/** Interface for bound model with stream and invoke methods */\nexport interface ChatModel {\n stream?: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AsyncIterable<AIMessageChunk>>;\n invoke: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AIMessageChunk>;\n}\n\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (\n graph: StandardGraph,\n ...args: T\n) => void;\n\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n};\n\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<\n infer Args\n >\n ? (...args: Args) => void\n : never;\n};\n\nexport type BaseGraphState = {\n messages: BaseMessage[];\n /**\n * Structured response when using structured output mode.\n * Contains the validated JSON response conforming to the configured schema.\n */\n structuredResponse?: Record<string, unknown>;\n};\n\nexport type MultiAgentGraphState = BaseGraphState & {\n agentMessages?: BaseMessage[];\n};\n\nexport type IState = BaseGraphState;\n\nexport interface EventHandler {\n handle(\n event: string,\n data:\n | StreamEventData\n | ModelEndData\n | RunStep\n | RunStepDeltaEvent\n | MessageDeltaEvent\n | ReasoningDeltaEvent\n | { result: ToolEndEvent },\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n ): void | Promise<void>;\n}\n\nexport type GraphStateChannels<T extends BaseGraphState> =\n StateGraphArgs<T>['channels'];\n\nexport type Workflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = StateGraph<T, U, N>;\n\nexport type CompiledWorkflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = CompiledStateGraph<T, U, N>;\n\nexport type CompiledStateWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledMultiAgentWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledAgentWorfklow = CompiledStateGraph<\n {\n messages: BaseMessage[];\n },\n {\n messages?: BaseMessage[] | undefined;\n },\n '__start__' | `agent=${string}` | `tools=${string}`,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition,\n {\n [x: `agent=${string}`]: Partial<BaseGraphState>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: `tools=${string}`]: any;\n }\n>;\n\nexport type SystemRunnable =\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined;\n\n/**\n * Optional compile options passed to workflow.compile().\n * These are intentionally untyped to avoid coupling to library internals.\n */\nexport type CompileOptions = {\n // A checkpointer instance (e.g., MemorySaver, SQL saver)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n checkpointer?: any;\n interruptBefore?: string[];\n interruptAfter?: string[];\n};\n\nexport type EventStreamCallbackHandlerInput =\n Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<\n infer T,\n 'autoClose'\n >\n ? T\n : never;\n\nexport type StreamChunk =\n | (ChatGenerationChunk & {\n message: AIMessageChunk;\n })\n | AIMessageChunk;\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: unknown;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: unknown;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: StreamChunk;\n /**\n * Runnable config for invoking other runnables within handlers.\n */\n config?: RunnableConfig;\n /**\n * Custom result from the runnable that generated the event.\n */\n result?: unknown;\n /**\n * Custom field to indicate the event was manually emitted, and may have been handled already\n */\n emitted?: boolean;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, unknown>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\nexport type GraphConfig = {\n provider: string;\n thread_id?: string;\n run_id?: string;\n};\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n output?: string;\n};\n\nexport type ModelEndData =\n | (StreamEventData & { output: AIMessageChunk | undefined })\n | undefined;\nexport type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];\nexport type StandardGraphInput = {\n runId?: string;\n signal?: AbortSignal;\n agents: AgentInputs[];\n tokenCounter?: TokenCounter;\n indexTokenCountMap?: Record<string, number>;\n};\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /** 'handoff' creates tools for dynamic routing, 'direct' creates direct edges, which also allow parallel execution */\n edgeType?: 'handoff' | 'direct';\n /**\n * For direct edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For handoff edges: Description for the input parameter that the handoff tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?:\n | string\n | ((\n messages: BaseMessage[],\n runStartIndex: number\n ) => string | Promise<string> | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For handoff edges: Customizes the parameter name for the handoff input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for handoff edges.\n */\n promptKey?: string;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n};\n\n/**\n * Structured output mode determines how the agent returns structured data.\n * - 'tool': Uses tool calling to return structured output (works with all tool-calling models)\n * - 'provider': Uses provider-native structured output via LangChain's jsonMode (OpenAI, Anthropic, etc.)\n * - 'native': Uses provider's constrained decoding API directly for guaranteed schema compliance\n * (Anthropic output_config.format, OpenAI response_format.json_schema). Falls back to 'tool' for unsupported providers.\n * - 'auto': Automatically selects the best strategy — 'native' for supported providers, 'tool' for others\n */\nexport type StructuredOutputMode = 'tool' | 'provider' | 'native' | 'auto';\n\n/**\n * Resolved method used internally after mode resolution.\n * Maps to LangChain's withStructuredOutput method parameter plus our native path.\n */\nexport type ResolvedStructuredOutputMethod = 'functionCalling' | 'jsonMode' | 'jsonSchema' | 'native' | undefined;\n\n/**\n * Error thrown when the model refuses to produce structured output due to safety policies.\n */\nexport class StructuredOutputRefusalError extends Error {\n constructor(public refusalText: string) {\n super(`Model refused to produce structured output: ${refusalText}`);\n this.name = 'StructuredOutputRefusalError';\n }\n}\n\n/**\n * Error thrown when the structured output response was truncated due to max_tokens.\n */\nexport class StructuredOutputTruncatedError extends Error {\n constructor(public stopReason: string) {\n super(\n `Structured output was truncated (stop_reason: ${stopReason}). ` +\n `Increase max_tokens to allow the full JSON response to be generated.`\n );\n this.name = 'StructuredOutputTruncatedError';\n }\n}\n\n/**\n * Configuration for structured JSON output from agents.\n * When configured, the agent will return a validated JSON response\n * instead of streaming text.\n */\nexport interface StructuredOutputConfig {\n /**\n * JSON Schema defining the output structure.\n * The model will be forced to return data conforming to this schema.\n */\n schema: Record<string, unknown>;\n /**\n * Name for the structured output format (used in tool mode).\n * @default 'StructuredResponse'\n */\n name?: string;\n /**\n * Description of what the structured output represents.\n * Helps the model understand the expected format.\n */\n description?: string;\n /**\n * Output mode strategy.\n * @default 'auto'\n */\n mode?: StructuredOutputMode;\n /**\n * Enable strict schema validation.\n * When true, the response must exactly match the schema.\n * @default true\n */\n strict?: boolean;\n /**\n * Error handling configuration.\n * - true: Auto-retry on validation errors (default)\n * - false: Throw error on validation failure\n * - string: Custom error message for retry\n */\n handleErrors?: boolean | string;\n /**\n * Maximum number of retry attempts on validation failure.\n * @default 2\n */\n maxRetries?: number;\n /**\n * Include the raw AI message along with structured response.\n * Useful for debugging.\n * @default false\n */\n includeRaw?: boolean;\n}\n\n/**\n * Database/API structured output format (snake_case with enabled flag).\n * This matches the format stored in MongoDB and sent from frontends.\n */\nexport interface StructuredOutputInput {\n /** Whether structured output is enabled */\n enabled?: boolean;\n /** JSON Schema defining the expected response structure */\n schema?: Record<string, unknown>;\n /** Name identifier for the structured output */\n name?: string;\n /** Description of what the structured output represents */\n description?: string;\n /** Mode for structured output: 'tool' | 'provider' | 'native' | 'auto' */\n mode?: StructuredOutputMode;\n /** Whether to enforce strict schema validation */\n strict?: boolean;\n}\n\nexport interface AgentInputs {\n agentId: string;\n /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */\n name?: string;\n toolEnd?: boolean;\n toolMap?: ToolMap;\n tools?: GraphTools;\n provider: Providers;\n instructions?: string;\n streamBuffer?: number;\n maxContextTokens?: number;\n clientOptions?: ClientOptions;\n additional_instructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */\n useLegacyContent?: boolean;\n /**\n * Tool definitions for all tools, including deferred and programmatic.\n * Used for tool search and programmatic tool calling.\n * Maps tool name to LCTool definition.\n */\n toolRegistry?: Map<string, LCTool>;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is injected as a user message rather than system prompt to preserve cache.\n * Keeping this separate from instructions ensures the system message stays static\n * and can be cached by Bedrock/Anthropic prompt caching.\n */\n dynamicContext?: string;\n /**\n * Structured output configuration (camelCase).\n * When set, disables streaming and returns a validated JSON response\n * conforming to the specified schema.\n */\n structuredOutput?: StructuredOutputConfig;\n /**\n * Structured output configuration (snake_case - database/API format).\n * Alternative to structuredOutput for compatibility with MongoDB/frontend.\n * Uses an `enabled` flag to control activation.\n * @deprecated Use structuredOutput instead when possible\n */\n structured_output?: StructuredOutputInput;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode, dispatching\n * ON_TOOL_EXECUTE events instead of invoking tools directly.\n */\n toolDefinitions?: LCTool[];\n /**\n * Tool names discovered from previous conversation history.\n * These tools will be pre-marked as discovered so they're included\n * in tool binding without requiring tool_search.\n */\n discoveredTools?: string[];\n /**\n * Optional callback for summarizing messages that were pruned from context.\n * When provided, discarded messages are summarized by the caller (e.g., Ranger)\n * using a cheap LLM call, and the summary is prepended to the context.\n */\n summarizeCallback?: (messagesToRefine: import('@langchain/core/messages').BaseMessage[]) => Promise<string | undefined>;\n}\n"],"names":[],"mappings":"AA0XA;;AAEG;AACG,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AAClC,IAAA,WAAA;AAAnB,IAAA,WAAA,CAAmB,WAAmB,EAAA;AACpC,QAAA,KAAK,CAAC,CAAA,4CAAA,EAA+C,WAAW,CAAA,CAAE,CAAC;QADlD,IAAW,CAAA,WAAA,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;;AAE7C;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAiD,8CAAA,EAAA,UAAU,CAAK,GAAA,CAAA;AAChE,YAAA,CAAA,oEAAA,CAAsE,CACvE;QAJgB,IAAU,CAAA,UAAA,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;;AAE/C;;;;"}
1
+ {"version":3,"file":"graph.mjs","sources":["../../../src/types/graph.ts"],"sourcesContent":["// src/types/graph.ts\nimport type {\n START,\n StateType,\n UpdateType,\n StateGraph,\n StateGraphArgs,\n StateDefinition,\n CompiledStateGraph,\n BinaryOperatorAggregate,\n} from '@langchain/langgraph';\nimport type { BindToolsInput } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n AIMessageChunk,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleAIToolType } from '@langchain/google-common';\nimport type { ToolMap, ToolEndEvent, GenericTool, LCTool, ToolApprovalConfig } from '@/types/tools';\nimport type { Providers, Callback, GraphNodeKeys } from '@/common';\nimport type { StandardGraph, MultiAgentGraph } from '@/graphs';\nimport type { ClientOptions } from '@/types/llm';\nimport type {\n RunStep,\n RunStepDeltaEvent,\n MessageDeltaEvent,\n ReasoningDeltaEvent,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\n\n/** Interface for bound model with stream and invoke methods */\nexport interface ChatModel {\n stream?: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AsyncIterable<AIMessageChunk>>;\n invoke: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AIMessageChunk>;\n}\n\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (\n graph: StandardGraph,\n ...args: T\n) => void;\n\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n};\n\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<\n infer Args\n >\n ? (...args: Args) => void\n : never;\n};\n\nexport type BaseGraphState = {\n messages: BaseMessage[];\n /**\n * Structured response when using structured output mode.\n * Contains the validated JSON response conforming to the configured schema.\n */\n structuredResponse?: Record<string, unknown>;\n};\n\nexport type MultiAgentGraphState = BaseGraphState & {\n agentMessages?: BaseMessage[];\n};\n\nexport type IState = BaseGraphState;\n\nexport interface EventHandler {\n handle(\n event: string,\n data:\n | StreamEventData\n | ModelEndData\n | RunStep\n | RunStepDeltaEvent\n | MessageDeltaEvent\n | ReasoningDeltaEvent\n | { result: ToolEndEvent },\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n ): void | Promise<void>;\n}\n\nexport type GraphStateChannels<T extends BaseGraphState> =\n StateGraphArgs<T>['channels'];\n\nexport type Workflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = StateGraph<T, U, N>;\n\nexport type CompiledWorkflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = CompiledStateGraph<T, U, N>;\n\nexport type CompiledStateWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledMultiAgentWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledAgentWorfklow = CompiledStateGraph<\n {\n messages: BaseMessage[];\n },\n {\n messages?: BaseMessage[] | undefined;\n },\n '__start__' | `agent=${string}` | `tools=${string}`,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition,\n {\n [x: `agent=${string}`]: Partial<BaseGraphState>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: `tools=${string}`]: any;\n }\n>;\n\nexport type SystemRunnable =\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined;\n\n/**\n * Optional compile options passed to workflow.compile().\n * These are intentionally untyped to avoid coupling to library internals.\n */\nexport type CompileOptions = {\n // A checkpointer instance (e.g., MemorySaver, SQL saver)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n checkpointer?: any;\n interruptBefore?: string[];\n interruptAfter?: string[];\n /**\n * Human-in-the-loop tool approval configuration.\n * When set, tools matching the policy will trigger an interrupt()\n * before execution, pausing the graph for human approval.\n * Requires a checkpointer to be set for interrupt/resume to work.\n */\n toolApprovalConfig?: ToolApprovalConfig;\n};\n\nexport type EventStreamCallbackHandlerInput =\n Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<\n infer T,\n 'autoClose'\n >\n ? T\n : never;\n\nexport type StreamChunk =\n | (ChatGenerationChunk & {\n message: AIMessageChunk;\n })\n | AIMessageChunk;\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: unknown;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: unknown;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: StreamChunk;\n /**\n * Runnable config for invoking other runnables within handlers.\n */\n config?: RunnableConfig;\n /**\n * Custom result from the runnable that generated the event.\n */\n result?: unknown;\n /**\n * Custom field to indicate the event was manually emitted, and may have been handled already\n */\n emitted?: boolean;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, unknown>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\nexport type GraphConfig = {\n provider: string;\n thread_id?: string;\n run_id?: string;\n};\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n output?: string;\n};\n\nexport type ModelEndData =\n | (StreamEventData & { output: AIMessageChunk | undefined })\n | undefined;\nexport type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];\nexport type StandardGraphInput = {\n runId?: string;\n signal?: AbortSignal;\n agents: AgentInputs[];\n tokenCounter?: TokenCounter;\n indexTokenCountMap?: Record<string, number>;\n};\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /** 'handoff' creates tools for dynamic routing, 'direct' creates direct edges, which also allow parallel execution */\n edgeType?: 'handoff' | 'direct';\n /**\n * For direct edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For handoff edges: Description for the input parameter that the handoff tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?:\n | string\n | ((\n messages: BaseMessage[],\n runStartIndex: number\n ) => string | Promise<string> | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For handoff edges: Customizes the parameter name for the handoff input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for handoff edges.\n */\n promptKey?: string;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n};\n\n/**\n * Structured output mode determines how the agent returns structured data.\n * - 'tool': Uses tool calling to return structured output (works with all tool-calling models)\n * - 'provider': Uses provider-native structured output via LangChain's jsonMode (OpenAI, Anthropic, etc.)\n * - 'native': Uses provider's constrained decoding API directly for guaranteed schema compliance\n * (Anthropic output_config.format, OpenAI response_format.json_schema). Falls back to 'tool' for unsupported providers.\n * - 'auto': Automatically selects the best strategy — 'native' for supported providers, 'tool' for others\n */\nexport type StructuredOutputMode = 'tool' | 'provider' | 'native' | 'auto';\n\n/**\n * Resolved method used internally after mode resolution.\n * Maps to LangChain's withStructuredOutput method parameter plus our native path.\n */\nexport type ResolvedStructuredOutputMethod = 'functionCalling' | 'jsonMode' | 'jsonSchema' | 'native' | undefined;\n\n/**\n * Error thrown when the model refuses to produce structured output due to safety policies.\n */\nexport class StructuredOutputRefusalError extends Error {\n constructor(public refusalText: string) {\n super(`Model refused to produce structured output: ${refusalText}`);\n this.name = 'StructuredOutputRefusalError';\n }\n}\n\n/**\n * Error thrown when the structured output response was truncated due to max_tokens.\n */\nexport class StructuredOutputTruncatedError extends Error {\n constructor(public stopReason: string) {\n super(\n `Structured output was truncated (stop_reason: ${stopReason}). ` +\n `Increase max_tokens to allow the full JSON response to be generated.`\n );\n this.name = 'StructuredOutputTruncatedError';\n }\n}\n\n/**\n * Configuration for structured JSON output from agents.\n * When configured, the agent will return a validated JSON response\n * instead of streaming text.\n */\nexport interface StructuredOutputConfig {\n /**\n * JSON Schema defining the output structure.\n * The model will be forced to return data conforming to this schema.\n */\n schema: Record<string, unknown>;\n /**\n * Name for the structured output format (used in tool mode).\n * @default 'StructuredResponse'\n */\n name?: string;\n /**\n * Description of what the structured output represents.\n * Helps the model understand the expected format.\n */\n description?: string;\n /**\n * Output mode strategy.\n * @default 'auto'\n */\n mode?: StructuredOutputMode;\n /**\n * Enable strict schema validation.\n * When true, the response must exactly match the schema.\n * @default true\n */\n strict?: boolean;\n /**\n * Error handling configuration.\n * - true: Auto-retry on validation errors (default)\n * - false: Throw error on validation failure\n * - string: Custom error message for retry\n */\n handleErrors?: boolean | string;\n /**\n * Maximum number of retry attempts on validation failure.\n * @default 2\n */\n maxRetries?: number;\n /**\n * Include the raw AI message along with structured response.\n * Useful for debugging.\n * @default false\n */\n includeRaw?: boolean;\n}\n\n/**\n * Database/API structured output format (snake_case with enabled flag).\n * This matches the format stored in MongoDB and sent from frontends.\n */\nexport interface StructuredOutputInput {\n /** Whether structured output is enabled */\n enabled?: boolean;\n /** JSON Schema defining the expected response structure */\n schema?: Record<string, unknown>;\n /** Name identifier for the structured output */\n name?: string;\n /** Description of what the structured output represents */\n description?: string;\n /** Mode for structured output: 'tool' | 'provider' | 'native' | 'auto' */\n mode?: StructuredOutputMode;\n /** Whether to enforce strict schema validation */\n strict?: boolean;\n}\n\nexport interface AgentInputs {\n agentId: string;\n /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */\n name?: string;\n toolEnd?: boolean;\n toolMap?: ToolMap;\n tools?: GraphTools;\n provider: Providers;\n instructions?: string;\n streamBuffer?: number;\n maxContextTokens?: number;\n clientOptions?: ClientOptions;\n additional_instructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */\n useLegacyContent?: boolean;\n /**\n * Tool definitions for all tools, including deferred and programmatic.\n * Used for tool search and programmatic tool calling.\n * Maps tool name to LCTool definition.\n */\n toolRegistry?: Map<string, LCTool>;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is injected as a user message rather than system prompt to preserve cache.\n * Keeping this separate from instructions ensures the system message stays static\n * and can be cached by Bedrock/Anthropic prompt caching.\n */\n dynamicContext?: string;\n /**\n * Structured output configuration (camelCase).\n * When set, disables streaming and returns a validated JSON response\n * conforming to the specified schema.\n */\n structuredOutput?: StructuredOutputConfig;\n /**\n * Structured output configuration (snake_case - database/API format).\n * Alternative to structuredOutput for compatibility with MongoDB/frontend.\n * Uses an `enabled` flag to control activation.\n * @deprecated Use structuredOutput instead when possible\n */\n structured_output?: StructuredOutputInput;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode, dispatching\n * ON_TOOL_EXECUTE events instead of invoking tools directly.\n */\n toolDefinitions?: LCTool[];\n /**\n * Tool names discovered from previous conversation history.\n * These tools will be pre-marked as discovered so they're included\n * in tool binding without requiring tool_search.\n */\n discoveredTools?: string[];\n /**\n * Optional callback for summarizing messages that were pruned from context.\n * When provided, discarded messages are summarized by the caller (e.g., Ranger)\n * using a cheap LLM call, and the summary is prepended to the context.\n */\n summarizeCallback?: (messagesToRefine: import('@langchain/core/messages').BaseMessage[]) => Promise<string | undefined>;\n}\n"],"names":[],"mappings":"AAiYA;;AAEG;AACG,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AAClC,IAAA,WAAA;AAAnB,IAAA,WAAA,CAAmB,WAAmB,EAAA;AACpC,QAAA,KAAK,CAAC,CAAA,4CAAA,EAA+C,WAAW,CAAA,CAAE,CAAC;QADlD,IAAW,CAAA,WAAA,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;;AAE7C;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAiD,8CAAA,EAAA,UAAU,CAAK,GAAA,CAAA;AAChE,YAAA,CAAA,oEAAA,CAAsE,CACvE;QAJgB,IAAU,CAAA,UAAA,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;;AAE/C;;;;"}
@@ -23,6 +23,8 @@ export declare enum GraphEvents {
23
23
  ON_STRUCTURED_OUTPUT = "on_structured_output",
24
24
  /** [Custom] Request to execute tools - dispatched by ToolNode, handled by host */
25
25
  ON_TOOL_EXECUTE = "on_tool_execute",
26
+ /** [Custom] Tool requires human approval before execution - dispatched by ToolNode HITL */
27
+ ON_TOOL_APPROVAL_REQUIRED = "on_tool_approval_required",
26
28
  /** Custom event, emitted by system */
27
29
  ON_CUSTOM_EVENT = "on_custom_event",
28
30
  /** Emitted when a chat model starts processing. */
@@ -24,7 +24,9 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
24
24
  private toolDefinitions?;
25
25
  /** Agent ID for event-driven mode */
26
26
  private agentId?;
27
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, toolDefinitions, agentId, }: t.ToolNodeConstructorParams);
27
+ /** HITL tool approval configuration */
28
+ private toolApprovalConfig?;
29
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, toolDefinitions, agentId, toolApprovalConfig, }: t.ToolNodeConstructorParams);
28
30
  /**
29
31
  * Returns cached programmatic tools, computing once on first access.
30
32
  * Single iteration builds both toolMap and toolDefs simultaneously.
@@ -35,6 +37,25 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
35
37
  * @returns A ReadonlyMap where keys are tool names and values are their usage counts.
36
38
  */
37
39
  getToolUsageCounts(): ReadonlyMap<string, number>;
40
+ /**
41
+ * Evaluates whether a tool call requires human approval.
42
+ * Returns true if approval is needed, false otherwise.
43
+ * Does NOT perform the actual approval flow - that's handled by requestApproval().
44
+ */
45
+ private requiresApproval;
46
+ /**
47
+ * Requests human approval for a tool call via event dispatch.
48
+ * Dispatches an ON_TOOL_APPROVAL_REQUIRED event and waits for the host
49
+ * to resolve the promise with an approval response.
50
+ *
51
+ * This uses the same pattern as ON_TOOL_EXECUTE: a promise-based event
52
+ * dispatch where the host calls resolve/reject when the human responds.
53
+ *
54
+ * @param call - The tool call requiring approval
55
+ * @param config - The runnable config for event dispatch
56
+ * @returns The approval response from the human
57
+ */
58
+ private requestApproval;
38
59
  /**
39
60
  * Runs a single tool call with error handling
40
61
  */
@@ -4,7 +4,7 @@ import type { BaseMessage, AIMessageChunk, SystemMessage } from '@langchain/core
4
4
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
5
5
  import type { ChatGenerationChunk } from '@langchain/core/outputs';
6
6
  import type { GoogleAIToolType } from '@langchain/google-common';
7
- import type { ToolMap, ToolEndEvent, GenericTool, LCTool } from '@/types/tools';
7
+ import type { ToolMap, ToolEndEvent, GenericTool, LCTool, ToolApprovalConfig } from '@/types/tools';
8
8
  import type { Providers, Callback, GraphNodeKeys } from '@/common';
9
9
  import type { StandardGraph, MultiAgentGraph } from '@/graphs';
10
10
  import type { ClientOptions } from '@/types/llm';
@@ -88,6 +88,13 @@ export type CompileOptions = {
88
88
  checkpointer?: any;
89
89
  interruptBefore?: string[];
90
90
  interruptAfter?: string[];
91
+ /**
92
+ * Human-in-the-loop tool approval configuration.
93
+ * When set, tools matching the policy will trigger an interrupt()
94
+ * before execution, pausing the graph for human approval.
95
+ * Requires a checkpointer to be set for interrupt/resume to work.
96
+ */
97
+ toolApprovalConfig?: ToolApprovalConfig;
91
98
  };
92
99
  export type EventStreamCallbackHandlerInput = Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<infer T, 'autoClose'> ? T : never;
93
100
  export type StreamChunk = (ChatGenerationChunk & {
@@ -37,6 +37,11 @@ export type ToolNodeOptions = {
37
37
  toolDefinitions?: Map<string, LCTool>;
38
38
  /** Agent ID for event-driven mode (used to identify which agent's context to use) */
39
39
  agentId?: string;
40
+ /**
41
+ * HITL tool approval configuration.
42
+ * When provided, tools matching the policy will call interrupt() before execution.
43
+ */
44
+ toolApprovalConfig?: ToolApprovalConfig;
40
45
  };
41
46
  export type ToolNodeConstructorParams = ToolRefs & ToolNodeOptions;
42
47
  export type ToolEndEvent = {
@@ -158,6 +163,88 @@ export type ProgrammaticCache = {
158
163
  toolMap: ToolMap;
159
164
  toolDefs: LCTool[];
160
165
  };
166
+ /**
167
+ * Execution context determines whether HITL approval is required.
168
+ * - 'interactive': User is present in the chat, approval prompts are shown.
169
+ * - 'scheduled': Automated/scheduled execution, approval is auto-granted.
170
+ */
171
+ export type ExecutionContext = 'interactive' | 'scheduled';
172
+ /**
173
+ * Policy for when a tool requires human approval.
174
+ * - 'always': Always require approval (default for interactive context).
175
+ * - 'never': Never require approval (used for safe read-only tools).
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").
179
+ */
180
+ export type ToolApprovalRule = 'always' | 'never' | ((toolName: string, args: Record<string, unknown>) => boolean);
181
+ /**
182
+ * Per-tool approval overrides. Keys are tool names (or glob patterns).
183
+ * When a tool is not listed, it falls back to the default policy.
184
+ */
185
+ export type ToolApprovalOverrides = Record<string, ToolApprovalRule>;
186
+ /**
187
+ * Configuration for the HITL approval system.
188
+ * Passed via CompileOptions or graph config metadata.
189
+ */
190
+ export type ToolApprovalConfig = {
191
+ /**
192
+ * Default policy for all tools when no override matches.
193
+ * @default 'always' for interactive, 'never' for scheduled
194
+ */
195
+ defaultPolicy?: ToolApprovalRule;
196
+ /**
197
+ * Per-tool overrides. Keys are tool names.
198
+ * Example: { 'search': 'never', 'outlook_operations': 'always' }
199
+ */
200
+ overrides?: ToolApprovalOverrides;
201
+ /**
202
+ * Execution context. When 'scheduled', all approvals are auto-granted.
203
+ * @default 'interactive'
204
+ */
205
+ executionContext?: ExecutionContext;
206
+ };
207
+ /**
208
+ * The interrupt payload sent to the host when a tool requires approval.
209
+ * This is the value passed to LangGraph's interrupt() function.
210
+ */
211
+ export type ToolApprovalRequest = {
212
+ /** Discriminator for the interrupt type */
213
+ type: 'tool_approval_required';
214
+ /** Tool call ID from the LLM */
215
+ toolCallId: string;
216
+ /** Tool name */
217
+ toolName: string;
218
+ /** Tool arguments the LLM wants to execute */
219
+ toolArgs: Record<string, unknown>;
220
+ /** Agent ID that requested the tool call */
221
+ agentId?: string;
222
+ /** Human-readable description of what the tool will do */
223
+ description?: string;
224
+ };
225
+ /**
226
+ * The response from the host after human review.
227
+ * This is the resume value passed via Command({ resume: ... }).
228
+ */
229
+ export type ToolApprovalResponse = {
230
+ /** Whether the tool call was approved */
231
+ approved: boolean;
232
+ /** Optional feedback from the human (e.g., reason for denial) */
233
+ feedback?: string;
234
+ /** Optional modified args (if the human edited the tool call) */
235
+ modifiedArgs?: Record<string, unknown>;
236
+ };
237
+ /**
238
+ * Event payload dispatched via ON_TOOL_APPROVAL_REQUIRED.
239
+ * Extends ToolApprovalRequest with promise resolve/reject for async flow.
240
+ * The host handles the event by showing UI and calling resolve/reject.
241
+ */
242
+ export type ToolApprovalEvent = ToolApprovalRequest & {
243
+ /** Promise resolver - host calls this with the approval response */
244
+ resolve: (response: ToolApprovalResponse) => void;
245
+ /** Promise rejector - host calls this on fatal error */
246
+ reject: (error: Error) => void;
247
+ };
161
248
  /** Search mode: code_interpreter uses external sandbox, local uses safe substring matching */
162
249
  export type ToolSearchMode = 'code_interpreter' | 'local';
163
250
  /** Parameters for creating a Tool Search tool */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@illuma-ai/agents",
3
- "version": "1.0.83",
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",
@@ -15,8 +15,12 @@
15
15
  "description": "Illuma AI Agents Library",
16
16
  "repository": {
17
17
  "type": "git",
18
- "url": "https://github.com/team-illuma/agents"
18
+ "url": "https://github.com/illuma-ai/agents"
19
19
  },
20
+ "bugs": {
21
+ "url": "https://github.com/illuma-ai/agents/issues"
22
+ },
23
+ "homepage": "https://github.com/illuma-ai/agents#readme",
20
24
  "author": "Illuma Team",
21
25
  "license": "UNLICENSED",
22
26
  "publishConfig": {