langchain 1.2.18 → 1.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/agents/index.cjs.map +1 -1
  3. package/dist/agents/index.js.map +1 -1
  4. package/dist/agents/middleware/types.cjs.map +1 -1
  5. package/dist/agents/middleware/types.d.cts +1 -1
  6. package/dist/agents/middleware/types.d.cts.map +1 -1
  7. package/dist/agents/middleware/types.d.ts +1 -1
  8. package/dist/agents/middleware/types.d.ts.map +1 -1
  9. package/dist/agents/middleware/types.js.map +1 -1
  10. package/dist/agents/middleware/utils.cjs +20 -3
  11. package/dist/agents/middleware/utils.cjs.map +1 -1
  12. package/dist/agents/middleware/utils.d.cts +8 -2
  13. package/dist/agents/middleware/utils.d.cts.map +1 -1
  14. package/dist/agents/middleware/utils.d.ts +8 -2
  15. package/dist/agents/middleware/utils.d.ts.map +1 -1
  16. package/dist/agents/middleware/utils.js +20 -3
  17. package/dist/agents/middleware/utils.js.map +1 -1
  18. package/dist/agents/nodes/AgentNode.cjs +86 -51
  19. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  20. package/dist/agents/nodes/AgentNode.js +87 -52
  21. package/dist/agents/nodes/AgentNode.js.map +1 -1
  22. package/dist/agents/nodes/middleware.cjs +4 -5
  23. package/dist/agents/nodes/middleware.cjs.map +1 -1
  24. package/dist/agents/nodes/middleware.js +4 -5
  25. package/dist/agents/nodes/middleware.js.map +1 -1
  26. package/dist/agents/responses.cjs.map +1 -1
  27. package/dist/agents/responses.d.cts +9 -0
  28. package/dist/agents/responses.d.cts.map +1 -1
  29. package/dist/agents/responses.d.ts +9 -0
  30. package/dist/agents/responses.d.ts.map +1 -1
  31. package/dist/agents/responses.js.map +1 -1
  32. package/dist/agents/utils.cjs.map +1 -1
  33. package/dist/agents/utils.js.map +1 -1
  34. package/dist/chat_models/universal.cjs.map +1 -1
  35. package/dist/chat_models/universal.js.map +1 -1
  36. package/dist/hub/base.cjs +6 -3
  37. package/dist/hub/base.cjs.map +1 -1
  38. package/dist/hub/base.d.cts +2 -0
  39. package/dist/hub/base.d.cts.map +1 -1
  40. package/dist/hub/base.d.ts +2 -0
  41. package/dist/hub/base.d.ts.map +1 -1
  42. package/dist/hub/base.js +6 -3
  43. package/dist/hub/base.js.map +1 -1
  44. package/dist/hub/index.cjs +2 -0
  45. package/dist/hub/index.cjs.map +1 -1
  46. package/dist/hub/index.d.cts +5 -0
  47. package/dist/hub/index.d.cts.map +1 -1
  48. package/dist/hub/index.d.ts +5 -0
  49. package/dist/hub/index.d.ts.map +1 -1
  50. package/dist/hub/index.js +2 -0
  51. package/dist/hub/index.js.map +1 -1
  52. package/dist/hub/node.cjs +2 -0
  53. package/dist/hub/node.cjs.map +1 -1
  54. package/dist/hub/node.d.cts +5 -0
  55. package/dist/hub/node.d.cts.map +1 -1
  56. package/dist/hub/node.d.ts +5 -0
  57. package/dist/hub/node.d.ts.map +1 -1
  58. package/dist/hub/node.js +2 -0
  59. package/dist/hub/node.js.map +1 -1
  60. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodInput","InferInteropZodOutput","InteropZodToStateDefinition","AnnotationRoot","StateSchema","InferStateSchemaUpdate","StateDefinitionInit","AIMessage","SystemMessage","ToolMessage","ToolCall","Command","ClientTool","ServerTool","JumpToTarget","Runtime","AgentBuiltInState","ModelRequest","PromiseOrValue","T","Promise","AnyAnnotationRoot","MiddlewareTypeConfig","TSchema","TContextSchema","TFullContext","TTools","DefaultMiddlewareTypeConfig","NormalizedSchemaInput","InferSchemaInput","MiddlewareResult","TState","ToolCallRequest","TContext","Record","ToolCallHandler","WrapToolCallHook","WrapModelCallHandler","Omit","WrapModelCallHook","BeforeAgentHandler","Partial","BeforeAgentHook","BeforeModelHandler","BeforeModelHook","AfterModelHandler","AfterModelHook","AfterAgentHandler","AfterAgentHook","MIDDLEWARE_BRAND","AgentMiddleware","FilterPrivateProps","K","ResolveMiddlewareTypeConfig","Types","InferMiddlewareType","InferMiddlewareSchema","InferMiddlewareContextSchema","InferMiddlewareFullContext","InferMiddlewareToolsFromConfig","InferChannelType","ToAnnotationRoot","InferMiddlewareState","InferMiddlewareInputState","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","InferMiddlewareContextInput","Inner","InferMiddlewareContexts","MergeContextTypes","A","B","InferMiddlewareContextInputs","InferContextInput","ContextSchema","TFields"],"sources":["../../../src/agents/middleware/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodInput, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot, StateSchema, InferStateSchemaUpdate, StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { AIMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\ntype PromiseOrValue<T> = T | Promise<T>;\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<TSchema extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\nexport type NormalizedSchemaInput<TSchema extends StateDefinitionInit | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaInput<TSchema> & AgentBuiltInState : AgentBuiltInState;\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = (TState & {\n jumpTo?: JumpToTarget;\n}) | void;\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<TState extends Record<string, unknown> = Record<string, unknown>, TContext = unknown> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, \n/**\n * allow to reset the system prompt or system message\n */\n\"systemPrompt\" | \"systemMessage\"> & {\n systemPrompt?: string;\n systemMessage?: SystemMessage;\n}) => PromiseOrValue<AIMessage>;\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage>;\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport declare const MIDDLEWARE_BRAND: unique symbol;\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<TSchema, TContextSchema, TFullContext, TTools>;\n /**\n * The name of the middleware.\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n} ? Types extends MiddlewareTypeConfig ? Types : never : T extends MiddlewareTypeConfig ? T : never;\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<T, K extends keyof MiddlewareTypeConfig> = ResolveMiddlewareTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<T, \"ContextSchema\">;\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<T, \"FullContext\">;\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>[\"State\"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined] ? [B] extends [undefined] ? undefined : B | undefined : [B] extends [undefined] ? A | undefined : [A] extends [B] ? A : [B] extends [A] ? B : A & B;\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? MergeContextTypes<InferMiddlewareContextInput<First>, InferMiddlewareContextInputs<Rest>> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\nexport type ToAnnotationRoot<A extends StateDefinitionInit> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? InteropZodToStateDefinition<A> : never;\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> : A extends InteropZodObject ? InferInteropZodOutput<A> : A extends AnyAnnotationRoot ? A[\"State\"] : {};\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;KAUKqB,oBAAoBC,IAAIC,QAAQD;AAAhCD,KACOG,iBAAAA,GAAoBlB,cADb,CAAA,GAAA,CAAA;;;;AAAiB;AACpC;AA6BA;;;;;;;;;;;;;;;;;;;;;AAQiB;AAMjB;AACYyB,UAfKN,oBAegBC,CAAAA,kBAfqBjB,mBAerB,GAAA,SAAA,GAfuDA,mBAevD,GAAA,SAAA,EAAA,yBAf+GT,gBAe/G,GAfkIC,iBAelI,CAfoJD,gBAepJ,CAAA,GAfwKE,kBAexK,CAf2LF,gBAe3L,CAAA,GAAA,SAAA,G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oBAAoBxB,oBAAoBkF,sBAAsBlF,mBAAmBG,qBAAqB+E,iBAAiBA,sBAAsB1D,oBAAoBwC,iBAAiBkB;KAC1NlB,2BAA2BvD,uBAAuBqE,UAAUtD,oBAAoBsD,IAAIA,UAAU9E,mBAAmBK,4BAA4ByE;KAC7I9C,2BAA2BvB,mCAAmCqE,UAAUvE,6BAA6BC,uBAAuB2E,WAAWL,UAAU9E,mBAAmBI,sBAAsB0E,KAAKA,UAAUtD,oBAAoBsD"}
