@librechat/agents 3.0.0-rc7 → 3.0.0-rc9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/cjs/graphs/Graph.cjs +0 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +103 -19
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/esm/graphs/Graph.mjs +0 -1
  6. package/dist/esm/graphs/Graph.mjs.map +1 -1
  7. package/dist/esm/graphs/MultiAgentGraph.mjs +103 -19
  8. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  9. package/dist/types/graphs/MultiAgentGraph.d.ts +11 -1
  10. package/package.json +5 -1
  11. package/src/graphs/Graph.ts +0 -1
  12. package/src/graphs/MultiAgentGraph.ts +120 -21
  13. package/src/scripts/multi-agent-chain.ts +278 -0
  14. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  15. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  16. package/src/scripts/test-tools-before-handoff.ts +233 -0
  17. package/dist/types/scripts/abort.d.ts +0 -1
  18. package/dist/types/scripts/ant_web_search.d.ts +0 -1
  19. package/dist/types/scripts/args.d.ts +0 -7
  20. package/dist/types/scripts/caching.d.ts +0 -1
  21. package/dist/types/scripts/cli.d.ts +0 -1
  22. package/dist/types/scripts/cli2.d.ts +0 -1
  23. package/dist/types/scripts/cli3.d.ts +0 -1
  24. package/dist/types/scripts/cli4.d.ts +0 -1
  25. package/dist/types/scripts/cli5.d.ts +0 -1
  26. package/dist/types/scripts/code_exec.d.ts +0 -1
  27. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  28. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  29. package/dist/types/scripts/content.d.ts +0 -1
  30. package/dist/types/scripts/empty_input.d.ts +0 -1
  31. package/dist/types/scripts/handoff-test.d.ts +0 -1
  32. package/dist/types/scripts/image.d.ts +0 -1
  33. package/dist/types/scripts/memory.d.ts +0 -1
  34. package/dist/types/scripts/multi-agent-conditional.d.ts +0 -1
  35. package/dist/types/scripts/multi-agent-parallel.d.ts +0 -1
  36. package/dist/types/scripts/multi-agent-sequence.d.ts +0 -1
  37. package/dist/types/scripts/multi-agent-supervisor.d.ts +0 -1
  38. package/dist/types/scripts/multi-agent-test.d.ts +0 -1
  39. package/dist/types/scripts/search.d.ts +0 -1
  40. package/dist/types/scripts/simple.d.ts +0 -1
  41. package/dist/types/scripts/stream.d.ts +0 -1
  42. package/dist/types/scripts/test-custom-prompt-key.d.ts +0 -2
  43. package/dist/types/scripts/test-handoff-input.d.ts +0 -1
  44. package/dist/types/scripts/test-multi-agent-list-handoff.d.ts +0 -2
  45. package/dist/types/scripts/thinking.d.ts +0 -1
  46. package/dist/types/scripts/tools.d.ts +0 -1
  47. package/dist/types/specs/spec.utils.d.ts +0 -1
  48. package/src/scripts/multi-agent-example-output.md +0 -110
@@ -209,7 +209,6 @@ class StandardGraph extends Graph {
209
209
  }
210
210
  }
