@illuma-ai/agents 1.1.19 → 1.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +87 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +14 -0
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +3 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/nodes/ApprovalGateNode.cjs +75 -0
- package/dist/cjs/nodes/ApprovalGateNode.cjs.map +1 -0
- package/dist/cjs/run.cjs +45 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +21 -18
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs +6 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +87 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +14 -0
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/nodes/ApprovalGateNode.mjs +72 -0
- package/dist/esm/nodes/ApprovalGateNode.mjs.map +1 -0
- package/dist/esm/run.mjs +45 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +22 -19
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/esm/utils/run.mjs +6 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/nodes/ApprovalGateNode.d.ts +49 -0
- package/dist/types/nodes/index.d.ts +2 -0
- package/dist/types/run.d.ts +25 -1
- package/dist/types/tools/ToolNode.d.ts +7 -5
- package/dist/types/types/graph.d.ts +31 -0
- package/dist/types/types/tools.d.ts +7 -9
- package/package.json +1 -1
- package/src/common/enum.ts +2 -0
- package/src/graphs/MultiAgentGraph.ts +108 -1
- package/src/index.ts +3 -0
- package/src/llm/bedrock/index.ts +17 -0
- package/src/nodes/ApprovalGateNode.ts +117 -0
- package/src/nodes/__tests__/ApprovalGateNode.test.ts +206 -0
- package/src/nodes/index.ts +5 -0
- package/src/run.ts +55 -1
- package/src/specs/agent-handoffs-bedrock.integration.test.ts +2 -2
- package/src/specs/agent-handoffs.test.ts +153 -6
- package/src/tools/ToolNode.ts +28 -23
- package/src/tools/__tests__/ToolApproval.test.ts +162 -325
- package/src/types/graph.ts +32 -0
- package/src/types/tools.ts +7 -9
- package/src/utils/run.ts +9 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { ExecutionContext } from './approval/constants';\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 != null && 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 /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\n /** Buffer for recovering truncated tool call arguments from streaming data */\n private streamingToolCallBuffer?: import('@/tools/StreamingToolCallBuffer').StreamingToolCallBuffer;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n streamingToolCallBuffer,\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.agentId = agentId;\n this.directToolNames = directToolNames;\n this.streamingToolCallBuffer = streamingToolCallBuffer;\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(\n toolName: string,\n args: Record<string, unknown>\n ): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const {\n defaultPolicy,\n overrides,\n executionContext,\n agentExecutionContextOverrides,\n } = this.toolApprovalConfig;\n\n // Resolve the effective execution context for this agent.\n // Per-agent overrides take precedence — allows handoff agents to bypass HITL\n // while the primary agent retains interactive approval.\n const effectiveContext = (\n this.agentId && agentExecutionContextOverrides?.[this.agentId]\n ) ?? executionContext;\n\n // Scheduled executions bypass all approval checks — no user is present\n if (effectiveContext === ExecutionContext.SCHEDULED) {\n return false;\n }\n\n // Handoff/delegate/workflow agents bypass HITL approval — these agents run\n // autonomously as part of a multi-agent pipeline. Blocking on user approval\n // would stall the entire graph since all agents share the same SSE stream.\n // The primary (user-facing) agent retains HITL; only delegated agents skip it.\n if (effectiveContext === ExecutionContext.HANDOFF) {\n return false;\n }\n\n // Graph-managed tools (handoff/transfer tools) bypass HITL approval —\n // these are internal routing mechanisms, not user-facing tool executions\n if (this.directToolNames?.has(toolName)) {\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 if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, turn);\n }\n let args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Recover truncated tool call arguments from the streaming buffer.\n // When max_tokens truncates a tool call mid-JSON, parsePartialJson may lose\n // content that was already streamed to the UI. The buffer has the raw accumulated\n // arg string, so we can extract field values that were dropped.\n if (call.id && this.streamingToolCallBuffer?.has(call.id)) {\n args = this.recoverTruncatedArgs(call.name, call.id, args);\n this.streamingToolCallBuffer.clear(call.id);\n }\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession != null && 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 (\n this.requiresApproval(call.name, call.args as Record<string, unknown>)\n ) {\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 != null && 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 = {\n ...invokeParams,\n args: approvalResponse.modifiedArgs,\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 // Skip TOON for content_tool — its output is line-numbered source code.\n // TOON corrupts embedded JSON in source files, causing edit (str_replace) failures\n // because the agent sees TOON-transformed content but strReplace matches original.\n const isContentTool = call.name === 'content_tool';\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: !isContentTool,\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 * Recover truncated tool call arguments using the raw streaming buffer.\n *\n * When parsePartialJson drops content (e.g., a large \"content\" field truncated\n * at max_tokens), this method extracts the field value from the raw accumulated\n * arg string and merges it back into the parsed args object.\n *\n * This is generic — it checks ALL string fields in the raw buffer, not just\n * content_tool fields. Any tool with a truncated string value benefits.\n */\n /**\n * Recover truncated tool call arguments using the raw streaming buffer.\n *\n * Strategy:\n * 1. If args are completely empty → try parsePartialJson on the raw buffer\n * 2. Otherwise → field-level recovery: extract missing fields from raw buffer\n *\n * @param toolName - Tool name (for logging)\n * @param toolCallId - The tool call ID\n * @param args - The parsed args (potentially incomplete from parsePartialJson)\n * @returns The args with recovered fields merged in\n */\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n private recoverTruncatedArgs(\n toolName: string,\n toolCallId: string,\n args: any\n ): any {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n if (!this.streamingToolCallBuffer) return args;\n\n const rawArgs = this.streamingToolCallBuffer.getRawArgs(toolCallId);\n if (!rawArgs) return args;\n\n const rawLen = rawArgs.length;\n\n // If args is completely empty (JSON parsing aborted before any key),\n // attempt to parse the raw accumulated string\n if (\n args == null ||\n (typeof args === 'object' && Object.keys(args).length === 0)\n ) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { parsePartialJson } = require('@langchain/core/utils/json');\n const recovered = parsePartialJson(rawArgs);\n if (\n recovered != null &&\n typeof recovered === 'object' &&\n Object.keys(recovered).length > 0\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +\n `parsedFields=[], recoveredFields=[${Object.keys(recovered).join(',')}] (full parse)`\n );\n return recovered;\n }\n } catch {\n // parsePartialJson failed — fall through to field-level extraction\n }\n }\n\n // Field-level recovery: extract missing fields from the raw buffer\n const parsedArgs = typeof args === 'object' ? { ...args } : {};\n const recoveredFields: string[] = [];\n\n // Extract field names from the raw JSON string\n const fieldPattern = /\"([^\"]+)\"\\s*:/g;\n let match;\n const rawFieldNames: string[] = [];\n while ((match = fieldPattern.exec(rawArgs)) !== null) {\n rawFieldNames.push(match[1]);\n }\n\n for (const fieldName of rawFieldNames) {\n if (\n parsedArgs[fieldName] == null ||\n parsedArgs[fieldName] === '' ||\n parsedArgs[fieldName] === undefined\n ) {\n const rawValue = this.streamingToolCallBuffer.extractFieldValue(\n toolCallId,\n fieldName\n );\n if (rawValue != null && rawValue !== '') {\n parsedArgs[fieldName] = rawValue;\n recoveredFields.push(fieldName);\n }\n }\n }\n\n if (recoveredFields.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(\n `[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +\n `parsedFields=[${Object.keys(args ?? {}).join(',')}], recoveredFields=[${recoveredFields.join(',')}]`\n );\n }\n\n return parsedArgs;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requests: t.ToolCallRequest[]\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requests.find((r) => r.id === result.toolCallId);\n if (\n request?.name !== Constants.EXECUTE_CODE &&\n request?.name !== Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n const newFiles = artifact.files ?? [];\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n // Store code session context from tool results\n if (\n this.sessions &&\n (call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING)\n ) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n const newFiles = artifact.files ?? [];\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof call.args === 'string'\n ? (call.args as string)\n : JSON.stringify((call.args as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig\n ): Promise<ToolMessage[]> {\n // ========================================================================\n // HITL: Check approval for event-dispatched tools (browser, MCP, etc.)\n // before dispatching. Denied tools return denial messages immediately.\n // ========================================================================\n const approvedCalls: ToolCall[] = [];\n const denialMessages: ToolMessage[] = [];\n\n for (const call of toolCalls) {\n if (\n this.requiresApproval(call.name, call.args as Record<string, unknown>)\n ) {\n const approvalResponse = await this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n denialMessages.push(\n new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback != null && 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 continue;\n }\n // Use modified args if provided\n if (approvalResponse.modifiedArgs) {\n call.args = approvalResponse.modifiedArgs;\n }\n }\n approvedCalls.push(call);\n }\n\n // If all tools were denied, return denial messages without dispatching\n if (approvedCalls.length === 0) {\n return denialMessages;\n }\n\n const requests: t.ToolCallRequest[] = approvedCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n\n // Recover truncated args from streaming buffer (same as runTool path)\n let args = call.args as Record<string, unknown>;\n if (call.id && this.streamingToolCallBuffer?.has(call.id)) {\n args = this.recoverTruncatedArgs(call.name, call.id, args) as Record<\n string,\n unknown\n >;\n this.streamingToolCallBuffer.clear(call.id);\n }\n\n const request: t.ToolCallRequest = {\n id: call.id!,\n name: call.name,\n args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n this.storeCodeSessionFromResults(results, requests);\n\n const eventMessages = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${result.toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n 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 [...denialMessages, ...eventMessages];\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const outputs = await this.dispatchToolEvents(toolCalls, config);\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n this.handleRunToolCompletions([input.lg_tool_call], outputs, config);\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n const directCalls = filteredCalls.filter((c) =>\n this.directToolNames!.has(c.name)\n );\n const eventCalls = filteredCalls.filter(\n (c) => !this.directToolNames!.has(c.name)\n );\n\n // Run direct tools and event tools in parallel — they are independent\n const [directOutputs, eventOutputs] = (await Promise.all([\n directCalls.length > 0\n ? Promise.all(directCalls.map((call) => this.runTool(call, config)))\n : [],\n eventCalls.length > 0\n ? this.dispatchToolEvents(eventCalls, config)\n : [],\n ])) as [(BaseMessage | Command)[], ToolMessage[]];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(directCalls, directOutputs, config);\n }\n\n outputs = [...directOutputs, ...eventOutputs];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n this.handleRunToolCompletions(filteredCalls, outputs, config);\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":["Send","RunnableCallable","ExecutionContext","safeDispatchCustomEvent","GraphEvents","Constants","ToolMessage","isCommand","isBaseMessage","processToolOutput","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;;AA2BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAA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ent":["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 interrupt,\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 { ExecutionContext } from './approval/constants';\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 != null && 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 /** Maps toolCallId → turn captured in runTool, used by handleRunToolCompletions */\n private toolCallTurns: Map<string, number> = new Map();\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n /** Tool names that bypass event dispatch and execute directly (e.g., graph-managed handoff tools) */\n private directToolNames?: Set<string>;\n /** HITL tool approval configuration */\n private toolApprovalConfig?: t.ToolApprovalConfig;\n /** Buffer for recovering truncated tool call arguments from streaming data */\n private streamingToolCallBuffer?: import('@/tools/StreamingToolCallBuffer').StreamingToolCallBuffer;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n agentId,\n directToolNames,\n streamingToolCallBuffer,\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.agentId = agentId;\n this.directToolNames = directToolNames;\n this.streamingToolCallBuffer = streamingToolCallBuffer;\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(\n toolName: string,\n args: Record<string, unknown>\n ): boolean {\n if (!this.toolApprovalConfig) {\n return false;\n }\n\n const {\n defaultPolicy,\n overrides,\n executionContext,\n agentExecutionContextOverrides,\n } = this.toolApprovalConfig;\n\n // Resolve the effective execution context for this agent.\n // Per-agent overrides take precedence — allows handoff agents to bypass HITL\n // while the primary agent retains interactive approval.\n const effectiveContext = (\n this.agentId && agentExecutionContextOverrides?.[this.agentId]\n ) ?? executionContext;\n\n // Scheduled executions bypass all approval checks — no user is present\n if (effectiveContext === ExecutionContext.SCHEDULED) {\n return false;\n }\n\n // Handoff/delegate/workflow agents bypass HITL approval — these agents run\n // autonomously as part of a multi-agent pipeline. Blocking on user approval\n // would stall the entire graph since all agents share the same SSE stream.\n // The primary (user-facing) agent retains HITL; only delegated agents skip it.\n if (effectiveContext === ExecutionContext.HANDOFF) {\n return false;\n }\n\n // Graph-managed tools (handoff/transfer tools) bypass HITL approval —\n // these are internal routing mechanisms, not user-facing tool executions\n if (this.directToolNames?.has(toolName)) {\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 using LangGraph's native interrupt().\n *\n * Flow:\n * 1. Dispatches ON_TOOL_APPROVAL_REQUIRED notification (no resolve/reject — data only)\n * so the host can persist the request and send UI events.\n * 2. Calls interrupt() which checkpoints graph state and pauses execution.\n * 3. When the host resumes via Command({ resume: ToolApprovalResponse }),\n * interrupt() returns the response synchronously.\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 requestApproval(\n call: ToolCall,\n config: RunnableConfig\n ): 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 // Notify host before interrupting — allows SSE event emission and DB persistence.\n // This is a fire-and-forget notification, NOT the approval mechanism.\n safeDispatchCustomEvent(\n GraphEvents.ON_TOOL_APPROVAL_REQUIRED,\n approvalRequest,\n config\n );\n\n // interrupt() throws GraphInterrupt on first call (checkpoints state),\n // returns the resume value on re-execution after Command({ resume }).\n const response = interrupt(approvalRequest) as t.ToolApprovalResponse;\n return response;\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n if (call.id != null && call.id !== '') {\n this.toolCallTurns.set(call.id, turn);\n }\n let args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Recover truncated tool call arguments from the streaming buffer.\n // When max_tokens truncates a tool call mid-JSON, parsePartialJson may lose\n // content that was already streamed to the UI. The buffer has the raw accumulated\n // arg string, so we can extract field values that were dropped.\n if (call.id && this.streamingToolCallBuffer?.has(call.id)) {\n args = this.recoverTruncatedArgs(call.name, call.id, args);\n this.streamingToolCallBuffer.clear(call.id);\n }\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n *\n * session_id is always injected when available (even without tracked files)\n * so the CodeExecutor can fall back to the /files endpoint for session continuity.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession != null && 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 LangGraph interrupt() — checkpoints state and pauses the graph.\n // Resumes when host sends Command({ resume: ToolApprovalResponse }).\n // ========================================================================\n if (\n this.requiresApproval(call.name, call.args as Record<string, unknown>)\n ) {\n const approvalResponse = 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 != null && 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 = {\n ...invokeParams,\n args: approvalResponse.modifiedArgs,\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 // Skip TOON for content_tool — its output is line-numbered source code.\n // TOON corrupts embedded JSON in source files, causing edit (str_replace) failures\n // because the agent sees TOON-transformed content but strReplace matches original.\n const isContentTool = call.name === 'content_tool';\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: !isContentTool,\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 * Recover truncated tool call arguments using the raw streaming buffer.\n *\n * When parsePartialJson drops content (e.g., a large \"content\" field truncated\n * at max_tokens), this method extracts the field value from the raw accumulated\n * arg string and merges it back into the parsed args object.\n *\n * This is generic — it checks ALL string fields in the raw buffer, not just\n * content_tool fields. Any tool with a truncated string value benefits.\n */\n /**\n * Recover truncated tool call arguments using the raw streaming buffer.\n *\n * Strategy:\n * 1. If args are completely empty → try parsePartialJson on the raw buffer\n * 2. Otherwise → field-level recovery: extract missing fields from raw buffer\n *\n * @param toolName - Tool name (for logging)\n * @param toolCallId - The tool call ID\n * @param args - The parsed args (potentially incomplete from parsePartialJson)\n * @returns The args with recovered fields merged in\n */\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n private recoverTruncatedArgs(\n toolName: string,\n toolCallId: string,\n args: any\n ): any {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n if (!this.streamingToolCallBuffer) return args;\n\n const rawArgs = this.streamingToolCallBuffer.getRawArgs(toolCallId);\n if (!rawArgs) return args;\n\n const rawLen = rawArgs.length;\n\n // If args is completely empty (JSON parsing aborted before any key),\n // attempt to parse the raw accumulated string\n if (\n args == null ||\n (typeof args === 'object' && Object.keys(args).length === 0)\n ) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { parsePartialJson } = require('@langchain/core/utils/json');\n const recovered = parsePartialJson(rawArgs);\n if (\n recovered != null &&\n typeof recovered === 'object' &&\n Object.keys(recovered).length > 0\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +\n `parsedFields=[], recoveredFields=[${Object.keys(recovered).join(',')}] (full parse)`\n );\n return recovered;\n }\n } catch {\n // parsePartialJson failed — fall through to field-level extraction\n }\n }\n\n // Field-level recovery: extract missing fields from the raw buffer\n const parsedArgs = typeof args === 'object' ? { ...args } : {};\n const recoveredFields: string[] = [];\n\n // Extract field names from the raw JSON string\n const fieldPattern = /\"([^\"]+)\"\\s*:/g;\n let match;\n const rawFieldNames: string[] = [];\n while ((match = fieldPattern.exec(rawArgs)) !== null) {\n rawFieldNames.push(match[1]);\n }\n\n for (const fieldName of rawFieldNames) {\n if (\n parsedArgs[fieldName] == null ||\n parsedArgs[fieldName] === '' ||\n parsedArgs[fieldName] === undefined\n ) {\n const rawValue = this.streamingToolCallBuffer.extractFieldValue(\n toolCallId,\n fieldName\n );\n if (rawValue != null && rawValue !== '') {\n parsedArgs[fieldName] = rawValue;\n recoveredFields.push(fieldName);\n }\n }\n }\n\n if (recoveredFields.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(\n `[TruncationRecovery] Tool=${toolName}, callId=${toolCallId}, rawBufferLen=${rawLen}, ` +\n `parsedFields=[${Object.keys(args ?? {}).join(',')}], recoveredFields=[${recoveredFields.join(',')}]`\n );\n }\n\n return parsedArgs;\n }\n\n /**\n * Builds code session context for injection into event-driven tool calls.\n * Mirrors the session injection logic in runTool() for direct execution.\n */\n private getCodeSessionContext(): t.ToolCallRequest['codeSessionContext'] {\n if (!this.sessions) {\n return undefined;\n }\n\n const codeSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (!codeSession) {\n return undefined;\n }\n\n const context: NonNullable<t.ToolCallRequest['codeSessionContext']> = {\n session_id: codeSession.session_id,\n };\n\n if (codeSession.files && codeSession.files.length > 0) {\n context.files = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n }\n\n return context;\n }\n\n /**\n * Extracts code execution session context from tool results and stores in Graph.sessions.\n * Mirrors the session storage logic in handleRunToolCompletions for direct execution.\n */\n private storeCodeSessionFromResults(\n results: t.ToolExecuteResult[],\n requests: t.ToolCallRequest[]\n ): void {\n if (!this.sessions) {\n return;\n }\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status !== 'success' || result.artifact == null) {\n continue;\n }\n\n const request = requests.find((r) => r.id === result.toolCallId);\n if (\n request?.name !== Constants.EXECUTE_CODE &&\n request?.name !== Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n continue;\n }\n\n const artifact = result.artifact as t.CodeExecutionArtifact | undefined;\n if (artifact?.session_id == null || artifact.session_id === '') {\n continue;\n }\n\n const newFiles = artifact.files ?? [];\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n }\n }\n\n /**\n * Post-processes standard runTool outputs: dispatches ON_RUN_STEP_COMPLETED\n * and stores code session context. Mirrors the completion handling in\n * dispatchToolEvents for the event-driven path.\n *\n * By handling completions here in graph context (rather than in the\n * stream consumer via ToolEndHandler), the race between the stream\n * consumer and graph execution is eliminated.\n */\n private handleRunToolCompletions(\n calls: ToolCall[],\n outputs: (BaseMessage | Command)[],\n config: RunnableConfig\n ): void {\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n const output = outputs[i];\n const turn = this.toolCallTurns.get(call.id!) ?? 0;\n\n if (isCommand(output)) {\n continue;\n }\n\n const toolMessage = output as ToolMessage;\n const toolCallId = call.id ?? '';\n\n // Skip error ToolMessages when errorHandler already dispatched ON_RUN_STEP_COMPLETED\n // via handleToolCallErrorStatic. Without this check, errors would be double-dispatched.\n if (toolMessage.status === 'error' && this.errorHandler != null) {\n continue;\n }\n\n // Store code session context from tool results\n if (\n this.sessions &&\n (call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING)\n ) {\n const artifact = toolMessage.artifact as\n | t.CodeExecutionArtifact\n | undefined;\n if (artifact?.session_id != null && artifact.session_id !== '') {\n const newFiles = artifact.files ?? [];\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n if (newFiles.length > 0) {\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n } else {\n this.sessions.set(Constants.EXECUTE_CODE, {\n session_id: artifact.session_id,\n files: existingFiles,\n lastUpdated: Date.now(),\n });\n }\n }\n }\n\n // Dispatch ON_RUN_STEP_COMPLETED via custom event (same path as dispatchToolEvents)\n const stepId = this.toolCallStepIds?.get(toolCallId) ?? '';\n if (!stepId) {\n continue;\n }\n\n const contentString =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof call.args === 'string'\n ? (call.args as string)\n : JSON.stringify((call.args as unknown) ?? {}),\n name: call.name,\n id: toolCallId,\n output: contentString,\n progress: 1,\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: turn,\n type: 'tool_call' as const,\n tool_call,\n },\n },\n config\n );\n }\n }\n\n /**\n * Dispatches tool calls to the host via ON_TOOL_EXECUTE event and returns raw ToolMessages.\n * Core logic for event-driven execution, separated from output shaping.\n */\n private async dispatchToolEvents(\n toolCalls: ToolCall[],\n config: RunnableConfig\n ): Promise<ToolMessage[]> {\n // ========================================================================\n // HITL: Check approval for event-dispatched tools (browser, MCP, etc.)\n // before dispatching. Uses LangGraph interrupt() for each tool needing\n // approval — counter-based matching handles sequential interrupts.\n // ========================================================================\n const approvedCalls: ToolCall[] = [];\n const denialMessages: ToolMessage[] = [];\n\n for (const call of toolCalls) {\n if (\n this.requiresApproval(call.name, call.args as Record<string, unknown>)\n ) {\n const approvalResponse = this.requestApproval(call, config);\n if (!approvalResponse.approved) {\n denialMessages.push(\n new ToolMessage({\n status: 'error',\n content: `Tool call \"${call.name}\" was denied by the user.${approvalResponse.feedback != null && 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 continue;\n }\n // Use modified args if provided\n if (approvalResponse.modifiedArgs) {\n call.args = approvalResponse.modifiedArgs;\n }\n }\n approvedCalls.push(call);\n }\n\n // If all tools were denied, return denial messages without dispatching\n if (approvedCalls.length === 0) {\n return denialMessages;\n }\n\n const requests: t.ToolCallRequest[] = approvedCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n\n // Recover truncated args from streaming buffer (same as runTool path)\n let args = call.args as Record<string, unknown>;\n if (call.id && this.streamingToolCallBuffer?.has(call.id)) {\n args = this.recoverTruncatedArgs(call.name, call.id, args) as Record<\n string,\n unknown\n >;\n this.streamingToolCallBuffer.clear(call.id);\n }\n\n const request: t.ToolCallRequest = {\n id: call.id!,\n name: call.name,\n args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n request.codeSessionContext = this.getCodeSessionContext();\n }\n\n return request;\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n this.storeCodeSessionFromResults(results, requests);\n\n const eventMessages = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n if (!stepId) {\n // eslint-disable-next-line no-console\n console.warn(\n `[ToolNode] toolCallStepIds missing entry for toolCallId=${result.toolCallId} (tool=${toolName}). ` +\n 'This indicates a race between the stream consumer and graph execution. ' +\n `Map size: ${this.toolCallStepIds?.size ?? 0}`\n );\n }\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n 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 [...denialMessages, ...eventMessages];\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const outputs = await this.dispatchToolEvents(toolCalls, config);\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n this.toolCallTurns.clear();\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n const isDirectTool = this.directToolNames?.has(input.lg_tool_call.name);\n if (this.eventDrivenMode && isDirectTool !== true) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n this.handleRunToolCompletions([input.lg_tool_call], outputs, config);\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n if (!this.directToolNames || this.directToolNames.size === 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n const directCalls = filteredCalls.filter((c) =>\n this.directToolNames!.has(c.name)\n );\n const eventCalls = filteredCalls.filter(\n (c) => !this.directToolNames!.has(c.name)\n );\n\n // Run direct tools and event tools in parallel — they are independent\n const [directOutputs, eventOutputs] = (await Promise.all([\n directCalls.length > 0\n ? Promise.all(directCalls.map((call) => this.runTool(call, config)))\n : [],\n eventCalls.length > 0\n ? this.dispatchToolEvents(eventCalls, config)\n : [],\n ])) as [(BaseMessage | Command)[], ToolMessage[]];\n\n if (directCalls.length > 0 && directOutputs.length > 0) {\n this.handleRunToolCompletions(directCalls, directOutputs, config);\n }\n\n outputs = [...directOutputs, ...eventOutputs];\n } else {\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n this.handleRunToolCompletions(filteredCalls, outputs, config);\n }\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":["Send","RunnableCallable","ExecutionContext","safeDispatchCustomEvent","GraphEvents","interrupt","Constants","ToolMessage","isCommand","isBaseMessage","processToolOutput","isGraphInterrupt","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;;AA4BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;IAChB;;AAGA,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;YACvB;iBAAO,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;;gBAErD,MAAM,GAAG,GAAG,KAAgC;AAC5C,gBAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;AACvD,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;gBAC1B;A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AG,CAAC,QAAQ,CAAC,EAAE,CAAC,CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ;IAC9D,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAA0B;AAEtE,IAAA,IACE,OAAO;AACP,QAAA,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;IACjB;AACA,IAAA,OAAOM,aAAG;AACZ;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.cjs","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 {\n ToolMap,\n ToolEndEvent,\n GenericTool,\n LCTool,\n ToolApprovalConfig,\n} 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\n/** Payload for ON_AGENT_TRANSITION events */\nexport type AgentTransitionEvent = {\n sourceAgentId?: string;\n sourceAgentName?: string;\n destinationAgentId: string;\n destinationAgentName: string;\n edgeType: string; // 'handoff' | 'transfer' | 'sequence'\n timestamp: number;\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 /**\n * EdgeType.HANDOFF — true agent handoff, parent calls child inline and gets result back.\n * EdgeType.TRANSFER — one-way transfer, parent exits and child takes over.\n * EdgeType.SEQUENCE — fixed graph edges for sequential/parallel transitions.\n */\n edgeType?: import('@/common').EdgeType;\n /**\n * For sequence 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 transfer edges: Description for the input parameter that the transfer 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 transfer edges: Customizes the parameter name for the transfer input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for transfer edges.\n *\n * For handoff edges: Customizes the parameter name for the handoff instruction input.\n */\n promptKey?: string;\n /**\n * For handoff edges: Maximum characters for the result returned to the parent.\n * Uses head/tail truncation (60/40 split) to preserve key findings and conclusions.\n * Defaults to DEFAULT_HANDOFF_MAX_RESULT_CHARS (32768 chars, ~8192 tokens).\n */\n maxResultChars?: number;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n /**\n * When set, the graph routes START to this agent instead of the default starting nodes.\n * Used for multi-turn resumption: the caller reads `lastActiveAgentId` from the\n * previous turn's metadata and passes it here so follow-up messages route to the\n * agent that last handled the conversation.\n *\n * If the agent ID is invalid (not in the graph), falls back to default starting nodes.\n */\n resumeFromAgentId?: string;\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 =\n | 'functionCalling'\n | 'jsonMode'\n | 'jsonSchema'\n | 'native'\n | 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\n/**\n * Trigger strategy for when summarization should activate.\n * - 'contextPercentage': Trigger when context utilization exceeds a threshold percentage\n * - 'messageCount': Trigger when pruned message count exceeds a threshold\n * - 'tokenThreshold': Trigger when total token count exceeds a raw threshold\n */\nexport type SummarizationTriggerType =\n | 'contextPercentage'\n | 'messageCount'\n | 'tokenThreshold';\n\n/**\n * Configuration for summarization behavior within the agent pipeline.\n * All fields are optional — sensible defaults are provided via constants.\n *\n * @see SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, PRUNING_EMA_ALPHA\n */\nexport interface SummarizationConfig {\n /**\n * Strategy for when summarization triggers.\n * @default 'contextPercentage'\n */\n triggerType?: SummarizationTriggerType;\n\n /**\n * Threshold value interpreted based on triggerType:\n * - contextPercentage: 0-100 (percentage of context window)\n * - messageCount: absolute count of messages pruned\n * - tokenThreshold: absolute token count\n * @default 80 (for contextPercentage)\n */\n triggerThreshold?: number;\n\n /**\n * Fraction of context window (0-1) reserved for recent messages.\n * Prevents over-pruning by ensuring at least this fraction of the\n * context budget is preserved as recent conversation history.\n * @default 0.3\n */\n reserveRatio?: number;\n\n /**\n * Whether context pruning is enabled (can be disabled for debugging).\n * @default true\n */\n contextPruning?: boolean;\n\n /**\n * Initial summary text to seed across runs.\n * Different from persistedSummary: this is provided by the caller as a\n * cross-conversation seed (e.g., agent personality or recurring context),\n * while persistedSummary is loaded from the conversation's own history.\n */\n initialSummary?: string;\n}\n\n/**\n * Runtime state for EMA-based pruning calibration.\n * Maintained across iterations within a single run to smooth pruning decisions.\n */\nexport interface PruneCalibrationState {\n /** Current EMA calibration ratio */\n ratio: number;\n /** Number of calibration updates applied */\n iterations: number;\n}\n\n/**\n * Lightweight file metadata entry for conversation-level file awareness.\n * Contains only IDs and names — NOT full content — so the agent always knows\n * what files exist in the conversation even after compaction pushes old messages\n * behind the summary window. The agent can retrieve full content on-demand\n * via file_search (RAG) or content_tool read (by contentId).\n */\nexport interface FileManifestEntry {\n /** Unique file identifier (e.g., MongoDB ObjectId or UUID) */\n fileId: string;\n /** Original filename (e.g., \"quarterly-report.pdf\") */\n filename: string;\n /** Content identifier for on-demand retrieval via content_tool read */\n contentId?: string;\n /** File source (e.g., \"local\", \"sharepoint\", \"onedrive\") */\n source?: string;\n /** Index of the message that introduced this file (0-based in the original message array) */\n messageIndex?: number;\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 /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: 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?: (\n messagesToRefine: import('@langchain/core/messages').BaseMessage[]\n ) => Promise<string | undefined>;\n /**\n * Pre-existing summary text loaded from persistent storage (MongoDB/Redis).\n * When provided, this summary is injected into the initial message context\n * so the agent has prior conversation history even on new turns.\n * Set by Ranger's SummaryStore when resuming a conversation.\n */\n persistedSummary?: string;\n /**\n * Summarization configuration controlling trigger strategy, reserve ratio,\n * and EMA calibration for pruning. When omitted, sensible defaults apply.\n * @see SummarizationConfig\n */\n summarizationConfig?: SummarizationConfig;\n /**\n * Lightweight file manifest for the conversation.\n * Contains file IDs, names, and metadata — NOT full content.\n *\n * Used by the compaction engine to inject a [Conversation Files] block\n * into the windowed view, ensuring the LLM always knows what files exist\n * even when old messages (with full file content) are behind the summary.\n *\n * The agent can retrieve full content on-demand via:\n * - file_search (RAG semantic search over embedded files)\n * - content_tool read (by contentId for exact file retrieval)\n *\n * Built by the orchestrator (e.g., Ranger) from message_file_map\n * and metadata.context_files across all conversation messages.\n */\n fileManifest?: FileManifestEntry[];\n}\n"],"names":[],"mappings":";;AA2aA;;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,IAAA,CAAA,WAAW,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;IAC5C;AACD;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAA,8CAAA,EAAiD,UAAU,CAAA,GAAA,CAAK;AAC9D,YAAA,sEAAsE,CACzE;QAJgB,IAAA,CAAA,UAAU,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;IAC9C;AACD;;;;;"}
|
|
1
|
+
{"version":3,"file":"graph.cjs","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 {\n ToolMap,\n ToolEndEvent,\n GenericTool,\n LCTool,\n ToolApprovalConfig,\n} 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\n/** Payload for ON_AGENT_TRANSITION events */\nexport type AgentTransitionEvent = {\n sourceAgentId?: string;\n sourceAgentName?: string;\n destinationAgentId: string;\n destinationAgentName: string;\n edgeType: string; // 'handoff' | 'transfer' | 'sequence'\n timestamp: number;\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\n/**\n * Configuration for an approval gate placed on a sequence edge.\n * When present, the graph inserts an approval gate node between the source\n * and destination agents. The gate ALWAYS fires (regardless of ExecutionContext)\n * and calls interrupt() to pause the graph for human approval.\n */\nexport type ApprovalGateConfig = {\n /** Unique identifier for this gate (used as node ID suffix) */\n gateId: string;\n /**\n * Approval channel — where the approval UI is rendered.\n * - 'chat': SSE-based chat UI (default)\n * - 'outlook': MS Graph Actionable Messages\n * - 'telegram': Telegram Bot inline keyboard\n */\n channel?: 'chat' | 'outlook' | 'telegram';\n /** Optional human-readable prompt shown to the approver */\n prompt?: string;\n /** Optional approver identifier (e.g., email, user ID) */\n approver?: string;\n /** Timeout in ms before the gate auto-expires (default: 5 minutes) */\n timeoutMs?: number;\n /** What to do on denial: 'stop' ends the graph, 'skip' skips the destination agent */\n onDeny?: 'stop' | 'skip';\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 /**\n * EdgeType.HANDOFF — true agent handoff, parent calls child inline and gets result back.\n * EdgeType.TRANSFER — one-way transfer, parent exits and child takes over.\n * EdgeType.SEQUENCE — fixed graph edges for sequential/parallel transitions.\n */\n edgeType?: import('@/common').EdgeType;\n /**\n * For sequence 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 transfer edges: Description for the input parameter that the transfer 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 transfer edges: Customizes the parameter name for the transfer input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for transfer edges.\n *\n * For handoff edges: Customizes the parameter name for the handoff instruction input.\n */\n promptKey?: string;\n /**\n * For handoff edges: Maximum characters for the result returned to the parent.\n * Uses head/tail truncation (60/40 split) to preserve key findings and conclusions.\n * Defaults to DEFAULT_HANDOFF_MAX_RESULT_CHARS (32768 chars, ~8192 tokens).\n */\n maxResultChars?: number;\n /**\n * Approval gate configuration for sequence edges.\n * When set, inserts an approval gate node between source and destination.\n * The gate ALWAYS fires regardless of ExecutionContext (unlike tool approval).\n */\n approvalGate?: ApprovalGateConfig;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n /**\n * When set, the graph routes START to this agent instead of the default starting nodes.\n * Used for multi-turn resumption: the caller reads `lastActiveAgentId` from the\n * previous turn's metadata and passes it here so follow-up messages route to the\n * agent that last handled the conversation.\n *\n * If the agent ID is invalid (not in the graph), falls back to default starting nodes.\n */\n resumeFromAgentId?: string;\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 =\n | 'functionCalling'\n | 'jsonMode'\n | 'jsonSchema'\n | 'native'\n | 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\n/**\n * Trigger strategy for when summarization should activate.\n * - 'contextPercentage': Trigger when context utilization exceeds a threshold percentage\n * - 'messageCount': Trigger when pruned message count exceeds a threshold\n * - 'tokenThreshold': Trigger when total token count exceeds a raw threshold\n */\nexport type SummarizationTriggerType =\n | 'contextPercentage'\n | 'messageCount'\n | 'tokenThreshold';\n\n/**\n * Configuration for summarization behavior within the agent pipeline.\n * All fields are optional — sensible defaults are provided via constants.\n *\n * @see SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, PRUNING_EMA_ALPHA\n */\nexport interface SummarizationConfig {\n /**\n * Strategy for when summarization triggers.\n * @default 'contextPercentage'\n */\n triggerType?: SummarizationTriggerType;\n\n /**\n * Threshold value interpreted based on triggerType:\n * - contextPercentage: 0-100 (percentage of context window)\n * - messageCount: absolute count of messages pruned\n * - tokenThreshold: absolute token count\n * @default 80 (for contextPercentage)\n */\n triggerThreshold?: number;\n\n /**\n * Fraction of context window (0-1) reserved for recent messages.\n * Prevents over-pruning by ensuring at least this fraction of the\n * context budget is preserved as recent conversation history.\n * @default 0.3\n */\n reserveRatio?: number;\n\n /**\n * Whether context pruning is enabled (can be disabled for debugging).\n * @default true\n */\n contextPruning?: boolean;\n\n /**\n * Initial summary text to seed across runs.\n * Different from persistedSummary: this is provided by the caller as a\n * cross-conversation seed (e.g., agent personality or recurring context),\n * while persistedSummary is loaded from the conversation's own history.\n */\n initialSummary?: string;\n}\n\n/**\n * Runtime state for EMA-based pruning calibration.\n * Maintained across iterations within a single run to smooth pruning decisions.\n */\nexport interface PruneCalibrationState {\n /** Current EMA calibration ratio */\n ratio: number;\n /** Number of calibration updates applied */\n iterations: number;\n}\n\n/**\n * Lightweight file metadata entry for conversation-level file awareness.\n * Contains only IDs and names — NOT full content — so the agent always knows\n * what files exist in the conversation even after compaction pushes old messages\n * behind the summary window. The agent can retrieve full content on-demand\n * via file_search (RAG) or content_tool read (by contentId).\n */\nexport interface FileManifestEntry {\n /** Unique file identifier (e.g., MongoDB ObjectId or UUID) */\n fileId: string;\n /** Original filename (e.g., \"quarterly-report.pdf\") */\n filename: string;\n /** Content identifier for on-demand retrieval via content_tool read */\n contentId?: string;\n /** File source (e.g., \"local\", \"sharepoint\", \"onedrive\") */\n source?: string;\n /** Index of the message that introduced this file (0-based in the original message array) */\n messageIndex?: number;\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 /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: 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?: (\n messagesToRefine: import('@langchain/core/messages').BaseMessage[]\n ) => Promise<string | undefined>;\n /**\n * Pre-existing summary text loaded from persistent storage (MongoDB/Redis).\n * When provided, this summary is injected into the initial message context\n * so the agent has prior conversation history even on new turns.\n * Set by Ranger's SummaryStore when resuming a conversation.\n */\n persistedSummary?: string;\n /**\n * Summarization configuration controlling trigger strategy, reserve ratio,\n * and EMA calibration for pruning. When omitted, sensible defaults apply.\n * @see SummarizationConfig\n */\n summarizationConfig?: SummarizationConfig;\n /**\n * Lightweight file manifest for the conversation.\n * Contains file IDs, names, and metadata — NOT full content.\n *\n * Used by the compaction engine to inject a [Conversation Files] block\n * into the windowed view, ensuring the LLM always knows what files exist\n * even when old messages (with full file content) are behind the summary.\n *\n * The agent can retrieve full content on-demand via:\n * - file_search (RAG semantic search over embedded files)\n * - content_tool read (by contentId for exact file retrieval)\n *\n * Built by the orchestrator (e.g., Ranger) from message_file_map\n * and metadata.context_files across all conversation messages.\n */\n fileManifest?: FileManifestEntry[];\n}\n"],"names":[],"mappings":";;AA2cA;;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,IAAA,CAAA,WAAW,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;IAC5C;AACD;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAA,8CAAA,EAAiD,UAAU,CAAA,GAAA,CAAK;AAC9D,YAAA,sEAAsE,CACzE;QAJgB,IAAA,CAAA,UAAU,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;IAC9C;AACD;;;;;"}
|
package/dist/cjs/utils/run.cjs
CHANGED
|
@@ -61,7 +61,12 @@ class RunnableCallable extends runnables.Runnable {
|
|
|
61
61
|
returnValue = await this._callWithConfig(this._tracedInvoke, input, runnables.mergeConfigs(this.config, options));
|
|
62
62
|
}
|
|
63
63
|
else {
|
|
64
|
-
|
|
64
|
+
const mergedConfig = runnables.mergeConfigs(this.config, options);
|
|
65
|
+
// Set up AsyncLocalStorage context so LangGraph's interrupt() can find
|
|
66
|
+
// the graph config via getRunnableConfig(). Without this, interrupt()
|
|
67
|
+
// throws "Called interrupt() outside the context of a graph" because
|
|
68
|
+
// RunnableCallable (unlike RunnableLambda) doesn't use _callWithConfig.
|
|
69
|
+
returnValue = await singletons.AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, () => this.func(input, mergedConfig));
|
|
65
70
|
}
|
|
66
71
|
if (runnables.Runnable.isRunnable(returnValue) && this.recurse) {
|
|
67
72
|
return await returnValue.invoke(input, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n // Defensive check: ensure runManager has getChild method before calling\n const childCallbacks =\n typeof runManager?.getChild === 'function'\n ? runManager.getChild()\n : undefined;\n let childConfig: Partial<RunnableConfig> | null = patchConfig(config, {\n callbacks: childCallbacks,\n });\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n try {\n const output = await this.func(input, childConfig);\n childConfig = null;\n resolve(output);\n } catch (e) {\n childConfig = null;\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n options?: Partial<RunnableConfig> | undefined\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnValue: any;\n\n if (this.trace) {\n returnValue = await this._callWithConfig(\n this._tracedInvoke,\n input,\n mergeConfigs(this.config, options)\n );\n } else {\n returnValue = await this.func(input,
|
|
1
|
+
{"version":3,"file":"run.cjs","sources":["../../../src/utils/run.ts"],"sourcesContent":["import { CallbackManagerForChainRun } from '@langchain/core/callbacks/manager';\nimport {\n mergeConfigs,\n patchConfig,\n Runnable,\n RunnableConfig,\n} from '@langchain/core/runnables';\nimport { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';\n\n/**\n * Delays the execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to delay.\n * @return {Promise<void>} A promise that resolves after the specified delay.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface RunnableCallableArgs extends Partial<any> {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n tags?: string[];\n trace?: boolean;\n recurse?: boolean;\n}\n\nexport class RunnableCallable<I = unknown, O = unknown> extends Runnable<I, O> {\n lc_namespace: string[] = ['langgraph'];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n func: (...args: any[]) => any;\n\n tags?: string[];\n\n config?: RunnableConfig;\n\n trace: boolean = true;\n\n recurse: boolean = true;\n\n constructor(fields: RunnableCallableArgs) {\n super();\n this.name = fields.name ?? fields.func.name;\n this.func = fields.func;\n this.config = fields.tags ? { tags: fields.tags } : undefined;\n this.trace = fields.trace ?? this.trace;\n this.recurse = fields.recurse ?? this.recurse;\n }\n\n protected async _tracedInvoke(\n input: I,\n config?: Partial<RunnableConfig>,\n runManager?: CallbackManagerForChainRun\n ): Promise<O> {\n return new Promise<O>((resolve, reject) => {\n // Defensive check: ensure runManager has getChild method before calling\n const childCallbacks =\n typeof runManager?.getChild === 'function'\n ? runManager.getChild()\n : undefined;\n let childConfig: Partial<RunnableConfig> | null = patchConfig(config, {\n callbacks: childCallbacks,\n });\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n try {\n const output = await this.func(input, childConfig);\n childConfig = null;\n resolve(output);\n } catch (e) {\n childConfig = null;\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n options?: Partial<RunnableConfig> | undefined\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnValue: any;\n\n if (this.trace) {\n returnValue = await this._callWithConfig(\n this._tracedInvoke,\n input,\n mergeConfigs(this.config, options)\n );\n } else {\n const mergedConfig = mergeConfigs(this.config, options);\n // Set up AsyncLocalStorage context so LangGraph's interrupt() can find\n // the graph config via getRunnableConfig(). Without this, interrupt()\n // throws \"Called interrupt() outside the context of a graph\" because\n // RunnableCallable (unlike RunnableLambda) doesn't use _callWithConfig.\n returnValue = await AsyncLocalStorageProviderSingleton.runWithConfig(\n mergedConfig,\n () => this.func(input, mergedConfig)\n );\n }\n\n if (Runnable.isRunnable(returnValue) && this.recurse) {\n return await returnValue.invoke(input, options);\n }\n\n return returnValue;\n }\n}\n"],"names":["Runnable","patchConfig","AsyncLocalStorageProviderSingleton","mergeConfigs"],"mappings":";;;;;AASA;;;;;AAKG;AACG,SAAU,KAAK,CAAC,EAAU,EAAA;AAC9B,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC1D;AAYM,MAAO,gBAA2C,SAAQA,kBA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G,IAAI;oBAClB,MAAM,CAAC,CAAC,CAAC;gBACX;AACF,YAAA,CAAC,CACF;AACH,QAAA,CAAC,CAAC;IACJ;AAEA,IAAA,MAAM,MAAM;;AAEV,IAAA,KAAU,EACV;;;;AAIA,QAAA,IAAI,WAAgB;AAEpB,QAAA,IAAI,IAAI,CAAC,KAAK,EAAE;YACd,WAAW,GAAG,MAAM,IAAI,CAAC,eAAe,CACtC,IAAI,CAAC,aAAa,EAClB,KAAK,EACLC,sBAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CACnC;QACH;aAAO;YACL,MAAM,YAAY,GAAGA,sBAAY,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;YAKvD,WAAW,GAAG,MAAMD,6CAAkC,CAAC,aAAa,CAClE,YAAY,EACZ,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,YAAY,CAAC,CACrC;QACH;QAEA,IAAIF,kBAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACpD,OAAO,MAAM,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC;QACjD;AAEA,QAAA,OAAO,WAAW;IACpB;AACD;;;;;"}
|
package/dist/esm/common/enum.mjs
CHANGED
|
@@ -31,6 +31,8 @@ var GraphEvents;
|
|
|
31
31
|
GraphEvents["ON_TOOL_APPROVAL_REQUIRED"] = "on_tool_approval_required";
|
|
32
32
|
/** [Custom] Agent transition event — dispatched when control passes between agents */
|
|
33
33
|
GraphEvents["ON_AGENT_TRANSITION"] = "on_agent_transition";
|
|
34
|
+
/** [Custom] Approval gate interrupt — dispatched by ApprovalGateNode before interrupt() */
|
|
35
|
+
GraphEvents["ON_APPROVAL_GATE"] = "on_approval_gate";
|
|
34
36
|
/* Official Events */
|
|
35
37
|
/** Custom event, emitted by system */
|
|
36
38
|
GraphEvents["ON_CUSTOM_EVENT"] = "on_custom_event";
|