{"version":3,"file":"types.cjs","names":[],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport type {\n  InteropZodObject,\n  InteropZodDefault,\n  InteropZodOptional,\n  InferInteropZodInput,\n  InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n  AnnotationRoot,\n  StateSchema,\n  InferStateSchemaValue,\n  InferStateSchemaUpdate,\n  StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n  AIMessage,\n  SystemMessage,\n  ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n *   (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n *   `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n *   typeof myStateSchema,\n *   typeof myContextSchema,\n *   MyContextType,\n *   typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n  TSchema extends StateDefinitionInit | undefined =\n    | StateDefinitionInit\n    | undefined,\n  TContextSchema extends\n    | InteropZodObject\n    | InteropZodDefault<InteropZodObject>\n    | InteropZodOptional<InteropZodObject>\n    | undefined =\n    | InteropZodObject\n    | InteropZodDefault<InteropZodObject>\n    | InteropZodOptional<InteropZodObject>\n    | undefined,\n  TFullContext = any,\n  TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n    | ClientTool\n    | ServerTool\n  )[],\n> {\n  /** The middleware state schema type */\n  Schema: TSchema;\n  /** The middleware context schema type */\n  ContextSchema: TContextSchema;\n  /** The full context type */\n  FullContext: TFullContext;\n  /** The tools array type */\n  Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type InferSchemaValueType<TSchema> = [TSchema] extends [never]\n  ? AgentBuiltInState\n  : TSchema extends StateSchema<infer TFields>\n    ? InferStateSchemaValue<TFields> & AgentBuiltInState\n    : TSchema extends InteropZodObject\n      ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n      : TSchema extends StateDefinitionInit\n        ? InferSchemaValue<TSchema> & AgentBuiltInState\n        : AgentBuiltInState;\n\nexport type InferSchemaUpdateType<TSchema> = [TSchema] extends [never]\n  ? AgentBuiltInState\n  : TSchema extends StateSchema<infer TFields>\n    ? InferStateSchemaUpdate<TFields> & AgentBuiltInState\n    : TSchema extends InteropZodObject\n      ? InferInteropZodInput<TSchema> & AgentBuiltInState\n      : TSchema extends StateDefinitionInit\n        ? InferSchemaInput<TSchema> & AgentBuiltInState\n        : AgentBuiltInState;\n\nexport type NormalizedSchemaInput<\n  TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaValueType<TSchema>;\n\nexport type NormalizedSchemaUpdate<\n  TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaUpdateType<TSchema>;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n  | (TState & {\n      jumpTo?: JumpToTarget;\n    })\n  | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n  TState extends Record<string, unknown> = Record<string, unknown>,\n  TContext = unknown,\n> {\n  /**\n   * The tool call to be executed\n   */\n  toolCall: ToolCall;\n  /**\n   * The BaseTool instance being invoked.\n   * Provides access to tool metadata like name, description, schema, etc.\n   *\n   * This will be `undefined` for dynamically registered tools that aren't\n   * declared upfront when creating the agent. In such cases, middleware\n   * should provide the tool implementation by spreading the request with\n   * the tool property.\n   *\n   * @example Dynamic tool handling\n   * ```ts\n   * wrapToolCall: async (request, handler) => {\n   *   if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n   *     // Provide the tool implementation for dynamically registered tools\n   *     return handler({ ...request, tool: myDynamicTool });\n   *   }\n   *   return handler(request);\n   * }\n   * ```\n   */\n  tool: ClientTool | ServerTool | undefined;\n  /**\n   * The current agent state (includes both middleware state and built-in state).\n   */\n  state: TState & AgentBuiltInState;\n  /**\n   * The runtime context containing metadata, signal, writer, interrupt, etc.\n   */\n  runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n  TSchema extends Record<string, unknown> = AgentBuiltInState,\n  TContext = unknown,\n> = (\n  request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> = (\n  request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n  handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> = (\n  request: Omit<\n    ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n    /**\n     * allow to reset the system prompt or system message\n     */\n    \"systemPrompt\" | \"systemMessage\"\n  > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> = (\n  request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n  handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n  state: InferSchemaValueType<TSchema>,\n  runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> =\n  | BeforeAgentHandler<TSchema, TContext>\n  | {\n      hook: BeforeAgentHandler<TSchema, TContext>;\n      canJumpTo?: JumpToTarget[];\n    };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n  state: InferSchemaValueType<TSchema>,\n  runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> =\n  | BeforeModelHandler<TSchema, TContext>\n  | {\n      hook: BeforeModelHandler<TSchema, TContext>;\n      canJumpTo?: JumpToTarget[];\n    };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n  state: InferSchemaValueType<TSchema>,\n  runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> =\n  | AfterModelHandler<TSchema, TContext>\n  | {\n      hook: AfterModelHandler<TSchema, TContext>;\n      canJumpTo?: JumpToTarget[];\n    };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n  state: InferSchemaValueType<TSchema>,\n  runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n  TSchema extends StateDefinitionInit | undefined = undefined,\n  TContext = unknown,\n> =\n  | AfterAgentHandler<TSchema, TContext>\n  | {\n      hook: AfterAgentHandler<TSchema, TContext>;\n      canJumpTo?: JumpToTarget[];\n    };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: symbol = Symbol.for(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n *   name: \"myMiddleware\",\n *   stateSchema: z.object({ count: z.number() }),\n *   tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n  TSchema extends StateDefinitionInit | undefined = any,\n  TContextSchema extends\n    | InteropZodObject\n    | InteropZodDefault<InteropZodObject>\n    | InteropZodOptional<InteropZodObject>\n    | undefined = any,\n  TFullContext = any,\n  TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n    | ClientTool\n    | ServerTool\n  )[],\n> {\n  /**\n   * Brand property to distinguish middleware instances from plain objects or functions.\n   * This is required and prevents accidental assignment of functions to middleware arrays.\n   */\n  readonly [MIDDLEWARE_BRAND]: true;\n\n  /**\n   * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n   * This is a phantom property used only for type inference.\n   * @internal\n   */\n  readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n    TSchema,\n    TContextSchema,\n    TFullContext,\n    TTools\n  >;\n\n  /**\n   * The name of the middleware.\n   */\n  name: string;\n\n  /**\n   * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n   * - A Zod object (InteropZodObject)\n   * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n   * - An AnnotationRoot\n   * - Undefined\n   */\n  stateSchema?: TSchema;\n\n  /**\n   * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n   * - A Zod object\n   * - A Zod optional object\n   * - A Zod default object\n   * - Undefined\n   */\n  contextSchema?: TContextSchema;\n\n  /**\n   * Additional tools registered by the middleware.\n   */\n  tools?: TTools;\n  /**\n   * Wraps tool execution with custom logic. This allows you to:\n   * - Modify tool call parameters before execution\n   * - Handle errors and retry with different parameters\n   * - Post-process tool results\n   * - Implement caching, logging, authentication, or other cross-cutting concerns\n   * - Return Command objects for advanced control flow\n   *\n   * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n   * along with a handler function to execute the actual tool.\n   *\n   * @param request - The tool call request containing toolCall, state, and runtime.\n   * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n   * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n   *\n   * @example\n   * ```ts\n   * wrapToolCall: async (request, handler) => {\n   *   console.log(`Calling tool: ${request.tool.name}`);\n   *   console.log(`Tool description: ${request.tool.description}`);\n   *\n   *   try {\n   *     // Execute the tool\n   *     const result = await handler(request);\n   *     console.log(`Tool ${request.tool.name} succeeded`);\n   *     return result;\n   *   } catch (error) {\n   *     console.error(`Tool ${request.tool.name} failed:`, error);\n   *     // Could return a custom error message or retry\n   *     throw error;\n   *   }\n   * }\n   * ```\n   *\n   * @example Authentication\n   * ```ts\n   * wrapToolCall: async (request, handler) => {\n   *   // Check if user is authorized for this tool\n   *   if (!request.runtime.context.isAuthorized(request.tool.name)) {\n   *     return new ToolMessage({\n   *       content: \"Unauthorized to call this tool\",\n   *       tool_call_id: request.toolCall.id,\n   *     });\n   *   }\n   *   return handler(request);\n   * }\n   * ```\n   *\n   * @example Caching\n   * ```ts\n   * const cache = new Map();\n   * wrapToolCall: async (request, handler) => {\n   *   const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n   *   if (cache.has(cacheKey)) {\n   *     return cache.get(cacheKey);\n   *   }\n   *   const result = await handler(request);\n   *   cache.set(cacheKey, result);\n   *   return result;\n   * }\n   * ```\n   */\n  wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n  /**\n   * Wraps the model invocation with custom logic. This allows you to:\n   * - Modify the request before calling the model\n   * - Handle errors and retry with different parameters\n   * - Post-process the response\n   * - Implement custom caching, logging, or other cross-cutting concerns\n   *\n   * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n   * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n   * @returns The response from the model (or a modified version).\n   *\n   * @example\n   * ```ts\n   * wrapModelCall: async (request, handler) => {\n   *   // Modify request before calling\n   *   const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n   *\n   *   try {\n   *     // Call the model\n   *     return await handler(modifiedRequest);\n   *   } catch (error) {\n   *     // Handle errors and retry with fallback\n   *     const fallbackRequest = { ...request, model: fallbackModel };\n   *     return await handler(fallbackRequest);\n   *   }\n   * }\n   * ```\n   */\n  wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n  /**\n   * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n   * It allows to modify the state of the agent before any model calls or tool executions.\n   *\n   * @param state - The middleware state\n   * @param runtime - The middleware runtime\n   * @returns The modified middleware state or undefined to pass through\n   */\n  beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n  /**\n   * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n   * It allows to modify the state of the agent.\n   *\n   * @param state - The middleware state\n   * @param runtime - The middleware runtime\n   * @returns The modified middleware state or undefined to pass through\n   */\n  beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n  /**\n   * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n   * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n   *\n   * @param state - The middleware state\n   * @param runtime - The middleware runtime\n   * @returns The modified middleware state or undefined to pass through\n   */\n  afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n  /**\n   * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n   * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n   *\n   * @param state - The middleware state\n   * @param runtime - The middleware runtime\n   * @returns The modified middleware state or undefined to pass through\n   */\n  afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n  [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n  \"~middlewareTypes\"?: infer Types;\n}\n  ? Types extends MiddlewareTypeConfig\n    ? Types\n    : never\n  : T extends MiddlewareTypeConfig\n    ? T\n    : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n  T,\n  K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n  T,\n  \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n  T,\n  \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n  T extends AnyAnnotationRoot\n    ? ToAnnotationRoot<T>[\"State\"]\n    : T extends InteropZodObject\n      ? InferInteropZodInput<T>\n      : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n  T extends AgentMiddleware<infer TSchema, any, any, any>\n    ? TSchema extends StateSchema<infer TFields>\n      ? FilterPrivateProps<InferStateSchemaValue<TFields>>\n      : TSchema extends InteropZodObject\n        ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n        : TSchema extends StateDefinitionInit\n          ? FilterPrivateProps<InferSchemaValue<TSchema>>\n          : {}\n    : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n  T extends AgentMiddleware<infer TSchema, any, any, any>\n    ? TSchema extends StateSchema<infer TFields>\n      ? FilterPrivateProps<InferStateSchemaUpdate<TFields>>\n      : TSchema extends InteropZodObject\n        ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n        : TSchema extends StateDefinitionInit\n          ? FilterPrivateProps<InferSchemaInput<TSchema>>\n          : {}\n    : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n  T extends readonly []\n    ? {}\n    : T extends readonly [infer First, ...infer Rest]\n      ? First extends AgentMiddleware\n        ? Rest extends readonly AgentMiddleware[]\n          ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n          : InferMiddlewareState<First>\n        : {}\n      : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n  T extends readonly []\n    ? {}\n    : T extends readonly [infer First, ...infer Rest]\n      ? First extends AgentMiddleware\n        ? Rest extends readonly AgentMiddleware[]\n          ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n          : InferMiddlewareInputState<First>\n        : {}\n      : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n  InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n  InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n  T extends AgentMiddleware<any, infer TContextSchema, any, any>\n    ? TContextSchema extends InteropZodObject\n      ? InferInteropZodInput<TContextSchema>\n      : {}\n    : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n  T extends AgentMiddleware<any, infer TContextSchema, any, any>\n    ? TContextSchema extends InteropZodOptional<infer Inner>\n      ? InferInteropZodInput<Inner> | undefined\n      : TContextSchema extends InteropZodObject\n        ? InferInteropZodInput<TContextSchema>\n        : {}\n    : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n  T extends readonly []\n    ? {}\n    : T extends readonly [infer First, ...infer Rest]\n      ? First extends AgentMiddleware\n        ? Rest extends readonly AgentMiddleware[]\n          ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n          : InferMiddlewareContext<First>\n        : {}\n      : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n  ? [B] extends [undefined]\n    ? undefined\n    : B | undefined\n  : [B] extends [undefined]\n    ? A | undefined\n    : [A] extends [B]\n      ? A\n      : [B] extends [A]\n        ? B\n        : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n  T extends readonly []\n    ? {}\n    : T extends readonly [infer First, ...infer Rest]\n      ? First extends AgentMiddleware\n        ? Rest extends readonly AgentMiddleware[]\n          ? MergeContextTypes<\n              InferMiddlewareContextInput<First>,\n              InferMiddlewareContextInputs<Rest>\n            >\n          : InferMiddlewareContextInput<First>\n        : {}\n      : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n  ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n  ? InferInteropZodInput<ContextSchema>\n  : ContextSchema extends AnyAnnotationRoot\n    ? ToAnnotationRoot<ContextSchema>[\"State\"]\n    : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n  A extends AnyAnnotationRoot\n    ? A\n    : A extends InteropZodObject\n      ? InteropZodToStateDefinition<A>\n      : never;\n\nexport type InferSchemaValue<A extends StateDefinitionInit | undefined> =\n  A extends StateSchema<infer TFields>\n    ? InferStateSchemaValue<TFields>\n    : A extends InteropZodObject\n      ? InferInteropZodOutput<A>\n      : A extends AnyAnnotationRoot\n        ? A[\"State\"]\n        : {};\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n  A extends StateSchema<infer TFields>\n    ? InferStateSchemaUpdate<TFields>\n    : A extends InteropZodObject\n      ? InferInteropZodInput<A>\n      : A extends AnyAnnotationRoot\n        ? A[\"Update\"]\n        : {};\n"],"mappings":";;;;;;AAsWA,MAAa,mBAA2B,OAAO,IAAI,kBAAkB"}