@librechat/agents 3.3.8 → 3.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs +47 -13
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +35 -2
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/hitl/askUserQuestion.cjs +3 -2
- package/dist/cjs/hitl/askUserQuestion.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs +18 -48
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +174 -29
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/langfuseConfig.cjs +12 -0
- package/dist/cjs/langfuseConfig.cjs.map +1 -1
- package/dist/cjs/langfuseRuntimeContext.cjs +23 -2
- package/dist/cjs/langfuseRuntimeContext.cjs.map +1 -1
- package/dist/cjs/langfuseRuntimeScope.cjs +39 -8
- package/dist/cjs/langfuseRuntimeScope.cjs.map +1 -1
- package/dist/cjs/langfuseSpanRegistry.cjs +95 -0
- package/dist/cjs/langfuseSpanRegistry.cjs.map +1 -0
- package/dist/cjs/langfuseTraceShaping.cjs +121 -4
- package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +39 -15
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +25 -5
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/init.cjs +3 -3
- package/dist/cjs/llm/invoke.cjs +5 -5
- package/dist/cjs/llm/openai/index.cjs +1 -1
- package/dist/cjs/main.cjs +10 -10
- package/dist/cjs/messages/prune.cjs +13 -1
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/prompts/activityLabel.cjs +24 -12
- package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
- package/dist/cjs/run.cjs +47 -22
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/messageSerialization.cjs +6 -0
- package/dist/cjs/session/messageSerialization.cjs.map +1 -1
- package/dist/cjs/stream.cjs +21 -10
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +5 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +253 -24
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +1 -1
- package/dist/cjs/tools/search/tool.cjs +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -1
- package/dist/cjs/utils/index.cjs +2 -2
- package/dist/esm/graphs/Graph.mjs +48 -14
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +35 -2
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/hitl/askUserQuestion.mjs +3 -2
- package/dist/esm/hitl/askUserQuestion.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs +18 -48
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +176 -28
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/langfuseConfig.mjs +10 -1
- package/dist/esm/langfuseConfig.mjs.map +1 -1
- package/dist/esm/langfuseRuntimeContext.mjs +21 -3
- package/dist/esm/langfuseRuntimeContext.mjs.map +1 -1
- package/dist/esm/langfuseRuntimeScope.mjs +39 -10
- package/dist/esm/langfuseRuntimeScope.mjs.map +1 -1
- package/dist/esm/langfuseSpanRegistry.mjs +91 -0
- package/dist/esm/langfuseSpanRegistry.mjs.map +1 -0
- package/dist/esm/langfuseTraceShaping.mjs +121 -4
- package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +39 -15
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +25 -5
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/init.mjs +2 -2
- package/dist/esm/llm/invoke.mjs +5 -5
- package/dist/esm/llm/openai/index.mjs +1 -1
- package/dist/esm/main.mjs +8 -8
- package/dist/esm/messages/prune.mjs +13 -1
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/prompts/activityLabel.mjs +24 -12
- package/dist/esm/prompts/activityLabel.mjs.map +1 -1
- package/dist/esm/run.mjs +47 -22
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/messageSerialization.mjs +6 -0
- package/dist/esm/session/messageSerialization.mjs.map +1 -1
- package/dist/esm/stream.mjs +21 -10
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +5 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +254 -25
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +1 -1
- package/dist/esm/tools/search/tool.mjs +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -1
- package/dist/esm/utils/index.mjs +2 -2
- package/dist/types/graphs/Graph.d.ts +19 -0
- package/dist/types/hitl/askUserQuestion.d.ts +11 -1
- package/dist/types/langfuse.d.ts +16 -8
- package/dist/types/langfuseConfig.d.ts +6 -0
- package/dist/types/langfuseRuntimeContext.d.ts +27 -1
- package/dist/types/langfuseRuntimeScope.d.ts +17 -2
- package/dist/types/langfuseSpanRegistry.d.ts +17 -0
- package/dist/types/langfuseTraceShaping.d.ts +2 -1
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
- package/dist/types/session/types.d.ts +1 -0
- package/dist/types/tools/ToolNode.d.ts +7 -1
- package/dist/types/types/hitl.d.ts +8 -0
- package/dist/types/types/tools.d.ts +30 -0
- package/package.json +7 -4
- package/src/__tests__/stream.eagerArgsDivergence.test.ts +753 -0
- package/src/graphs/Graph.ts +69 -20
- package/src/graphs/MultiAgentGraph.ts +56 -2
- package/src/graphs/__tests__/composition.smoke.test.ts +4 -0
- package/src/hitl/askUserQuestion.ts +14 -1
- package/src/instrumentation.ts +35 -77
- package/src/langfuse.ts +320 -43
- package/src/langfuseConfig.ts +24 -0
- package/src/langfuseRuntimeContext.ts +43 -1
- package/src/langfuseRuntimeScope.ts +94 -21
- package/src/langfuseSpanRegistry.ts +131 -0
- package/src/langfuseTraceShaping.ts +194 -7
- package/src/llm/anthropic/utils/message_inputs.ts +70 -19
- package/src/llm/anthropic/utils/streaming-tool-input.test.ts +186 -11
- package/src/llm/bedrock/utils/message_inputs.test.ts +120 -4
- package/src/llm/bedrock/utils/message_inputs.ts +32 -7
- package/src/messages/prune.ts +12 -1
- package/src/prompts/activityLabel.ts +23 -6
- package/src/run.ts +76 -45
- package/src/scripts/activity-labels/captured.json +56 -0
- package/src/scripts/activity-labels/checks.cjs +205 -0
- package/src/scripts/activity-labels/corpus.cjs +473 -0
- package/src/scripts/activity-labels/report.cjs +203 -0
- package/src/scripts/activity-labels/rescore.cjs +102 -0
- package/src/scripts/activity-labels/run.ts +705 -0
- package/src/scripts/activity-labels/variants.ts +71 -0
- package/src/session/messageSerialization.ts +12 -1
- package/src/session/types.ts +1 -0
- package/src/specs/activity-label-prompt.test.ts +26 -10
- package/src/specs/agent-handoffs.test.ts +306 -0
- package/src/specs/langfuse-callbacks.test.ts +456 -0
- package/src/specs/langfuse-routing.integration.test.ts +138 -1
- package/src/specs/langfuse-span-registry.test.ts +70 -0
- package/src/specs/langfuse-trace-shaping.test.ts +294 -0
- package/src/specs/prune.test.ts +38 -1
- package/src/stream.ts +70 -6
- package/src/summarization/node.ts +5 -0
- package/src/tools/ToolNode.ts +400 -9
- package/src/tools/__tests__/ToolNode.invalidToolCalls.test.ts +757 -0
- package/src/tools/__tests__/hitl.test.ts +58 -0
- package/src/types/hitl.ts +8 -0
- package/src/types/tools.ts +35 -1
|
@@ -50,6 +50,28 @@ function extractLegacyHandoffInstructions(content, promptLabels) {
|
|
|
50
50
|
if (markerIndex >= 0) return content.slice(markerIndex + markerLength).trim();
|
|
51
51
|
return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;
|
|
52
52
|
}
|
|
53
|
+
/** Whether a tool name marks a handoff transfer (static or conditional). */
|
|
54
|
+
function isTransferToolName(name) {
|
|
55
|
+
return typeof name === "string" && (name.startsWith("lc_transfer_to_") || name === "conditional_transfer");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Drop transfer `tool_use` content blocks from an AI message's array content.
|
|
59
|
+
* Companion to the reception's tool-call filtering: array-content providers
|
|
60
|
+
* (Anthropic) serialize retained blocks verbatim, so a transfer block whose
|
|
61
|
+
* call/result the reception stripped — or a parallel sibling's transfer block,
|
|
62
|
+
* whose result never reaches this recipient's state — would replay as an
|
|
63
|
+
* unmatched `tool_use`. Matched by the gathered ids AND by transfer name
|
|
64
|
+
* (sibling blocks have no collectable id here). String content passes through.
|
|
65
|
+
*/
|
|
66
|
+
function filterTransferToolUseBlocks(content, transferToolCallIds) {
|
|
67
|
+
if (!Array.isArray(content)) return content;
|
|
68
|
+
return content.filter((block) => {
|
|
69
|
+
if (typeof block !== "object" || block?.type !== "tool_use") return true;
|
|
70
|
+
const toolUse = block;
|
|
71
|
+
if (toolUse.id != null && transferToolCallIds.has(toolUse.id)) return false;
|
|
72
|
+
return !isTransferToolName(toolUse.name);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
53
75
|
function isValidHandoffGroupId(value) {
|
|
54
76
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
55
77
|
}
|
|
@@ -528,9 +550,20 @@ var MultiAgentGraph = class extends StandardGraph {
|
|
|
528
550
|
const remainingToolCalls = toolCalls.filter((tc) => tc.id == null || !transferToolCallIds.has(tc.id));
|
|
529
551
|
if (remainingToolCalls.length < toolCalls.length) {
|
|
530
552
|
if (remainingToolCalls.length > 0 || typeof aiMsg.content === "string" && aiMsg.content.trim()) {
|
|
531
|
-
/**
|
|
553
|
+
/**
|
|
554
|
+
* Keep the message but without transfer tool calls — AND
|
|
555
|
+
* without their `tool_use` content blocks. Array-content
|
|
556
|
+
* providers (Anthropic) serialize the retained blocks
|
|
557
|
+
* verbatim, so a transfer block whose call/result this
|
|
558
|
+
* filter just stripped would reach the receiving agent as
|
|
559
|
+
* an unmatched `tool_use` and the provider rejects the
|
|
560
|
+
* request. Filtered by transfer NAME as well as the
|
|
561
|
+
* gathered ids: a parallel sibling's transfer block has no
|
|
562
|
+
* result in THIS recipient's state, so its id is never
|
|
563
|
+
* collected, but its name still marks it.
|
|
564
|
+
*/
|
|
532
565
|
const filteredAiMsg = new AIMessage({
|
|
533
|
-
content: aiMsg.content,
|
|
566
|
+
content: filterTransferToolUseBlocks(aiMsg.content, transferToolCallIds),
|
|
534
567
|
tool_calls: remainingToolCalls,
|
|
535
568
|
id: aiMsg.id
|
|
536
569
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultiAgentGraph.mjs","names":["aiMsg"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\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;\nconst HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';\n\n/**\n * Handoff and fan-in prompts that route work between agents. Built in-run and\n * never persisted as standalone payload entries, so they are marked synthetic:\n * `messagesStateReducer` would otherwise give them a plain UUID and downstream\n * consumers — compaction coverage anchors — could not tell them apart from a\n * message replayed out of the payload.\n */\nfunction buildRoutingPrompt(content: string): HumanMessage {\n return new HumanMessage({\n content,\n additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },\n });\n}\n\nfunction getHandoffInstructions(\n input: Record<string, unknown>,\n promptKey: string,\n hasHandoffInput: boolean\n): string | null {\n if (\n !hasHandoffInput ||\n !Object.prototype.hasOwnProperty.call(input, promptKey)\n ) {\n return null;\n }\n const value = input[promptKey];\n return typeof value === 'string' ? value : null;\n}\n\nfunction formatHandoffPromptLabel(promptKey: string): string {\n return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);\n}\n\nfunction extractLegacyHandoffInstructions(\n content: string,\n promptLabels: Set<string> | undefined\n): string | null {\n let markerIndex = -1;\n let markerLength = 0;\n for (const label of promptLabels ?? []) {\n const marker = `\\n\\n${label}:`;\n const index = content.indexOf(marker);\n if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {\n markerIndex = index;\n markerLength = marker.length;\n }\n }\n if (markerIndex >= 0) {\n return content.slice(markerIndex + markerLength).trim();\n }\n return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction withHandoffGroupMetadata(\n config: LangGraphRunnableConfig | undefined,\n groupId: number | undefined\n): LangGraphRunnableConfig {\n return {\n ...config,\n metadata: {\n ...config?.metadata,\n [Constants.HANDOFF_GROUP_ID]: groupId ?? null,\n },\n };\n}\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 private handoffPromptLabels: Map<string, Set<string>> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\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 if (typeof edge.prompt === 'string') {\n const label = formatHandoffPromptLabel(\n edge.promptKey ?? 'instructions'\n );\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n const labels =\n this.handoffPromptLabels.get(destination) ?? new Set<string>();\n labels.add(label);\n this.handoffPromptLabels.set(destination, labels);\n }\n }\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 if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.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 (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? '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 const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Conditionally transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\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 ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\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 ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const 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 (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Successfully transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\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 ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n const state = runtime.state 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 ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n parallelGroupId?: number;\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * A handoff is active only while resolving the most recent assistant\n * tool-call round. Older transfer results remain in conversation history,\n * but must not be reused when this agent is reached later through a direct\n * edge or cycle.\n */\n const activeTransferToolCallIds = new Set<string>();\n let activeToolMessageStartIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'tool') continue;\n\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n activeTransferToolCallIds.add(toolCall.id);\n }\n }\n activeToolMessageStartIndex = i + 1;\n }\n break;\n }\n\n if (activeTransferToolCallIds.size === 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 >= activeToolMessageStartIndex; 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 (\n typeof toolName !== 'string' ||\n !activeTransferToolCallIds.has(candidateMsg.tool_call_id)\n ) {\n continue;\n }\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 : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n\n const structuredInstructions =\n toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];\n const instructions =\n typeof structuredInstructions === 'string'\n ? structuredInstructions.trim()\n : extractLegacyHandoffInstructions(\n contentStr,\n this.handoffPromptLabels.get(agentId)\n );\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n const storedParallelGroupId =\n toolMessage.additional_kwargs[Constants.HANDOFF_GROUP_ID];\n const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId)\n ? storedParallelGroupId\n : undefined;\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') {\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (\n typeof tName === 'string' &&\n (tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer')\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n } else if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n transferToolCallIds.add(toolCall.id);\n }\n }\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 {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n parallelGroupId,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.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 config?: LangGraphRunnableConfig\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 const agentContext = this.agentContexts.get(agentId);\n\n if (\n handoffContext?.sourceAgentName != null &&\n handoffContext.sourceAgentName !== ''\n ) {\n agentContext?.setHandoffContext(\n handoffContext.sourceAgentName,\n handoffContext.parallelSiblings\n );\n } else {\n agentContext?.clearHandoffContext();\n }\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, parallelGroupId } =\n handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n buildRoutingPrompt(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n buildRoutingPrompt(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(config, parallelGroupId)\n );\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 if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** 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: [buildRoutingPrompt(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 const promptMessage = buildRoutingPrompt(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\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"],"mappings":";;;;;;;;;;;AA0BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;;;;;;;;AASjC,SAAS,mBAAmB,SAA+B;CACzD,OAAO,IAAI,aAAa;EACtB;EACA,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;GAAM,QAAQ;EAAU;CACrE,CAAC;AACH;AAEA,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;CAET,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,yBAAyB,WAA2B;CAC3D,OAAO,UAAU,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,UAAU,MAAM,CAAC;AAC9D;AAEA,SAAS,iCACP,SACA,cACe;CACf,IAAI,cAAc;CAClB,IAAI,eAAe;CACnB,KAAK,MAAM,SAAS,gBAAgB,CAAC,GAAG;EACtC,MAAM,SAAS,OAAO,MAAM;EAC5B,MAAM,QAAQ,QAAQ,QAAQ,MAAM;EACpC,IAAI,SAAS,MAAM,cAAc,KAAK,QAAQ,cAAc;GAC1D,cAAc;GACd,eAAe,OAAO;EACxB;CACF;CACA,IAAI,eAAe,GACjB,OAAO,QAAQ,MAAM,cAAc,YAAY,CAAC,CAA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K,UAAU;MAChE,MAAM,gBAAgB,mBAAmB,UAAU;MACnD,OAAO;OACL,UAAU,CAAC,aAAa;OACxB,eAAe,qBAAqB,kBAAkB,CACpD,aACF,CAAC;MACH;KACF;;KAGA,OAAO,CAAC;IACV,CAAC;;IAGD,KAAK,MAAM,QAAQ,OAAO;KACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;KACjE,KAAK,MAAM,UAAU;;KAGnB,QAAQ,QAAQ,QAAQ,aAAa;IAEzC;;;IAKA,QAAQ,QAAQ,eAAe,WAAW;GAC5C;;GAEE,KAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;IACjE,KAAK,MAAM,UAAU,SAAS;;KAE5B,MAAM,qBAAqB,KAAK,aAAa,QAAQ,MAAM;MAEzD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;KACD,MAAM,oBAAoB,KAAK,YAAY,QAAQ,MAAM;MAEvD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
|
|
1
|
+
{"version":3,"file":"MultiAgentGraph.mjs","names":["aiMsg"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\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;\nconst HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';\n\n/**\n * Handoff and fan-in prompts that route work between agents. Built in-run and\n * never persisted as standalone payload entries, so they are marked synthetic:\n * `messagesStateReducer` would otherwise give them a plain UUID and downstream\n * consumers — compaction coverage anchors — could not tell them apart from a\n * message replayed out of the payload.\n */\nfunction buildRoutingPrompt(content: string): HumanMessage {\n return new HumanMessage({\n content,\n additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },\n });\n}\n\nfunction getHandoffInstructions(\n input: Record<string, unknown>,\n promptKey: string,\n hasHandoffInput: boolean\n): string | null {\n if (\n !hasHandoffInput ||\n !Object.prototype.hasOwnProperty.call(input, promptKey)\n ) {\n return null;\n }\n const value = input[promptKey];\n return typeof value === 'string' ? value : null;\n}\n\nfunction formatHandoffPromptLabel(promptKey: string): string {\n return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);\n}\n\nfunction extractLegacyHandoffInstructions(\n content: string,\n promptLabels: Set<string> | undefined\n): string | null {\n let markerIndex = -1;\n let markerLength = 0;\n for (const label of promptLabels ?? []) {\n const marker = `\\n\\n${label}:`;\n const index = content.indexOf(marker);\n if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {\n markerIndex = index;\n markerLength = marker.length;\n }\n }\n if (markerIndex >= 0) {\n return content.slice(markerIndex + markerLength).trim();\n }\n return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;\n}\n\n/** Whether a tool name marks a handoff transfer (static or conditional). */\nfunction isTransferToolName(name: unknown): boolean {\n return (\n typeof name === 'string' &&\n (name.startsWith(Constants.LC_TRANSFER_TO_) ||\n name === 'conditional_transfer')\n );\n}\n\n/**\n * Drop transfer `tool_use` content blocks from an AI message's array content.\n * Companion to the reception's tool-call filtering: array-content providers\n * (Anthropic) serialize retained blocks verbatim, so a transfer block whose\n * call/result the reception stripped — or a parallel sibling's transfer block,\n * whose result never reaches this recipient's state — would replay as an\n * unmatched `tool_use`. Matched by the gathered ids AND by transfer name\n * (sibling blocks have no collectable id here). String content passes through.\n */\nfunction filterTransferToolUseBlocks(\n content: AIMessage['content'],\n transferToolCallIds: ReadonlySet<string>\n): AIMessage['content'] {\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((block) => {\n if (\n typeof block !== 'object' ||\n (block as { type?: string } | null)?.type !== 'tool_use'\n ) {\n return true;\n }\n const toolUse = block as { id?: string; name?: string };\n if (toolUse.id != null && transferToolCallIds.has(toolUse.id)) {\n return false;\n }\n return !isTransferToolName(toolUse.name);\n });\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction withHandoffGroupMetadata(\n config: LangGraphRunnableConfig | undefined,\n groupId: number | undefined\n): LangGraphRunnableConfig {\n return {\n ...config,\n metadata: {\n ...config?.metadata,\n [Constants.HANDOFF_GROUP_ID]: groupId ?? null,\n },\n };\n}\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 private handoffPromptLabels: Map<string, Set<string>> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\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 if (typeof edge.prompt === 'string') {\n const label = formatHandoffPromptLabel(\n edge.promptKey ?? 'instructions'\n );\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n const labels =\n this.handoffPromptLabels.get(destination) ?? new Set<string>();\n labels.add(label);\n this.handoffPromptLabels.set(destination, labels);\n }\n }\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 if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.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 (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? '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 const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Conditionally transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\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 ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\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 ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const 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 (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Successfully transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\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 ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n const state = runtime.state 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 ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n parallelGroupId?: number;\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * A handoff is active only while resolving the most recent assistant\n * tool-call round. Older transfer results remain in conversation history,\n * but must not be reused when this agent is reached later through a direct\n * edge or cycle.\n */\n const activeTransferToolCallIds = new Set<string>();\n let activeToolMessageStartIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'tool') continue;\n\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n activeTransferToolCallIds.add(toolCall.id);\n }\n }\n activeToolMessageStartIndex = i + 1;\n }\n break;\n }\n\n if (activeTransferToolCallIds.size === 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 >= activeToolMessageStartIndex; 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 (\n typeof toolName !== 'string' ||\n !activeTransferToolCallIds.has(candidateMsg.tool_call_id)\n ) {\n continue;\n }\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 : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n\n const structuredInstructions =\n toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];\n const instructions =\n typeof structuredInstructions === 'string'\n ? structuredInstructions.trim()\n : extractLegacyHandoffInstructions(\n contentStr,\n this.handoffPromptLabels.get(agentId)\n );\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n const storedParallelGroupId =\n toolMessage.additional_kwargs[Constants.HANDOFF_GROUP_ID];\n const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId)\n ? storedParallelGroupId\n : undefined;\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') {\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (\n typeof tName === 'string' &&\n (tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer')\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n } else if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n transferToolCallIds.add(toolCall.id);\n }\n }\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 /**\n * Keep the message but without transfer tool calls — AND\n * without their `tool_use` content blocks. Array-content\n * providers (Anthropic) serialize the retained blocks\n * verbatim, so a transfer block whose call/result this\n * filter just stripped would reach the receiving agent as\n * an unmatched `tool_use` and the provider rejects the\n * request. Filtered by transfer NAME as well as the\n * gathered ids: a parallel sibling's transfer block has no\n * result in THIS recipient's state, so its id is never\n * collected, but its name still marks it.\n */\n const filteredAiMsg = new AIMessage({\n content: filterTransferToolUseBlocks(\n aiMsg.content,\n transferToolCallIds\n ),\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 {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n parallelGroupId,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.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 config?: LangGraphRunnableConfig\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 const agentContext = this.agentContexts.get(agentId);\n\n if (\n handoffContext?.sourceAgentName != null &&\n handoffContext.sourceAgentName !== ''\n ) {\n agentContext?.setHandoffContext(\n handoffContext.sourceAgentName,\n handoffContext.parallelSiblings\n );\n } else {\n agentContext?.clearHandoffContext();\n }\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, parallelGroupId } =\n handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n buildRoutingPrompt(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n buildRoutingPrompt(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(config, parallelGroupId)\n );\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 if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** 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: [buildRoutingPrompt(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 const promptMessage = buildRoutingPrompt(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\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"],"mappings":";;;;;;;;;;;AA0BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;;;;;;;;AASjC,SAAS,mBAAmB,SAA+B;CACzD,OAAO,IAAI,aAAa;EACtB;EACA,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;GAAM,QAAQ;EAAU;CACrE,CAAC;AACH;AAEA,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;CAET,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,yBAAyB,WAA2B;CAC3D,OAAO,UAAU,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,UAAU,MAAM,CAAC;AAC9D;AAEA,SAAS,iCACP,SACA,cACe;CACf,IAAI,cAAc;CAClB,IAAI,eAAe;CACnB,KAAK,MAAM,SAAS,gBAAgB,CAAC,GAAG;EACtC,MAAM,SAAS,OAAO,MAAM;EAC5B,MAAM,QAAQ,QAAQ,QAAQ,MAAM;EACpC,IAAI,SAAS,MAAM,cAAc,KAAK,QAAQ,cAAc;GAC1D,cAAc;GACd,eAAe,OAAO;EACxB;CACF;CACA,IAAI,eAAe,GACjB,OAAO,Q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QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
|
|
@@ -53,10 +53,11 @@ import { interrupt } from "@langchain/langgraph";
|
|
|
53
53
|
* });
|
|
54
54
|
* ```
|
|
55
55
|
*/
|
|
56
|
-
function askUserQuestion(question) {
|
|
56
|
+
function askUserQuestion(question, options) {
|
|
57
57
|
return interrupt({
|
|
58
58
|
type: "ask_user_question",
|
|
59
|
-
question
|
|
59
|
+
question,
|
|
60
|
+
...options?.toolCallId != null && options.toolCallId !== "" && { tool_call_id: options.toolCallId }
|
|
60
61
|
});
|
|
61
62
|
}
|
|
62
63
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"askUserQuestion.mjs","names":[],"sources":["../../../src/hitl/askUserQuestion.ts"],"sourcesContent":["/**\n * Typed convenience wrapper around LangGraph's `interrupt()` for the\n * `ask_user_question` interrupt category. Lets a custom graph node\n * (or a tool implementation) suspend execution to collect a free-form\n * answer from the human, without the host having to assemble the\n * interrupt payload by hand. The companion to `Run.resume(answer)` on\n * the host side.\n *\n * AsyncLocalStorage anchoring: this helper does NOT call\n * `runWithConfig` itself — it expects to be invoked from inside a\n * LangGraph node where the framework has already established the\n * runnable config. ToolNode is the one place in this codebase that\n * needs the manual `runWithConfig` shim, because its\n * `RunnableCallable.trace = false` skips the upstream tracing path\n * that normally sets up the AsyncLocalStorage frame; ordinary user\n * nodes (RunnableLambda, addNode callbacks) do not have that\n * constraint.\n */\n\nimport { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionRequest,\n AskUserQuestionResolution,\n AskUserQuestionInterruptPayload,\n} from '@/types/hitl';\n\n/**\n * Suspend the current graph node to ask the human a question. Returns\n * the host-supplied resolution after `Run.resume(resolution)` is\n * called against a Run rebuilt with the same `thread_id` and\n * checkpointer.\n *\n * On the FIRST call (no resume value available), `interrupt()` throws\n * a `GraphInterrupt` that LangGraph catches; this function does not\n * return — execution unwinds, the SDK persists the checkpoint, and\n * the run completes with `run.getInterrupt()` returning a\n * `RunInterruptResult` whose `payload` is an\n * `AskUserQuestionInterruptPayload`.\n *\n * On RESUME, LangGraph re-runs the node from the start and this call\n * returns the host's `AskUserQuestionResolution` directly.\n *\n * Hosts that prefer the raw `interrupt()` (e.g., to attach extra\n * metadata) can construct an `AskUserQuestionInterruptPayload` and\n * call `interrupt()` themselves — this helper is purely convenience.\n *\n * @example\n * ```ts\n * const builder = new StateGraph(MessagesAnnotation)\n * .addNode('clarifier', () => {\n * const { answer } = askUserQuestion({\n * question: 'Which environment should I deploy to?',\n * options: [\n * { label: 'Staging', value: 'staging' },\n * { label: 'Production', value: 'production' },\n * ],\n * });\n * return { messages: [new HumanMessage(`Use ${answer}`)] };\n * });\n * ```\n */\nexport function askUserQuestion(\n question: AskUserQuestionRequest\n): AskUserQuestionResolution {\n const payload: AskUserQuestionInterruptPayload = {\n type: 'ask_user_question',\n question,\n };\n return interrupt<AskUserQuestionInterruptPayload, AskUserQuestionResolution>(\n payload\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,SAAgB,gBACd,
|
|
1
|
+
{"version":3,"file":"askUserQuestion.mjs","names":[],"sources":["../../../src/hitl/askUserQuestion.ts"],"sourcesContent":["/**\n * Typed convenience wrapper around LangGraph's `interrupt()` for the\n * `ask_user_question` interrupt category. Lets a custom graph node\n * (or a tool implementation) suspend execution to collect a free-form\n * answer from the human, without the host having to assemble the\n * interrupt payload by hand. The companion to `Run.resume(answer)` on\n * the host side.\n *\n * AsyncLocalStorage anchoring: this helper does NOT call\n * `runWithConfig` itself — it expects to be invoked from inside a\n * LangGraph node where the framework has already established the\n * runnable config. ToolNode is the one place in this codebase that\n * needs the manual `runWithConfig` shim, because its\n * `RunnableCallable.trace = false` skips the upstream tracing path\n * that normally sets up the AsyncLocalStorage frame; ordinary user\n * nodes (RunnableLambda, addNode callbacks) do not have that\n * constraint.\n */\n\nimport { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionRequest,\n AskUserQuestionResolution,\n AskUserQuestionInterruptPayload,\n} from '@/types/hitl';\n\n/**\n * Suspend the current graph node to ask the human a question. Returns\n * the host-supplied resolution after `Run.resume(resolution)` is\n * called against a Run rebuilt with the same `thread_id` and\n * checkpointer.\n *\n * On the FIRST call (no resume value available), `interrupt()` throws\n * a `GraphInterrupt` that LangGraph catches; this function does not\n * return — execution unwinds, the SDK persists the checkpoint, and\n * the run completes with `run.getInterrupt()` returning a\n * `RunInterruptResult` whose `payload` is an\n * `AskUserQuestionInterruptPayload`.\n *\n * On RESUME, LangGraph re-runs the node from the start and this call\n * returns the host's `AskUserQuestionResolution` directly.\n *\n * Hosts that prefer the raw `interrupt()` (e.g., to attach extra\n * metadata) can construct an `AskUserQuestionInterruptPayload` and\n * call `interrupt()` themselves — this helper is purely convenience.\n *\n * @example\n * ```ts\n * const builder = new StateGraph(MessagesAnnotation)\n * .addNode('clarifier', () => {\n * const { answer } = askUserQuestion({\n * question: 'Which environment should I deploy to?',\n * options: [\n * { label: 'Staging', value: 'staging' },\n * { label: 'Production', value: 'production' },\n * ],\n * });\n * return { messages: [new HumanMessage(`Use ${answer}`)] };\n * });\n * ```\n */\nexport function askUserQuestion(\n question: AskUserQuestionRequest,\n options?: {\n /**\n * The calling tool's `tool_call_id`, surfaced on the interrupt payload\n * as `tool_call_id` so hosts can attribute the question (and answer) to\n * the exact tool-call content part. Tool bodies created with\n * `tool(fn, …)` receive it as `config.toolCall.id` — LangChain stamps\n * the full ToolCall onto the config when a tool is invoked with one.\n * Optional: positional hosts and custom nodes can omit it.\n */\n toolCallId?: string;\n }\n): AskUserQuestionResolution {\n const payload: AskUserQuestionInterruptPayload = {\n type: 'ask_user_question',\n question,\n ...(options?.toolCallId != null &&\n options.toolCallId !== '' && { tool_call_id: options.toolCallId }),\n };\n return interrupt<AskUserQuestionInterruptPayload, AskUserQuestionResolution>(\n payload\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,SAAgB,gBACd,UACA,SAW2B;CAO3B,OAAO,UACL;EANA,MAAM;EACN;EACA,GAAI,SAAS,cAAc,QACzB,QAAQ,eAAe,MAAM,EAAE,cAAc,QAAQ,WAAW;CAG5D,CACR;AACF"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { traceIdFromSeed } from "./langfuseRuntimeContext.mjs";
|
|
2
2
|
import { isPresent } from "./utils/misc.mjs";
|
|
3
3
|
import { resolveLangfuseConfigForSpan, resolveTraceIdSeedForSpan } from "./langfuseRuntimeScope.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { getLangfuseDestinationKey, getLangfuseSpanProcessorParams, registerLangfuseManagedSpan } from "./langfuseSpanRegistry.mjs";
|
|
5
|
+
import { createLibreChatTraceAttributes } from "./langfuse.mjs";
|
|
5
6
|
import { createLangfuseSpanProcessor } from "./langfuseToolOutputTracing.mjs";
|
|
6
7
|
import { ROOT_CONTEXT, context, createContextKey } from "@opentelemetry/api";
|
|
7
8
|
import { setLangfuseTracerProvider } from "@langfuse/tracing";
|
|
8
|
-
import {
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
9
10
|
import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
|
|
10
11
|
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
|
|
11
12
|
//#region src/instrumentation.ts
|
|
@@ -41,48 +42,12 @@ function ensureOpenTelemetryContextManager() {
|
|
|
41
42
|
contextManager.enable();
|
|
42
43
|
if (!context.setGlobalContextManager(contextManager)) contextManager.disable();
|
|
43
44
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
process.env.NODE_ENV
|
|
49
|
-
];
|
|
50
|
-
for (const candidate of candidates) if (candidate != null && candidate.trim() !== "") return candidate.trim();
|
|
51
|
-
}
|
|
52
|
-
function getLangfuseSpanProcessorParams(langfuse) {
|
|
53
|
-
if (langfuse?.enabled === false) return;
|
|
54
|
-
const environment = resolveLangfuseEnvironment(langfuse);
|
|
55
|
-
if (hasLangfuseConfigCredentials(langfuse)) return {
|
|
56
|
-
publicKey: langfuse.publicKey,
|
|
57
|
-
secretKey: langfuse.secretKey,
|
|
58
|
-
...isPresent(langfuse.baseUrl) ? { baseUrl: langfuse.baseUrl } : {},
|
|
59
|
-
...isPresent(environment) ? { environment } : {}
|
|
60
|
-
};
|
|
61
|
-
if (hasLangfuseEnvConfig()) {
|
|
62
|
-
const baseUrl = langfuse?.baseUrl ?? process.env.LANGFUSE_BASE_URL ?? process.env.LANGFUSE_BASEURL;
|
|
63
|
-
return {
|
|
64
|
-
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
|
|
65
|
-
secretKey: process.env.LANGFUSE_SECRET_KEY,
|
|
66
|
-
...isPresent(baseUrl) ? { baseUrl } : {},
|
|
67
|
-
...isPresent(environment) ? { environment } : {}
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
if (isPresent(langfuse?.baseUrl) && hasLangfuseEnvCredentials()) return {
|
|
71
|
-
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
|
|
72
|
-
secretKey: process.env.LANGFUSE_SECRET_KEY,
|
|
73
|
-
baseUrl: langfuse.baseUrl,
|
|
74
|
-
...isPresent(environment) ? { environment } : {}
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
function hashCacheKeyValue(value) {
|
|
78
|
-
return isPresent(value) ? createHash("sha256").update(value, "utf8").digest("hex") : void 0;
|
|
79
|
-
}
|
|
80
|
-
function getLangfuseTracerProviderKey(params, langfuse) {
|
|
45
|
+
/** Cache key for processor instances: the destination plus processor-level
|
|
46
|
+
* policy (`toolOutputTracing` is baked into each processor's redaction
|
|
47
|
+
* behavior), unlike the pure destination identity used for span parenting. */
|
|
48
|
+
function getLangfuseProcessorCacheKey(destinationKey, langfuse) {
|
|
81
49
|
return JSON.stringify({
|
|
82
|
-
|
|
83
|
-
secretKeyHash: hashCacheKeyValue(params.secretKey),
|
|
84
|
-
baseUrl: params.baseUrl,
|
|
85
|
-
environment: params.environment,
|
|
50
|
+
destinationKey,
|
|
86
51
|
toolOutputTracing: langfuse?.toolOutputTracing
|
|
87
52
|
});
|
|
88
53
|
}
|
|
@@ -92,17 +57,22 @@ var RoutingLangfuseSpanProcessor = class {
|
|
|
92
57
|
ensureProcessor(langfuse) {
|
|
93
58
|
const params = getLangfuseSpanProcessorParams(langfuse);
|
|
94
59
|
if (params == null) return;
|
|
95
|
-
|
|
96
|
-
|
|
60
|
+
return this.ensureProcessorForKey(getLangfuseProcessorCacheKey(getLangfuseDestinationKey(params), langfuse), params, langfuse);
|
|
61
|
+
}
|
|
62
|
+
ensureProcessorForKey(processorCacheKey, params, langfuse) {
|
|
63
|
+
const existing = this.processors.get(processorCacheKey);
|
|
97
64
|
if (existing != null) return existing;
|
|
98
65
|
const processor = createLangfuseSpanProcessor(params, langfuse);
|
|
99
|
-
this.processors.set(
|
|
66
|
+
this.processors.set(processorCacheKey, processor);
|
|
100
67
|
return processor;
|
|
101
68
|
}
|
|
102
69
|
onStart(span, parentContext) {
|
|
103
70
|
const langfuse = resolveLangfuseConfigForSpan(parentContext);
|
|
104
|
-
const
|
|
105
|
-
if (
|
|
71
|
+
const params = getLangfuseSpanProcessorParams(langfuse);
|
|
72
|
+
if (params == null) return;
|
|
73
|
+
const destinationKey = getLangfuseDestinationKey(params);
|
|
74
|
+
const processor = this.ensureProcessorForKey(getLangfuseProcessorCacheKey(destinationKey, langfuse), params, langfuse);
|
|
75
|
+
registerLangfuseManagedSpan(span, destinationKey);
|
|
106
76
|
const librechatTraceAttributes = createLibreChatTraceAttributes(langfuse?.librechatTraceAttributes ?? {});
|
|
107
77
|
if (Object.keys(librechatTraceAttributes).length > 0) span.setAttributes(librechatTraceAttributes);
|
|
108
78
|
this.spanProcessors.set(span, processor);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.mjs","names":[],"sources":["../../src/instrumentation.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport { setLangfuseTracerProvider } from '@langfuse/tracing';\nimport { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport { context, ROOT_CONTEXT, createContextKey } from '@opentelemetry/api';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport type {\n IdGenerator,\n ReadableSpan,\n Span,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\nimport type { LangfuseSpanProcessorParams } from '@langfuse/otel';\nimport type { Context } from '@opentelemetry/api';\nimport type * as t from '@/types';\nimport {\n createLibreChatTraceAttributes,\n hasLangfuseConfigCredentials,\n hasLangfuseEnvCredentials,\n hasLangfuseEnvConfig,\n} from '@/langfuse';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n} from '@/langfuseRuntimeScope';\nimport { createLangfuseSpanProcessor } from '@/langfuseToolOutputTracing';\nimport { traceIdFromSeed } from '@/langfuseRuntimeContext';\nimport { isPresent } from '@/utils/misc';\n\n/**\n * Per-run seed for deterministic Langfuse trace ids. When a run opts in\n * (`LangfuseConfig.deterministicTraceId`), it executes its stream inside\n * `runWithTraceIdSeed(runId, ...)` from `./langfuseRuntimeContext`, and the\n * IdGenerator below derives the root trace id from that seed instead of a\n * random one. This lets external systems (e.g. a host app recording user\n * feedback after the fact) attach scores or observations to the trace by\n * regenerating the same id from the run/message id; no trace lookup required.\n * With no active seed it falls back to random ids, so default behavior is\n * unchanged.\n */\nclass SeededTraceIdGenerator implements IdGenerator {\n generateTraceId(): string {\n const seed = resolveTraceIdSeedForSpan(context.active());\n return isPresent(seed)\n ? traceIdFromSeed(seed)\n : randomBytes(16).toString('hex');\n }\n\n generateSpanId(): string {\n return randomBytes(8).toString('hex');\n }\n}\n\nlet langfuseTracerProvider: BasicTracerProvider | undefined;\nlet langfuseRoutingSpanProcessor: RoutingLangfuseSpanProcessor | undefined;\nconst contextManagerProbeKey = createContextKey(\n 'langfuse-context-manager-probe'\n);\n\nfunction hasActiveContextManager(): boolean {\n return context.with(\n ROOT_CONTEXT.setValue(contextManagerProbeKey, true),\n () => context.active().getValue(contextManagerProbeKey) === true\n );\n}\n\nexport function ensureOpenTelemetryContextManager(): void {\n if (hasActiveContextManager()) {\n return;\n }\n\n const contextManager = new AsyncLocalStorageContextManager();\n contextManager.enable();\n if (!context.setGlobalContextManager(contextManager)) {\n contextManager.disable();\n }\n}\n\nfunction resolveLangfuseEnvironment(\n langfuse?: t.LangfuseConfig\n): string | undefined {\n const candidates = [\n langfuse?.environment,\n process.env.LANGFUSE_TRACING_ENVIRONMENT,\n process.env.NODE_ENV,\n ];\n for (const candidate of candidates) {\n if (candidate != null && candidate.trim() !== '') {\n return candidate.trim();\n }\n }\n return undefined;\n}\n\nfunction getLangfuseSpanProcessorParams(\n langfuse?: t.LangfuseConfig\n): LangfuseSpanProcessorParams | undefined {\n if (langfuse?.enabled === false) {\n return undefined;\n }\n const environment = resolveLangfuseEnvironment(langfuse);\n if (hasLangfuseConfigCredentials(langfuse)) {\n return {\n publicKey: langfuse.publicKey,\n secretKey: langfuse.secretKey,\n ...(isPresent(langfuse.baseUrl) ? { baseUrl: langfuse.baseUrl } : {}),\n ...(isPresent(environment) ? { environment } : {}),\n };\n }\n if (hasLangfuseEnvConfig()) {\n const baseUrl =\n langfuse?.baseUrl ??\n process.env.LANGFUSE_BASE_URL ??\n process.env.LANGFUSE_BASEURL;\n return {\n publicKey: process.env.LANGFUSE_PUBLIC_KEY as string,\n secretKey: process.env.LANGFUSE_SECRET_KEY as string,\n ...(isPresent(baseUrl) ? { baseUrl } : {}),\n ...(isPresent(environment) ? { environment } : {}),\n };\n }\n if (isPresent(langfuse?.baseUrl) && hasLangfuseEnvCredentials()) {\n return {\n publicKey: process.env.LANGFUSE_PUBLIC_KEY as string,\n secretKey: process.env.LANGFUSE_SECRET_KEY as string,\n baseUrl: langfuse.baseUrl,\n ...(isPresent(environment) ? { environment } : {}),\n };\n }\n return undefined;\n}\n\nfunction hashCacheKeyValue(value: string | undefined): string | undefined {\n return isPresent(value)\n ? createHash('sha256').update(value, 'utf8').digest('hex')\n : undefined;\n}\n\nfunction getLangfuseTracerProviderKey(\n params: LangfuseSpanProcessorParams,\n langfuse?: t.LangfuseConfig\n): string {\n return JSON.stringify({\n publicKey: params.publicKey,\n secretKeyHash: hashCacheKeyValue(params.secretKey),\n baseUrl: params.baseUrl,\n environment: params.environment,\n toolOutputTracing: langfuse?.toolOutputTracing,\n });\n}\n\nclass RoutingLangfuseSpanProcessor implements SpanProcessor {\n // Processors live for the process lifetime. LibreChat tenant Langfuse\n // destinations are expected to be a bounded admin-managed set, and shutdown\n // drains every cached processor when the provider is disposed.\n private readonly processors = new Map<string, SpanProcessor>();\n private readonly spanProcessors = new WeakMap<object, SpanProcessor>();\n\n ensureProcessor(langfuse?: t.LangfuseConfig): SpanProcessor | undefined {\n const params = getLangfuseSpanProcessorParams(langfuse);\n if (params == null) {\n return undefined;\n }\n\n const processorKey = getLangfuseTracerProviderKey(params, langfuse);\n const existing = this.processors.get(processorKey);\n if (existing != null) {\n return existing;\n }\n\n const processor = createLangfuseSpanProcessor(params, langfuse);\n this.processors.set(processorKey, processor);\n return processor;\n }\n\n onStart(span: Span, parentContext: Context): void {\n const langfuse = resolveLangfuseConfigForSpan(parentContext);\n const processor = this.ensureProcessor(langfuse);\n if (processor == null) {\n return;\n }\n\n const librechatTraceAttributes = createLibreChatTraceAttributes(\n langfuse?.librechatTraceAttributes ?? {}\n );\n if (Object.keys(librechatTraceAttributes).length > 0) {\n span.setAttributes(librechatTraceAttributes);\n }\n\n this.spanProcessors.set(span, processor);\n processor.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n this.spanProcessors.get(span)?.onEnd(span);\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(\n Array.from(this.processors.values(), (processor) =>\n processor.forceFlush()\n )\n );\n }\n\n async shutdown(): Promise<void> {\n await Promise.all(\n Array.from(this.processors.values(), (processor) => processor.shutdown())\n );\n }\n}\n\nexport function initializeLangfuseTracing(\n langfuse?: t.LangfuseConfig\n): BasicTracerProvider | undefined {\n const params = getLangfuseSpanProcessorParams(langfuse);\n if (params == null) {\n return undefined;\n }\n\n if (langfuseTracerProvider != null) {\n langfuseRoutingSpanProcessor?.ensureProcessor(langfuse);\n return langfuseTracerProvider;\n }\n\n ensureOpenTelemetryContextManager();\n langfuseRoutingSpanProcessor = new RoutingLangfuseSpanProcessor();\n langfuseRoutingSpanProcessor.ensureProcessor(langfuse);\n langfuseTracerProvider = new BasicTracerProvider({\n spanProcessors: [langfuseRoutingSpanProcessor],\n idGenerator: new SeededTraceIdGenerator(),\n });\n\n setLangfuseTracerProvider(langfuseTracerProvider);\n return langfuseTracerProvider;\n}\n\nexport function initializeLangfuseTracingFromEnv():\n | BasicTracerProvider\n | undefined {\n return initializeLangfuseTracing();\n}\n\ninitializeLangfuseTracingFromEnv();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,yBAAN,MAAoD;CAClD,kBAA0B;EACxB,MAAM,OAAO,0BAA0B,QAAQ,OAAO,CAAC;EACvD,OAAO,UAAU,IAAI,IACjB,gBAAgB,IAAI,IACpB,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CACpC;CAEA,iBAAyB;EACvB,OAAO,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK;CACtC;AACF;AAEA,IAAI;AACJ,IAAI;AACJ,MAAM,yBAAyB,iBAC7B,gCACF;AAEA,SAAS,0BAAmC;CAC1C,OAAO,QAAQ,KACb,aAAa,SAAS,wBAAwB,IAAI,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AK,WAAW,OAAO,IAAI,cAAc,UAAU,SAAS,CAAC,CAC1E;CACF;AACF;AAEA,SAAgB,0BACd,UACiC;CAEjC,IADe,+BAA+B,QACrC,KAAK,MACZ;CAGF,IAAI,0BAA0B,MAAM;EAClC,8BAA8B,gBAAgB,QAAQ;EACtD,OAAO;CACT;CAEA,kCAAkC;CAClC,+BAA+B,IAAI,6BAA6B;CAChE,6BAA6B,gBAAgB,QAAQ;CACrD,yBAAyB,IAAI,oBAAoB;EAC/C,gBAAgB,CAAC,4BAA4B;EAC7C,aAAa,IAAI,uBAAuB;CAC1C,CAAC;CAED,0BAA0B,sBAAsB;CAChD,OAAO;AACT;AAEA,SAAgB,mCAEF;CACZ,OAAO,0BAA0B;AACnC;AAEA,iCAAiC"}
|
|
1
|
+
{"version":3,"file":"instrumentation.mjs","names":[],"sources":["../../src/instrumentation.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { setLangfuseTracerProvider } from '@langfuse/tracing';\nimport { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport { context, ROOT_CONTEXT, createContextKey } from '@opentelemetry/api';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport type {\n IdGenerator,\n ReadableSpan,\n Span,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\nimport type { LangfuseSpanProcessorParams } from '@langfuse/otel';\nimport type { Context } from '@opentelemetry/api';\nimport type * as t from '@/types';\nimport {\n getLangfuseDestinationKey,\n getLangfuseSpanProcessorParams,\n registerLangfuseManagedSpan,\n} from '@/langfuseSpanRegistry';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n} from '@/langfuseRuntimeScope';\nimport { createLangfuseSpanProcessor } from '@/langfuseToolOutputTracing';\nimport { createLibreChatTraceAttributes } from '@/langfuse';\nimport { traceIdFromSeed } from '@/langfuseRuntimeContext';\nimport { isPresent } from '@/utils/misc';\n\n/**\n * Per-run seed for deterministic Langfuse trace ids. When a run opts in\n * (`LangfuseConfig.deterministicTraceId`), it executes its stream inside\n * `runWithTraceIdSeed(runId, ...)` from `./langfuseRuntimeContext`, and the\n * IdGenerator below derives the root trace id from that seed instead of a\n * random one. This lets external systems (e.g. a host app recording user\n * feedback after the fact) attach scores or observations to the trace by\n * regenerating the same id from the run/message id; no trace lookup required.\n * With no active seed it falls back to random ids, so default behavior is\n * unchanged.\n */\nclass SeededTraceIdGenerator implements IdGenerator {\n generateTraceId(): string {\n const seed = resolveTraceIdSeedForSpan(context.active());\n return isPresent(seed)\n ? traceIdFromSeed(seed)\n : randomBytes(16).toString('hex');\n }\n\n generateSpanId(): string {\n return randomBytes(8).toString('hex');\n }\n}\n\nlet langfuseTracerProvider: BasicTracerProvider | undefined;\nlet langfuseRoutingSpanProcessor: RoutingLangfuseSpanProcessor | undefined;\nconst contextManagerProbeKey = createContextKey(\n 'langfuse-context-manager-probe'\n);\n\nfunction hasActiveContextManager(): boolean {\n return context.with(\n ROOT_CONTEXT.setValue(contextManagerProbeKey, true),\n () => context.active().getValue(contextManagerProbeKey) === true\n );\n}\n\nexport function ensureOpenTelemetryContextManager(): void {\n if (hasActiveContextManager()) {\n return;\n }\n\n const contextManager = new AsyncLocalStorageContextManager();\n contextManager.enable();\n if (!context.setGlobalContextManager(contextManager)) {\n contextManager.disable();\n }\n}\n\n/** Cache key for processor instances: the destination plus processor-level\n * policy (`toolOutputTracing` is baked into each processor's redaction\n * behavior), unlike the pure destination identity used for span parenting. */\nfunction getLangfuseProcessorCacheKey(\n destinationKey: string,\n langfuse?: t.LangfuseConfig\n): string {\n return JSON.stringify({\n destinationKey,\n toolOutputTracing: langfuse?.toolOutputTracing,\n });\n}\n\nclass RoutingLangfuseSpanProcessor implements SpanProcessor {\n // Processors live for the process lifetime. LibreChat tenant Langfuse\n // destinations are expected to be a bounded admin-managed set, and shutdown\n // drains every cached processor when the provider is disposed.\n private readonly processors = new Map<string, SpanProcessor>();\n private readonly spanProcessors = new WeakMap<object, SpanProcessor>();\n\n ensureProcessor(langfuse?: t.LangfuseConfig): SpanProcessor | undefined {\n const params = getLangfuseSpanProcessorParams(langfuse);\n if (params == null) {\n return undefined;\n }\n return this.ensureProcessorForKey(\n getLangfuseProcessorCacheKey(getLangfuseDestinationKey(params), langfuse),\n params,\n langfuse\n );\n }\n\n private ensureProcessorForKey(\n processorCacheKey: string,\n params: LangfuseSpanProcessorParams,\n langfuse?: t.LangfuseConfig\n ): SpanProcessor {\n const existing = this.processors.get(processorCacheKey);\n if (existing != null) {\n return existing;\n }\n\n const processor = createLangfuseSpanProcessor(params, langfuse);\n this.processors.set(processorCacheKey, processor);\n return processor;\n }\n\n onStart(span: Span, parentContext: Context): void {\n const langfuse = resolveLangfuseConfigForSpan(parentContext);\n const params = getLangfuseSpanProcessorParams(langfuse);\n if (params == null) {\n return;\n }\n\n const destinationKey = getLangfuseDestinationKey(params);\n const processor = this.ensureProcessorForKey(\n getLangfuseProcessorCacheKey(destinationKey, langfuse),\n params,\n langfuse\n );\n registerLangfuseManagedSpan(span, destinationKey);\n\n const librechatTraceAttributes = createLibreChatTraceAttributes(\n langfuse?.librechatTraceAttributes ?? {}\n );\n if (Object.keys(librechatTraceAttributes).length > 0) {\n span.setAttributes(librechatTraceAttributes);\n }\n\n this.spanProcessors.set(span, processor);\n processor.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n this.spanProcessors.get(span)?.onEnd(span);\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(\n Array.from(this.processors.values(), (processor) =>\n processor.forceFlush()\n )\n );\n }\n\n async shutdown(): Promise<void> {\n await Promise.all(\n Array.from(this.processors.values(), (processor) => processor.shutdown())\n );\n }\n}\n\nexport function initializeLangfuseTracing(\n langfuse?: t.LangfuseConfig\n): BasicTracerProvider | undefined {\n const params = getLangfuseSpanProcessorParams(langfuse);\n if (params == null) {\n return undefined;\n }\n\n if (langfuseTracerProvider != null) {\n langfuseRoutingSpanProcessor?.ensureProcessor(langfuse);\n return langfuseTracerProvider;\n }\n\n ensureOpenTelemetryContextManager();\n langfuseRoutingSpanProcessor = new RoutingLangfuseSpanProcessor();\n langfuseRoutingSpanProcessor.ensureProcessor(langfuse);\n langfuseTracerProvider = new BasicTracerProvider({\n spanProcessors: [langfuseRoutingSpanProcessor],\n idGenerator: new SeededTraceIdGenerator(),\n });\n\n setLangfuseTracerProvider(langfuseTracerProvider);\n return langfuseTracerProvider;\n}\n\nexport function initializeLangfuseTracingFromEnv():\n | BasicTracerProvider\n | undefined {\n return initializeLangfuseTracing();\n}\n\ninitializeLangfuseTracingFromEnv();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,yBAAN,MAAoD;CAClD,kBAA0B;EACxB,MAAM,OAAO,0BAA0B,QAAQ,OAAO,CAAC;EACvD,OAAO,UAAU,IAAI,IACjB,gBAAgB,IAAI,IACpB,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CACpC;CAEA,iBAAyB;EACvB,OAAO,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK;CACtC;AACF;AAEA,IAAI;AACJ,IAAI;AACJ,MAAM,yBAAyB,iBAC7B,gCACF;AAEA,SAAS,0BAAmC;CAC1C,OAAO,QAAQ,KACb,aAAa,SAAS,wBAAwB,IAAI,SAC5C,QAAQ,OAAO,CAAC,CAAC,SAAS,sBAAsB,MAAM,IAC9D;AACF;AAEA,SAAgB,oCAA0C;CACxD,IAAI,wBAAwB,GAC1B;CAGF,MAAM,iBAAiB,IAAI,gCAAgC;CAC3D,eAAe,OAAO;CACtB,IAAI,CAAC,QAAQ,wBAAwB,cAAc,GACjD,eAAe,QAAQ;AAE3B;;;;AAKA,SAAS,6BACP,gBACA,UACQ;CACR,OAAO,KAAK,UAAU;EACpB;EACA,mBAAmB,UAAU;CAC/B,CAAC;AACH;AAEA,IAAM,+BAAN,MAA4D;CAI1D,6BAA8B,IAAI,IAA2B;CAC7D,iCAAkC,IAAI,QAA+B;CAErE,gBAAgB,UAAwD;EACtE,MA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