211
211
  initializeTools({ currentTools, currentToolMap, }) {
212
- // return new ToolNode<t.BaseGraphState>(this.tools);
213
212
  return new ToolNode.ToolNode({
214
213
  tools: currentTools ?? [],
215
214
  toolMap: currentToolMap,
@@ -1 +1 @@
1
- {"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n convertMessagesToContent,\n modifyDeltaProperties,\n formatArtifactPayload,\n createPruneMessages,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n ((\n (clientOptions as t.AnthropicClientOptions).clientOptions\n ?.defaultHeaders as Record<string, string> | undefined\n )?.['anthropic-beta']?.includes('prompt-caching') ??\n false)\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n // return new ToolNode<t.BaseGraphState>(this.tools);\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default', currentModel?: t.ChatModel) {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No Graph model found');\n }\n if (!config) {\n throw new Error('No config provided');\n }\n\n // Ensure token calculations are complete before proceeding\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n let messagesToUse = messages;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n const finalMessages = messagesToUse;\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(agentContext.provider) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n let currentModel = this.initializeModel({\n tools: agentContext.tools,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n currentModel = agentContext.systemRunnable.pipe(currentModel);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId, currentModel))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["GraphNodeKeys","AgentContext","resetIfNotEmpty","joinKeys","nanoid","ContentTypes","convertMessagesToContent","Providers","SystemMessage","RunnableLambda","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","manualToolStreamProviders","stream","safeDispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","messages","createPruneMessages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","toolsCondition","Annotation","messagesStateReducer","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AA2DA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa;MAEhB,KAAK,CAAA;AAyDzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;AAChB;AAEK,MAAO,aAAc,SAAQ,KAAoC,CAAA;AACrE,IAAA,aAAa;;AAEb,IAAA,cAAc;IACd,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;IACL,UAAU,GAAW,CAAC;AACtB,IAAA,MAAM;;AAEN,IAAA,aAAa,GAA8B,IAAI,GAAG,EAAE;;AAEpD,IAAA,cAAc;IAEd,WAAY,CAAA;;IAEV,KAAK,EACL,MAAM,EACN,MAAM,EACN,YAAY,EACZ,kBAAkB,GACG,EAAA;AACrB,QAAA,KAAK,EAAE;AACP,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;AAEpB,QAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,YAAA,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC;;AAGjE,QAAA,KAAK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],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n convertMessagesToContent,\n modifyDeltaProperties,\n formatArtifactPayload,\n createPruneMessages,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n ((\n (clientOptions as t.AnthropicClientOptions).clientOptions\n ?.defaultHeaders as Record<string, string> | undefined\n )?.['anthropic-beta']?.includes('prompt-caching') ??\n false)\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default', currentModel?: t.ChatModel) {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No Graph model found');\n }\n if (!config) {\n throw new Error('No config provided');\n }\n\n // Ensure token calculations are complete before proceeding\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n let messagesToUse = messages;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n const finalMessages = messagesToUse;\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(agentContext.provider) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n let currentModel = this.initializeModel({\n tools: agentContext.tools,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n currentModel = agentContext.systemRunnable.pipe(currentModel);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId, currentModel))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["GraphNodeKeys","AgentContext","resetIfNotEmpty","joinKeys","nanoid","ContentTypes","convertMessagesToContent","Providers","SystemMessage","RunnableLambda","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","manualToolStreamProviders","stream","safeDispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","messages","createPruneMessages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","toolsCondition","Annotation","messagesStateReducer","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AA2DA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa;MAEhB,KAAK,CAAA;AAyDzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;AAChB;AAEK,MAAO,aAAc,SAAQ,KAAoC,CAAA;AACrE,IAAA,aAAa;;AAEb,IAAA,cAAc;IACd,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;IACL,UAAU,GAAW,CAAC;AACtB,IAAA,MAAM;;AAEN,IAAA,aAAa,GAA8B,IAAI,GAAG,EAAE;;AAEpD,IAAA,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I,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;AACD,QAAA,MAAMD,8BAAuB,CAC3BC,iBAAW,CAAC,kBAAkB,EAC9B,cAAc,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;;"}
@@ -10,7 +10,17 @@ var _enum = require('../common/enum.cjs');
10
10
 
11
11
  /**
12
12
  * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows
13
- * with handoffs, fan-in/fan-out, and other composable patterns
13
+ * with handoffs, fan-in/fan-out, and other composable patterns.
14
+ *
15
+ * Key behavior:
16
+ * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination
17
+ * - Agents with ONLY direct edges: Always follow their direct edges
18
+ * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)
19
+ * - If handoff occurs: Only the handoff destination executes
20
+ * - If no handoff: Direct edges execute (potentially in parallel)
21
+ *
22
+ * This enables the common pattern where an agent either delegates (handoff)
23
+ * OR continues its workflow (direct edges), but not both simultaneously.
14
24
  */
15
25
  class MultiAgentGraph extends Graph.StandardGraph {
16
26
  edges;
@@ -104,13 +114,6 @@ class MultiAgentGraph extends Graph.StandardGraph {
104
114
  agentContext.tools = [];
105
115
  }
106
116
  agentContext.tools.push(...handoffTools);
107
- // Update tool map
108
- for (const tool of handoffTools) {
109
- if (!agentContext.toolMap) {
110
- agentContext.toolMap = new Map();
111
- }
112
- agentContext.toolMap.set(tool.name, tool);
113
- }
114
117
  }
115
118
  }
