langchain 1.2.13 → 1.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","StateDefinitionInit","LanguageModelLike","BaseMessage","SystemMessage","MessageStructure","MessageToolDefinition","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","DynamicStructuredTool","StructuredToolInterface","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","InferMiddlewareStates","InferMiddlewareContexts","JumpToTarget","AgentTypeConfig","TResponse","TState","TContext","TMiddleware","TTools","Record","DefaultAgentTypeConfig","InferMiddlewareTools","T","InferMiddlewareToolsArray","First","Rest","CombineTools","TAgentTools","ExtractToolDefinition","SchemaInputT","ToolOutputT","ToolsToMessageToolSet","K","N","ResolveAgentTypeConfig","Types","InferAgentType","InferAgentResponse","InferAgentStateSchema","InferAgentState","InferAgentContextSchema","InferAgentContext","InferAgentMiddleware","InferAgentTools","Interrupt","TValue","BuiltInState","TMessageStructure","UserInput","TStateSchema","ToolCall","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","A","WithStateGraphNodes","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph, StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage, MessageStructure, MessageToolDefinition } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool, DynamicStructuredTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput, InferMiddlewareStates, InferMiddlewareContexts } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\n/**\n * Type bag that encapsulates all agent type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the agent 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 TResponse - The structured response type when using `responseFormat`.\n * Defaults to `Record<string, any>`. Set to `ResponseFormatUndefined` when no\n * response format is configured.\n *\n * @typeParam TState - The custom state schema type. Can be an `AnnotationRoot`,\n * `InteropZodObject`, or `undefined`. The state persists across agent invocations\n * when using a checkpointer.\n *\n * @typeParam TContext - The context schema type. Context is read-only and not\n * persisted between invocations. Defaults to `AnyAnnotationRoot`.\n *\n * @typeParam TMiddleware - The middleware array type. Must be a readonly array\n * of `AgentMiddleware` instances.\n *\n * @typeParam TTools - The combined tools type from both `createAgent` tools parameter\n * and middleware tools. This is a readonly array of `ClientTool | ServerTool`.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyAgentTypes = AgentTypeConfig<\n * { name: string; email: string }, // Response type\n * typeof MyStateSchema, // State schema\n * typeof MyContextSchema, // Context schema\n * typeof myMiddleware, // Middleware array\n * typeof myTools // Tools array\n * >;\n *\n * // Use with ReactAgent\n * const agent: ReactAgent<MyAgentTypes> = createAgent({ ... });\n * ```\n */\nexport interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /** The structured response type when using `responseFormat` */\n Response: TResponse;\n /** The custom state schema type */\n State: TState;\n /** The context schema type */\n Context: TContext;\n /** The middleware array type */\n Middleware: TMiddleware;\n /** The combined tools type from agent and middleware */\n Tools: TTools;\n}\n/**\n * Default type configuration for agents.\n * Used when no explicit type parameters are provided.\n */\nexport interface DefaultAgentTypeConfig extends AgentTypeConfig {\n Response: Record<string, any>;\n State: undefined;\n Context: AnyAnnotationRoot;\n Middleware: readonly AgentMiddleware[];\n Tools: readonly (ClientTool | ServerTool)[];\n}\n/**\n * Helper type to infer tools from a single middleware instance.\n * Extracts the TTools type parameter from AgentMiddleware.\n */\nexport type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];\n/**\n * Helper type to infer and merge tools from an array of middleware.\n * Recursively extracts tools from each middleware and combines them into a single tuple.\n */\nexport type InferMiddlewareToolsArray<T extends readonly AgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? readonly [\n ...InferMiddlewareTools<First>,\n ...InferMiddlewareToolsArray<Rest>\n] : InferMiddlewareTools<First> : readonly [] : readonly [];\n/**\n * Helper type to combine agent tools with middleware tools into a single readonly array.\n */\nexport type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];\n/**\n * Helper type to extract the tool name, input type, and output type from a tool.\n * Converts a single tool to a MessageToolDefinition entry.\n */\ntype ExtractToolDefinition<T> = T extends DynamicStructuredTool<infer _SchemaT, infer _SchemaOutputT, infer SchemaInputT, infer ToolOutputT, infer _NameT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : T extends StructuredToolInterface<infer _SchemaT, infer SchemaInputT, infer ToolOutputT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : MessageToolDefinition;\n/**\n * Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet.\n * This maps each tool's name (as a literal type) to its MessageToolDefinition containing\n * the input and output types.\n *\n * @example\n * ```typescript\n * const myTool = tool(async (input: { a: number }) => 42, {\n * name: \"myTool\",\n * schema: z.object({ a: z.number() })\n * });\n *\n * // Results in: { myTool: MessageToolDefinition<{ a: number }, number> }\n * type ToolSet = ToolsToMessageToolSet<readonly [typeof myTool]>;\n * ```\n */\nexport type ToolsToMessageToolSet<T extends readonly (ClientTool | ServerTool)[]> = {\n [K in T[number] as K extends {\n name: infer N extends string;\n } ? N : never]: ExtractToolDefinition<K>;\n};\n/**\n * Helper type to resolve an AgentTypeConfig from either:\n * - An AgentTypeConfig directly\n * - A ReactAgent instance (using `typeof agent`)\n *\n * @example\n * ```typescript\n * const agent = createAgent({ ... });\n *\n * // From ReactAgent instance\n * type Types = ResolveAgentTypeConfig<typeof agent>;\n *\n * // From AgentTypeConfig directly\n * type Types2 = ResolveAgentTypeConfig<AgentTypeConfig<...>>;\n * ```\n */\nexport type ResolveAgentTypeConfig<T> = T extends {\n \"~agentTypes\": infer Types;\n} ? Types extends AgentTypeConfig ? Types : never : T extends AgentTypeConfig ? T : never;\n/**\n * Helper type to extract any property from an AgentTypeConfig or ReactAgent.\n *\n * @typeParam T - The AgentTypeConfig or ReactAgent to extract from\n * @typeParam K - The property key to extract (\"Response\" | \"State\" | \"Context\" | \"Middleware\" | \"Tools\")\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [myTool], ... });\n *\n * // Extract from agent instance\n * type Tools = InferAgentType<typeof agent, \"Tools\">;\n *\n * // Extract from type config\n * type Response = InferAgentType<MyTypeConfig, \"Response\">;\n * ```\n */\nexport type InferAgentType<T, K extends keyof AgentTypeConfig> = ResolveAgentTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ responseFormat: z.object({ name: z.string() }), ... });\n * type Response = InferAgentResponse<typeof agent>; // { name: string }\n * ```\n */\nexport type InferAgentResponse<T> = InferAgentType<T, \"Response\">;\n/**\n * Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `stateSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged state (what `invoke` returns), use {@link InferAgentState}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ stateSchema: mySchema, ... });\n * type Schema = InferAgentStateSchema<typeof agent>;\n * ```\n */\nexport type InferAgentStateSchema<T> = InferAgentType<T, \"State\">;\n/**\n * Helper type to infer the full merged state from an agent, including:\n * - The agent's own state schema (if provided via `stateSchema`)\n * - All middleware states\n *\n * This matches the state type returned by `invoke` and used throughout the agent.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"counter\",\n * stateSchema: z.object({ count: z.number() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * stateSchema: z.object({ userId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type State = InferAgentState<typeof agent>;\n * // { userId: string; count: number }\n * ```\n */\nexport type InferAgentState<T> = InferSchemaInput<InferAgentType<T, \"State\">> & InferMiddlewareStates<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `contextSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged context (agent context + middleware contexts), use {@link InferAgentContext}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ contextSchema: myContextSchema, ... });\n * type Schema = InferAgentContextSchema<typeof agent>;\n * ```\n */\nexport type InferAgentContextSchema<T> = InferAgentType<T, \"Context\">;\n/**\n * Helper type to infer the full merged context from an agent, including:\n * - The agent's own context schema (if provided via `contextSchema`)\n * - All middleware context schemas\n *\n * This matches the context type available throughout the agent runtime.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"auth\",\n * contextSchema: z.object({ userId: z.string() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * contextSchema: z.object({ sessionId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type Context = InferAgentContext<typeof agent>;\n * // { sessionId: string; userId: string }\n * ```\n */\nexport type InferAgentContext<T> = InferSchemaInput<InferAgentType<T, \"Context\">> & InferMiddlewareContexts<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ middleware: [authMiddleware, loggingMiddleware], ... });\n * type Middleware = InferAgentMiddleware<typeof agent>;\n * ```\n */\nexport type InferAgentMiddleware<T> = InferAgentType<T, \"Middleware\">;\n/**\n * Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [searchTool, calculatorTool], ... });\n * type Tools = InferAgentTools<typeof agent>; // readonly [typeof searchTool, typeof calculatorTool]\n * ```\n */\nexport type InferAgentTools<T> = InferAgentType<T, \"Tools\">;\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState<TMessageStructure extends MessageStructure = MessageStructure> {\n messages: BaseMessage<TMessageStructure>[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends StateDefinitionInit | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, TStateSchema extends StateDefinitionInit | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: TStateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;;;;;AAiDA;;;;;;;;;;;;;;;;;;;;;;AAUiB;AAMjB;;;;;;;AAA+D;AAW/D;;;;;;AAA6Je,UA3B5Ie,eA2B4If,CAAAA,kBA3B1GqB,MA2B0GrB,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GA3BpFQ,uBA2BoFR,GA3B1DqB,MA2B0DrB,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GA3BpCQ,uBA2BoCR,EAA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A6CV0D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEO;;;;;iBAKD9D;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS8D;;;;;;;wBAOKlD;;;;;;;;;;;;;;;;;;;;WAoBbmD;;;;;;;;;;;;;;;;;KAiBDC,wCAAwC3E,yBAAyBsC,oBAAoBtC,0CAA0CyC,sBAAsBzC,wBAAwB4E,IAAID,qBAAqBlC,QAAQmC;KAC9MC,iDAA+CC,cAAc3E,6EAA6EA,WAAW4E,IAAIC,GAAGC,GAAGhC,IAAID,KAAGkC,GAAGC,GAAGC"}
1
+ {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","StateDefinitionInit","LanguageModelLike","BaseMessage","SystemMessage","MessageStructure","MessageToolDefinition","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","DynamicStructuredTool","StructuredToolInterface","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","InferMiddlewareStates","InferMiddlewareContexts","JumpToTarget","AgentTypeConfig","TResponse","TState","TContext","TMiddleware","TTools","Record","DefaultAgentTypeConfig","InferMiddlewareTools","T","InferMiddlewareToolsArray","First","Rest","CombineTools","TAgentTools","ExtractToolDefinition","SchemaInputT","ToolOutputT","ToolsToMessageToolSet","K","N","ResolveAgentTypeConfig","Types","InferAgentType","InferAgentResponse","InferAgentStateSchema","InferAgentState","InferAgentContextSchema","InferAgentContext","InferAgentMiddleware","InferAgentTools","Interrupt","TValue","BuiltInState","TMessageStructure","UserInput","TStateSchema","ToolCall","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","A","WithStateGraphNodes","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph, StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage, MessageStructure, MessageToolDefinition } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool, DynamicStructuredTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput, InferMiddlewareStates, InferMiddlewareContexts } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\n/**\n * Type bag that encapsulates all agent type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the agent 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 TResponse - The structured response type when using `responseFormat`.\n * Defaults to `Record<string, any>`. Set to `ResponseFormatUndefined` when no\n * response format is configured.\n *\n * @typeParam TState - The custom state schema type. Can be an `AnnotationRoot`,\n * `InteropZodObject`, or `undefined`. The state persists across agent invocations\n * when using a checkpointer.\n *\n * @typeParam TContext - The context schema type. Context is read-only and not\n * persisted between invocations. Defaults to `AnyAnnotationRoot`.\n *\n * @typeParam TMiddleware - The middleware array type. Must be a readonly array\n * of `AgentMiddleware` instances.\n *\n * @typeParam TTools - The combined tools type from both `createAgent` tools parameter\n * and middleware tools. This is a readonly array of `ClientTool | ServerTool`.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyAgentTypes = AgentTypeConfig<\n * { name: string; email: string }, // Response type\n * typeof MyStateSchema, // State schema\n * typeof MyContextSchema, // Context schema\n * typeof myMiddleware, // Middleware array\n * typeof myTools // Tools array\n * >;\n *\n * // Use with ReactAgent\n * const agent: ReactAgent<MyAgentTypes> = createAgent({ ... });\n * ```\n */\nexport interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /** The structured response type when using `responseFormat` */\n Response: TResponse;\n /** The custom state schema type */\n State: TState;\n /** The context schema type */\n Context: TContext;\n /** The middleware array type */\n Middleware: TMiddleware;\n /** The combined tools type from agent and middleware */\n Tools: TTools;\n}\n/**\n * Default type configuration for agents.\n * Used when no explicit type parameters are provided.\n */\nexport interface DefaultAgentTypeConfig extends AgentTypeConfig {\n Response: Record<string, any>;\n State: undefined;\n Context: AnyAnnotationRoot;\n Middleware: readonly AgentMiddleware[];\n Tools: readonly (ClientTool | ServerTool)[];\n}\n/**\n * Helper type to infer tools from a single middleware instance.\n * Extracts the TTools type parameter from AgentMiddleware.\n */\nexport type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];\n/**\n * Helper type to infer and merge tools from an array of middleware.\n * Recursively extracts tools from each middleware and combines them into a single tuple.\n */\nexport type InferMiddlewareToolsArray<T extends readonly AgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? readonly [\n ...InferMiddlewareTools<First>,\n ...InferMiddlewareToolsArray<Rest>\n] : InferMiddlewareTools<First> : readonly [] : readonly [];\n/**\n * Helper type to combine agent tools with middleware tools into a single readonly array.\n */\nexport type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];\n/**\n * Helper type to extract the tool name, input type, and output type from a tool.\n * Converts a single tool to a MessageToolDefinition entry.\n */\ntype ExtractToolDefinition<T> = T extends DynamicStructuredTool<infer _SchemaT, infer _SchemaOutputT, infer SchemaInputT, infer ToolOutputT, infer _NameT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : T extends StructuredToolInterface<infer _SchemaT, infer SchemaInputT, infer ToolOutputT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : MessageToolDefinition;\n/**\n * Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet.\n * This maps each tool's name (as a literal type) to its MessageToolDefinition containing\n * the input and output types.\n *\n * @example\n * ```typescript\n * const myTool = tool(async (input: { a: number }) => 42, {\n * name: \"myTool\",\n * schema: z.object({ a: z.number() })\n * });\n *\n * // Results in: { myTool: MessageToolDefinition<{ a: number }, number> }\n * type ToolSet = ToolsToMessageToolSet<readonly [typeof myTool]>;\n * ```\n */\nexport type ToolsToMessageToolSet<T extends readonly (ClientTool | ServerTool)[]> = {\n [K in T[number] as K extends {\n name: infer N extends string;\n } ? N : never]: ExtractToolDefinition<K>;\n};\n/**\n * Helper type to resolve an AgentTypeConfig from either:\n * - An AgentTypeConfig directly\n * - A ReactAgent instance (using `typeof agent`)\n *\n * @example\n * ```typescript\n * const agent = createAgent({ ... });\n *\n * // From ReactAgent instance\n * type Types = ResolveAgentTypeConfig<typeof agent>;\n *\n * // From AgentTypeConfig directly\n * type Types2 = ResolveAgentTypeConfig<AgentTypeConfig<...>>;\n * ```\n */\nexport type ResolveAgentTypeConfig<T> = T extends {\n \"~agentTypes\": infer Types;\n} ? Types extends AgentTypeConfig ? Types : never : T extends AgentTypeConfig ? T : never;\n/**\n * Helper type to extract any property from an AgentTypeConfig or ReactAgent.\n *\n * @typeParam T - The AgentTypeConfig or ReactAgent to extract from\n * @typeParam K - The property key to extract (\"Response\" | \"State\" | \"Context\" | \"Middleware\" | \"Tools\")\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [myTool], ... });\n *\n * // Extract from agent instance\n * type Tools = InferAgentType<typeof agent, \"Tools\">;\n *\n * // Extract from type config\n * type Response = InferAgentType<MyTypeConfig, \"Response\">;\n * ```\n */\nexport type InferAgentType<T, K extends keyof AgentTypeConfig> = ResolveAgentTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ responseFormat: z.object({ name: z.string() }), ... });\n * type Response = InferAgentResponse<typeof agent>; // { name: string }\n * ```\n */\nexport type InferAgentResponse<T> = InferAgentType<T, \"Response\">;\n/**\n * Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `stateSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged state (what `invoke` returns), use {@link InferAgentState}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ stateSchema: mySchema, ... });\n * type Schema = InferAgentStateSchema<typeof agent>;\n * ```\n */\nexport type InferAgentStateSchema<T> = InferAgentType<T, \"State\">;\n/**\n * Helper type to infer the full merged state from an agent, including:\n * - The agent's own state schema (if provided via `stateSchema`)\n * - All middleware states\n *\n * This matches the state type returned by `invoke` and used throughout the agent.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"counter\",\n * stateSchema: z.object({ count: z.number() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * stateSchema: z.object({ userId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type State = InferAgentState<typeof agent>;\n * // { userId: string; count: number }\n * ```\n */\nexport type InferAgentState<T> = InferSchemaInput<InferAgentType<T, \"State\">> & InferMiddlewareStates<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `contextSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged context (agent context + middleware contexts), use {@link InferAgentContext}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ contextSchema: myContextSchema, ... });\n * type Schema = InferAgentContextSchema<typeof agent>;\n * ```\n */\nexport type InferAgentContextSchema<T> = InferAgentType<T, \"Context\">;\n/**\n * Helper type to infer the full merged context from an agent, including:\n * - The agent's own context schema (if provided via `contextSchema`)\n * - All middleware context schemas\n *\n * This matches the context type available throughout the agent runtime.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"auth\",\n * contextSchema: z.object({ userId: z.string() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * contextSchema: z.object({ sessionId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type Context = InferAgentContext<typeof agent>;\n * // { sessionId: string; userId: string }\n * ```\n */\nexport type InferAgentContext<T> = InferSchemaInput<InferAgentType<T, \"Context\">> & InferMiddlewareContexts<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ middleware: [authMiddleware, loggingMiddleware], ... });\n * type Middleware = InferAgentMiddleware<typeof agent>;\n * ```\n */\nexport type InferAgentMiddleware<T> = InferAgentType<T, \"Middleware\">;\n/**\n * Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [searchTool, calculatorTool], ... });\n * type Tools = InferAgentTools<typeof agent>; // readonly [typeof searchTool, typeof calculatorTool]\n * ```\n */\nexport type InferAgentTools<T> = InferAgentType<T, \"Tools\">;\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState<TMessageStructure extends MessageStructure = MessageStructure> {\n messages: BaseMessage<TMessageStructure>[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends StateDefinitionInit | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, TStateSchema extends StateDefinitionInit | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: TStateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\nexport {};\n//# sourceMappingURL=types.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AqBJ,iBAAiBE,kBAAkBoD,0BAA0BrD,aAAaqD,0BAA0BnD,iBAAiBmD,0BAA0BjD;;;;;;;;;;;;;;;;;;;;;;;;kBAwBvfjB;;;;;;;;;;;;;;;;;;;;;;WAsBPS,aAAaD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAsEEN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBA6CV0D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEO;;;;;iBAKD9D;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS8D;;;;;;;wBAOKlD;;;;;;;;;;;;;;;;;;;;WAoBbmD;;;;;;;;;;;;;;;;;KAiBDC,wCAAwC3E,yBAAyBsC,oBAAoBtC,0CAA0CyC,sBAAsBzC,wBAAwB4E,IAAID,qBAAqBlC,QAAQmC;KAC9MC,iDAA+CC,cAAc3E,6EAA6EA,WAAW4E,IAAIC,GAAGC,GAAGhC,IAAID,KAAGkC,GAAGC,GAAGC"}
@@ -10,6 +10,26 @@ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@
10
10
  const NAME_PATTERN = /<name>(.*?)<\/name>/s;
