@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.
Files changed (58) hide show
  1. package/dist/cjs/common/enum.cjs +2 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +87 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/index.cjs +14 -0
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +3 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/nodes/ApprovalGateNode.cjs +75 -0
  10. package/dist/cjs/nodes/ApprovalGateNode.cjs.map +1 -0
  11. package/dist/cjs/run.cjs +45 -0
  12. package/dist/cjs/run.cjs.map +1 -1
  13. package/dist/cjs/tools/ToolNode.cjs +21 -18
  14. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  15. package/dist/cjs/types/graph.cjs.map +1 -1
  16. package/dist/cjs/utils/run.cjs +6 -1
  17. package/dist/cjs/utils/run.cjs.map +1 -1
  18. package/dist/esm/common/enum.mjs +2 -0
  19. package/dist/esm/common/enum.mjs.map +1 -1
  20. package/dist/esm/graphs/MultiAgentGraph.mjs +87 -1
  21. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  22. package/dist/esm/llm/bedrock/index.mjs +14 -0
  23. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  24. package/dist/esm/main.mjs +1 -0
  25. package/dist/esm/main.mjs.map +1 -1
  26. package/dist/esm/nodes/ApprovalGateNode.mjs +72 -0
  27. package/dist/esm/nodes/ApprovalGateNode.mjs.map +1 -0
  28. package/dist/esm/run.mjs +45 -0
  29. package/dist/esm/run.mjs.map +1 -1
  30. package/dist/esm/tools/ToolNode.mjs +22 -19
  31. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  32. package/dist/esm/types/graph.mjs.map +1 -1
  33. package/dist/esm/utils/run.mjs +6 -1
  34. package/dist/esm/utils/run.mjs.map +1 -1
  35. package/dist/types/common/enum.d.ts +2 -0
  36. package/dist/types/index.d.ts +1 -0
  37. package/dist/types/nodes/ApprovalGateNode.d.ts +49 -0
  38. package/dist/types/nodes/index.d.ts +2 -0
  39. package/dist/types/run.d.ts +25 -1
  40. package/dist/types/tools/ToolNode.d.ts +7 -5
  41. package/dist/types/types/graph.d.ts +31 -0
  42. package/dist/types/types/tools.d.ts +7 -9
  43. package/package.json +1 -1
  44. package/src/common/enum.ts +2 -0
  45. package/src/graphs/MultiAgentGraph.ts +108 -1
  46. package/src/index.ts +3 -0
  47. package/src/llm/bedrock/index.ts +17 -0
  48. package/src/nodes/ApprovalGateNode.ts +117 -0
  49. package/src/nodes/__tests__/ApprovalGateNode.test.ts +206 -0
  50. package/src/nodes/index.ts +5 -0
  51. package/src/run.ts +55 -1
  52. package/src/specs/agent-handoffs-bedrock.integration.test.ts +2 -2
  53. package/src/specs/agent-handoffs.test.ts +153 -6
  54. package/src/tools/ToolNode.ts +28 -23
  55. package/src/tools/__tests__/ToolApproval.test.ts +162 -325
  56. package/src/types/graph.ts +32 -0
  57. package/src/types/tools.ts +7 -9
  58. package/src/utils/run.ts +9 -1
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.mjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { summarize, createEmergencySummary } from '@/messages';\nimport { StandardGraph } from './Graph';\nimport {\n Constants,\n EdgeType,\n GraphEvents,\n DEFAULT_HANDOFF_MAX_RESULT_CHARS,\n} from '@/common';\nimport { safeDispatchCustomEvent } from '@/utils/events';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst TRANSFER_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY transfer edges: Can dynamically route to any transfer destination\n * - Agents with ONLY sequence edges: Always follow their sequence edges\n * - Agents with BOTH: Use Command for exclusive routing (transfer OR sequence, not both)\n * - If transfer occurs: Only the transfer destination executes\n * - If no transfer: Sequence edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either transfers (one-way)\n * OR continues its workflow (sequence edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private sequenceEdges: t.GraphEdge[] = [];\n private transferEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Lazily populated registry of compiled subgraphs, keyed by agentId.\n * Handoff tools are created in the constructor but reference subgraphs\n * that are only created in createWorkflow(). This Map bridges that gap —\n * tools capture the Map reference in their closure, and createWorkflow()\n * populates it before any tool invocation occurs.\n */\n private subgraphRegistry: Map<string, t.CompiledAgentWorfklow> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n /**\n * Tracks the ID of the last agent that produced output.\n * Used by auto-continuation to know which agent's context to preserve after handoff.\n */\n private lastActiveAgentId: string | undefined;\n\n /**\n * When set, the graph routes START to this agent instead of the default starting nodes.\n * Enables multi-turn resumption: follow-up messages go to the agent that last handled\n * the conversation rather than restarting from the root/router agent.\n */\n private resumeFromAgentId: string | undefined;\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.resumeFromAgentId = input.resumeFromAgentId;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createTransferTools();\n this.createHandoffTools();\n console.debug(\n `[MultiAgentGraph] Constructor complete: ${this.agentContexts.size} agents, ${this.edges.length} edges`\n );\n }\n\n /**\n * Categorize edges into handoff, transfer, and sequence types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n if (edge.edgeType === EdgeType.HANDOFF) {\n this.handoffEdges.push(edge);\n } else if (edge.edgeType === EdgeType.SEQUENCE) {\n this.sequenceEdges.push(edge);\n } else if (edge.edgeType === EdgeType.TRANSFER || edge.condition != null) {\n this.transferEdges.push(edge);\n } else {\n // Default: single-to-single edges are transfer, single-to-multiple are sequence\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to sequence\n this.sequenceEdges.push(edge);\n } else {\n // Everything else defaults to transfer\n this.transferEdges.push(edge);\n }\n }\n }\n console.debug(\n `[MultiAgentGraph] Edge categorization: ${this.handoffEdges.length} handoff, ${this.transferEdges.length} transfer, ${this.sequenceEdges.length} sequence (of ${this.edges.length} total)`\n );\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n console.debug(\n `[MultiAgentGraph] Starting nodes identified: [${Array.from(this.startingNodes).join(', ')}]`\n );\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find sequence edges from this node\n for (const edge of this.sequenceEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow transfer and handoff edges for traversal (they don't create parallel groups)\n for (const edge of [...this.transferEdges, ...this.handoffEdges]) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Returns the ID of the last agent that produced output.\n * Used by auto-continuation to determine which agent's context to preserve\n * when a response is truncated after an agent handoff.\n */\n getLastActiveAgentId(): string | undefined {\n return this.lastActiveAgentId;\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create transfer tools for agents based on transfer edges only.\n * Transfer tools return Command for one-way routing — parent exits, child takes over.\n */\n private createTransferTools(): void {\n const transfersByAgent = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.transferEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!transfersByAgent.has(source)) {\n transfersByAgent.set(source, []);\n }\n transfersByAgent.get(source)!.push(edge);\n });\n }\n\n for (const [agentId, edges] of transfersByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n const transferTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n transferTools.push(\n ...this.createTransferToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...transferTools);\n console.debug(\n `[MultiAgentGraph] Transfer tools for \"${agentId}\": [${transferTools.map((t) => t.name).join(', ')}]`\n );\n }\n }\n\n /**\n * Create transfer tools for an edge (handles multiple destinations).\n * Transfer tools return Command for one-way routing — parent exits, child takes over.\n * @param edge - The graph edge defining the transfer\n * @param sourceAgentId - The ID of the agent that will perform the transfer\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createTransferToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasTransferInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const transferInputDescription = hasTransferInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasTransferInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasTransferInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: transferInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const destContext = this.agentContexts.get(destination);\n const toolDescription =\n edge.description ??\n this.buildDefaultTransferDescription(destContext, destination);\n\n /** Check if we have a prompt for handoff input */\n const hasTransferInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const transferInputDescription = hasTransferInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasTransferInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasTransferInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: transferInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Builds a meaningful default description for a transfer tool when no explicit\n * edge.description is provided. Uses the destination agent's name and description\n * so the LLM can make informed routing decisions.\n * @param destContext - AgentContext of the destination agent (may be undefined)\n * @param destinationId - Raw agent ID (fallback when context unavailable)\n */\n private buildDefaultTransferDescription(\n destContext: import('@/agents/AgentContext').AgentContext | undefined,\n destinationId: string\n ): string {\n const displayName = destContext?.name ?? destinationId;\n const agentDescription = destContext?.description;\n\n if (agentDescription != null && agentDescription !== '') {\n return `Transfer to \"${displayName}\": ${agentDescription}`;\n }\n return `Transfer control to \"${displayName}\"`;\n }\n\n /**\n * Create handoff tools for agents based on handoff edges.\n * Handoff tools invoke child agent subgraphs inline and return the result\n * as a string to the parent agent's context. Unlike transfer tools (which\n * return Command for one-way routing), handoff tools execute the child,\n * extract the final text, and return it within the parent's agent loop.\n *\n * This enables the supervisor pattern: parent calls child → gets result → thinks → calls another.\n */\n private createHandoffTools(): void {\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n const handoffTools: t.GenericTool[] = [];\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n console.debug(\n `[MultiAgentGraph] Handoff tools for \"${agentId}\": [${handoffTools.map((t) => t.name).join(', ')}]`\n );\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations).\n * Each handoff tool invokes the child agent's compiled subgraph inline,\n * extracts the final AI message text, truncates it, and returns it as\n * a string (which becomes a ToolMessage in the parent's context).\n *\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the parent/supervisor agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const maxResultChars =\n edge.maxResultChars ?? DEFAULT_HANDOFF_MAX_RESULT_CHARS;\n\n for (const destination of destinations) {\n const toolName = `${Constants.LC_HANDOFF_TO_}${destination}`;\n const destContext = this.agentContexts.get(destination);\n const toolDescription =\n edge.description ??\n this.buildDefaultHandoffDescription(destContext, destination);\n\n const hasPromptInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const promptInputDescription = hasPromptInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n /** Capture registry reference — Map populated in createWorkflow() */\n const registry = this.subgraphRegistry;\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const subgraph = registry.get(destination);\n if (!subgraph) {\n throw new Error(\n `Handoff target \"${destination}\" subgraph not found in registry. ` +\n 'This is a bug: createWorkflow() should have populated the subgraph registry.'\n );\n }\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n let childMessages = [...state.messages];\n\n /** Inject instructions as HumanMessage if provided by the parent LLM */\n if (\n hasPromptInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n childMessages = [\n ...childMessages,\n new HumanMessage(String(input[promptKey])),\n ];\n }\n\n const childState: t.BaseGraphState = {\n messages: childMessages,\n };\n\n console.debug(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" START ` +\n `(messages: ${childMessages.length})`\n );\n\n try {\n /**\n * Invoke the child subgraph with config propagation.\n * Config carries callbacks (for SSE streaming), abort signal,\n * and configurable data (thread_id, user_id) to the child.\n */\n const result = await subgraph.invoke(childState, config);\n\n const resultText = MultiAgentGraph.extractHandoffResult(\n result.messages,\n destination\n );\n const truncatedResult = MultiAgentGraph.truncateHandoffResult(\n resultText,\n maxResultChars\n );\n\n console.debug(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" DONE ` +\n `(result: ${resultText.length} chars` +\n `${truncatedResult.length < resultText.length ? `, truncated to ${truncatedResult.length}` : ''})`\n );\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: sourceAgentId,\n sourceAgentName: this.agentContexts.get(sourceAgentId)?.name ?? sourceAgentId,\n destinationAgentId: destination,\n destinationAgentName: destContext?.name ?? destination,\n edgeType: EdgeType.HANDOFF,\n timestamp: Date.now(),\n },\n config\n );\n\n return truncatedResult;\n } catch (err) {\n const errorMessage =\n err instanceof Error ? err.message : String(err);\n console.error(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" ERROR:`,\n errorMessage\n );\n return `[Handoff to \"${destination}\" failed: ${errorMessage}]`;\n }\n },\n {\n name: toolName,\n schema: hasPromptInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: promptInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n\n return tools;\n }\n\n /**\n * Extract the final text result from a child agent's output messages.\n * Walks backwards to find the last AIMessage with text content.\n * Handles both string content and array content (multi-modal messages).\n * @param messages - The child agent's output messages\n * @param agentId - The child agent ID (for fallback message)\n */\n static extractHandoffResult(\n messages: BaseMessage[],\n agentId: string\n ): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'ai') continue;\n\n const content = msg.content;\n if (typeof content === 'string' && content.trim()) {\n return content.trim();\n }\n\n /** Handle array content (multi-modal messages with text blocks) */\n if (Array.isArray(content)) {\n const textParts = content\n .filter(\n (\n block\n ): block is {\n type: string;\n text: string;\n } =>\n typeof block === 'object' &&\n block !== null &&\n 'type' in block &&\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string'\n )\n .map((block) => block.text);\n\n const text = textParts.join('\\n').trim();\n if (text) return text;\n }\n }\n\n return `[Agent \"${agentId}\" completed but produced no text output]`;\n }\n\n /**\n * Truncate handoff result using head/tail strategy (60/40 split).\n * Preserves the beginning (key findings) and end (conclusions).\n * Matches the TaskTool.truncateResult pattern from Ranger.\n * @param result - The full result text\n * @param maxChars - Maximum allowed characters\n */\n static truncateHandoffResult(result: string, maxChars: number): string {\n if (!result || result.length <= maxChars) {\n return result;\n }\n\n const truncationNotice =\n '\\n\\n[... handoff output truncated — middle section omitted to fit parent context ...]\\n\\n';\n const available = maxChars - truncationNotice.length;\n if (available <= 0) {\n return result.substring(0, maxChars);\n }\n\n const headSize = Math.floor(available * 0.6);\n const tailSize = available - headSize;\n\n return (\n result.substring(0, headSize) +\n truncationNotice +\n result.substring(result.length - tailSize)\n );\n }\n\n /**\n * Build a meaningful default description for a handoff tool.\n * @param destContext - AgentContext of the destination agent\n * @param destinationId - Raw agent ID (fallback)\n */\n private buildDefaultHandoffDescription(\n destContext: import('@/agents/AgentContext').AgentContext | undefined,\n destinationId: string\n ): string {\n const displayName = destContext?.name ?? destinationId;\n const agentDescription = destContext?.description;\n\n if (agentDescription != null && agentDescription !== '') {\n return `Hand off task to \"${displayName}\": ${agentDescription}. The agent will execute and return its result.`;\n }\n return `Hand off task to \"${displayName}\" and receive its result.`;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processTransferReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const transferDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof transferDest === 'string' ? transferDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(TRANSFER_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls.\n * Trim trailing whitespace to prevent Bedrock validation errors. */\n const trimmedContent =\n typeof aiMsg.content === 'string'\n ? aiMsg.content.trimEnd()\n : aiMsg.content;\n const filteredAiMsg = new AIMessage({\n content: trimmedContent,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n /**\n * Flatten tool call/result pairs into text summaries for handoff.\n *\n * When agent A uses tools and then hands off to agent B, agent B may not\n * have the same tools configured. Providers like Bedrock require toolConfig\n * when tool_use/tool_result blocks are in the message history. Converting\n * tool interactions to text summaries avoids this and reduces context bloat.\n *\n * Strategy: Walk through messages and merge each (AIMessage-with-tool_calls +\n * following ToolMessages) group into a single AIMessage containing the original\n * text plus a textual summary of the tool interaction. This preserves proper\n * message role ordering (human/assistant alternation).\n */\n const compactedMessages: BaseMessage[] = [];\n\n for (let i = 0; i < filteredMessages.length; i++) {\n const msg = filteredMessages[i];\n const msgType = msg.getType();\n\n if (msgType === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Extract text content from the AIMessage */\n const textContent =\n typeof aiMsg.content === 'string'\n ? aiMsg.content\n : Array.isArray(aiMsg.content)\n ? aiMsg.content\n .filter(\n (b): b is { type: string; text: string } =>\n typeof b === 'object' &&\n b.type === 'text' &&\n 'text' in b\n )\n .map((b) => b.text)\n .join('\\n')\n : '';\n\n /** Collect tool_call_ids so we can match following ToolMessages */\n const callIds = new Set(toolCalls.map((tc) => tc.id).filter(Boolean));\n\n /** Build summary of what tools were called */\n const callSummaries = toolCalls.map((tc) => `[Called \"${tc.name}\"]`);\n\n /** Consume following ToolMessages that belong to this AI message */\n const resultSummaries: string[] = [];\n while (i + 1 < filteredMessages.length) {\n const next = filteredMessages[i + 1];\n if (next.getType() !== 'tool') break;\n\n const toolMsg = next as ToolMessage;\n if (!callIds.has(toolMsg.tool_call_id)) break;\n\n /** Extract and summarize the tool result */\n const rawContent =\n typeof toolMsg.content === 'string'\n ? toolMsg.content\n : Array.isArray(toolMsg.content)\n ? toolMsg.content\n .filter(\n (b): b is { type: string; text: string } =>\n typeof b === 'object' &&\n 'text' in b &&\n typeof (b as Record<string, unknown>).text ===\n 'string'\n )\n .map((b) => b.text)\n .join('\\n')\n : JSON.stringify(toolMsg.content);\n\n const summary =\n rawContent.length > 500\n ? rawContent.split('\\n')[0] + ' [truncated for handoff]'\n : rawContent;\n\n resultSummaries.push(\n `[Tool \"${toolMsg.name}\" returned: ${summary}]`\n );\n i++; // Skip this ToolMessage in the outer loop\n }\n\n /** Merge everything into a single AIMessage */\n const parts = [\n textContent,\n ...callSummaries,\n ...resultSummaries,\n ].filter(Boolean);\n\n /** Bedrock rejects messages with trailing whitespace */\n const mergedContent = (\n parts.join('\\n') || '[Agent processed tools]'\n ).trimEnd();\n compactedMessages.push(\n new AIMessage({\n content: mergedContent,\n id: aiMsg.id,\n })\n );\n continue;\n }\n }\n\n /** Skip orphaned ToolMessages (their AI parent was already handled above,\n * or they belong to a transfer that was already filtered out) */\n if (msgType === 'tool') {\n continue;\n }\n\n /** Trim trailing whitespace on AI messages to prevent Bedrock validation errors */\n if (\n msgType === 'ai' &&\n typeof msg.content === 'string' &&\n msg.content !== msg.content.trimEnd()\n ) {\n compactedMessages.push(\n new AIMessage({ content: msg.content.trimEnd(), id: msg.id })\n );\n continue;\n }\n\n compactedMessages.push(msg);\n }\n\n return {\n filteredMessages: compactedMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with handoffs, transfers, and sequences\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const transferDestinations = new Set<string>();\n const sequenceDestinations = new Set<string>();\n\n // Check transfer edges for destinations\n for (const edge of this.transferEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => transferDestinations.add(dest));\n }\n }\n\n // Check sequence edges for destinations\n for (const edge of this.sequenceEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => sequenceDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH transfer and sequence edges */\n const hasTransferEdges = transferDestinations.size > 0;\n const hasSequenceEdges = sequenceDestinations.size > 0;\n const needsCommandRouting = hasTransferEdges && hasSequenceEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...transferDestinations,\n ...sequenceDestinations,\n ]);\n if (transferDestinations.size > 0 || sequenceDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Register subgraph for handoff tools (lazy reference resolution) */\n this.subgraphRegistry.set(agentId, agentSubgraph);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" wrapper ENTRY (messages: ${state.messages.length}, needsCommandRouting: ${needsCommandRouting})`\n );\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a transfer.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const transferContext = this.processTransferReception(\n state.messages,\n agentId\n );\n\n if (transferContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = transferContext;\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" receiving transfer from \"${sourceAgentName}\" (instructions: ${instructions != null}, parallelSiblings: ${parallelSiblings.length})`\n );\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** Track the last agent that produced output for continuation support */\n this.lastActiveAgentId = agentId;\n\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" wrapper EXIT (result messages: ${result.messages.length})`\n );\n\n /** If agent has both transfer and sequence edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a transfer occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Transfer occurred - extract destination and navigate there exclusively */\n const transferDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n console.debug(\n `[MultiAgentGraph] Command routing: \"${agentId}\" -> transfer to \"${transferDest}\" (sequence edges skipped: [${Array.from(sequenceDestinations).join(', ')}])`\n );\n\n /** Validate destination agent exists */\n if (!this.agentContexts.has(transferDest)) {\n const availableAgents = Array.from(\n this.agentContexts.keys()\n ).join(', ');\n console.error(\n `[MultiAgentGraph] Transfer to non-existent agent \"${transferDest}\". Available: ${availableAgents}`\n );\n /** Return error to model so it can self-correct */\n const errorMsg = new ToolMessage({\n content: `Transfer failed: agent \"${transferDest}\" does not exist. Available agents: ${availableAgents}. Please choose a valid agent to transfer to.`,\n tool_call_id: (lastMessage as ToolMessage).tool_call_id,\n name: lastMessage.name,\n });\n (errorMsg as ToolMessage).status = 'error';\n return {\n messages: [...result.messages, errorMsg],\n };\n }\n\n /** Pre-handoff context compaction: if receiving agent has smaller budget */\n const receiverContext = this.agentContexts.get(transferDest);\n const senderContext = this.agentContexts.get(agentId);\n if (\n receiverContext?.maxContextTokens != null &&\n senderContext?.tokenCounter != null &&\n receiverContext.maxContextTokens > 0\n ) {\n let currentSize = 0;\n for (const msg of result.messages) {\n currentSize += senderContext.tokenCounter(msg);\n }\n const receiverBudget = receiverContext.maxContextTokens;\n\n if (currentSize > receiverBudget * 0.7) {\n console.warn(\n `[MultiAgentGraph] Pre-handoff compaction: context (${currentSize} tokens) exceeds ` +\n `70% of receiver \"${transferDest}\" budget (${receiverBudget} tokens)`\n );\n\n /** Generate handoff briefing */\n const senderName = senderContext.name ?? agentId;\n if (senderContext.summarizeCallback) {\n try {\n const briefingResult = await summarize(\n result.messages,\n async (prompt, _maxTokens) =>\n senderContext.summarizeCallback!([\n new HumanMessage(prompt),\n ]),\n {\n tokenCounter: senderContext.tokenCounter,\n summaryBudget: Math.floor(receiverBudget * 0.2),\n isMultiAgent: true,\n agentWorkflowState: {\n currentAgentId: transferDest,\n agentChain: [agentId, transferDest],\n pendingAgents: [],\n },\n }\n );\n\n const briefingMsg = new SystemMessage(\n `[Handoff Briefing from \"${senderName}\"]\\n${briefingResult.summary}`\n );\n\n /** Replace messages with briefing + last 3 messages */\n const keepCount = Math.min(3, result.messages.length);\n result = {\n ...result,\n messages: [\n briefingMsg,\n ...result.messages.slice(\n result.messages.length - keepCount\n ),\n ],\n };\n\n console.info(\n `[MultiAgentGraph] Pre-handoff compaction complete: ${currentSize} tokens → briefing + ${keepCount} messages`\n );\n } catch (compactErr) {\n console.error(\n '[MultiAgentGraph] Pre-handoff compaction failed:',\n compactErr\n );\n /** Continue without compaction — let receiver handle the overflow */\n }\n } else {\n /** No summary callback — use emergency summary */\n const emergencySummary = createEmergencySummary(\n result.messages\n );\n const briefingMsg = new SystemMessage(\n `[Handoff Briefing from \"${senderName}\" — Emergency]\\n${emergencySummary}`\n );\n const keepCount = Math.min(3, result.messages.length);\n result = {\n ...result,\n messages: [\n briefingMsg,\n ...result.messages.slice(\n result.messages.length - keepCount\n ),\n ],\n };\n }\n }\n }\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: agentId,\n sourceAgentName: this.agentContexts.get(agentId)?.name ?? agentId,\n destinationAgentId: transferDest,\n destinationAgentName: this.agentContexts.get(transferDest)?.name ?? transferDest,\n edgeType: EdgeType.TRANSFER,\n timestamp: Date.now(),\n },\n config\n );\n\n return new Command({\n update: result,\n goto: transferDest,\n });\n } else {\n /** No transfer - proceed with sequence edges */\n console.debug(\n `[MultiAgentGraph] Command routing: \"${agentId}\" -> no transfer, following sequence edges: [${Array.from(sequenceDestinations).join(', ')}]`\n );\n const directDests = Array.from(sequenceDestinations);\n for (const dest of directDests) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: agentId,\n sourceAgentName: this.agentContexts.get(agentId)?.name ?? agentId,\n destinationAgentId: dest,\n destinationAgentName: this.agentContexts.get(dest)?.name ?? dest,\n edgeType: EdgeType.SEQUENCE,\n timestamp: Date.now(),\n },\n config\n );\n }\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n /**\n * Add starting edges from START to entry agent(s).\n *\n * Multi-turn resumption: when `resumeFromAgentId` is set and refers to a\n * valid agent in this graph, START routes exclusively to that agent so\n * follow-up messages continue where the previous turn left off.\n *\n * Default behavior (no resume): static edges to all starting nodes,\n * preserving parallel execution for graphs with multiple entry points.\n */\n const validResumeAgent =\n this.resumeFromAgentId != null &&\n this.agentContexts.has(this.resumeFromAgentId);\n\n if (validResumeAgent) {\n const resumeAgentId = this.resumeFromAgentId!;\n console.debug(\n `[MultiAgentGraph] Multi-turn resumption: routing START → \"${resumeAgentId}\" (skipping default starting nodes: [${Array.from(this.startingNodes).join(', ')}])`\n );\n\n /**\n * Build route map containing both the resume agent and default starting\n * nodes. This is required by LangGraph — all possible destinations must\n * be declared even if the router always picks one.\n */\n const allPossibleStarts = new Set([\n ...this.startingNodes,\n resumeAgentId,\n ]);\n const routeMap: Record<string, string> = {};\n for (const nodeId of allPossibleStarts) {\n routeMap[nodeId] = nodeId;\n }\n\n builder.addConditionalEdges(\n START,\n () => resumeAgentId,\n routeMap as unknown as never\n );\n } else {\n if (this.resumeFromAgentId != null) {\n console.warn(\n `[MultiAgentGraph] resumeFromAgentId \"${this.resumeFromAgentId}\" not found in graph — falling back to default starting nodes`\n );\n }\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n }\n\n /**\n * Add sequence edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.sequenceEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n return {\n messages: [new HumanMessage(promptText)],\n agentMessages: messagesStateReducer(filteredMessages, [\n new HumanMessage(promptText),\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both transfer and sequence edges */\n const sourceTransferEdges = this.transferEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceSequenceEdges = this.sequenceEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceTransferEdges.length > 0 && sourceSequenceEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAgCA;AACA,MAAM,6BAA6B,GAAG,qCAAqC;AAE3E;;;;;;;;;;;;;AAaG;AACG,MAAO,eAAgB,SAAQ,aAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACt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I,KAAK,EAAE;oBACxB,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;AAClE,oBAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;;wBAE5B,MAAM,mBAAmB,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BAC1D,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;wBACF,MAAM,mBAAmB,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BAC1D,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;;AAGF,wBAAA,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE;4BACpE;wBACF;;;AAIA,wBAAA,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC;oBACtC;gBACF;YACF;QACF;QAEA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,cAAkC,CAAC;IACjE;AACD;;;;"}
1
+ {"version":3,"file":"MultiAgentGraph.mjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { summarize, createEmergencySummary } from '@/messages';\nimport { StandardGraph } from './Graph';\nimport {\n Constants,\n EdgeType,\n GraphEvents,\n DEFAULT_HANDOFF_MAX_RESULT_CHARS,\n} from '@/common';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport {\n createApprovalGateNode,\n getApprovalGateNodeId,\n} from '@/nodes/ApprovalGateNode';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst TRANSFER_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY transfer edges: Can dynamically route to any transfer destination\n * - Agents with ONLY sequence edges: Always follow their sequence edges\n * - Agents with BOTH: Use Command for exclusive routing (transfer OR sequence, not both)\n * - If transfer occurs: Only the transfer destination executes\n * - If no transfer: Sequence edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either transfers (one-way)\n * OR continues its workflow (sequence edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private sequenceEdges: t.GraphEdge[] = [];\n private transferEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Lazily populated registry of compiled subgraphs, keyed by agentId.\n * Handoff tools are created in the constructor but reference subgraphs\n * that are only created in createWorkflow(). This Map bridges that gap —\n * tools capture the Map reference in their closure, and createWorkflow()\n * populates it before any tool invocation occurs.\n */\n private subgraphRegistry: Map<string, t.CompiledAgentWorfklow> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n /**\n * Tracks the ID of the last agent that produced output.\n * Used by auto-continuation to know which agent's context to preserve after handoff.\n */\n private lastActiveAgentId: string | undefined;\n\n /**\n * When set, the graph routes START to this agent instead of the default starting nodes.\n * Enables multi-turn resumption: follow-up messages go to the agent that last handled\n * the conversation rather than restarting from the root/router agent.\n */\n private resumeFromAgentId: string | undefined;\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.resumeFromAgentId = input.resumeFromAgentId;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createTransferTools();\n this.createHandoffTools();\n console.debug(\n `[MultiAgentGraph] Constructor complete: ${this.agentContexts.size} agents, ${this.edges.length} edges`\n );\n }\n\n /**\n * Categorize edges into handoff, transfer, and sequence types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n if (edge.edgeType === EdgeType.HANDOFF) {\n this.handoffEdges.push(edge);\n } else if (edge.edgeType === EdgeType.SEQUENCE) {\n this.sequenceEdges.push(edge);\n } else if (edge.edgeType === EdgeType.TRANSFER || edge.condition != null) {\n this.transferEdges.push(edge);\n } else {\n // Default: single-to-single edges are transfer, single-to-multiple are sequence\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to sequence\n this.sequenceEdges.push(edge);\n } else {\n // Everything else defaults to transfer\n this.transferEdges.push(edge);\n }\n }\n }\n console.debug(\n `[MultiAgentGraph] Edge categorization: ${this.handoffEdges.length} handoff, ${this.transferEdges.length} transfer, ${this.sequenceEdges.length} sequence (of ${this.edges.length} total)`\n );\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n console.debug(\n `[MultiAgentGraph] Starting nodes identified: [${Array.from(this.startingNodes).join(', ')}]`\n );\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find sequence edges from this node\n for (const edge of this.sequenceEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow transfer and handoff edges for traversal (they don't create parallel groups)\n for (const edge of [...this.transferEdges, ...this.handoffEdges]) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Returns the ID of the last agent that produced output.\n * Used by auto-continuation to determine which agent's context to preserve\n * when a response is truncated after an agent handoff.\n */\n getLastActiveAgentId(): string | undefined {\n return this.lastActiveAgentId;\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create transfer tools for agents based on transfer edges only.\n * Transfer tools return Command for one-way routing — parent exits, child takes over.\n */\n private createTransferTools(): void {\n const transfersByAgent = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.transferEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!transfersByAgent.has(source)) {\n transfersByAgent.set(source, []);\n }\n transfersByAgent.get(source)!.push(edge);\n });\n }\n\n for (const [agentId, edges] of transfersByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n const transferTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n transferTools.push(\n ...this.createTransferToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...transferTools);\n console.debug(\n `[MultiAgentGraph] Transfer tools for \"${agentId}\": [${transferTools.map((t) => t.name).join(', ')}]`\n );\n }\n }\n\n /**\n * Create transfer tools for an edge (handles multiple destinations).\n * Transfer tools return Command for one-way routing — parent exits, child takes over.\n * @param edge - The graph edge defining the transfer\n * @param sourceAgentId - The ID of the agent that will perform the transfer\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createTransferToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasTransferInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const transferInputDescription = hasTransferInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasTransferInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasTransferInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: transferInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const destContext = this.agentContexts.get(destination);\n const toolDescription =\n edge.description ??\n this.buildDefaultTransferDescription(destContext, destination);\n\n /** Check if we have a prompt for handoff input */\n const hasTransferInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const transferInputDescription = hasTransferInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasTransferInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasTransferInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: transferInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Builds a meaningful default description for a transfer tool when no explicit\n * edge.description is provided. Uses the destination agent's name and description\n * so the LLM can make informed routing decisions.\n * @param destContext - AgentContext of the destination agent (may be undefined)\n * @param destinationId - Raw agent ID (fallback when context unavailable)\n */\n private buildDefaultTransferDescription(\n destContext: import('@/agents/AgentContext').AgentContext | undefined,\n destinationId: string\n ): string {\n const displayName = destContext?.name ?? destinationId;\n const agentDescription = destContext?.description;\n\n if (agentDescription != null && agentDescription !== '') {\n return `Transfer to \"${displayName}\": ${agentDescription}`;\n }\n return `Transfer control to \"${displayName}\"`;\n }\n\n /**\n * Create handoff tools for agents based on handoff edges.\n * Handoff tools invoke child agent subgraphs inline and return the result\n * as a string to the parent agent's context. Unlike transfer tools (which\n * return Command for one-way routing), handoff tools execute the child,\n * extract the final text, and return it within the parent's agent loop.\n *\n * This enables the supervisor pattern: parent calls child → gets result → thinks → calls another.\n */\n private createHandoffTools(): void {\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n const handoffTools: t.GenericTool[] = [];\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n console.debug(\n `[MultiAgentGraph] Handoff tools for \"${agentId}\": [${handoffTools.map((t) => t.name).join(', ')}]`\n );\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations).\n * Each handoff tool invokes the child agent's compiled subgraph inline,\n * extracts the final AI message text, truncates it, and returns it as\n * a string (which becomes a ToolMessage in the parent's context).\n *\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the parent/supervisor agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const maxResultChars =\n edge.maxResultChars ?? DEFAULT_HANDOFF_MAX_RESULT_CHARS;\n\n for (const destination of destinations) {\n const toolName = `${Constants.LC_HANDOFF_TO_}${destination}`;\n const destContext = this.agentContexts.get(destination);\n const toolDescription =\n edge.description ??\n this.buildDefaultHandoffDescription(destContext, destination);\n\n const hasPromptInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const promptInputDescription = hasPromptInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n /** Capture registry reference — Map populated in createWorkflow() */\n const registry = this.subgraphRegistry;\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const subgraph = registry.get(destination);\n if (!subgraph) {\n throw new Error(\n `Handoff target \"${destination}\" subgraph not found in registry. ` +\n 'This is a bug: createWorkflow() should have populated the subgraph registry.'\n );\n }\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n let childMessages = [...state.messages];\n\n /** Inject instructions as HumanMessage if provided by the parent LLM */\n if (\n hasPromptInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n childMessages = [\n ...childMessages,\n new HumanMessage(String(input[promptKey])),\n ];\n }\n\n const childState: t.BaseGraphState = {\n messages: childMessages,\n };\n\n console.debug(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" START ` +\n `(messages: ${childMessages.length})`\n );\n\n try {\n /**\n * Invoke the child subgraph with config propagation.\n * Config carries callbacks (for SSE streaming), abort signal,\n * and configurable data (thread_id, user_id) to the child.\n */\n const result = await subgraph.invoke(childState, config);\n\n const resultText = MultiAgentGraph.extractHandoffResult(\n result.messages,\n destination\n );\n const truncatedResult = MultiAgentGraph.truncateHandoffResult(\n resultText,\n maxResultChars\n );\n\n console.debug(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" DONE ` +\n `(result: ${resultText.length} chars` +\n `${truncatedResult.length < resultText.length ? `, truncated to ${truncatedResult.length}` : ''})`\n );\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: sourceAgentId,\n sourceAgentName: this.agentContexts.get(sourceAgentId)?.name ?? sourceAgentId,\n destinationAgentId: destination,\n destinationAgentName: destContext?.name ?? destination,\n edgeType: EdgeType.HANDOFF,\n timestamp: Date.now(),\n },\n config\n );\n\n return truncatedResult;\n } catch (err) {\n const errorMessage =\n err instanceof Error ? err.message : String(err);\n console.error(\n `[MultiAgentGraph] Handoff \"${sourceAgentId}\" -> \"${destination}\" ERROR:`,\n errorMessage\n );\n return `[Handoff to \"${destination}\" failed: ${errorMessage}]`;\n }\n },\n {\n name: toolName,\n schema: hasPromptInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: promptInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n\n return tools;\n }\n\n /**\n * Extract the final text result from a child agent's output messages.\n * Walks backwards to find the last AIMessage with text content.\n * Handles both string content and array content (multi-modal messages).\n * @param messages - The child agent's output messages\n * @param agentId - The child agent ID (for fallback message)\n */\n static extractHandoffResult(\n messages: BaseMessage[],\n agentId: string\n ): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'ai') continue;\n\n const content = msg.content;\n if (typeof content === 'string' && content.trim()) {\n return content.trim();\n }\n\n /** Handle array content (multi-modal messages with text blocks) */\n if (Array.isArray(content)) {\n const textParts = content\n .filter(\n (\n block\n ): block is {\n type: string;\n text: string;\n } =>\n typeof block === 'object' &&\n block !== null &&\n 'type' in block &&\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string'\n )\n .map((block) => block.text);\n\n const text = textParts.join('\\n').trim();\n if (text) return text;\n }\n }\n\n return `[Agent \"${agentId}\" completed but produced no text output]`;\n }\n\n /**\n * Truncate handoff result using head/tail strategy (60/40 split).\n * Preserves the beginning (key findings) and end (conclusions).\n * Matches the TaskTool.truncateResult pattern from Ranger.\n * @param result - The full result text\n * @param maxChars - Maximum allowed characters\n */\n static truncateHandoffResult(result: string, maxChars: number): string {\n if (!result || result.length <= maxChars) {\n return result;\n }\n\n const truncationNotice =\n '\\n\\n[... handoff output truncated — middle section omitted to fit parent context ...]\\n\\n';\n const available = maxChars - truncationNotice.length;\n if (available <= 0) {\n return result.substring(0, maxChars);\n }\n\n const headSize = Math.floor(available * 0.6);\n const tailSize = available - headSize;\n\n return (\n result.substring(0, headSize) +\n truncationNotice +\n result.substring(result.length - tailSize)\n );\n }\n\n /**\n * Build a meaningful default description for a handoff tool.\n * @param destContext - AgentContext of the destination agent\n * @param destinationId - Raw agent ID (fallback)\n */\n private buildDefaultHandoffDescription(\n destContext: import('@/agents/AgentContext').AgentContext | undefined,\n destinationId: string\n ): string {\n const displayName = destContext?.name ?? destinationId;\n const agentDescription = destContext?.description;\n\n if (agentDescription != null && agentDescription !== '') {\n return `Hand off task to \"${displayName}\": ${agentDescription}. The agent will execute and return its result.`;\n }\n return `Hand off task to \"${displayName}\" and receive its result.`;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processTransferReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const transferDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof transferDest === 'string' ? transferDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(TRANSFER_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls.\n * Trim trailing whitespace to prevent Bedrock validation errors. */\n const trimmedContent =\n typeof aiMsg.content === 'string'\n ? aiMsg.content.trimEnd()\n : aiMsg.content;\n const filteredAiMsg = new AIMessage({\n content: trimmedContent,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n /**\n * Flatten tool call/result pairs into text summaries for handoff.\n *\n * When agent A uses tools and then hands off to agent B, agent B may not\n * have the same tools configured. Providers like Bedrock require toolConfig\n * when tool_use/tool_result blocks are in the message history. Converting\n * tool interactions to text summaries avoids this and reduces context bloat.\n *\n * Strategy: Walk through messages and merge each (AIMessage-with-tool_calls +\n * following ToolMessages) group into a single AIMessage containing the original\n * text plus a textual summary of the tool interaction. This preserves proper\n * message role ordering (human/assistant alternation).\n */\n const compactedMessages: BaseMessage[] = [];\n\n for (let i = 0; i < filteredMessages.length; i++) {\n const msg = filteredMessages[i];\n const msgType = msg.getType();\n\n if (msgType === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Extract text content from the AIMessage */\n const textContent =\n typeof aiMsg.content === 'string'\n ? aiMsg.content\n : Array.isArray(aiMsg.content)\n ? aiMsg.content\n .filter(\n (b): b is { type: string; text: string } =>\n typeof b === 'object' &&\n b.type === 'text' &&\n 'text' in b\n )\n .map((b) => b.text)\n .join('\\n')\n : '';\n\n /** Collect tool_call_ids so we can match following ToolMessages */\n const callIds = new Set(toolCalls.map((tc) => tc.id).filter(Boolean));\n\n /** Build summary of what tools were called */\n const callSummaries = toolCalls.map((tc) => `[Called \"${tc.name}\"]`);\n\n /** Consume following ToolMessages that belong to this AI message */\n const resultSummaries: string[] = [];\n while (i + 1 < filteredMessages.length) {\n const next = filteredMessages[i + 1];\n if (next.getType() !== 'tool') break;\n\n const toolMsg = next as ToolMessage;\n if (!callIds.has(toolMsg.tool_call_id)) break;\n\n /** Extract and summarize the tool result */\n const rawContent =\n typeof toolMsg.content === 'string'\n ? toolMsg.content\n : Array.isArray(toolMsg.content)\n ? toolMsg.content\n .filter(\n (b): b is { type: string; text: string } =>\n typeof b === 'object' &&\n 'text' in b &&\n typeof (b as Record<string, unknown>).text ===\n 'string'\n )\n .map((b) => b.text)\n .join('\\n')\n : JSON.stringify(toolMsg.content);\n\n const summary =\n rawContent.length > 500\n ? rawContent.split('\\n')[0] + ' [truncated for handoff]'\n : rawContent;\n\n resultSummaries.push(\n `[Tool \"${toolMsg.name}\" returned: ${summary}]`\n );\n i++; // Skip this ToolMessage in the outer loop\n }\n\n /** Merge everything into a single AIMessage */\n const parts = [\n textContent,\n ...callSummaries,\n ...resultSummaries,\n ].filter(Boolean);\n\n /** Bedrock rejects messages with trailing whitespace */\n const mergedContent = (\n parts.join('\\n') || '[Agent processed tools]'\n ).trimEnd();\n compactedMessages.push(\n new AIMessage({\n content: mergedContent,\n id: aiMsg.id,\n })\n );\n continue;\n }\n }\n\n /** Skip orphaned ToolMessages (their AI parent was already handled above,\n * or they belong to a transfer that was already filtered out) */\n if (msgType === 'tool') {\n continue;\n }\n\n /** Trim trailing whitespace on AI messages to prevent Bedrock validation errors */\n if (\n msgType === 'ai' &&\n typeof msg.content === 'string' &&\n msg.content !== msg.content.trimEnd()\n ) {\n compactedMessages.push(\n new AIMessage({ content: msg.content.trimEnd(), id: msg.id })\n );\n continue;\n }\n\n compactedMessages.push(msg);\n }\n\n return {\n filteredMessages: compactedMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with handoffs, transfers, and sequences\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n /**\n * Identify agents that are ONLY handoff destinations (not transfer/sequence\n * destinations and not starting nodes). These agents are invoked inline via\n * subgraph.invoke() inside handoff tools — they must NOT be added as\n * top-level nodes in the parent graph because LangGraph validates that all\n * nodes are reachable from START via edges.\n */\n const handoffOnlyDestinations = new Set<string>();\n const transferOrSequenceDestinations = new Set<string>();\n\n for (const edge of this.handoffEdges) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((d) => handoffOnlyDestinations.add(d));\n }\n for (const edge of [...this.transferEdges, ...this.sequenceEdges]) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((d) => transferOrSequenceDestinations.add(d));\n }\n // Remove agents that are also transfer/sequence destinations or starting nodes\n for (const d of transferOrSequenceDestinations) {\n handoffOnlyDestinations.delete(d);\n }\n for (const startNode of this.startingNodes) {\n handoffOnlyDestinations.delete(startNode);\n }\n\n if (handoffOnlyDestinations.size > 0) {\n console.debug(\n `[MultiAgentGraph] Handoff-only children (subgraph only, no top-level node): [${Array.from(handoffOnlyDestinations).join(', ')}]`\n );\n }\n\n // Add agents as nodes — skip handoff-only children (they exist as subgraphs only)\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const transferDestinations = new Set<string>();\n const sequenceDestinations = new Set<string>();\n\n // Check transfer edges for destinations\n for (const edge of this.transferEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => transferDestinations.add(dest));\n }\n }\n\n // Check sequence edges for destinations\n for (const edge of this.sequenceEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => sequenceDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH transfer and sequence edges */\n const hasTransferEdges = transferDestinations.size > 0;\n const hasSequenceEdges = sequenceDestinations.size > 0;\n const needsCommandRouting = hasTransferEdges && hasSequenceEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...transferDestinations,\n ...sequenceDestinations,\n ]);\n if (transferDestinations.size > 0 || sequenceDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Register subgraph for handoff tools (lazy reference resolution) */\n this.subgraphRegistry.set(agentId, agentSubgraph);\n\n /**\n * Handoff-only children are invoked inline via subgraph.invoke() — they\n * don't need a top-level node. Adding them would cause LangGraph to reject\n * the graph because no edge routes to them (UNREACHABLE_NODE).\n */\n if (handoffOnlyDestinations.has(agentId)) {\n continue;\n }\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" wrapper ENTRY (messages: ${state.messages.length}, needsCommandRouting: ${needsCommandRouting})`\n );\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a transfer.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const transferContext = this.processTransferReception(\n state.messages,\n agentId\n );\n\n if (transferContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = transferContext;\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" receiving transfer from \"${sourceAgentName}\" (instructions: ${instructions != null}, parallelSiblings: ${parallelSiblings.length})`\n );\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** Track the last agent that produced output for continuation support */\n this.lastActiveAgentId = agentId;\n\n console.debug(\n `[MultiAgentGraph] Agent \"${agentId}\" wrapper EXIT (result messages: ${result.messages.length})`\n );\n\n /** If agent has both transfer and sequence edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a transfer occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Transfer occurred - extract destination and navigate there exclusively */\n const transferDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n console.debug(\n `[MultiAgentGraph] Command routing: \"${agentId}\" -> transfer to \"${transferDest}\" (sequence edges skipped: [${Array.from(sequenceDestinations).join(', ')}])`\n );\n\n /** Validate destination agent exists */\n if (!this.agentContexts.has(transferDest)) {\n const availableAgents = Array.from(\n this.agentContexts.keys()\n ).join(', ');\n console.error(\n `[MultiAgentGraph] Transfer to non-existent agent \"${transferDest}\". Available: ${availableAgents}`\n );\n /** Return error to model so it can self-correct */\n const errorMsg = new ToolMessage({\n content: `Transfer failed: agent \"${transferDest}\" does not exist. Available agents: ${availableAgents}. Please choose a valid agent to transfer to.`,\n tool_call_id: (lastMessage as ToolMessage).tool_call_id,\n name: lastMessage.name,\n });\n (errorMsg as ToolMessage).status = 'error';\n return {\n messages: [...result.messages, errorMsg],\n };\n }\n\n /** Pre-handoff context compaction: if receiving agent has smaller budget */\n const receiverContext = this.agentContexts.get(transferDest);\n const senderContext = this.agentContexts.get(agentId);\n if (\n receiverContext?.maxContextTokens != null &&\n senderContext?.tokenCounter != null &&\n receiverContext.maxContextTokens > 0\n ) {\n let currentSize = 0;\n for (const msg of result.messages) {\n currentSize += senderContext.tokenCounter(msg);\n }\n const receiverBudget = receiverContext.maxContextTokens;\n\n if (currentSize > receiverBudget * 0.7) {\n console.warn(\n `[MultiAgentGraph] Pre-handoff compaction: context (${currentSize} tokens) exceeds ` +\n `70% of receiver \"${transferDest}\" budget (${receiverBudget} tokens)`\n );\n\n /** Generate handoff briefing */\n const senderName = senderContext.name ?? agentId;\n if (senderContext.summarizeCallback) {\n try {\n const briefingResult = await summarize(\n result.messages,\n async (prompt, _maxTokens) =>\n senderContext.summarizeCallback!([\n new HumanMessage(prompt),\n ]),\n {\n tokenCounter: senderContext.tokenCounter,\n summaryBudget: Math.floor(receiverBudget * 0.2),\n isMultiAgent: true,\n agentWorkflowState: {\n currentAgentId: transferDest,\n agentChain: [agentId, transferDest],\n pendingAgents: [],\n },\n }\n );\n\n const briefingMsg = new SystemMessage(\n `[Handoff Briefing from \"${senderName}\"]\\n${briefingResult.summary}`\n );\n\n /** Replace messages with briefing + last 3 messages */\n const keepCount = Math.min(3, result.messages.length);\n result = {\n ...result,\n messages: [\n briefingMsg,\n ...result.messages.slice(\n result.messages.length - keepCount\n ),\n ],\n };\n\n console.info(\n `[MultiAgentGraph] Pre-handoff compaction complete: ${currentSize} tokens → briefing + ${keepCount} messages`\n );\n } catch (compactErr) {\n console.error(\n '[MultiAgentGraph] Pre-handoff compaction failed:',\n compactErr\n );\n /** Continue without compaction — let receiver handle the overflow */\n }\n } else {\n /** No summary callback — use emergency summary */\n const emergencySummary = createEmergencySummary(\n result.messages\n );\n const briefingMsg = new SystemMessage(\n `[Handoff Briefing from \"${senderName}\" — Emergency]\\n${emergencySummary}`\n );\n const keepCount = Math.min(3, result.messages.length);\n result = {\n ...result,\n messages: [\n briefingMsg,\n ...result.messages.slice(\n result.messages.length - keepCount\n ),\n ],\n };\n }\n }\n }\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: agentId,\n sourceAgentName: this.agentContexts.get(agentId)?.name ?? agentId,\n destinationAgentId: transferDest,\n destinationAgentName: this.agentContexts.get(transferDest)?.name ?? transferDest,\n edgeType: EdgeType.TRANSFER,\n timestamp: Date.now(),\n },\n config\n );\n\n return new Command({\n update: result,\n goto: transferDest,\n });\n } else {\n /** No transfer - proceed with sequence edges */\n console.debug(\n `[MultiAgentGraph] Command routing: \"${agentId}\" -> no transfer, following sequence edges: [${Array.from(sequenceDestinations).join(', ')}]`\n );\n const directDests = Array.from(sequenceDestinations);\n for (const dest of directDests) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_AGENT_TRANSITION,\n {\n sourceAgentId: agentId,\n sourceAgentName: this.agentContexts.get(agentId)?.name ?? agentId,\n destinationAgentId: dest,\n destinationAgentName: this.agentContexts.get(dest)?.name ?? dest,\n edgeType: EdgeType.SEQUENCE,\n timestamp: Date.now(),\n },\n config\n );\n }\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n /**\n * Add starting edges from START to entry agent(s).\n *\n * Multi-turn resumption: when `resumeFromAgentId` is set and refers to a\n * valid agent in this graph, START routes exclusively to that agent so\n * follow-up messages continue where the previous turn left off.\n *\n * Default behavior (no resume): static edges to all starting nodes,\n * preserving parallel execution for graphs with multiple entry points.\n */\n const validResumeAgent =\n this.resumeFromAgentId != null &&\n this.agentContexts.has(this.resumeFromAgentId);\n\n if (validResumeAgent) {\n const resumeAgentId = this.resumeFromAgentId!;\n console.debug(\n `[MultiAgentGraph] Multi-turn resumption: routing START → \"${resumeAgentId}\" (skipping default starting nodes: [${Array.from(this.startingNodes).join(', ')}])`\n );\n\n /**\n * Build route map containing both the resume agent and default starting\n * nodes. This is required by LangGraph — all possible destinations must\n * be declared even if the router always picks one.\n */\n const allPossibleStarts = new Set([\n ...this.startingNodes,\n resumeAgentId,\n ]);\n const routeMap: Record<string, string> = {};\n for (const nodeId of allPossibleStarts) {\n routeMap[nodeId] = nodeId;\n }\n\n builder.addConditionalEdges(\n START,\n () => resumeAgentId,\n routeMap as unknown as never\n );\n } else {\n if (this.resumeFromAgentId != null) {\n console.warn(\n `[MultiAgentGraph] resumeFromAgentId \"${this.resumeFromAgentId}\" not found in graph — falling back to default starting nodes`\n );\n }\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n }\n\n /**\n * Add approval gate nodes for sequence edges with approvalGate config.\n * Gates are inserted between source and destination agents.\n * They ALWAYS fire regardless of ExecutionContext.\n */\n const gatedEdges = new Set<t.GraphEdge>();\n\n for (const edge of this.sequenceEdges) {\n if (!edge.approvalGate) {\n continue;\n }\n\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n for (const source of sources) {\n for (const dest of destinations) {\n const gateNodeId = getApprovalGateNodeId(edge.approvalGate.gateId);\n const onDeny = edge.approvalGate.onDeny ?? 'stop';\n\n // Add the gate node\n const gateNode = createApprovalGateNode(\n edge.approvalGate,\n source,\n dest,\n );\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addNode(gateNodeId, gateNode);\n\n // Wire: source → gate\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, gateNodeId);\n\n // Wire: gate → destination (always, since approval is handled\n // by the interrupt/resume mechanism — if denied, the host\n // can choose not to resume, or resume with approved=false\n // and the gate returns empty state)\n if (onDeny === 'skip') {\n // Conditional edge: approved → destination, denied → END\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(gateNodeId, dest);\n } else {\n // Direct edge to destination — denial stops via non-resume or\n // the host terminates the graph\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(gateNodeId, dest);\n }\n }\n }\n\n gatedEdges.add(edge);\n }\n\n /**\n * Add sequence edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n * Skip edges that have approval gates (already handled above)\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.sequenceEdges) {\n if (gatedEdges.has(edge)) {\n continue;\n }\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n return {\n messages: [new HumanMessage(promptText)],\n agentMessages: messagesStateReducer(filteredMessages, [\n new HumanMessage(promptText),\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both transfer and sequence edges */\n const sourceTransferEdges = this.transferEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceSequenceEdges = this.sequenceEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceTransferEdges.length > 0 && sourceSequenceEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAoCA;AACA,MAAM,6BAA6B,GAAG,qCAAqC;AAE3E;;;;;;;;;;;;;AAaG;AACG,MAAO,eAAgB,SAAQ,aAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACtC,aAAa,GAAkB,EAAE;IACjC,aAAa,GAAkB,EAAE;IACjC,YAAY,GAAkB,EAAE;AACxC;;;;;;AAMG;AACK,IAAA,gBAAgB,GAAyC,IAAI,GAAG,EAAE;AAC1E;;;;;;;;;AASG;AACK,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AAC5D;;;AAGG;AACK,IAAA,iBAAiB;AAEzB;;;;AAIG;AACK,IAAA,iBAAiB;AAEz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AE;;wBAE5B,MAAM,mBAAmB,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BAC1D,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;wBACF,MAAM,mBAAmB,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BAC1D,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,wBAAA,CAAC,CAAC;;AAGF,wBAAA,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,IAAI,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE;4BACpE;wBACF;;;AAIA,wBAAA,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC;oBACtC;gBACF;YACF;QACF;QAEA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,cAAkC,CAAC;IACjE;AACD;;;;"}
@@ -90,6 +90,20 @@ class IllumaBedrockConverse extends ChatBedrockConverse {
90
90
  invocationParams(options) {
91
91
  const params = super.invocationParams(options);
92
92
  // Add cachePoint to tools array if promptCache is enabled and tools exist
93
+ /**
94
+ * Bedrock requires all toolSpec.description fields to be non-empty strings.
95
+ * Some tools (e.g., MCP-sourced or dynamically created) may have empty or
96
+ * missing descriptions. Patch them here to avoid Bedrock validation errors.
97
+ */
98
+ if (params.toolConfig?.tools &&
99
+ Array.isArray(params.toolConfig.tools)) {
100
+ for (const t of params.toolConfig.tools) {
101
+ const spec = t.toolSpec;
102
+ if (spec && (!spec.description || spec.description === '')) {
103
+ spec.description = spec.description || `Tool: ${spec.name ?? 'unknown'}`;
104
+ }
105
+ }
106
+ }
93
107
  // Only Claude models support cachePoint - check model name
94
108
  const modelId = this.model.toLowerCase();
95
109
  const isClaudeModel = modelId.includes('claude') || modelId.includes('anthropic');