116
119
  /**
@@ -275,37 +278,105 @@ class MultiAgentGraph extends Graph.StandardGraph {
275
278
  dests.forEach((dest) => directDestinations.add(dest));
276
279
  }
277
280
  }
278
- /** If agent has handoff destinations, add END to possible ends
279
- * If agent only has direct destinations, it naturally ends without explicit END
280
- */
281
- const destinations = new Set([...handoffDestinations]);
281
+ /** Check if this agent has BOTH handoff and direct edges */
282
+ const hasHandoffEdges = handoffDestinations.size > 0;
283
+ const hasDirectEdges = directDestinations.size > 0;
284
+ const needsCommandRouting = hasHandoffEdges && hasDirectEdges;
285
+ /** Collect all possible destinations for this agent */
286
+ const allDestinations = new Set([
287
+ ...handoffDestinations,
288
+ ...directDestinations,
289
+ ]);
282
290
  if (handoffDestinations.size > 0 || directDestinations.size === 0) {
283
- destinations.add(langgraph.END);
291
+ allDestinations.add(langgraph.END);
284
292
  }
285
293
  /** Agent subgraph (includes agent + tools) */
286
294
  const agentSubgraph = this.createAgentSubgraph(agentId);
287
- /** Wrapper function that handles agentMessages channel */
295
+ /** Wrapper function that handles agentMessages channel and conditional routing */
288
296
  const agentWrapper = async (state) => {
297
+ let result;
289
298
  if (state.agentMessages != null && state.agentMessages.length > 0) {
299
+ /**
300
+ * When using agentMessages (excludeResults=true), we need to update
301
+ * the token map to account for the new prompt message
302
+ */
303
+ const agentContext = this.agentContexts.get(agentId);
304
+ if (agentContext && agentContext.tokenCounter) {
305
+ // The agentMessages contains:
306
+ // 1. Filtered messages (0 to startIndex) - already have token counts
307
+ // 2. New prompt message - needs token counting
308
+ const freshTokenMap = {};
309
+ // Copy existing token counts for filtered messages (0 to startIndex)
310
+ for (let i = 0; i < this.startIndex; i++) {
311
+ const tokenCount = agentContext.indexTokenCountMap[i];
312
+ if (tokenCount !== undefined) {
313
+ freshTokenMap[i] = tokenCount;
314
+ }
315
+ }
316
+ // Calculate tokens only for the new prompt message (last message)
317
+ const promptMessageIndex = state.agentMessages.length - 1;
318
+ if (promptMessageIndex >= this.startIndex) {
319
+ const promptMessage = state.agentMessages[promptMessageIndex];
320
+ freshTokenMap[promptMessageIndex] =
321
+ agentContext.tokenCounter(promptMessage);
322
+ }
323
+ // Update the agent's token map with instructions added
324
+ agentContext.updateTokenMapWithInstructions(freshTokenMap);
325
+ }
290
326
  /** Temporary state with messages replaced by `agentMessages` */
291
327
  const transformedState = {
292
328
  ...state,
293
329
  messages: state.agentMessages,
294
330
  };
295
- const result = await agentSubgraph.invoke(transformedState);
296
- return {
331
+ result = await agentSubgraph.invoke(transformedState);
332
+ result = {
297
333
  ...result,
298
334
  /** Clear agentMessages for next agent */
299
335
  agentMessages: [],
300
336
  };
301
337
  }
302
338
  else {
303
- return await agentSubgraph.invoke(state);
339
+ result = await agentSubgraph.invoke(state);
304
340
  }
341
+ /** If agent has both handoff and direct edges, use Command for exclusive routing */
342
+ if (needsCommandRouting) {
343
+ /** Check if a handoff occurred */
344
+ const lastMessage = result.messages[result.messages.length - 1];
345
+ if (lastMessage != null &&
346
+ lastMessage.getType() === 'tool' &&
347
+ typeof lastMessage.name === 'string' &&
348
+ lastMessage.name.startsWith(_enum.Constants.LC_TRANSFER_TO_)) {
349
+ /** Handoff occurred - extract destination and navigate there exclusively */
350
+ const handoffDest = lastMessage.name.replace(_enum.Constants.LC_TRANSFER_TO_, '');
351
+ return new langgraph.Command({
352
+ update: result,
353
+ goto: handoffDest,
354
+ });
355
+ }
356
+ else {
357
+ /** No handoff - proceed with direct edges */
358
+ const directDests = Array.from(directDestinations);
359
+ if (directDests.length === 1) {
360
+ return new langgraph.Command({
361
+ update: result,
362
+ goto: directDests[0],
363
+ });
364
+ }
365
+ else if (directDests.length > 1) {
366
+ /** Multiple direct destinations - they'll run in parallel */
367
+ return new langgraph.Command({
368
+ update: result,
369
+ goto: directDests,
370
+ });
371
+ }
372
+ }
373
+ }
374
+ /** No special routing needed - return state normally */
375
+ return result;
305
376
  };
306
377
  /** Wrapped agent as a node with its possible destinations */
307
378
  builder.addNode(agentId, agentWrapper, {
308
- ends: Array.from(destinations),
379
+ ends: Array.from(allDestinations),
309
380
  });
310
381
  }