1
+ {"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodInput","InferInteropZodOutput","InteropZodToStateDefinition","AnnotationRoot","StateSchema","InferStateSchemaUpdate","StateDefinitionInit","AIMessage","SystemMessage","ToolMessage","ToolCall","Command","ClientTool","ServerTool","JumpToTarget","Runtime","AgentBuiltInState","ModelRequest","PromiseOrValue","T","Promise","AnyAnnotationRoot","MiddlewareTypeConfig","TSchema","TContextSchema","TFullContext","TTools","DefaultMiddlewareTypeConfig","NormalizedSchemaInput","InferSchemaInput","MiddlewareResult","TState","ToolCallRequest","TContext","Record","ToolCallHandler","WrapToolCallHook","WrapModelCallHandler","Omit","WrapModelCallHook","BeforeAgentHandler","Partial","BeforeAgentHook","BeforeModelHandler","BeforeModelHook","AfterModelHandler","AfterModelHook","AfterAgentHandler","AfterAgentHook","MIDDLEWARE_BRAND","AgentMiddleware","FilterPrivateProps","K","ResolveMiddlewareTypeConfig","Types","InferMiddlewareType","InferMiddlewareSchema","InferMiddlewareContextSchema","InferMiddlewareFullContext","InferMiddlewareToolsFromConfig","InferChannelType","ToAnnotationRoot","InferMiddlewareState","InferMiddlewareInputState","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","InferMiddlewareContextInput","Inner","InferMiddlewareContexts","MergeContextTypes","A","B","InferMiddlewareContextInputs","InferContextInput","ContextSchema","TFields"],"sources":["../../../src/agents/middleware/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodInput, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot, StateSchema, InferStateSchemaUpdate, StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { AIMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\ntype PromiseOrValue<T> = T | Promise<T>;\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<TSchema extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\nexport type NormalizedSchemaInput<TSchema extends StateDefinitionInit | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaInput<TSchema> & AgentBuiltInState : AgentBuiltInState;\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = (TState & {\n jumpTo?: JumpToTarget;\n}) | void;\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<TState extends Record<string, unknown> = Record<string, unknown>, TContext = unknown> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, \n/**\n * allow to reset the system prompt or system message\n */\n\"systemPrompt\" | \"systemMessage\"> & {\n systemPrompt?: string;\n systemMessage?: SystemMessage;\n}) => PromiseOrValue<AIMessage>;\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage | Command>;\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport declare const MIDDLEWARE_BRAND: unique symbol;\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<TSchema, TContextSchema, TFullContext, TTools>;\n /**\n * The name of the middleware.\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n} ? Types extends MiddlewareTypeConfig ? Types : never : T extends MiddlewareTypeConfig ? T : never;\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<T, K extends keyof MiddlewareTypeConfig> = ResolveMiddlewareTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<T, \"ContextSchema\">;\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<T, \"FullContext\">;\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>[\"State\"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined] ? [B] extends [undefined] ? undefined : B | undefined : [B] extends [undefined] ? A | undefined : [A] extends [B] ? A : [B] extends [A] ? B : A & B;\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? MergeContextTypes<InferMiddlewareContextInput<First>, InferMiddlewareContextInputs<Rest>> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\nexport type ToAnnotationRoot<A extends StateDefinitionInit> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? InteropZodToStateDefinition<A> : never;\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> : A extends InteropZodObject ? InferInteropZodOutput<A> : A extends AnyAnnotationRoot ? A[\"State\"] : {};\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;KAUKqB,oBAAoBC,IAAIC,QAAQD;AAAhCD,KACOG,iBAAAA,GAAoBlB,cADb,CAAA,GAAA,CAAA;;;;AAAiB;AACpC;AA6BA;;;;;;;;;;;;;;;;;;;;;AAQiB;AAMjB;AACYyB,UAfKN,oBAegBC,CAAAA,kBAfqBjB,mBAerB,GAAA,SAAA,GAfuDA,mBAevD,GAAA,SAAA,EAAA,yBAf+GT,gBAe/G,GAfkIC,iBAelI,CAfoJD,gBAepJ,CAAA,GAfwKE,kBAexK,CAf2LF,gBAe3L,CAAA,GAAA,SAAA,GAf2NA,gBAe3N,GAf8OC,iBAe9O,CAfgQD,gBAehQ,CAAA,GAfoRE,kBAepR,CAfuSF,gBAevS,CAAA,GAAA,SAAA,EAAA,eAAA,GAAA,EAAA,eAAA,SAAA,CAfmXe,UAenX,GAfgYC,UAehY,CAAA,EAAA,GAAA,SAAA,CAf0ZD,UAe1Z,GAfuaC,UAeva,CAAA,EAAA,CAAA,CAAA;EAAiBP;EAAkDiB,MAAAA,EAbxFA,SAawFA;EAA2BP;EAAoBO,aAAAA,EAXhIC,gBAWgID;EAAgB1B;EAAyC0B,WAAAA,EAT3LE,YAS2LF;EAAtBtB;EAAiCe,KA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LEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;AAmVA,MAAaA,mBAAkC,OAAO,kBAAkB"}
1
+ {"version":3,"file":"types.js","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;AAmVA,MAAaA,mBAAkC,OAAO,kBAAkB"}
@@ -1,14 +1,31 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
3
+ const __langchain_core_tools = require_rolldown_runtime.__toESM(require("@langchain/core/tools"));
4
+ const __langchain_core_utils_function_calling = require_rolldown_runtime.__toESM(require("@langchain/core/utils/function_calling"));
3
5
 
