@librechat/agents 3.0.64 → 3.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.cjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\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 { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_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 handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct 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 directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\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 constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\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 direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\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 // 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 direct edges from this node\n for (const edge of this.directEdges) {\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 handoff edges for traversal (but they don't create parallel groups)\n for (const edge of 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 * 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 handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\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 // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n for (const edge of edges) {\n handoffTools.push(...this.createHandoffToolsForEdge(edge));\n }\n\n // Add handoff tools to the agent's existing tools\n if (!agentContext.tools) {\n agentContext.tools = [];\n }\n agentContext.tools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n */\n private createHandoffToolsForEdge(edge: t.GraphEdge): 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 hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\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 hasHandoffInput &&\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 },\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: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\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 toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\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 });\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: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\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 * extracted from the transfer to be injected as a HumanMessage preamble.\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 and extracted instructions, or null if not a handoff\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): { filteredMessages: BaseMessage[]; instructions: string | null } | 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 handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : 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(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\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 const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\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 return { filteredMessages, instructions };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\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 handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\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) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\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) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\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 handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions } = handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /** If there are instructions, inject them as a HumanMessage to ground the agent */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n\n /** Update token map if we have a token counter */\n const agentContext = this.agentContexts.get(agentId);\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 instructions message */\n const instructionsMsg = new HumanMessage(instructions);\n freshTokenMap[messagesForAgent.length - 1] =\n agentContext.tokenCounter(instructionsMsg);\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState);\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);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff 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 /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\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 // Add starting edges for all starting nodes\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 * Add direct 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.directEdges) {\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 handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.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 (sourceHandoffEdges.length > 0 && sourceDirectEdges.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":["StandardGraph","tools","tool","getCurrentTaskInput","ToolMessage","Command","z","Constants","messages","AIMessage","Annotation","messagesStateReducer","StateGraph","END","HumanMessage","START","getBufferString","PromptTemplate"],"mappings":";;;;;;;;;;AAwBA;AACA,MAAM,4BAA4B,GAAG,qCAAqC;AAE1E;;;;;;;;;;;;;AAaG;AACG,MAAO,eAAgB,SAAQA,mBAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACtC,WAAW,GAAkB,EAAE;IAC/B,YAAY,GAAkB,EAAE;AACxC;;;;;;;;;AASG;AACK,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AAE5D,IAAA,WAAA,CAAY,KAA6B,EAAA;QACvC,KAAK,CAAC,KAAK,CAAC;AACZ,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK;QACxB,IAAI,CAAC,eAAe,EAAE;QACtB,IAAI,CAAC,YAAY,EAAE;QACnB,IAAI,CAAC,kBAAkB,EAAE;;AAG3B;;AAEG;IACK,eAAe,GAAA;AACrB,QAAA,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE;;;AAG7B,YAAA,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,EAAE;AAC9B,gBAAA,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC;;AACtB,iBAAA,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;AAChE,gBAAA,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;;iBACvB;;gBAEL,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBACjE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,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CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,yBAAC,CAAC;wBACF,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BACtD,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,yBAAC,CAAC;;AAGF,wBAAA,IAAI,kBAAkB,CAAC,MAAM,GAAG,CAAC,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;4BACjE;;;;AAKF,wBAAA,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC;;;;;QAM5C,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,cAAkC,CAAC;;AAElE;;;;"}
1
+ {"version":3,"file":"MultiAgentGraph.cjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\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 { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_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 handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct 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 directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\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 constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\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 direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\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 // 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 direct edges from this node\n for (const edge of this.directEdges) {\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 handoff edges for traversal (but they don't create parallel groups)\n for (const edge of 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 * 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 handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\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 // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n // Add handoff tools to the agent's existing tools\n if (!agentContext.tools) {\n agentContext.tools = [];\n }\n agentContext.tools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\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 hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\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 hasHandoffInput &&\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: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\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 toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\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: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\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 * and source agent 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, and source agent, or null if not a handoff\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\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 handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : 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(HANDOFF_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 /** 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 const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\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 return { filteredMessages, instructions, sourceAgentName };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\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 handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\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) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\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) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\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 handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, sourceAgentName } =\n handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * This updates the system message to include agent identity info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /** If there are instructions, inject them as a HumanMessage to ground the agent */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\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 instructions message */\n const instructionsMsg = new HumanMessage(instructions);\n freshTokenMap[messagesForAgent.length - 1] =\n agentContext.tokenCounter(instructionsMsg);\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState);\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);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff 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 /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\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 // Add starting edges for all starting nodes\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 * Add direct 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.directEdges) {\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 handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.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 (sourceHandoffEdges.length > 0 && sourceDirectEdges.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":["StandardGraph","tools","tool","getCurrentTaskInput","ToolMessage","Command","z","Constants","messages","AIMessage","Annotation","messagesStateReducer","StateGraph","END","HumanMessage","START","getBuffer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an AgentContext from configuration with token accounting initialization
14
14
  */
15
15
  static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
16
- const { agentId, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, } = agentConfig;
16
+ const { agentId, name, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, } = agentConfig;
17
17
  const agentContext = new AgentContext({
18
18
  agentId,
19
+ name: name ?? agentId,
19
20
  provider,
20
21
  clientOptions,
21
22
  maxContextTokens,
@@ -55,6 +56,8 @@ class AgentContext {
55
56
  }
56
57
  /** Agent identifier */
57
58
  agentId;
59
+ /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */
60
+ name;
58
61
  /** Provider for this specific agent */
59
62
  provider;
60
63
  /** Client options for this agent */
@@ -110,8 +113,14 @@ class AgentContext {
110
113
  tokenCalculationPromise;
111
114
  /** Format content blocks as strings (for legacy compatibility) */
112
115
  useLegacyContent = false;
113
- constructor({ agentId, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, instructions, additionalInstructions, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }) {
116
+ /**
117
+ * Handoff context when this agent receives control via handoff.
118
+ * Contains source agent name for system message identity context.
119
+ */
120
+ handoffContext;
121
+ constructor({ agentId, name, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, instructions, additionalInstructions, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }) {
114
122
  this.agentId = agentId;
123
+ this.name = name;
115
124
  this.provider = provider;
116
125
  this.clientOptions = clientOptions;
117
126
  this.maxContextTokens = maxContextTokens;
@@ -207,22 +216,48 @@ class AgentContext {
207
216
  }
208
217
  /**
209
218
  * Builds the raw instructions string (without creating SystemMessage).
219
+ * Includes agent identity preamble and handoff context when available.
210
220
  */
211
221
  buildInstructionsString() {
212
- let result = this.instructions ?? '';
222
+ const parts = [];
223
+ /** Build agent identity and handoff context preamble */
224
+ const identityPreamble = this.buildIdentityPreamble();
225
+ if (identityPreamble) {
226
+ parts.push(identityPreamble);
227
+ }
228
+ /** Add main instructions */
229
+ if (this.instructions != null && this.instructions !== '') {
230
+ parts.push(this.instructions);
231
+ }
232
+ /** Add additional instructions */
213
233
  if (this.additionalInstructions != null &&
214
234
  this.additionalInstructions !== '') {
215
- result = result
216
- ? `${result}\n\n${this.additionalInstructions}`
217
- : this.additionalInstructions;
235
+ parts.push(this.additionalInstructions);
218
236
  }
237
+ /** Add programmatic tools documentation */
219
238
  const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
220
239
  if (programmaticToolsDoc) {
221
- result = result
222
- ? `${result}${programmaticToolsDoc}`
223
- : programmaticToolsDoc;
240
+ parts.push(programmaticToolsDoc);
241
+ }
242
+ return parts.join('\n\n');
243
+ }
244
+ /**
245
+ * Builds the agent identity preamble including handoff context if present.
246
+ * This helps the agent understand its role in the multi-agent workflow.
247
+ */
248
+ buildIdentityPreamble() {
249
+ /** Only include preamble if we have handoff context (indicates multi-agent workflow) */
250
+ if (!this.handoffContext)
251
+ return '';
252
+ /** Use name (falls back to agentId if not provided) */
253
+ const displayName = this.name ?? this.agentId;
254
+ const lines = [];
255
+ lines.push('## Agent Context');
256
+ lines.push(`You are the "${displayName}" agent.`);
257
+ if (this.handoffContext.sourceAgentName) {
258
+ lines.push(`Control was transferred to you from the "${this.handoffContext.sourceAgentName}" agent.`);
224
259
  }
225
- return result;
260
+ return lines.join('\n');
226
261
  }
227
262
  /**
228
263
  * Build system runnable from pre-built instructions string.
@@ -281,6 +316,7 @@ class AgentContext {
281
316
  this.tokenTypeSwitch = undefined;
282
317
  this.currentTokenType = ContentTypes.TEXT;
283
318
  this.discoveredToolNames.clear();
319
+ this.handoffContext = undefined;
284
320
  }
285
321
  /**
286
322
  * Update the token count map with instruction tokens
@@ -340,6 +376,26 @@ class AgentContext {
340
376
  }
341
377
  return registry;
342
378
  }
379
+ /**
380
+ * Sets the handoff context for this agent.
381
+ * Call this when the agent receives control via handoff from another agent.
382
+ * Marks system runnable as stale to include handoff context in system message.
383
+ * @param sourceAgentName - The name of the agent that handed off to this agent
384
+ */
385
+ setHandoffContext(sourceAgentName) {
386
+ this.handoffContext = { sourceAgentName };
387
+ this.systemRunnableStale = true;
388
+ }
389
+ /**
390
+ * Clears any handoff context.
391
+ * Call this when resetting the agent or when handoff context is no longer relevant.
392
+ */
393
+ clearHandoffContext() {
394
+ if (this.handoffContext) {
395
+ this.handoffContext = undefined;
396
+ this.systemRunnableStale = true;
397
+ }
398
+ }
343
399
  /**
344
400
  * Marks tools as discovered via tool search.
345
401
  * Discovered tools will be included in the next model binding.
@@ -1 +1 @@
1
- {"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;AACjB,SAAA,CAAC;QAEF,IAAI,YAAY,EAAE;;;;YAIhB,YAAY,CAAC,wBAAwB,EAAE;AAEvC,YAAA,MAAM,QAAQ,GAAG,kBAAkB,IAAI,EAAE;AACzC,YAAA,YAAY,CAAC,kBAAkB,GAAG,QAAQ;YAC1C,YAAY,CAAC,uBAAuB,GAAG;iBACpC,0BAA0B,CAAC,YAAY;iBACvC,IAAI,CAAC,MAAK;;AAET,gBAAA,YAAY,CAAC,8BAA8B,CAAC,QAAQ,CAAC;AACvD,aAAC;AACA,i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,kBAAkB,GAAA;QAChB,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACrC,OAAO,IAAI,CAAC,KAAK;;QAGnB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;AAChD,YAAA,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,EAAE;gBACrB,OAAO,IAAI,CAAC;;AAGd,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,IAAI,CAAC;;;YAId,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
1
+ {"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n name,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n name?: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /**\n * Handoff context when this agent receives control via handoff.\n * Contains source agent name for system message identity context.\n */\n handoffContext?: {\n sourceAgentName: string;\n };\n\n constructor({\n agentId,\n name,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n name?: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n * Includes agent identity preamble and handoff context when available.\n */\n private buildInstructionsString(): string {\n const parts: string[] = [];\n\n /** Build agent identity and handoff context preamble */\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n /** Add main instructions */\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n /** Add additional instructions */\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n /** Add programmatic tools documentation */\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the agent identity preamble including handoff context if present.\n * This helps the agent understand its role in the multi-agent workflow.\n */\n private buildIdentityPreamble(): string {\n /** Only include preamble if we have handoff context (indicates multi-agent workflow) */\n if (!this.handoffContext) return '';\n\n /** Use name (falls back to agentId if not provided) */\n const displayName = this.name ?? this.agentId;\n\n const lines: string[] = [];\n lines.push('## Agent Context');\n lines.push(`You are the \"${displayName}\" agent.`);\n\n if (this.handoffContext.sourceAgentName) {\n lines.push(\n `Control was transferred to you from the \"${this.handoffContext.sourceAgentName}\" agent.`\n );\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n this.handoffContext = undefined;\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Sets the handoff context for this agent.\n * Call this when the agent receives control via handoff from another agent.\n * Marks system runnable as stale to include handoff context in system message.\n * @param sourceAgentName - The name of the agent that handed off to this agent\n */\n setHandoffContext(sourceAgentName: string): void {\n this.handoffContext = { sourceAgentName };\n this.systemRunnableStale = true;\n }\n\n /**\n * Clears any handoff context.\n * Call this when resetting the agent or when handoff context is no longer relevant.\n */\n clearHandoffContext(): void {\n if (this.handoffContext) {\n this.handoffContext = undefined;\n this.systemRunnableStale = true;\n }\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,IAAI,EAAE,IAAI,IAAI,OAAO;YACrB,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;AACjB,SAAA,CAAC;QAEF,IAAI,YAAY,EAAE;;;;YAIhB,YAAY,CAAC,wBAAwB,EAAE;AAEvC,YAAA,MAAM,QAAQ,GAAG,k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