311
382
  // Add starting edges for all starting nodes
@@ -404,10 +475,23 @@ class MultiAgentGraph extends Graph.StandardGraph {
404
475
  builder.addEdge(wrapperNodeId, destination);
405
476
  }
406
477
  else {
407
- /** No prompt instructions, add direct edges */
478
+ /** No prompt instructions, add direct edges (skip if source uses Command routing) */
408
479
  for (const edge of edges) {
409
480
  const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
410
481
  for (const source of sources) {
482
+ /** Check if this source node has both handoff and direct edges */
483
+ const sourceHandoffEdges = this.handoffEdges.filter((e) => {
484
+ const eSources = Array.isArray(e.from) ? e.from : [e.from];
485
+ return eSources.includes(source);
486
+ });
487
+ const sourceDirectEdges = this.directEdges.filter((e) => {
488
+ const eSources = Array.isArray(e.from) ? e.from : [e.from];
489
+ return eSources.includes(source);
490
+ });
491
+ /** Skip adding edge if source uses Command routing (has both types) */
492
+ if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {
493
+ continue;
494
+ }
411
495
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
412
496
  /** @ts-ignore */
413
497
  builder.addEdge(source, destination);
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.cjs","sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool } from '@langchain/core/tools';\nimport {\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n for (const edge of edges) {\n handoffTools.push(...this.createHandoffToolsForEdge(edge));\n }\n\n // Add handoff tools to the agent's existing tools\n if (!agentContext.tools) {\n agentContext.tools = [];\n }\n agentContext.tools.push(...handoffTools);\n\n // Update tool map\n for (const tool of handoffTools) {\n if (!agentContext.toolMap) {\n agentContext.toolMap = new Map();\n }\n agentContext.toolMap.set(tool.name, tool);\n }\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n */\n private createHandoffToolsForEdge(edge: t.GraphEdge): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n }\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 * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** If agent has handoff destinations, add END to possible ends\n * If agent only has direct destinations, it naturally ends without explicit END\n */\n const destinations = new Set([...handoffDestinations]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n destinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel */\n const agentWrapper = async (\n state: t.MultiAgentGraphState\n ): Promise<t.MultiAgentGraphState> => {\n if (state.agentMessages != null && state.agentMessages.length > 0) {\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n const result = await agentSubgraph.invoke(transformedState);\n return {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n return await agentSubgraph.invoke(state);\n }\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(destinations),\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 = 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 = ChatPromptTemplate.fromTemplate(prompt);\n const formattedPromptValue = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = formattedPromptValue.messages[0].content.toString();\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n return {\n messages: [new HumanMessage(promptText)],\n agentMessages: messagesStateReducer(filteredMessages, [\n new HumanMessage(promptText),\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges */\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, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"names":["StandardGraph","tools","tool","getCurrentTaskInput","ToolMessage","Command","z","Constants","Annotation","messagesStateReducer","StateGraph","END","START","getBufferString","ChatPromptTemplate","HumanMessage"],"mappings":";;;;;;;;;;AAuBA;;;AAGG;AACG,MAAO,eAAgB,SAAQA,mBAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACtC,WAAW,GAAkB,EAAE;IAC/B,YAAY,GAAkB,EAAE;AAExC,IAAA,WAAA,CAAY,KAA6B,EAAA;QACvC,KAAK,CAAC,KAAK,CAAC;AACZ,QAAA,IAAI,CAAC,KAAK,GAAG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import { tool } from '@langchain/core/tools';\nimport {\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n for (const edge of edges) {\n handoffTools.push(...this.createHandoffToolsForEdge(edge));\n }\n\n // Add handoff tools to the agent's existing tools\n if (!agentContext.tools) {\n agentContext.tools = [];\n }\n agentContext.tools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n */\n private createHandoffToolsForEdge(edge: t.GraphEdge): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (input: Record<string, unknown>, config) => {\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? z.object({\n [promptKey]: z\n .string()\n .optional()\n .describe(handoffInputDescription as string),\n })\n : z.object({}),\n description: toolDescription,\n }\n )\n );\n }\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 * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n if (state.agentMessages != null && state.agentMessages.length > 0) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n // The agentMessages contains:\n // 1. Filtered messages (0 to startIndex) - already have token counts\n // 2. New prompt message - needs token counting\n\n const freshTokenMap: Record<string, number> = {};\n\n // Copy existing token counts for filtered messages (0 to startIndex)\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n // Calculate tokens only for the new prompt message (last message)\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n // Update the agent's token map with instructions added\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = 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 = ChatPromptTemplate.fromTemplate(prompt);\n const formattedPromptValue = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = formattedPromptValue.messages[0].content.toString();\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n return {\n messages: [new HumanMessage(promptText)],\n agentMessages: messagesStateReducer(filteredMessages, [\n new HumanMessage(promptText),\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"names":["StandardGraph","tools","tool","getCurrentTaskInput","ToolMessage","Command","z","Constants","Annotation","messagesStateReducer","StateGraph","END","START","getBufferString","ChatPromptTemplate","HumanMessage"],"mappings":";;;;;;;;;;AAuBA;;;;;;;;;;;;;AAaG;AACG,MAAO,eAAgB,SAAQA,mBAAa,CAAA;AACxC,IAAA,KAAK;AACL,IAAA,aAAa,GAAgB,IAAI,GAAG,EAAE;IACtC,WAAW,GAAkB,EAAE;IAC/B,YAAY,GAAkB,EAAE;AAExC,IAAA,WAAA,CAAY,KAA6B,EAAA;QACvC,KAAK,CAAC,KAAK,CAAC;AACZ,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK;QACxB,IAAI,CAAC,eAAe,EAAE;QACtB,IAAI,CAAC,YAAY,EAAE;QACnB,IA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AAW,CAAC;;iBACtC;;AAEL,gBAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;oBACxB,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;AAClE,oBAAA,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;;wBAE5B,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BACxD,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,yBAAC,CAAC;wBACF,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,KAAI;4BACtD,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,4BAAA,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;AAClC,yBAAC,CAAC;;AAGF,wBAAA,IAAI,kBAAkB,CAAC,MAAM,GAAG,CAAC,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;4BACjE;;;;AAKF,wBAAA,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC;;;;;QAM5C,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,cAAkC,CAAC;;AAElE;;;;"}
@@ -207,7 +207,6 @@ class StandardGraph extends Graph {
207
207
  }
208
208
  }
209
209
  initializeTools({ currentTools, currentToolMap, }) {
210
- // return new ToolNode<t.BaseGraphState>(this.tools);
211
210
  return new ToolNode({
212
211
  tools: currentTools ?? [],
213
212
  toolMap: currentToolMap,