11
11
  const CONTENT_PATTERN = /<content>(.*?)<\/content>/s;
12
12
  /**
13
+ * Parse middleware state from the full agent state based on the middleware's stateSchema.
14
+ *
15
+ * Handles two types of state schemas:
16
+ * 1. Zod schemas (v3 or v4) - parsed using interopParse
17
+ * 2. LangGraph StateSchema - extracts only the keys defined in `fields`
18
+ *
19
+ * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)
20
+ * @param state - The full agent state to parse from
21
+ * @returns Parsed state containing only the keys defined in the schema
22
+ */
23
+ function parseMiddlewareState(stateSchema, state) {
24
+ if (__langchain_langgraph.StateSchema.isInstance(stateSchema)) {
25
+ const result = {};
26
+ for (const key of Object.keys(stateSchema.fields)) if (key in state) result[key] = state[key];
27
+ return result;
28
+ }
29
+ if ((0, __langchain_core_utils_types.isInteropZodSchema)(stateSchema)) return (0, __langchain_core_utils_types.interopParse)(stateSchema, state);
30
+ throw new Error(`Invalid state schema type: ${typeof stateSchema}`);
31
+ }
32
+ /**
13
33
  * Attach formatted agent names to the messages passed to and from a language model.
14
34
  *
15
35
  * This is useful for making a message history with multiple agents more coherent.
@@ -346,7 +366,7 @@ function wrapToolCall(middleware) {
346
366
  ...request,
347
367
  state: {
348
368
  messages: originalState.messages,
349
- ...m.stateSchema ? (0, __langchain_core_utils_types.interopParse)(m.stateSchema, { ...originalState }) : {}
369
+ ...m.stateSchema ? parseMiddlewareState(m.stateSchema, { ...originalState }) : {}
350
370
  }
351
371
  }, wrappedInnerHandler);
352
372
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["message: T","AIMessage","AIMessageChunk","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","llm: LanguageModelLike","isBaseChatModel","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","RunnableSequence","step: RunnableLike","isConfigurableModel","MultipleToolsBoundError","message?: BaseMessage","systemPrompt?: string | SystemMessage","SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook","wrappedInnerHandler: ToolCallHandler","ToolMessage","MiddlewareError"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? interopParse(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;;AAyCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;AACf,KAAI,CAACC,oCAAU,WAAW,QAAQ,IAAIC,yCAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;E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C,QAAO;AACR;;;;;;;;;AAUD,SAAgB,aACdC,YACA;CACA,MAAM,6BAA6B,WAAW,OAAO,CAAC,MAAM,EAAE,aAAa;AAE3E,KAAI,2BAA2B,WAAW,EACxC;AAGF,QAAO,sBACL,2BAA2B,IAAI,CAAC,MAAM;EACpC,MAAM,kBAAkB,EAAE;;;;EAI1B,MAAMC,iBAAmC,OAAO,SAAS,YAAY;;;;;;;GAOnE,MAAM,gBAAgB,QAAQ;;;;;GAM9B,MAAMC,sBAAuC,OAAO,kBAAkB;;;;;;IAMpE,MAAM,cAAc;KAClB,GAAG;KACH,GAAG,cAAc;IAClB;AACD,WAAO,QAAQ;KACb,GAAG;KACH,OAAO;IACR,EAAC;GACH;AAED,OAAI;IACF,MAAM,SAAS,MAAM,gBACnB;KACE,GAAG;KAIH,OAAO;MACL,UAAU,cAAc;MACxB,GAAI,EAAE,6DACW,EAAE,aAAa,EAAE,GAAG,cAAe,EAAC,GACjD,CAAE;KACP;IACF,GACD,oBACD;;;;AAKD,QAAI,CAACC,sCAAY,WAAW,OAAO,IAAI,sCAAW,OAAO,CACvD,OAAM,IAAI,MACR,CAAC,oDAAoD,EAAE,EAAE,KAAK,wCAAG,EACvB,OAAO,QAAQ;AAI7D,WAAO;GACR,SAAQ,OAAO;AACd,UAAMC,+BAAgB,KAAK,OAAO,EAAE,KAAK;GAC1C;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
1
+ {"version":3,"file":"utils.cjs","names":["stateSchema: unknown","state: Record<string, unknown>","StateSchema","result: Record<string, unknown>","message: T","AIMessage","AIMessageChunk","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","llm: LanguageModelLike","isBaseChatModel","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","RunnableSequence","step: RunnableLike","isConfigurableModel","MultipleToolsBoundError","message?: BaseMessage","systemPrompt?: string | SystemMessage","SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook","wrappedInnerHandler: ToolCallHandler","ToolMessage","MiddlewareError"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;;AA0CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACPA,aACAC,OACyB;AAEzB,KAAIC,kCAAY,WAAW,YAAY,EAAE;EACvC,MAAMC,SAAkC,CAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,YAAY,OAAO,CAC/C,KAAI,OAAO,OACT,OAAO,OAAO,MAAM;AAGxB,SAAO;CACR;AAGD,0DAAuB,YAAY,CACjC,uDAAoB,aAAiC,MAAM;AAG7D,OAAM,IAAI,MAAM,CAAC,2BAA2B,EAAE,OAAO,aAAa;AACnE;;;;;;;;;;;;;;;AAkBD,SAAgB,oBACdC,SACe;AACf,KAAI,CAACC,oCAAU,WAAW,QAAQ,IAAIC,yCAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,oCAAU;EACnB,G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MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KACxC,SAAS,WAAW,SAAS,IAAI,OAAO;AAG1C,QAAO;AACR;;;;;;;;;AAUD,SAAgB,aACdC,YACA;CACA,MAAM,6BAA6B,WAAW,OAAO,CAAC,MAAM,EAAE,aAAa;AAE3E,KAAI,2BAA2B,WAAW,EACxC;AAGF,QAAO,sBACL,2BAA2B,IAAI,CAAC,MAAM;EACpC,MAAM,kBAAkB,EAAE;;;;EAI1B,MAAMC,iBAAmC,OAAO,SAAS,YAAY;;;;;;;GAOnE,MAAM,gBAAgB,QAAQ;;;;;GAM9B,MAAMC,sBAAuC,OAAO,kBAAkB;;;;;;IAMpE,MAAM,cAAc;KAClB,GAAG;KACH,GAAG,cAAc;IAClB;AACD,WAAO,QAAQ;KACb,GAAG;KACH,OAAO;IACR,EAAC;GACH;AAED,OAAI;IACF,MAAM,SAAS,MAAM,gBACnB;KACE,GAAG;KAIH,OAAO;MACL,UAAU,cAAc;MACxB,GAAI,EAAE,cACF,qBAAqB,EAAE,aAAa,EAAE,GAAG,cAAe,EAAC,GACzD,CAAE;KACP;IACF,GACD,oBACD;;;;AAKD,QAAI,CAACC,sCAAY,WAAW,OAAO,IAAI,sCAAW,OAAO,CACvD,OAAM,IAAI,MACR,CAAC,oDAAoD,EAAE,EAAE,KAAK,wCAAG,EACvB,OAAO,QAAQ;AAI7D,WAAO;GACR,SAAQ,OAAO;AACd,UAAMC,+BAAgB,KAAK,OAAO,EAAE,KAAK;GAC1C;EACF;AACD,SAAO;CACR,EAAC,CACH;AACF"}
@@ -2,13 +2,33 @@ import { isBaseChatModel, isConfigurableModel } from "./model.js";
2
2
  import { MiddlewareError, MultipleToolsBoundError } from "./errors.js";
3
3
  import { AIMessage, AIMessageChunk, SystemMessage, ToolMessage } from "@langchain/core/messages";
4
4
  import { Runnable, RunnableBinding, RunnableSequence } from "@langchain/core/runnables";
5
- import { isCommand } from "@langchain/langgraph";
6
- import { interopParse } from "@langchain/core/utils/types";
5
+ import { StateSchema, isCommand } from "@langchain/langgraph";
6
+ import { interopParse, isInteropZodSchema } from "@langchain/core/utils/types";
7
7
 
8
8
  //#region src/agents/utils.ts
9
9
  const NAME_PATTERN = /<name>(.*?)<\/name>/s;
10
10
  const CONTENT_PATTERN = /<content>(.*?)<\/content>/s;
11
11
  /**
12
+ * Parse middleware state from the full agent state based on the middleware's stateSchema.
13
+ *
14
+ * Handles two types of state schemas:
15
+ * 1. Zod schemas (v3 or v4) - parsed using interopParse
16
+ * 2. LangGraph StateSchema - extracts only the keys defined in `fields`
17
+ *
18
+ * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)
19
+ * @param state - The full agent state to parse from
20
+ * @returns Parsed state containing only the keys defined in the schema
21
+ */
22
+ function parseMiddlewareState(stateSchema, state) {
23
+ if (StateSchema.isInstance(stateSchema)) {
24
+ const result = {};
25
+ for (const key of Object.keys(stateSchema.fields)) if (key in state) result[key] = state[key];
26
+ return result;
27
+ }
28
+ if (isInteropZodSchema(stateSchema)) return interopParse(stateSchema, state);
29
+ throw new Error(`Invalid state schema type: ${typeof stateSchema}`);
30
+ }
31
+ /**
12
32
  * Attach formatted agent names to the messages passed to and from a language model.
13
33
  *
14
34
  * This is useful for making a message history with multiple agents more coherent.
@@ -345,7 +365,7 @@ function wrapToolCall(middleware) {
345
365
  ...request,
346
366
  state: {
347
367
  messages: originalState.messages,
348
- ...m.stateSchema ? interopParse(m.stateSchema, { ...originalState }) : {}
368
+ ...m.stateSchema ? parseMiddlewareState(m.stateSchema, { ...originalState }) : {}
349
369
  }
350
370
  }, wrappedInnerHandler);
351
371
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["message: T","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","llm: LanguageModelLike","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","step: RunnableLike","message?: BaseMessage","systemPrompt?: string | SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook","wrappedInnerHandler: ToolCallHandler"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? interopParse(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;AA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{"version":3,"file":"utils.js","names":["stateSchema: unknown","state: Record<string, unknown>","result: Record<string, unknown>","message: T","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","llm: LanguageModelLike","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","step: RunnableLike","message?: BaseMessage","systemPrompt?: string | SystemMessage","model","nextSteps: unknown[]","handlers: WrapToolCallHook[]","outer: WrapToolCallHook","inner: WrapToolCallHook","innerHandler: ToolCallHandler","middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]","wrappedHandler: WrapToolCallHook","wrappedInnerHandler: ToolCallHandler"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;AA0CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACPA,aACAC,OACyB;AAEzB,KAAI,YAAY,WAAW,YAAY,EAAE;EACvC,MAAMC,SAAkC,CAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,YAAY,OAAO,CAC/C,KAAI,OAAO,OACT,OAAO,OAAO,MAAM;AAGxB,SAAO;CACR;AAGD,KAAI,mBAAmB,YAAY,CACjC,QAAO,aAAa,aAAiC,MAAM;AAG7D,OAAM,IAAI,MAAM,CAAC,2BAA2B,EAAE,OAAO,aAAa;AACnE;;;;;;;;;;;;;;;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3
- "version": "1.2.13",
3
+ "version": "1.2.15",
4
4
  "description": "Typescript bindings for langchain",
5
5
  "author": "LangChain",
6
6
  "license": "MIT",