4
6
  //#region src/agents/middleware/utils.ts
5
7
  /**
6
- * Default token counter that approximates based on character count
8
+ * Default token counter that approximates based on character count.
9
+ *
10
+ * If tools are provided, the token count also includes stringified tool schemas.
11
+ *
7
12
  * @param messages Messages to count tokens for
13
+ * @param tools Optional list of tools to include in the token count. Each tool
14
+ * can be either a LangChain tool instance or a dict representing a tool schema.
15
+ * LangChain tool instances are converted to OpenAI tool format before counting.
8
16
  * @returns Approximate token count
9
17
  */
10
- function countTokensApproximately(messages) {
18
+ function countTokensApproximately(messages, tools) {
19
+ const charsPerToken = 4;
11
20
  let totalChars = 0;
21
+ if (tools && tools.length > 0) {
22
+ let toolsChars = 0;
23
+ for (const tool of tools) {
24
+ const toolDict = (0, __langchain_core_tools.isLangChainTool)(tool) ? (0, __langchain_core_utils_function_calling.convertToOpenAITool)(tool) : tool;
25
+ toolsChars += JSON.stringify(toolDict).length;
26
+ }
27
+ totalChars += toolsChars;
28
+ }
12
29
  for (const msg of messages) {
13
30
  let textContent;
14
31
  if (typeof msg.content === "string") textContent = msg.content;
@@ -22,7 +39,7 @@ function countTokensApproximately(messages) {
22
39
  if (__langchain_core_messages.ToolMessage.isInstance(msg)) textContent += msg.tool_call_id ?? "";
23
40
  totalChars += textContent.length;
24
41
  }
25
- return Math.ceil(totalChars / 4);
42
+ return Math.ceil(totalChars / charsPerToken);
26
43
  }
27
44
  function getHookConstraint(hook) {
28
45
  if (!hook || typeof hook === "function") return void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["messages: BaseMessage[]","textContent: string","AIMessage","ToolMessage","hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined","arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook","ms: number","config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n }","retryNumber: number","delay: number"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count\n * @param messages Messages to count tokens for\n * @returns Approximate token count\n */\nexport function countTokensApproximately(messages: BaseMessage[]): number {\n let totalChars = 0;\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / 4);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return delay;\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,yBAAyBA,UAAiC;CACxE,IAAI,aAAa;AACjB,MAAK,MAAM,OAAO,UAAU;EAC1B,IAAIC;AACJ,MAAI,OAAO,IAAI,YAAY,UACzB,cAAc,IAAI;WACT,MAAM,QAAQ,IAAI,QAAQ,EACnC,cAAc,IAAI,QACf,IAAI,CAAC,SAAS;AACb,OAAI,OAAO,SAAS,SAAU,QAAO;AACrC,OAAI,KAAK,SAAS,UAAU,UAAU,KAAM,QAAO,KAAK;AACxD,UAAO;EACR,EAAC,CACD,KAAK,GAAG;OAEX,cAAc;AAGhB,MACEC,oCAAU,WAAW,IAAI,IACzB,MAAM,QAAQ,IAAI,WAAW,IAC7B,IAAI,WAAW,SAAS,GAExB,eAAe,KAAK,UAAU,IAAI,WAAW;AAG/C,MAAIC,sCAAY,WAAW,IAAI,EAC7B,eAAe,IAAI,gBAAgB;EAGrC,cAAc,YAAY;CAC3B;AAED,QAAO,KAAK,KAAK,aAAa,EAAE;AACjC;AAED,SAAgB,kBACdC,MAM4B;AAC5B,KAAI,CAAC,QAAQ,OAAO,SAAS,WAC3B,QAAO;AAET,QAAO,KAAK;AACb;AAED,SAAgB,gBACdC,KACA;AACA,KAAI,OAAO,QAAQ,WACjB,QAAO;AAET,QAAO,IAAI;AACZ;;;;AAKD,SAAgB,MAAMC,IAA2B;AAC/C,QAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAG;AACxD;;;;;;;;;;AAWD,SAAgB,oBACdC,QAMAC,aACQ;CACR,MAAM,EAAE,eAAe,gBAAgB,YAAY,QAAQ,GAAG;CAE9D,IAAIC;AACJ,KAAI,kBAAkB,GACpB,QAAQ;MAER,QAAQ,iBAAiB,iBAAiB;CAI5C,QAAQ,KAAK,IAAI,OAAO,WAAW;AAEnC,KAAI,UAAU,QAAQ,GAAG;EACvB,MAAM,eAAe,QAAQ;EAC7B,QAAQ,SAAS,KAAK,QAAQ,GAAG,IAAI,KAAK;EAE1C,QAAQ,KAAK,IAAI,GAAG,MAAM;CAC3B;AAED,QAAO;AACR"}
1
+ {"version":3,"file":"utils.cjs","names":["messages: BaseMessage[]","tools?: Array<Record<string, any>> | null","textContent: string","AIMessage","ToolMessage","hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined","arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook","ms: number","config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n }","retryNumber: number","delay: number"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport { isLangChainTool } from \"@langchain/core/tools\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport function countTokensApproximately(\n messages: BaseMessage[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: Array<Record<string, any>> | null\n): number {\n const charsPerToken = 4;\n let totalChars = 0;\n\n // Count tokens for tools if provided\n if (tools && tools.length > 0) {\n let toolsChars = 0;\n for (const tool of tools) {\n const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;\n toolsChars += JSON.stringify(toolDict).length;\n }\n totalChars += toolsChars;\n }\n\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / charsPerToken);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return delay;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACdA,UAEAC,OACQ;CACR,MAAM,gBAAgB;CACtB,IAAI,aAAa;AAGjB,KAAI,SAAS,MAAM,SAAS,GAAG;EAC7B,IAAI,aAAa;AACjB,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,uDAA2B,KAAK,oEAAuB,KAAK,GAAG;GACrE,cAAc,KAAK,UAAU,SAAS,CAAC;EACxC;EACD,cAAc;CACf;AAED,MAAK,MAAM,OAAO,UAAU;EAC1B,IAAIC;AACJ,MAAI,OAAO,IAAI,YAAY,UACzB,cAAc,IAAI;WACT,MAAM,QAAQ,IAAI,QAAQ,EACnC,cAAc,IAAI,QACf,IAAI,CAAC,SAAS;AACb,OAAI,OAAO,SAAS,SAAU,QAAO;AACrC,OAAI,KAAK,SAAS,UAAU,UAAU,KAAM,QAAO,KAAK;AACxD,UAAO;EACR,EAAC,CACD,KAAK,GAAG;OAEX,cAAc;AAGhB,MACEC,oCAAU,WAAW,IAAI,IACzB,MAAM,QAAQ,IAAI,WAAW,IAC7B,IAAI,WAAW,SAAS,GAExB,eAAe,KAAK,UAAU,IAAI,WAAW;AAG/C,MAAIC,sCAAY,WAAW,IAAI,EAC7B,eAAe,IAAI,gBAAgB;EAGrC,cAAc,YAAY;CAC3B;AAED,QAAO,KAAK,KAAK,aAAa,cAAc;AAC7C;AAED,SAAgB,kBACdC,MAM4B;AAC5B,KAAI,CAAC,QAAQ,OAAO,SAAS,WAC3B,QAAO;AAET,QAAO,KAAK;AACb;AAED,SAAgB,gBACdC,KACA;AACA,KAAI,OAAO,QAAQ,WACjB,QAAO;AAET,QAAO,IAAI;AACZ;;;;AAKD,SAAgB,MAAMC,IAA2B;AAC/C,QAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAG;AACxD;;;;;;;;;;AAWD,SAAgB,oBACdC,QAMAC,aACQ;CACR,MAAM,EAAE,eAAe,gBAAgB,YAAY,QAAQ,GAAG;CAE9D,IAAIC;AACJ,KAAI,kBAAkB,GACpB,QAAQ;MAER,QAAQ,iBAAiB,iBAAiB;CAI5C,QAAQ,KAAK,IAAI,OAAO,WAAW;AAEnC,KAAI,UAAU,QAAQ,GAAG;EACvB,MAAM,eAAe,QAAQ;EAC7B,QAAQ,SAAS,KAAK,QAAQ,GAAG,IAAI,KAAK;EAE1C,QAAQ,KAAK,IAAI,GAAG,MAAM;CAC3B;AAED,QAAO;AACR"}
@@ -3,11 +3,17 @@ import { BaseMessage } from "@langchain/core/messages";
3
3
  //#region src/agents/middleware/utils.d.ts
4
4
 
5
5
  /**
6
- * Default token counter that approximates based on character count
6
+ * Default token counter that approximates based on character count.
7
+ *
8
+ * If tools are provided, the token count also includes stringified tool schemas.
9
+ *
7
10
  * @param messages Messages to count tokens for
11
+ * @param tools Optional list of tools to include in the token count. Each tool
12
+ * can be either a LangChain tool instance or a dict representing a tool schema.
13
+ * LangChain tool instances are converted to OpenAI tool format before counting.
8
14
  * @returns Approximate token count
9
15
  */
10
- declare function countTokensApproximately(messages: BaseMessage[]): number;
16
+ declare function countTokensApproximately(messages: BaseMessage[], tools?: Array<Record<string, any>> | null): number;
11
17
  //#endregion
12
18
  export { countTokensApproximately };
13
19
  //# sourceMappingURL=utils.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","names":["__types_js0","BaseMessage","AfterModelHook","AfterAgentHook","BeforeAgentHook","BeforeModelHook","JumpToTarget","countTokensApproximately","getHookConstraint","getHookFunction","___runtime_js0","AgentBuiltInState","Runtime","Partial","MiddlewareResult","Promise","sleep","calculateRetryDelay"],"sources":["../../../src/agents/middleware/utils.d.ts"],"sourcesContent":["import { type BaseMessage } from \"@langchain/core/messages\";\nimport { AfterModelHook, AfterAgentHook, BeforeAgentHook, BeforeModelHook } from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n/**\n * Default token counter that approximates based on character count\n * @param messages Messages to count tokens for\n * @returns Approximate token count\n */\nexport declare function countTokensApproximately(messages: BaseMessage[]): number;\nexport declare function getHookConstraint(hook: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook | undefined): JumpToTarget[] | undefined;\nexport declare function getHookFunction(arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook): ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>);\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport declare function sleep(ms: number): Promise<void>;\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport declare function calculateRetryDelay(config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}, retryNumber: number): number;\n//# sourceMappingURL=utils.d.ts.map"],"mappings":";;;;AAQA;;;;;iBAAwBO,wBAAAA,WAAmCN"}
1
+ {"version":3,"file":"utils.d.cts","names":["__types_js0","BaseMessage","AfterModelHook","AfterAgentHook","BeforeAgentHook","BeforeModelHook","JumpToTarget","countTokensApproximately","Record","Array","getHookConstraint","getHookFunction","___runtime_js0","AgentBuiltInState","Runtime","Partial","MiddlewareResult","Promise","sleep","calculateRetryDelay"],"sources":["../../../src/agents/middleware/utils.d.ts"],"sourcesContent":["import { type BaseMessage } from \"@langchain/core/messages\";\nimport { AfterModelHook, AfterAgentHook, BeforeAgentHook, BeforeModelHook } from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport declare function countTokensApproximately(messages: BaseMessage[], tools?: Array<Record<string, any>> | null): number;\nexport declare function getHookConstraint(hook: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook | undefined): JumpToTarget[] | undefined;\nexport declare function getHookFunction(arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook): ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>);\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport declare function sleep(ms: number): Promise<void>;\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport declare function calculateRetryDelay(config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}, retryNumber: number): number;\n//# sourceMappingURL=utils.d.ts.map"],"mappings":";;;;AAcA;;;;AAAuF;;;;;;;iBAA/DO,wBAAAA,WAAmCN,uBAAuBQ,MAAMD"}
@@ -5,11 +5,17 @@ import { BaseMessage } from "@langchain/core/messages";
5
5
  //#region src/agents/middleware/utils.d.ts
6
6
 
7
7
  /**
8
- * Default token counter that approximates based on character count
8
+ * Default token counter that approximates based on character count.
9
+ *
10
+ * If tools are provided, the token count also includes stringified tool schemas.
11
+ *
9
12
  * @param messages Messages to count tokens for
13
+ * @param tools Optional list of tools to include in the token count. Each tool
14
+ * can be either a LangChain tool instance or a dict representing a tool schema.
15
+ * LangChain tool instances are converted to OpenAI tool format before counting.
10
16
  * @returns Approximate token count
11
17
  */
12
- declare function countTokensApproximately(messages: BaseMessage[]): number;
18
+ declare function countTokensApproximately(messages: BaseMessage[], tools?: Array<Record<string, any>> | null): number;
13
19
  //#endregion
14
20
  export { countTokensApproximately };
15
21
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","names":["__types_js0","BaseMessage","AfterModelHook","AfterAgentHook","BeforeAgentHook","BeforeModelHook","JumpToTarget","countTokensApproximately","getHookConstraint","getHookFunction","___runtime_js0","AgentBuiltInState","Runtime","Partial","MiddlewareResult","Promise","sleep","calculateRetryDelay"],"sources":["../../../src/agents/middleware/utils.d.ts"],"sourcesContent":["import { type BaseMessage } from \"@langchain/core/messages\";\nimport { AfterModelHook, AfterAgentHook, BeforeAgentHook, BeforeModelHook } from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n/**\n * Default token counter that approximates based on character count\n * @param messages Messages to count tokens for\n * @returns Approximate token count\n */\nexport declare function countTokensApproximately(messages: BaseMessage[]): number;\nexport declare function getHookConstraint(hook: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook | undefined): JumpToTarget[] | undefined;\nexport declare function getHookFunction(arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook): ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>);\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport declare function sleep(ms: number): Promise<void>;\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport declare function calculateRetryDelay(config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}, retryNumber: number): number;\n//# sourceMappingURL=utils.d.ts.map"],"mappings":";;;;;;;;AAQA;;;iBAAwBO,wBAAAA,WAAmCN"}
1
+ {"version":3,"file":"utils.d.ts","names":["__types_js0","BaseMessage","AfterModelHook","AfterAgentHook","BeforeAgentHook","BeforeModelHook","JumpToTarget","countTokensApproximately","Record","Array","getHookConstraint","getHookFunction","___runtime_js0","AgentBuiltInState","Runtime","Partial","MiddlewareResult","Promise","sleep","calculateRetryDelay"],"sources":["../../../src/agents/middleware/utils.d.ts"],"sourcesContent":["import { type BaseMessage } from \"@langchain/core/messages\";\nimport { AfterModelHook, AfterAgentHook, BeforeAgentHook, BeforeModelHook } from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport declare function countTokensApproximately(messages: BaseMessage[], tools?: Array<Record<string, any>> | null): number;\nexport declare function getHookConstraint(hook: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook | undefined): JumpToTarget[] | undefined;\nexport declare function getHookFunction(arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook): ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>) | ((state: import(\"../runtime.js\").AgentBuiltInState, runtime: import(\"../runtime.js\").Runtime<unknown>) => Promise<import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>> | import(\"./types.js\").MiddlewareResult<Partial<import(\"../runtime.js\").AgentBuiltInState>>);\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport declare function sleep(ms: number): Promise<void>;\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport declare function calculateRetryDelay(config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}, retryNumber: number): number;\n//# sourceMappingURL=utils.d.ts.map"],"mappings":";;;;;;;;AAcA;;;;AAAuF;;;;;iBAA/DO,wBAAAA,WAAmCN,uBAAuBQ,MAAMD"}
@@ -1,13 +1,30 @@
1
1
  import { AIMessage, ToolMessage } from "@langchain/core/messages";
2
+ import { isLangChainTool } from "@langchain/core/tools";
3
+ import { convertToOpenAITool } from "@langchain/core/utils/function_calling";
2
4
 
3
5
  //#region src/agents/middleware/utils.ts
4
6
  /**
5
- * Default token counter that approximates based on character count
7
+ * Default token counter that approximates based on character count.
8
+ *
9
+ * If tools are provided, the token count also includes stringified tool schemas.
10
+ *
6
11
  * @param messages Messages to count tokens for
12
+ * @param tools Optional list of tools to include in the token count. Each tool
13
+ * can be either a LangChain tool instance or a dict representing a tool schema.
14
+ * LangChain tool instances are converted to OpenAI tool format before counting.
7
15
  * @returns Approximate token count
8
16
  */
9
- function countTokensApproximately(messages) {
17
+ function countTokensApproximately(messages, tools) {
18
+ const charsPerToken = 4;
10
19
  let totalChars = 0;
20
+ if (tools && tools.length > 0) {
21
+ let toolsChars = 0;
22
+ for (const tool$1 of tools) {
23
+ const toolDict = isLangChainTool(tool$1) ? convertToOpenAITool(tool$1) : tool$1;
24
+ toolsChars += JSON.stringify(toolDict).length;
25
+ }
26
+ totalChars += toolsChars;
27
+ }
11
28
  for (const msg of messages) {
12
29
  let textContent;
13
30
  if (typeof msg.content === "string") textContent = msg.content;
@@ -21,7 +38,7 @@ function countTokensApproximately(messages) {
21
38
  if (ToolMessage.isInstance(msg)) textContent += msg.tool_call_id ?? "";
22
39
  totalChars += textContent.length;
23
40
  }
24
- return Math.ceil(totalChars / 4);
41
+ return Math.ceil(totalChars / charsPerToken);
25
42
  }
26
43
  function getHookConstraint(hook) {
27
44
  if (!hook || typeof hook === "function") return void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["messages: BaseMessage[]","textContent: string","hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined","arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook","ms: number","config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n }","retryNumber: number","delay: number"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count\n * @param messages Messages to count tokens for\n * @returns Approximate token count\n */\nexport function countTokensApproximately(messages: BaseMessage[]): number {\n let totalChars = 0;\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / 4);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return delay;\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,yBAAyBA,U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AACR"}
1
+ {"version":3,"file":"utils.js","names":["messages: BaseMessage[]","tools?: Array<Record<string, any>> | null","tool","textContent: string","hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined","arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook","ms: number","config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n }","retryNumber: number","delay: number"],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport { isLangChainTool } from \"@langchain/core/tools\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport function countTokensApproximately(\n messages: BaseMessage[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: Array<Record<string, any>> | null\n): number {\n const charsPerToken = 4;\n let totalChars = 0;\n\n // Count tokens for tools if provided\n if (tools && tools.length > 0) {\n let toolsChars = 0;\n for (const tool of tools) {\n const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;\n toolsChars += JSON.stringify(toolDict).length;\n }\n totalChars += toolsChars;\n }\n\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / charsPerToken);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return delay;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACdA,UAEAC,OACQ;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