langchain 1.2.27 → 1.2.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/agents/ReactAgent.cjs +12 -0
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +5 -1
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +5 -1
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +12 -0
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/middleware/types.cjs +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +1 -6
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +1 -6
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware.cjs +2 -2
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +2 -2
- package/dist/agents/middleware.d.ts +2 -2
- package/dist/agents/middleware.js +2 -2
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +15 -4
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +15 -4
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +2 -3
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js +2 -3
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/dist/agents/responses.cjs +16 -7
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +10 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +10 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +16 -7
- package/dist/agents/responses.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReactAgent.js","names":["#defaultConfig","#toolBehaviorVersion","#agentNode","#stateManager","#createBeforeAgentRouter","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","#createToolsRouter","#graph","#initializeMiddlewareStates"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type GetStateOptions,\n type LangGraphRunnableConfig,\n type StreamMode,\n type StreamOutputMap,\n type PregelOptions,\n} from \"@langchain/langgraph\";\nimport type { CheckpointListOptions } from \"@langchain/langgraph-checkpoint\";\nimport {\n ToolMessage,\n AIMessage,\n MessageStructure,\n} from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport {\n mergeConfigs,\n type Runnable,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { createAgentState } from \"./annotation.js\";\nimport {\n isClientTool,\n validateLLMHasNoBoundTools,\n wrapToolCall,\n normalizeSystemPrompt,\n} from \"./utils.js\";\n\nimport { AgentNode, AGENT_NODE_NAME } from \"./nodes/AgentNode.js\";\nimport { ToolNode, TOOLS_NODE_NAME } from \"./nodes/ToolNode.js\";\nimport { BeforeAgentNode } from \"./nodes/BeforeAgentNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModelNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModelNode.js\";\nimport { AfterAgentNode } from \"./nodes/AfterAgentNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\nimport { StateManager } from \"./state.js\";\n\nimport type {\n WithStateGraphNodes,\n AgentTypeConfig,\n CreateAgentParams,\n ToolsToMessageToolSet,\n} from \"./types.js\";\n\nimport type { BuiltInState, JumpTo, UserInput } from \"./types.js\";\nimport type { InvokeConfiguration, StreamConfiguration } from \"./runtime.js\";\nimport type {\n AgentMiddleware,\n InferMiddlewareContextInputs,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n InferContextInput,\n AnyAnnotationRoot,\n InferSchemaValue,\n ToAnnotationRoot,\n} from \"./middleware/types.js\";\nimport { type ResponseFormatUndefined } from \"./responses.js\";\nimport { getHookConstraint } from \"./middleware/utils.js\";\n\n/**\n * In the ReAct pattern we have three main nodes:\n * - model_request: The node that makes the model call.\n * - tools: The node that calls the tools.\n * - END: The end of the graph.\n *\n * These are the only nodes that can be jumped to from other nodes.\n */\ntype BaseGraphDestination =\n | typeof TOOLS_NODE_NAME\n | typeof AGENT_NODE_NAME\n | typeof END;\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<Types extends AgentTypeConfig> = InferSchemaValue<\n Types[\"State\"]\n> &\n (Types[\"Response\"] extends ResponseFormatUndefined\n ? Omit<\n BuiltInState<MessageStructure<ToolsToMessageToolSet<Types[\"Tools\"]>>>,\n \"jumpTo\"\n >\n : Omit<\n BuiltInState<MessageStructure<ToolsToMessageToolSet<Types[\"Tools\"]>>>,\n \"jumpTo\"\n > & {\n structuredResponse: Types[\"Response\"];\n }) &\n InferMiddlewareStates<Types[\"Middleware\"]>;\n\ntype InvokeStateParameter<Types extends AgentTypeConfig> =\n | (UserInput<Types[\"State\"]> &\n InferMiddlewareInputStates<Types[\"Middleware\"]>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<Types extends AgentTypeConfig> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<Types>,\n ToAnnotationRoot<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n >[\"spec\"],\n unknown\n>;\n\n/**\n * ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines\n * language models with tools and middleware.\n *\n * The agent is parameterized by a single type bag `Types` that encapsulates all\n * type information:\n *\n * @typeParam Types - An {@link AgentTypeConfig} that bundles:\n * - `Response`: The structured response type\n * - `State`: The custom state schema type\n * - `Context`: The context schema type\n * - `Middleware`: The middleware array type\n * - `Tools`: The combined tools type from agent and middleware\n *\n * @example\n * ```typescript\n * // Using the type bag pattern\n * type MyTypes = AgentTypeConfig<\n * { name: string }, // Response\n * typeof myState, // State\n * typeof myContext, // Context\n * typeof middleware, // Middleware\n * typeof tools // Tools\n * >;\n *\n * const agent: ReactAgent<MyTypes> = createAgent({ ... });\n * ```\n */\nexport class ReactAgent<\n Types extends AgentTypeConfig = AgentTypeConfig<\n Record<string, any>,\n undefined,\n AnyAnnotationRoot,\n readonly AgentMiddleware[],\n readonly (ClientTool | ServerTool)[]\n >,\n> {\n /**\n * Type marker for extracting the AgentTypeConfig from a ReactAgent instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n declare readonly \"~agentTypes\": Types;\n\n #graph: AgentGraph<Types>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n #agentNode: AgentNode<any, AnyAnnotationRoot>;\n\n #stateManager = new StateManager();\n\n #defaultConfig: RunnableConfig;\n\n constructor(\n public options: CreateAgentParams<\n Types[\"Response\"],\n Types[\"State\"],\n Types[\"Context\"]\n >,\n defaultConfig?: RunnableConfig\n ) {\n this.#defaultConfig = defaultConfig ?? {};\n if (options.name) {\n this.#defaultConfig = mergeConfigs(this.#defaultConfig, {\n metadata: { lc_agent_name: options.name },\n });\n }\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * validate that model option is provided\n */\n if (!options.model) {\n throw new Error(\"`model` option is required to create an agent.\");\n }\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (typeof options.model !== \"string\") {\n validateLLMHasNoBoundTools(options.model);\n }\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [...(options.tools ?? []), ...middlewareTools];\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n /**\n * Create a schema that merges agent base schema with middleware state schemas\n * Using Zod with withLangGraph ensures LangGraph Studio gets proper metadata\n */\n const { state, input, output } = createAgentState<\n Types[\"State\"],\n Types[\"Middleware\"]\n >(\n this.options.responseFormat !== undefined,\n this.options.stateSchema as Types[\"State\"],\n this.options.middleware as Types[\"Middleware\"]\n );\n\n const workflow = new StateGraph(state, {\n input,\n output,\n context: this.options.contextSchema,\n });\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n typeof TOOLS_NODE_NAME | typeof AGENT_NODE_NAME | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any,\n ][] = [];\n\n this.#agentNode = new AgentNode({\n model: this.options.model,\n systemMessage: normalizeSystemPrompt(this.options.systemPrompt),\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n wrapModelCallHookMiddleware,\n });\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeAgentNode: BeforeAgentNode | undefined;\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n let afterAgentNode: AfterAgentNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeAgent) {\n beforeAgentNode = new BeforeAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeAgentNode);\n const name = `${m.name}.before_agent`;\n beforeAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeAgent),\n });\n allNodeWorkflows.addNode(\n name,\n beforeAgentNode,\n beforeAgentNode.nodeOptions\n );\n }\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeModelNode);\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeModel),\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterModelNode);\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterModel),\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n if (m.afterAgent) {\n afterAgentNode = new AfterAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterAgentNode);\n const name = `${m.name}.after_agent`;\n afterAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterAgent),\n });\n allNodeWorkflows.addNode(\n name,\n afterAgentNode,\n afterAgentNode.nodeOptions\n );\n }\n\n if (m.wrapModelCall) {\n wrapModelCallHookMiddleware.push([\n m,\n () => this.#stateManager.getState(m.name),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(AGENT_NODE_NAME, this.#agentNode);\n\n /**\n * Check if any middleware has wrapToolCall defined.\n * If so, we need to create a ToolNode even without pre-registered tools\n * to allow middleware to handle dynamically registered tools.\n */\n const hasWrapToolCallMiddleware = middleware.some((m) => m.wrapToolCall);\n const clientTools = toolClasses.filter(isClientTool);\n\n /**\n * Create ToolNode if we have client-side tools OR if middleware defines wrapToolCall\n * (which may handle dynamically registered tools)\n */\n if (clientTools.length > 0 || hasWrapToolCallMiddleware) {\n const toolNode = new ToolNode(clientTools, {\n signal: this.options.signal,\n wrapToolCall: wrapToolCall(middleware),\n });\n allNodeWorkflows.addNode(TOOLS_NODE_NAME, toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine the entry node (runs once at start): before_agent -> before_model -> model_request\n let entryNode: string;\n if (beforeAgentNodes.length > 0) {\n entryNode = beforeAgentNodes[0].name;\n } else if (beforeModelNodes.length > 0) {\n entryNode = beforeModelNodes[0].name;\n } else {\n entryNode = AGENT_NODE_NAME;\n }\n\n // Determine the loop entry node (beginning of agent loop, excludes before_agent)\n // This is where tools will loop back to for the next iteration\n const loopEntryNode =\n beforeModelNodes.length > 0 ? beforeModelNodes[0].name : AGENT_NODE_NAME;\n\n // Determine the exit node (runs once at end): after_agent or END\n const exitNode =\n afterAgentNodes.length > 0\n ? afterAgentNodes[afterAgentNodes.length - 1].name\n : END;\n\n allNodeWorkflows.addEdge(START, entryNode);\n\n /**\n * Determine if we have tools available for routing.\n * This includes both registered client tools AND dynamic tools via middleware.\n */\n const hasToolsAvailable =\n clientTools.length > 0 || hasWrapToolCallMiddleware;\n\n // Connect beforeAgent nodes (run once at start)\n for (let i = 0; i < beforeAgentNodes.length; i++) {\n const node = beforeAgentNodes[i];\n const current = node.name;\n const isLast = i === beforeAgentNodes.length - 1;\n const nextDefault = isLast ? loopEntryNode : beforeAgentNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n // Replace END with exitNode (which could be an afterAgent node)\n const destinations = Array.from(\n new Set([\n nextDefault,\n ...allowedMapped.map((dest) => (dest === END ? exitNode : dest)),\n ])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeAgentRouter(\n clientTools,\n nextDefault,\n exitNode,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? AGENT_NODE_NAME\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n clientTools,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(AGENT_NODE_NAME, lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(\n clientTools,\n false,\n hasToolsAvailable\n );\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as BaseGraphDestination[];\n if (destinations.length === 1) {\n allNodeWorkflows.addEdge(AGENT_NODE_NAME, destinations[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n AGENT_NODE_NAME,\n this.#createModelRouter(exitNode),\n destinations\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n clientTools,\n node.allowed,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n\n // Include exitNode in the paths since afterModel should be able to route to after_agent or END\n const modelPaths = this.#getModelPaths(\n clientTools,\n true,\n hasToolsAvailable\n ).filter((p) => p !== TOOLS_NODE_NAME || hasToolsAvailable);\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n clientTools,\n allowJump,\n exitNode,\n hasToolsAvailable\n ),\n destinations\n );\n }\n\n // Connect afterAgent nodes (run once at end, in reverse order like afterModel)\n for (let i = afterAgentNodes.length - 1; i > 0; i--) {\n const node = afterAgentNodes[i];\n const current = node.name;\n const nextDefault = afterAgentNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n clientTools,\n node.allowed,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect the first afterAgent node (last to execute) to END\n if (afterAgentNodes.length > 0) {\n const firstAfterAgent = afterAgentNodes[0];\n const firstAfterAgentNode = firstAfterAgent.name;\n\n if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) {\n const allowedMapped = firstAfterAgent.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n\n /**\n * For after_agent, only use explicitly allowed destinations (don't add loopEntryNode)\n * The default destination (when no jump occurs) should be END\n */\n const destinations = Array.from(\n new Set([END, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterAgentNode,\n this.#createAfterModelSequenceRouter(\n clientTools,\n firstAfterAgent.allowed,\n END as string,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(firstAfterAgentNode, END);\n }\n }\n\n /**\n * add edges for tools node (includes both registered tools and dynamic tools via middleware)\n */\n if (hasToolsAvailable) {\n // Tools should return to loop entry node (not including before_agent)\n const toolReturnTarget = loopEntryNode;\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n TOOLS_NODE_NAME,\n this.#createToolsRouter(shouldReturnDirect, exitNode),\n [toolReturnTarget, exitNode as string]\n );\n } else {\n allNodeWorkflows.addEdge(TOOLS_NODE_NAME, toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as unknown as AgentGraph<Types>;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<Types> {\n return this.#graph;\n }\n\n /**\n * Creates a new ReactAgent with the given config merged into the existing config.\n * Follows the same pattern as LangGraph's Pregel.withConfig().\n *\n * The merged config is applied as a default that gets merged with any config\n * passed at invocation time (invoke/stream). Invocation-time config takes precedence.\n *\n * @param config - Configuration to merge with existing config\n * @returns A new ReactAgent instance with the merged configuration\n *\n * @example\n * ```typescript\n * const agent = createAgent({ model: \"gpt-4o\", tools: [...] });\n *\n * // Set a default recursion limit\n * const configuredAgent = agent.withConfig({ recursionLimit: 1000 });\n *\n * // Chain multiple configs\n * const debugAgent = agent\n * .withConfig({ recursionLimit: 1000 })\n * .withConfig({ tags: [\"debug\"] });\n * ```\n */\n withConfig(\n config: Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\">\n ): ReactAgent<Types> {\n return new ReactAgent(\n this.options,\n mergeConfigs(this.#defaultConfig, config)\n );\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @param hasToolsAvailable whether tools are available (includes dynamic tools via middleware)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ): BaseGraphDestination[] {\n const paths: BaseGraphDestination[] = [];\n if (hasToolsAvailable) {\n paths.push(TOOLS_NODE_NAME);\n }\n\n if (includeModelRequest) {\n paths.push(AGENT_NODE_NAME);\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(\n shouldReturnDirect: Set<string>,\n exitNode: string | typeof END\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n const messages = builtInState.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly to exit node (could be after_agent or END)\n return this.options.responseFormat ? AGENT_NODE_NAME : exitNode;\n }\n\n // For non-returnDirect tools, always route back to agent\n return AGENT_NODE_NAME;\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n * @param exitNode - The exit node to route to (could be after_agent or END)\n */\n #createModelRouter(exitNode: string | typeof END = END) {\n /**\n * determine if the agent should continue or not\n */\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n const messages = builtInState.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to exit node\n // The AgentNode will handle these internally and return the structured response\n return exitNode;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return TOOLS_NODE_NAME;\n }\n\n /**\n * Route to tools node (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return exitNode;\n }\n\n return regularToolCalls.map(\n (toolCall) =>\n new Send(TOOLS_NODE_NAME, { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @param allowJump - Whether jumping is allowed\n * @param exitNode - The exit node to route to (could be after_agent or END)\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean,\n exitNode: string | typeof END,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as Omit<BuiltInState, \"jumpTo\"> & {\n jumpTo?: JumpTo;\n };\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to exitNode\n const messages = builtInState.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return exitNode;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && builtInState.jumpTo) {\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n return exitNode;\n }\n if (destination === TOOLS_NODE_NAME) {\n // If trying to jump to tools but no tools are available, go to exitNode\n if (!hasToolsAvailable) {\n return exitNode;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) =>\n new Send(TOOLS_NODE_NAME, { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return AGENT_NODE_NAME;\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return exitNode;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return TOOLS_NODE_NAME;\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n * @param toolClasses - Available tool classes for validation\n * @param allowed - List of allowed jump targets\n * @param nextDefault - Default node to route to\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (builtInState.jumpTo) {\n const dest = parseJumpToTarget(builtInState.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === TOOLS_NODE_NAME && allowedSet.has(TOOLS_NODE_NAME)) {\n if (!hasToolsAvailable) return END;\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n if (dest === AGENT_NODE_NAME && allowedSet.has(AGENT_NODE_NAME)) {\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n }\n }\n return nextDefault;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeAgent hooks.\n * Falls back to the default next node if no jumpTo is present.\n * When jumping to END, routes to exitNode (which could be an afterAgent node).\n * @param toolClasses - Available tool classes for validation\n * @param nextDefault - Default node to route to\n * @param exitNode - Exit node to route to (could be after_agent or END)\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createBeforeAgentRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n exitNode: string | typeof END,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (!builtInState.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n /**\n * When beforeAgent jumps to END, route to exitNode (first afterAgent node)\n */\n return exitNode;\n }\n if (destination === TOOLS_NODE_NAME) {\n if (!hasToolsAvailable) {\n return exitNode;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n * @param toolClasses - Available tool classes for validation\n * @param nextDefault - Default node to route to\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (!builtInState.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === TOOLS_NODE_NAME) {\n if (!hasToolsAvailable) {\n return END;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<Types>,\n config: RunnableConfig\n ): Promise<InvokeStateParameter<Types>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const threadState = await this.#graph\n .getState(config)\n .catch(() => ({ values: {} }));\n const updatedState = {\n ...threadState.values,\n ...state,\n } as InvokeStateParameter<Types>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<Types>,\n config?: InvokeConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>\n >\n ) {\n type FullState = MergedAgentState<Types>;\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n mergedConfig as RunnableConfig\n );\n\n return this.#graph.invoke(\n initializedState,\n mergedConfig as unknown as InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of state updates as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams high-level state updates in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - React to state changes as nodes complete\n *\n * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of state updates.\n * Each update contains the current state after a node completes.\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const chunk of stream) {\n * console.log(chunk); // State update from each node\n * }\n * ```\n */\n async stream<\n TStreamMode extends StreamMode | StreamMode[] | undefined,\n TSubgraphs extends boolean,\n TEncoding extends \"text/event-stream\" | undefined,\n >(\n state: InvokeStateParameter<Types>,\n config?: StreamConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>,\n TStreamMode,\n TSubgraphs,\n TEncoding\n >\n ) {\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n mergedConfig as RunnableConfig\n );\n return this.#graph.stream(\n initializedState,\n mergedConfig as Record<string, any>\n ) as Promise<\n IterableReadableStream<\n StreamOutputMap<\n TStreamMode,\n TSubgraphs,\n MergedAgentState<Types>,\n MergedAgentState<Types>,\n string,\n unknown,\n unknown,\n TEncoding\n >\n >\n >;\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n\n /**\n * The following are internal methods to enable support for LangGraph Platform.\n * They are not part of the createAgent public API.\n *\n * Note: we intentionally return as `never` to avoid type errors due to type inference.\n */\n\n /**\n * @internal\n */\n streamEvents(\n state: InvokeStateParameter<Types>,\n config?: StreamConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>,\n StreamMode | StreamMode[] | undefined,\n boolean,\n \"text/event-stream\" | undefined\n > & { version?: \"v1\" | \"v2\" },\n streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]\n ): IterableReadableStream<StreamEvent> {\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n return this.#graph.streamEvents(\n state,\n {\n ...(mergedConfig as Partial<\n PregelOptions<\n any,\n any,\n any,\n StreamMode | StreamMode[] | undefined,\n boolean,\n \"text/event-stream\"\n >\n >),\n version: config?.version ?? \"v2\",\n },\n streamOptions\n );\n }\n /**\n * @internal\n */\n getGraphAsync(config?: RunnableConfig) {\n return this.#graph.getGraphAsync(config) as never;\n }\n /**\n * @internal\n */\n getState(config: RunnableConfig, options?: GetStateOptions) {\n return this.#graph.getState(config, options) as never;\n }\n /**\n * @internal\n */\n getStateHistory(config: RunnableConfig, options?: CheckpointListOptions) {\n return this.#graph.getStateHistory(config, options) as never;\n }\n /**\n * @internal\n */\n getSubgraphs(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphs(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n getSubgraphAsync(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphsAsync(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown> | unknown,\n asNode?: string\n ) {\n return this.#graph.updateState(inputConfig, values, asNode) as never;\n }\n\n /**\n * @internal\n */\n get builder() {\n return this.#graph.builder;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuJA,IAAa,aAAb,MAAa,WAQX;CAQA;CAEA,uBAAoC;CAEpC;CAEA,gBAAgB,IAAI,cAAc;CAElC;CAEA,YACE,AAAO,SAKP,eACA;EANO;AAOP,QAAKA,gBAAiB,iBAAiB,EAAE;AACzC,MAAI,QAAQ,KACV,OAAKA,gBAAiB,aAAa,MAAKA,eAAgB,EACtD,UAAU,EAAE,eAAe,QAAQ,MAAM,EAC1C,CAAC;AAEJ,QAAKC,sBAAuB,QAAQ,WAAW,MAAKA;;;;AAKpD,MAAI,CAAC,QAAQ,MACX,OAAM,IAAI,MAAM,iDAAiD;;;;AAMnE,MAAI,OAAO,QAAQ,UAAU,SAC3B,4BAA2B,QAAQ,MAAM;;;;EAM3C,MAAM,kBAAm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,aAAa,WAAoB,SAAmB;AAClD,SAAO,MAAKA,MAAO,aAAa,WAAW,QAAQ;;;;;CAKrD,iBAAiB,WAAoB,SAAmB;AACtD,SAAO,MAAKA,MAAO,kBAAkB,WAAW,QAAQ;;;;;CAK1D,YACE,aACA,QACA,QACA;AACA,SAAO,MAAKA,MAAO,YAAY,aAAa,QAAQ,OAAO;;;;;CAM7D,IAAI,UAAU;AACZ,SAAO,MAAKA,MAAO"}
|
|
1
|
+
{"version":3,"file":"ReactAgent.js","names":["#defaultConfig","#toolBehaviorVersion","#agentNode","#stateManager","#createBeforeAgentRouter","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","#createToolsRouter","#graph","#initializeMiddlewareStates"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type GetStateOptions,\n type LangGraphRunnableConfig,\n type StreamMode,\n type StreamOutputMap,\n type PregelOptions,\n} from \"@langchain/langgraph\";\nimport type {\n BaseCheckpointSaver,\n BaseStore,\n CheckpointListOptions,\n} from \"@langchain/langgraph-checkpoint\";\nimport {\n ToolMessage,\n AIMessage,\n MessageStructure,\n} from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport {\n mergeConfigs,\n type Runnable,\n type RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { createAgentState } from \"./annotation.js\";\nimport {\n isClientTool,\n validateLLMHasNoBoundTools,\n wrapToolCall,\n normalizeSystemPrompt,\n} from \"./utils.js\";\n\nimport { AgentNode, AGENT_NODE_NAME } from \"./nodes/AgentNode.js\";\nimport { ToolNode, TOOLS_NODE_NAME } from \"./nodes/ToolNode.js\";\nimport { BeforeAgentNode } from \"./nodes/BeforeAgentNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModelNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModelNode.js\";\nimport { AfterAgentNode } from \"./nodes/AfterAgentNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\nimport { StateManager } from \"./state.js\";\n\nimport type {\n WithStateGraphNodes,\n AgentTypeConfig,\n CreateAgentParams,\n ToolsToMessageToolSet,\n} from \"./types.js\";\n\nimport type { BuiltInState, JumpTo, UserInput } from \"./types.js\";\nimport type { InvokeConfiguration, StreamConfiguration } from \"./runtime.js\";\nimport type {\n AgentMiddleware,\n InferMiddlewareContextInputs,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n InferContextInput,\n AnyAnnotationRoot,\n InferSchemaValue,\n ToAnnotationRoot,\n} from \"./middleware/types.js\";\nimport { type ResponseFormatUndefined } from \"./responses.js\";\nimport { getHookConstraint } from \"./middleware/utils.js\";\n\n/**\n * In the ReAct pattern we have three main nodes:\n * - model_request: The node that makes the model call.\n * - tools: The node that calls the tools.\n * - END: The end of the graph.\n *\n * These are the only nodes that can be jumped to from other nodes.\n */\ntype BaseGraphDestination =\n | typeof TOOLS_NODE_NAME\n | typeof AGENT_NODE_NAME\n | typeof END;\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<Types extends AgentTypeConfig> = InferSchemaValue<\n Types[\"State\"]\n> &\n (Types[\"Response\"] extends ResponseFormatUndefined\n ? Omit<\n BuiltInState<MessageStructure<ToolsToMessageToolSet<Types[\"Tools\"]>>>,\n \"jumpTo\"\n >\n : Omit<\n BuiltInState<MessageStructure<ToolsToMessageToolSet<Types[\"Tools\"]>>>,\n \"jumpTo\"\n > & {\n structuredResponse: Types[\"Response\"];\n }) &\n InferMiddlewareStates<Types[\"Middleware\"]>;\n\ntype InvokeStateParameter<Types extends AgentTypeConfig> =\n | (UserInput<Types[\"State\"]> &\n InferMiddlewareInputStates<Types[\"Middleware\"]>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<Types extends AgentTypeConfig> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<Types>,\n ToAnnotationRoot<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n >[\"spec\"],\n unknown\n>;\n\n/**\n * ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines\n * language models with tools and middleware.\n *\n * The agent is parameterized by a single type bag `Types` that encapsulates all\n * type information:\n *\n * @typeParam Types - An {@link AgentTypeConfig} that bundles:\n * - `Response`: The structured response type\n * - `State`: The custom state schema type\n * - `Context`: The context schema type\n * - `Middleware`: The middleware array type\n * - `Tools`: The combined tools type from agent and middleware\n *\n * @example\n * ```typescript\n * // Using the type bag pattern\n * type MyTypes = AgentTypeConfig<\n * { name: string }, // Response\n * typeof myState, // State\n * typeof myContext, // Context\n * typeof middleware, // Middleware\n * typeof tools // Tools\n * >;\n *\n * const agent: ReactAgent<MyTypes> = createAgent({ ... });\n * ```\n */\nexport class ReactAgent<\n Types extends AgentTypeConfig = AgentTypeConfig<\n Record<string, any>,\n undefined,\n AnyAnnotationRoot,\n readonly AgentMiddleware[],\n readonly (ClientTool | ServerTool)[]\n >,\n> {\n /**\n * Type marker for extracting the AgentTypeConfig from a ReactAgent instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n declare readonly \"~agentTypes\": Types;\n\n #graph: AgentGraph<Types>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n #agentNode: AgentNode<any, AnyAnnotationRoot>;\n\n #stateManager = new StateManager();\n\n #defaultConfig: RunnableConfig;\n\n constructor(\n public options: CreateAgentParams<\n Types[\"Response\"],\n Types[\"State\"],\n Types[\"Context\"]\n >,\n defaultConfig?: RunnableConfig\n ) {\n this.#defaultConfig = defaultConfig ?? {};\n if (options.name) {\n this.#defaultConfig = mergeConfigs(this.#defaultConfig, {\n metadata: { lc_agent_name: options.name },\n });\n }\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * validate that model option is provided\n */\n if (!options.model) {\n throw new Error(\"`model` option is required to create an agent.\");\n }\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (typeof options.model !== \"string\") {\n validateLLMHasNoBoundTools(options.model);\n }\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [...(options.tools ?? []), ...middlewareTools];\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n /**\n * Create a schema that merges agent base schema with middleware state schemas\n * Using Zod with withLangGraph ensures LangGraph Studio gets proper metadata\n */\n const { state, input, output } = createAgentState<\n Types[\"State\"],\n Types[\"Middleware\"]\n >(\n this.options.responseFormat !== undefined,\n this.options.stateSchema as Types[\"State\"],\n this.options.middleware as Types[\"Middleware\"]\n );\n\n const workflow = new StateGraph(state, {\n input,\n output,\n context: this.options.contextSchema,\n });\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n typeof TOOLS_NODE_NAME | typeof AGENT_NODE_NAME | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any,\n ][] = [];\n\n this.#agentNode = new AgentNode({\n model: this.options.model,\n systemMessage: normalizeSystemPrompt(this.options.systemPrompt),\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n wrapModelCallHookMiddleware,\n });\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeAgentNode: BeforeAgentNode | undefined;\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n let afterAgentNode: AfterAgentNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeAgent) {\n beforeAgentNode = new BeforeAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeAgentNode);\n const name = `${m.name}.before_agent`;\n beforeAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeAgent),\n });\n allNodeWorkflows.addNode(\n name,\n beforeAgentNode,\n beforeAgentNode.nodeOptions\n );\n }\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeModelNode);\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeModel),\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterModelNode);\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterModel),\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n if (m.afterAgent) {\n afterAgentNode = new AfterAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterAgentNode);\n const name = `${m.name}.after_agent`;\n afterAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterAgent),\n });\n allNodeWorkflows.addNode(\n name,\n afterAgentNode,\n afterAgentNode.nodeOptions\n );\n }\n\n if (m.wrapModelCall) {\n wrapModelCallHookMiddleware.push([\n m,\n () => this.#stateManager.getState(m.name),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(AGENT_NODE_NAME, this.#agentNode);\n\n /**\n * Check if any middleware has wrapToolCall defined.\n * If so, we need to create a ToolNode even without pre-registered tools\n * to allow middleware to handle dynamically registered tools.\n */\n const hasWrapToolCallMiddleware = middleware.some((m) => m.wrapToolCall);\n const clientTools = toolClasses.filter(isClientTool);\n\n /**\n * Create ToolNode if we have client-side tools OR if middleware defines wrapToolCall\n * (which may handle dynamically registered tools)\n */\n if (clientTools.length > 0 || hasWrapToolCallMiddleware) {\n const toolNode = new ToolNode(clientTools, {\n signal: this.options.signal,\n wrapToolCall: wrapToolCall(middleware),\n });\n allNodeWorkflows.addNode(TOOLS_NODE_NAME, toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine the entry node (runs once at start): before_agent -> before_model -> model_request\n let entryNode: string;\n if (beforeAgentNodes.length > 0) {\n entryNode = beforeAgentNodes[0].name;\n } else if (beforeModelNodes.length > 0) {\n entryNode = beforeModelNodes[0].name;\n } else {\n entryNode = AGENT_NODE_NAME;\n }\n\n // Determine the loop entry node (beginning of agent loop, excludes before_agent)\n // This is where tools will loop back to for the next iteration\n const loopEntryNode =\n beforeModelNodes.length > 0 ? beforeModelNodes[0].name : AGENT_NODE_NAME;\n\n // Determine the exit node (runs once at end): after_agent or END\n const exitNode =\n afterAgentNodes.length > 0\n ? afterAgentNodes[afterAgentNodes.length - 1].name\n : END;\n\n allNodeWorkflows.addEdge(START, entryNode);\n\n /**\n * Determine if we have tools available for routing.\n * This includes both registered client tools AND dynamic tools via middleware.\n */\n const hasToolsAvailable =\n clientTools.length > 0 || hasWrapToolCallMiddleware;\n\n // Connect beforeAgent nodes (run once at start)\n for (let i = 0; i < beforeAgentNodes.length; i++) {\n const node = beforeAgentNodes[i];\n const current = node.name;\n const isLast = i === beforeAgentNodes.length - 1;\n const nextDefault = isLast ? loopEntryNode : beforeAgentNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n // Replace END with exitNode (which could be an afterAgent node)\n const destinations = Array.from(\n new Set([\n nextDefault,\n ...allowedMapped.map((dest) => (dest === END ? exitNode : dest)),\n ])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeAgentRouter(\n clientTools,\n nextDefault,\n exitNode,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? AGENT_NODE_NAME\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n clientTools,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(AGENT_NODE_NAME, lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(\n clientTools,\n false,\n hasToolsAvailable\n );\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as BaseGraphDestination[];\n if (destinations.length === 1) {\n allNodeWorkflows.addEdge(AGENT_NODE_NAME, destinations[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n AGENT_NODE_NAME,\n this.#createModelRouter(exitNode),\n destinations\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n clientTools,\n node.allowed,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n\n // Include exitNode in the paths since afterModel should be able to route to after_agent or END\n const modelPaths = this.#getModelPaths(\n clientTools,\n true,\n hasToolsAvailable\n ).filter((p) => p !== TOOLS_NODE_NAME || hasToolsAvailable);\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n clientTools,\n allowJump,\n exitNode,\n hasToolsAvailable\n ),\n destinations\n );\n }\n\n // Connect afterAgent nodes (run once at end, in reverse order like afterModel)\n for (let i = afterAgentNodes.length - 1; i > 0; i--) {\n const node = afterAgentNodes[i];\n const current = node.name;\n const nextDefault = afterAgentNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n clientTools,\n node.allowed,\n nextDefault,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect the first afterAgent node (last to execute) to END\n if (afterAgentNodes.length > 0) {\n const firstAfterAgent = afterAgentNodes[0];\n const firstAfterAgentNode = firstAfterAgent.name;\n\n if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) {\n const allowedMapped = firstAfterAgent.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== TOOLS_NODE_NAME || hasToolsAvailable);\n\n /**\n * For after_agent, only use explicitly allowed destinations (don't add loopEntryNode)\n * The default destination (when no jump occurs) should be END\n */\n const destinations = Array.from(\n new Set([END, ...allowedMapped])\n ) as BaseGraphDestination[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterAgentNode,\n this.#createAfterModelSequenceRouter(\n clientTools,\n firstAfterAgent.allowed,\n END as string,\n hasToolsAvailable\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(firstAfterAgentNode, END);\n }\n }\n\n /**\n * add edges for tools node (includes both registered tools and dynamic tools via middleware)\n */\n if (hasToolsAvailable) {\n // Tools should return to loop entry node (not including before_agent)\n const toolReturnTarget = loopEntryNode;\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n TOOLS_NODE_NAME,\n this.#createToolsRouter(shouldReturnDirect, exitNode),\n [toolReturnTarget, exitNode as string]\n );\n } else {\n allNodeWorkflows.addEdge(TOOLS_NODE_NAME, toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as unknown as AgentGraph<Types>;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<Types> {\n return this.#graph;\n }\n\n get checkpointer(): BaseCheckpointSaver | boolean | undefined {\n return this.#graph.checkpointer;\n }\n\n set checkpointer(value: BaseCheckpointSaver | boolean | undefined) {\n this.#graph.checkpointer = value;\n }\n\n get store(): BaseStore | undefined {\n return this.#graph.store;\n }\n\n set store(value: BaseStore | undefined) {\n this.#graph.store = value;\n }\n\n /**\n * Creates a new ReactAgent with the given config merged into the existing config.\n * Follows the same pattern as LangGraph's Pregel.withConfig().\n *\n * The merged config is applied as a default that gets merged with any config\n * passed at invocation time (invoke/stream). Invocation-time config takes precedence.\n *\n * @param config - Configuration to merge with existing config\n * @returns A new ReactAgent instance with the merged configuration\n *\n * @example\n * ```typescript\n * const agent = createAgent({ model: \"gpt-4o\", tools: [...] });\n *\n * // Set a default recursion limit\n * const configuredAgent = agent.withConfig({ recursionLimit: 1000 });\n *\n * // Chain multiple configs\n * const debugAgent = agent\n * .withConfig({ recursionLimit: 1000 })\n * .withConfig({ tags: [\"debug\"] });\n * ```\n */\n withConfig(\n config: Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\">\n ): ReactAgent<Types> {\n return new ReactAgent(\n this.options,\n mergeConfigs(this.#defaultConfig, config)\n );\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @param hasToolsAvailable whether tools are available (includes dynamic tools via middleware)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ): BaseGraphDestination[] {\n const paths: BaseGraphDestination[] = [];\n if (hasToolsAvailable) {\n paths.push(TOOLS_NODE_NAME);\n }\n\n if (includeModelRequest) {\n paths.push(AGENT_NODE_NAME);\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(\n shouldReturnDirect: Set<string>,\n exitNode: string | typeof END\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n const messages = builtInState.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly to exit node (could be after_agent or END)\n return this.options.responseFormat ? AGENT_NODE_NAME : exitNode;\n }\n\n // For non-returnDirect tools, always route back to agent\n return AGENT_NODE_NAME;\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n * @param exitNode - The exit node to route to (could be after_agent or END)\n */\n #createModelRouter(exitNode: string | typeof END = END) {\n /**\n * determine if the agent should continue or not\n */\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n const messages = builtInState.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to exit node\n // The AgentNode will handle these internally and return the structured response\n return exitNode;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return TOOLS_NODE_NAME;\n }\n\n /**\n * Route to tools node (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return exitNode;\n }\n\n return regularToolCalls.map(\n (toolCall) =>\n new Send(TOOLS_NODE_NAME, { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @param allowJump - Whether jumping is allowed\n * @param exitNode - The exit node to route to (could be after_agent or END)\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean,\n exitNode: string | typeof END,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as Omit<BuiltInState, \"jumpTo\"> & {\n jumpTo?: JumpTo;\n };\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to exitNode\n const messages = builtInState.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return exitNode;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && builtInState.jumpTo) {\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n return exitNode;\n }\n if (destination === TOOLS_NODE_NAME) {\n // If trying to jump to tools but no tools are available, go to exitNode\n if (!hasToolsAvailable) {\n return exitNode;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) =>\n new Send(TOOLS_NODE_NAME, { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return AGENT_NODE_NAME;\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return exitNode;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return TOOLS_NODE_NAME;\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n * @param toolClasses - Available tool classes for validation\n * @param allowed - List of allowed jump targets\n * @param nextDefault - Default node to route to\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (builtInState.jumpTo) {\n const dest = parseJumpToTarget(builtInState.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === TOOLS_NODE_NAME && allowedSet.has(TOOLS_NODE_NAME)) {\n if (!hasToolsAvailable) return END;\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n if (dest === AGENT_NODE_NAME && allowedSet.has(AGENT_NODE_NAME)) {\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n }\n }\n return nextDefault;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeAgent hooks.\n * Falls back to the default next node if no jumpTo is present.\n * When jumping to END, routes to exitNode (which could be an afterAgent node).\n * @param toolClasses - Available tool classes for validation\n * @param nextDefault - Default node to route to\n * @param exitNode - Exit node to route to (could be after_agent or END)\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createBeforeAgentRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n exitNode: string | typeof END,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (!builtInState.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n /**\n * When beforeAgent jumps to END, route to exitNode (first afterAgent node)\n */\n return exitNode;\n }\n if (destination === TOOLS_NODE_NAME) {\n if (!hasToolsAvailable) {\n return exitNode;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n * @param toolClasses - Available tool classes for validation\n * @param nextDefault - Default node to route to\n * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware)\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n hasToolsAvailable: boolean = toolClasses.length > 0\n ) {\n return (state: Record<string, unknown>) => {\n const builtInState = state as unknown as BuiltInState;\n if (!builtInState.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(builtInState.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === TOOLS_NODE_NAME) {\n if (!hasToolsAvailable) {\n return END;\n }\n return new Send(TOOLS_NODE_NAME, { ...state, jumpTo: undefined });\n }\n return new Send(AGENT_NODE_NAME, { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<Types>,\n config: RunnableConfig\n ): Promise<InvokeStateParameter<Types>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const threadState = await this.#graph\n .getState(config)\n .catch(() => ({ values: {} }));\n const updatedState = {\n ...threadState.values,\n ...state,\n } as InvokeStateParameter<Types>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<Types>,\n config?: InvokeConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>\n >\n ) {\n type FullState = MergedAgentState<Types>;\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n mergedConfig as RunnableConfig\n );\n\n return this.#graph.invoke(\n initializedState,\n mergedConfig as unknown as InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of state updates as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams high-level state updates in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - React to state changes as nodes complete\n *\n * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of state updates.\n * Each update contains the current state after a node completes.\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const chunk of stream) {\n * console.log(chunk); // State update from each node\n * }\n * ```\n */\n async stream<\n TStreamMode extends StreamMode | StreamMode[] | undefined,\n TSubgraphs extends boolean,\n TEncoding extends \"text/event-stream\" | undefined,\n >(\n state: InvokeStateParameter<Types>,\n config?: StreamConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>,\n TStreamMode,\n TSubgraphs,\n TEncoding\n >\n ) {\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n mergedConfig as RunnableConfig\n );\n return this.#graph.stream(\n initializedState,\n mergedConfig as Record<string, any>\n ) as Promise<\n IterableReadableStream<\n StreamOutputMap<\n TStreamMode,\n TSubgraphs,\n MergedAgentState<Types>,\n MergedAgentState<Types>,\n string,\n unknown,\n unknown,\n TEncoding\n >\n >\n >;\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n\n /**\n * The following are internal methods to enable support for LangGraph Platform.\n * They are not part of the createAgent public API.\n *\n * Note: we intentionally return as `never` to avoid type errors due to type inference.\n */\n\n /**\n * @internal\n */\n streamEvents(\n state: InvokeStateParameter<Types>,\n config?: StreamConfiguration<\n InferContextInput<\n Types[\"Context\"] extends AnyAnnotationRoot | InteropZodObject\n ? Types[\"Context\"]\n : AnyAnnotationRoot\n > &\n InferMiddlewareContextInputs<Types[\"Middleware\"]>,\n StreamMode | StreamMode[] | undefined,\n boolean,\n \"text/event-stream\" | undefined\n > & { version?: \"v1\" | \"v2\" },\n streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]\n ): IterableReadableStream<StreamEvent> {\n const mergedConfig = mergeConfigs(this.#defaultConfig, config);\n return this.#graph.streamEvents(\n state,\n {\n ...(mergedConfig as Partial<\n PregelOptions<\n any,\n any,\n any,\n StreamMode | StreamMode[] | undefined,\n boolean,\n \"text/event-stream\"\n >\n >),\n version: config?.version ?? \"v2\",\n },\n streamOptions\n );\n }\n /**\n * @internal\n */\n getGraphAsync(config?: RunnableConfig) {\n return this.#graph.getGraphAsync(config) as never;\n }\n /**\n * @internal\n */\n getState(config: RunnableConfig, options?: GetStateOptions) {\n return this.#graph.getState(config, options) as never;\n }\n /**\n * @internal\n */\n getStateHistory(config: RunnableConfig, options?: CheckpointListOptions) {\n return this.#graph.getStateHistory(config, options) as never;\n }\n /**\n * @internal\n */\n getSubgraphs(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphs(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n getSubgraphAsync(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphsAsync(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown> | unknown,\n asNode?: string\n ) {\n return this.#graph.updateState(inputConfig, values, asNode) as never;\n }\n\n /**\n * @internal\n */\n get builder() {\n return this.#graph.builder;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BACA,aACD;;;;;;;;;;;;CA0BH,MAAM,eAAe,QAMlB;EAGD,MAAM,cAAc,OADN,OADS,MAAM,MAAKA,MAAO,eAAe,EACrB,eAAe,OAAO,EACzB,aAAa;AAE7C,SADe,IAAI,WAAW,YAAY;;;;;;;;;;;;CAc5C,MAAM,YAAY,QAMf;AAED,UADuB,MAAM,MAAKA,MAAO,eAAe,EAClC,YAAY,OAAO;;;;;;;;;;;CAa3C,aACE,OACA,QAWA,eACqC;EACrC,MAAM,eAAe,aAAa,MAAKX,eAAgB,OAAO;AAC9D,SAAO,MAAKW,MAAO,aACjB,OACA;GACE,GAAI;GAUJ,SAAS,QAAQ,WAAW;GAC7B,EACD,cACD;;;;;CAKH,cAAc,QAAyB;AACrC,SAAO,MAAKA,MAAO,cAAc,OAAO;;;;;CAK1C,SAAS,QAAwB,SAA2B;AAC1D,SAAO,MAAKA,MAAO,SAAS,QAAQ,QAAQ;;;;;CAK9C,gBAAgB,QAAwB,SAAiC;AACvE,SAAO,MAAKA,MAAO,gBAAgB,QAAQ,QAAQ;;;;;CAKrD,aAAa,WAAoB,SAAmB;AAClD,SAAO,MAAKA,MAAO,aAAa,WAAW,QAAQ;;;;;CAKrD,iBAAiB,WAAoB,SAAmB;AACtD,SAAO,MAAKA,MAAO,kBAAkB,WAAW,QAAQ;;;;;CAK1D,YACE,aACA,QACA,QACA;AACA,SAAO,MAAKA,MAAO,YAAY,aAAa,QAAQ,OAAO;;;;;CAM7D,IAAI,UAAU;AACZ,SAAO,MAAKA,MAAO"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* This prevents functions from being accidentally assignable to AgentMiddleware
|
|
6
6
|
* since functions have a 'name' property that would otherwise make them structurally compatible.
|
|
7
7
|
*/
|
|
8
|
-
const MIDDLEWARE_BRAND = Symbol("AgentMiddleware");
|
|
8
|
+
const MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware");
|
|
9
9
|
|
|
10
10
|
//#endregion
|
|
11
11
|
exports.MIDDLEWARE_BRAND = MIDDLEWARE_BRAND;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","names":[],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaValue,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type InferSchemaValueType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaValue<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type InferSchemaUpdateType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodInput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaValueType<TSchema>;\n\nexport type NormalizedSchemaUpdate<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaUpdateType<TSchema>;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<TSchema, TContext>\n | {\n hook: BeforeAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<TSchema, TContext>\n | {\n hook: BeforeModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<TSchema, TContext>\n | {\n hook: AfterModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<TSchema, TContext>\n | {\n hook: AfterAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaValue<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaValue<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaUpdate<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaValue<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodInput<A>\n : A extends AnyAnnotationRoot\n ? A[\"Update\"]\n : {};\n"],"mappings":";;;;;;;AAsWA,MAAa,mBAAkC,OAAO,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"types.cjs","names":[],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaValue,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type InferSchemaValueType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaValue<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type InferSchemaUpdateType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodInput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaValueType<TSchema>;\n\nexport type NormalizedSchemaUpdate<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaUpdateType<TSchema>;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<TSchema, TContext>\n | {\n hook: BeforeAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<TSchema, TContext>\n | {\n hook: BeforeModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<TSchema, TContext>\n | {\n hook: AfterModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<TSchema, TContext>\n | {\n hook: AfterAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: symbol = Symbol.for(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaValue<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaValue<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaUpdate<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaValue<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodInput<A>\n : A extends AnyAnnotationRoot\n ? A[\"Update\"]\n : {};\n"],"mappings":";;;;;;;AAsWA,MAAa,mBAA2B,OAAO,IAAI,kBAAkB"}
|
|
@@ -220,7 +220,7 @@ type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined,
|
|
|
220
220
|
* This prevents functions from being accidentally assignable to AgentMiddleware
|
|
221
221
|
* since functions have a 'name' property that would otherwise make them structurally compatible.
|
|
222
222
|
*/
|
|
223
|
-
declare const MIDDLEWARE_BRAND:
|
|
223
|
+
declare const MIDDLEWARE_BRAND: symbol;
|
|
224
224
|
/**
|
|
225
225
|
* Base middleware interface.
|
|
226
226
|
*
|
|
@@ -239,11 +239,6 @@ declare const MIDDLEWARE_BRAND: unique symbol;
|
|
|
239
239
|
* ```
|
|
240
240
|
*/
|
|
241
241
|
interface AgentMiddleware<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
|
|
242
|
-
/**
|
|
243
|
-
* Brand property to distinguish middleware instances from plain objects or functions.
|
|
244
|
-
* This is required and prevents accidental assignment of functions to middleware arrays.
|
|
245
|
-
*/
|
|
246
|
-
readonly [MIDDLEWARE_BRAND]: true;
|
|
247
242
|
/**
|
|
248
243
|
* Type marker for extracting the MiddlewareTypeConfig from a middleware instance.
|
|
249
244
|
* This is a phantom property used only for type inference.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../../src/agents/middleware/types.ts"],"mappings":";;;;;;;;;;;KA6BK,cAAA,MAAoB,CAAA,GAAI,OAAA,CAAQ,CAAA;AAAA,KAEzB,iBAAA,GAAoB,cAAA;;;;;;;;;;;;;;AAAhC;;;;;AA8BA;;;;;;;;;;UAAiB,oBAAA,iBACC,mBAAA,eACZ,mBAAA,qCAGA,gBAAA,GACA,iBAAA,CAAkB,gBAAA,IAClB,kBAAA,CAAmB,gBAAA,gBAEnB,gBAAA,GACA,iBAAA,CAAkB,gBAAA,IAClB,kBAAA,CAAmB,gBAAA,4DAGE,UAAA,GAAa,UAAA,gBAClC,UAAA,GACA,UAAA;EANkB;EAUtB,MAAA,EAAQ,OAAA;EATe;EAWvB,aAAA,EAAe,cAAA;EARU;EAUzB,WAAA,EAAa,YAAA;EATT;EAWJ,KAAA,EAAO,MAAA;AAAA;;;;;KAOG,2BAAA,GAA8B,oBAAA;AAAA,KAE9B,oBAAA,aAAiC,OAAA,oBACzC,iBAAA,GACA,OAAA,SAAgB,WAAA,kBACd,qBAAA,CAAsB,OAAA,IAAW,iBAAA,GACjC,OAAA,SAAgB,gBAAA,GACd,qBAAA,CAAsB,OAAA,IAAW,iBAAA,GACjC,OAAA,SAAgB,mBAAA,GACd,gBAAA,CAAiB,OAAA,IAAW,iBAAA,GAC5B,iBAAA;AAAA,KAEE,qBAAA,aAAkC,OAAA,oBAC1C,iBAAA,GACA,OAAA,SAAgB,WAAA,kBACd,sBAAA,CAAuB,OAAA,IAAW,iBAAA,GAClC,OAAA,SAAgB,gBAAA,GACd,oBAAA,CAAqB,OAAA,IAAW,iBAAA,GAChC,OAAA,SAAgB,mBAAA,GACd,gBAAA,CAAiB,OAAA,IAAW,iBAAA,GAC5B,iBAAA;AAAA,KAEE,qBAAA,iBACM,mBAAA,8B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AA,GACN,CAAA,GACA,CAAA,SAAU,gBAAA,GACR,2BAAA,CAA4B,CAAA;AAAA,KAGxB,gBAAA,WAA2B,mBAAA,gBACrC,CAAA,SAAU,WAAA,kBACN,qBAAA,CAAsB,OAAA,IACtB,CAAA,SAAU,gBAAA,GACR,qBAAA,CAAsB,CAAA,IACtB,CAAA,SAAU,iBAAA,GACR,CAAA;AAAA,KAGE,gBAAA,WAA2B,mBAAA,gBACrC,CAAA,SAAU,WAAA,kBACN,sBAAA,CAAuB,OAAA,IACvB,CAAA,SAAU,gBAAA,GACR,oBAAA,CAAqB,CAAA,IACrB,CAAA,SAAU,iBAAA,GACR,CAAA"}
|
|
@@ -220,7 +220,7 @@ type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined,
|
|
|
220
220
|
* This prevents functions from being accidentally assignable to AgentMiddleware
|
|
221
221
|
* since functions have a 'name' property that would otherwise make them structurally compatible.
|
|
222
222
|
*/
|
|
223
|
-
declare const MIDDLEWARE_BRAND:
|
|
223
|
+
declare const MIDDLEWARE_BRAND: symbol;
|
|
224
224
|
/**
|
|
225
225
|
* Base middleware interface.
|
|
226
226
|
*
|
|
@@ -239,11 +239,6 @@ declare const MIDDLEWARE_BRAND: unique symbol;
|
|
|
239
239
|
* ```
|
|
240
240
|
*/
|
|
241
241
|
interface AgentMiddleware<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
|
|
242
|
-
/**
|
|
243
|
-
* Brand property to distinguish middleware instances from plain objects or functions.
|
|
244
|
-
* This is required and prevents accidental assignment of functions to middleware arrays.
|
|
245
|
-
*/
|
|
246
|
-
readonly [MIDDLEWARE_BRAND]: true;
|
|
247
242
|
/**
|
|
248
243
|
* Type marker for extracting the MiddlewareTypeConfig from a middleware instance.
|
|
249
244
|
* This is a phantom property used only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CAA4B,CAAA;AAAA,KAGxB,gBAAA,WAA2B,mBAAA,gBACrC,CAAA,SAAU,WAAA,kBACN,qBAAA,CAAsB,OAAA,IACtB,CAAA,SAAU,gBAAA,GACR,qBAAA,CAAsB,CAAA,IACtB,CAAA,SAAU,iBAAA,GACR,CAAA;AAAA,KAGE,gBAAA,WAA2B,mBAAA,gBACrC,CAAA,SAAU,WAAA,kBACN,sBAAA,CAAuB,OAAA,IACvB,CAAA,SAAU,gBAAA,GACR,oBAAA,CAAqB,CAAA,IACrB,CAAA,SAAU,iBAAA,GACR,CAAA"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* This prevents functions from being accidentally assignable to AgentMiddleware
|
|
5
5
|
* since functions have a 'name' property that would otherwise make them structurally compatible.
|
|
6
6
|
*/
|
|
7
|
-
const MIDDLEWARE_BRAND = Symbol("AgentMiddleware");
|
|
7
|
+
const MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware");
|
|
8
8
|
|
|
9
9
|
//#endregion
|
|
10
10
|
export { MIDDLEWARE_BRAND };
|