langchain 1.2.26 → 1.2.27

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 (64) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts +2 -2
  4. package/dist/agents/ReactAgent.d.ts +2 -2
  5. package/dist/agents/ReactAgent.js.map +1 -1
  6. package/dist/agents/index.d.cts +1 -1
  7. package/dist/agents/index.d.ts +1 -1
  8. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  9. package/dist/agents/middleware/llmToolSelector.d.cts +37 -2
  10. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  11. package/dist/agents/middleware/llmToolSelector.d.ts +37 -2
  12. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  13. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  14. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  15. package/dist/agents/middleware/modelFallback.d.cts +2 -1
  16. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  17. package/dist/agents/middleware/modelFallback.d.ts +2 -1
  18. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  19. package/dist/agents/middleware/modelFallback.js.map +1 -1
  20. package/dist/agents/middleware/modelRetry.cjs.map +1 -1
  21. package/dist/agents/middleware/modelRetry.d.cts +43 -1
  22. package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
  23. package/dist/agents/middleware/modelRetry.d.ts +43 -1
  24. package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
  25. package/dist/agents/middleware/modelRetry.js.map +1 -1
  26. package/dist/agents/middleware/pii.cjs +7 -4
  27. package/dist/agents/middleware/pii.cjs.map +1 -1
  28. package/dist/agents/middleware/pii.d.cts +28 -2
  29. package/dist/agents/middleware/pii.d.cts.map +1 -1
  30. package/dist/agents/middleware/pii.d.ts +28 -2
  31. package/dist/agents/middleware/pii.d.ts.map +1 -1
  32. package/dist/agents/middleware/pii.js +7 -4
  33. package/dist/agents/middleware/pii.js.map +1 -1
  34. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  35. package/dist/agents/middleware/piiRedaction.d.cts +15 -2
  36. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  37. package/dist/agents/middleware/piiRedaction.d.ts +15 -2
  38. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  39. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  40. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  41. package/dist/agents/middleware/toolEmulator.d.cts +2 -2
  42. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
  43. package/dist/agents/middleware/toolEmulator.d.ts +2 -2
  44. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
  45. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  46. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  47. package/dist/agents/middleware/toolRetry.d.cts +55 -1
  48. package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
  49. package/dist/agents/middleware/toolRetry.d.ts +55 -1
  50. package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
  51. package/dist/agents/middleware/toolRetry.js.map +1 -1
  52. package/dist/agents/middleware/types.cjs.map +1 -1
  53. package/dist/agents/middleware/types.d.cts +22 -18
  54. package/dist/agents/middleware/types.d.cts.map +1 -1
  55. package/dist/agents/middleware/types.d.ts +22 -18
  56. package/dist/agents/middleware/types.d.ts.map +1 -1
  57. package/dist/agents/middleware/types.js.map +1 -1
  58. package/dist/agents/types.d.cts +3 -3
  59. package/dist/agents/types.d.cts.map +1 -1
  60. package/dist/agents/types.d.ts +3 -3
  61. package/dist/agents/types.d.ts.map +1 -1
  62. package/dist/index.d.cts +2 -2
  63. package/dist/index.d.ts +2 -2
  64. package/package.json +5 -5
@@ -152,7 +152,61 @@ type ToolRetryMiddlewareConfig = z.input<typeof ToolRetryMiddlewareOptionsSchema
152
152
  * @param config - Configuration options for the retry middleware
153
153
  * @returns A middleware instance that handles tool failures with retries
154
154
  */
155
- declare function toolRetryMiddleware(config?: ToolRetryMiddlewareConfig): AgentMiddleware;
155
+ declare function toolRetryMiddleware(config?: ToolRetryMiddlewareConfig): AgentMiddleware<undefined, z.ZodObject<{
156
+ /**
157
+ * Optional list of tools or tool names to apply retry logic to.
158
+ * Can be a list of `BaseTool` instances or tool name strings.
159
+ * If `undefined`, applies to all tools. Default is `undefined`.
160
+ */
161
+ tools: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodType<ClientTool, z.ZodTypeDef, ClientTool>, z.ZodType<ServerTool, z.ZodTypeDef, ServerTool>, z.ZodString]>, "many">>;
162
+ /**
163
+ * Behavior when all retries are exhausted. Options:
164
+ * - `"continue"` (default): Return an AIMessage with error details, allowing
165
+ * the agent to potentially handle the failure gracefully.
166
+ * - `"error"`: Re-raise the exception, stopping agent execution.
167
+ * - Custom function: Function that takes the exception and returns a string
168
+ * for the AIMessage content, allowing custom error formatting.
169
+ *
170
+ * Deprecated values:
171
+ * - `"raise"`: use `"error"` instead.
172
+ * - `"return_message"`: use `"continue"` instead.
173
+ */
174
+ onFailure: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"error">, z.ZodLiteral<"continue">, z.ZodLiteral<"raise">, z.ZodLiteral<"return_message">, z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodString>]>>;
175
+ } & {
176
+ maxRetries: z.ZodDefault<z.ZodNumber>;
177
+ retryOn: z.ZodDefault<z.ZodUnion<[z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodBoolean>, z.ZodArray<z.ZodType<new (...args: any[]) => Error, z.ZodTypeDef, new (...args: any[]) => Error>, "many">]>>;
178
+ backoffFactor: z.ZodDefault<z.ZodNumber>;
179
+ initialDelayMs: z.ZodDefault<z.ZodNumber>;
180
+ maxDelayMs: z.ZodDefault<z.ZodNumber>;
181
+ jitter: z.ZodDefault<z.ZodBoolean>;
182
+ }, "strip", z.ZodTypeAny, {
183
+ maxRetries: number;
184
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
185
+ backoffFactor: number;
186
+ initialDelayMs: number;
187
+ maxDelayMs: number;
188
+ jitter: boolean;
189
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
190
+ onFailure: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string);
191
+ }, {
192
+ maxRetries?: number | undefined;
193
+ retryOn?: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean) | undefined;
194
+ backoffFactor?: number | undefined;
195
+ initialDelayMs?: number | undefined;
196
+ maxDelayMs?: number | undefined;
197
+ jitter?: boolean | undefined;
198
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
199
+ onFailure?: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string) | undefined;
200
+ }>, {
201
+ maxRetries: number;
202
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
203
+ backoffFactor: number;
204
+ initialDelayMs: number;
205
+ maxDelayMs: number;
206
+ jitter: boolean;
207
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
208
+ onFailure: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string);
209
+ }, readonly (ServerTool | ClientTool)[]>;
156
210
  //#endregion
157
211
  export { ToolRetryMiddlewareConfig, toolRetryMiddleware };
158
212
  //# sourceMappingURL=toolRetry.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolRetry.d.cts","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"mappings":";;;;;;;;cAgBa,gCAAA,EAAgC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2CjC,yBAAA,GAA4B,CAAA,CAAE,KAAA,QACjC,gCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsGO,mBAAA,CACd,MAAA,GAAQ,yBAAA,GACP,eAAA"}
1
+ {"version":3,"file":"toolRetry.d.cts","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"mappings":";;;;;AAeA;;;AAAA,cAAa,gCAAA,EAAgC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2CjC,yBAAA,GAA4B,CAAA,CAAE,KAAA,QACjC,gCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsGO,mBAAA,CAAoB,MAAA,GAAQ,yBAAA,8BAA8B,CAAA,CAAA,SAAA"}
@@ -152,7 +152,61 @@ type ToolRetryMiddlewareConfig = z.input<typeof ToolRetryMiddlewareOptionsSchema
152
152
  * @param config - Configuration options for the retry middleware
153
153
  * @returns A middleware instance that handles tool failures with retries
154
154
  */
155
- declare function toolRetryMiddleware(config?: ToolRetryMiddlewareConfig): AgentMiddleware;
155
+ declare function toolRetryMiddleware(config?: ToolRetryMiddlewareConfig): AgentMiddleware<undefined, z.ZodObject<{
156
+ /**
157
+ * Optional list of tools or tool names to apply retry logic to.
158
+ * Can be a list of `BaseTool` instances or tool name strings.
159
+ * If `undefined`, applies to all tools. Default is `undefined`.
160
+ */
161
+ tools: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodType<ClientTool, z.ZodTypeDef, ClientTool>, z.ZodType<ServerTool, z.ZodTypeDef, ServerTool>, z.ZodString]>, "many">>;
162
+ /**
163
+ * Behavior when all retries are exhausted. Options:
164
+ * - `"continue"` (default): Return an AIMessage with error details, allowing
165
+ * the agent to potentially handle the failure gracefully.
166
+ * - `"error"`: Re-raise the exception, stopping agent execution.
167
+ * - Custom function: Function that takes the exception and returns a string
168
+ * for the AIMessage content, allowing custom error formatting.
169
+ *
170
+ * Deprecated values:
171
+ * - `"raise"`: use `"error"` instead.
172
+ * - `"return_message"`: use `"continue"` instead.
173
+ */
174
+ onFailure: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"error">, z.ZodLiteral<"continue">, z.ZodLiteral<"raise">, z.ZodLiteral<"return_message">, z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodString>]>>;
175
+ } & {
176
+ maxRetries: z.ZodDefault<z.ZodNumber>;
177
+ retryOn: z.ZodDefault<z.ZodUnion<[z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodBoolean>, z.ZodArray<z.ZodType<new (...args: any[]) => Error, z.ZodTypeDef, new (...args: any[]) => Error>, "many">]>>;
178
+ backoffFactor: z.ZodDefault<z.ZodNumber>;
179
+ initialDelayMs: z.ZodDefault<z.ZodNumber>;
180
+ maxDelayMs: z.ZodDefault<z.ZodNumber>;
181
+ jitter: z.ZodDefault<z.ZodBoolean>;
182
+ }, "strip", z.ZodTypeAny, {
183
+ maxRetries: number;
184
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
185
+ backoffFactor: number;
186
+ initialDelayMs: number;
187
+ maxDelayMs: number;
188
+ jitter: boolean;
189
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
190
+ onFailure: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string);
191
+ }, {
192
+ maxRetries?: number | undefined;
193
+ retryOn?: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean) | undefined;
194
+ backoffFactor?: number | undefined;
195
+ initialDelayMs?: number | undefined;
196
+ maxDelayMs?: number | undefined;
197
+ jitter?: boolean | undefined;
198
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
199
+ onFailure?: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string) | undefined;
200
+ }>, {
201
+ maxRetries: number;
202
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
203
+ backoffFactor: number;
204
+ initialDelayMs: number;
205
+ maxDelayMs: number;
206
+ jitter: boolean;
207
+ tools?: (string | ServerTool | ClientTool)[] | undefined;
208
+ onFailure: "continue" | "error" | "raise" | "return_message" | ((args_0: Error, ...args: unknown[]) => string);
209
+ }, readonly (ServerTool | ClientTool)[]>;
156
210
  //#endregion
157
211
  export { ToolRetryMiddlewareConfig, toolRetryMiddleware };
158
212
  //# sourceMappingURL=toolRetry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolRetry.d.ts","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"mappings":";;;;;;;;cAgBa,gCAAA,EAAgC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2CjC,yBAAA,GAA4B,CAAA,CAAE,KAAA,QACjC,gCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsGO,mBAAA,CACd,MAAA,GAAQ,yBAAA,GACP,eAAA"}
1
+ {"version":3,"file":"toolRetry.d.ts","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"mappings":";;;;;AAeA;;;AAAA,cAAa,gCAAA,EAAgC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2CjC,yBAAA,GAA4B,CAAA,CAAE,KAAA,QACjC,gCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsGO,mBAAA,CAAoB,MAAA,GAAQ,yBAAA,8BAA8B,CAAA,CAAA,SAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"toolRetry.js","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"sourcesContent":["/**\n * Tool retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Tool Retry Middleware.\n */\nexport const ToolRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Optional list of tools or tool names to apply retry logic to.\n * Can be a list of `BaseTool` instances or tool name strings.\n * If `undefined`, applies to all tools. Default is `undefined`.\n */\n tools: z\n .array(\n z.union([z.custom<ClientTool>(), z.custom<ServerTool>(), z.string()])\n )\n .optional(),\n\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n *\n * Deprecated values:\n * - `\"raise\"`: use `\"error\"` instead.\n * - `\"return_message\"`: use `\"continue\"` instead.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n /**\n * @deprecated Use `\"error\"` instead.\n */\n z.literal(\"raise\"),\n /**\n * @deprecated Use `\"continue\"` instead.\n */\n z.literal(\"return_message\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ToolRetryMiddlewareConfig = z.input<\n typeof ToolRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed tool calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, toolRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [toolRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { toolRetryMiddleware } from \"langchain\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on 5xx errors\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return 500 <= statusCode && statusCode < 600;\n * }\n * return false;\n * }\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Apply to specific tools with custom error handling\n * ```ts\n * const formatError = (error: Error) =>\n * \"Database temporarily unavailable. Please try again later.\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [\"search_database\"],\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Apply to specific tools using BaseTool instances\n * ```ts\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const searchDatabase = tool(\n * async ({ query }) => {\n * // Search implementation\n * return results;\n * },\n * {\n * name: \"search_database\",\n * description: \"Search the database\",\n * schema: z.object({ query: z.string() }),\n * }\n * );\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [searchDatabase], // Pass BaseTool instance\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"raise\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles tool failures with retries\n */\nexport function toolRetryMiddleware(\n config: ToolRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ToolRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n tools,\n retryOn,\n onFailure: onFailureConfig,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n let onFailure = onFailureConfig;\n if (onFailureConfig === \"raise\") {\n console.warn(\n \"⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead.\"\n );\n onFailure = \"error\";\n } else if (onFailureConfig === \"return_message\") {\n console.warn(\n \"⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead.\"\n );\n onFailure = \"continue\";\n }\n\n // Extract tool names from BaseTool instances or strings\n const toolFilter: string[] = [];\n for (const tool of tools ?? []) {\n if (typeof tool === \"string\") {\n toolFilter.push(tool);\n } else if (\"name\" in tool && typeof tool.name === \"string\") {\n toolFilter.push(tool.name);\n } else {\n throw new TypeError(\n \"Expected a tool name string or tool instance to be passed to toolRetryMiddleware\"\n );\n }\n }\n\n /**\n * Check if retry logic should apply to this tool.\n */\n const shouldRetryTool = (toolName: string): boolean => {\n if (toolFilter.length === 0) {\n return true;\n }\n return toolFilter.includes(toolName);\n };\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some((ErrorConstructor) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return error instanceof ErrorConstructor;\n });\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (\n toolName: string,\n error: Error,\n attemptsMade: number\n ): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Tool '${toolName}' failed after ${attemptsMade} ${attemptWord} with ${errorType}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (\n toolName: string,\n toolCallId: string,\n error: Error,\n attemptsMade: number\n ): ToolMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(toolName, error, attemptsMade);\n }\n\n return new ToolMessage({\n content,\n tool_call_id: toolCallId,\n name: toolName,\n status: \"error\",\n });\n };\n\n return createMiddleware({\n name: \"toolRetryMiddleware\",\n contextSchema: ToolRetryMiddlewareOptionsSchema,\n wrapToolCall: async (request, handler) => {\n const toolName = (request.tool?.name ?? request.toolCall.name) as string;\n\n // Check if retry should apply to this tool\n if (!shouldRetryTool(toolName)) {\n return handler(request);\n }\n\n const toolCallId = request.toolCall.id ?? \"\";\n\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure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;AACvD,SAAI,QAAQ,EACV,OAAM,MAAM,MAAM;UAKpB,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;;AAMnE,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
1
+ {"version":3,"file":"toolRetry.js","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"sourcesContent":["/**\n * Tool retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Tool Retry Middleware.\n */\nexport const ToolRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Optional list of tools or tool names to apply retry logic to.\n * Can be a list of `BaseTool` instances or tool name strings.\n * If `undefined`, applies to all tools. Default is `undefined`.\n */\n tools: z\n .array(\n z.union([z.custom<ClientTool>(), z.custom<ServerTool>(), z.string()])\n )\n .optional(),\n\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n *\n * Deprecated values:\n * - `\"raise\"`: use `\"error\"` instead.\n * - `\"return_message\"`: use `\"continue\"` instead.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n /**\n * @deprecated Use `\"error\"` instead.\n */\n z.literal(\"raise\"),\n /**\n * @deprecated Use `\"continue\"` instead.\n */\n z.literal(\"return_message\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ToolRetryMiddlewareConfig = z.input<\n typeof ToolRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed tool calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, toolRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [toolRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { toolRetryMiddleware } from \"langchain\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on 5xx errors\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return 500 <= statusCode && statusCode < 600;\n * }\n * return false;\n * }\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Apply to specific tools with custom error handling\n * ```ts\n * const formatError = (error: Error) =>\n * \"Database temporarily unavailable. Please try again later.\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [\"search_database\"],\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Apply to specific tools using BaseTool instances\n * ```ts\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const searchDatabase = tool(\n * async ({ query }) => {\n * // Search implementation\n * return results;\n * },\n * {\n * name: \"search_database\",\n * description: \"Search the database\",\n * schema: z.object({ query: z.string() }),\n * }\n * );\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [searchDatabase], // Pass BaseTool instance\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"raise\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles tool failures with retries\n */\nexport function toolRetryMiddleware(config: ToolRetryMiddlewareConfig = {}) {\n const { success, error, data } =\n ToolRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n tools,\n retryOn,\n onFailure: onFailureConfig,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n let onFailure = onFailureConfig;\n if (onFailureConfig === \"raise\") {\n console.warn(\n \"⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead.\"\n );\n onFailure = \"error\";\n } else if (onFailureConfig === \"return_message\") {\n console.warn(\n \"⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead.\"\n );\n onFailure = \"continue\";\n }\n\n // Extract tool names from BaseTool instances or strings\n const toolFilter: string[] = [];\n for (const tool of tools ?? []) {\n if (typeof tool === \"string\") {\n toolFilter.push(tool);\n } else if (\"name\" in tool && typeof tool.name === \"string\") {\n toolFilter.push(tool.name);\n } else {\n throw new TypeError(\n \"Expected a tool name string or tool instance to be passed to toolRetryMiddleware\"\n );\n }\n }\n\n /**\n * Check if retry logic should apply to this tool.\n */\n const shouldRetryTool = (toolName: string): boolean => {\n if (toolFilter.length === 0) {\n return true;\n }\n return toolFilter.includes(toolName);\n };\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some((ErrorConstructor) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return error instanceof ErrorConstructor;\n });\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (\n toolName: string,\n error: Error,\n attemptsMade: number\n ): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Tool '${toolName}' failed after ${attemptsMade} ${attemptWord} with ${errorType}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (\n toolName: string,\n toolCallId: string,\n error: Error,\n attemptsMade: number\n ): ToolMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(toolName, error, attemptsMade);\n }\n\n return new ToolMessage({\n content,\n tool_call_id: toolCallId,\n name: toolName,\n status: \"error\",\n });\n };\n\n return createMiddleware({\n name: \"toolRetryMiddleware\",\n contextSchema: ToolRetryMiddlewareOptionsSchema,\n wrapToolCall: async (request, handler) => {\n const toolName = (request.tool?.name ?? request.toolCall.name) as string;\n\n // Check if retry should apply to this tool\n if (!shouldRetryTool(toolName)) {\n return handler(request);\n }\n\n const toolCallId = request.toolCall.id ?? \"\";\n\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected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AQ,EACV,OAAM,MAAM,MAAM;UAKpB,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;;AAMnE,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","names":[],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n 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,MAAa,mBAAkC,OAAO,kBAAkB"}
1
+ {"version":3,"file":"types.cjs","names":[],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaValue,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type InferSchemaValueType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaValue<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type InferSchemaUpdateType<TSchema> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields> & AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodInput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaValueType<TSchema>;\n\nexport type NormalizedSchemaUpdate<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = InferSchemaUpdateType<TSchema>;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<TSchema, TContext>\n | {\n hook: BeforeAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<TSchema, TContext>\n | {\n hook: BeforeModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<TSchema, TContext>\n | {\n hook: AfterModelHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: InferSchemaValueType<TSchema>,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<TSchema, TContext>\n | {\n hook: AfterAgentHandler<TSchema, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaValue<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaValue<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends StateSchema<infer TFields>\n ? FilterPrivateProps<InferStateSchemaUpdate<TFields>>\n : TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaValue<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaValue<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodInput<A>\n : A extends AnyAnnotationRoot\n ? A[\"Update\"]\n : {};\n"],"mappings":";;;;;;;AAsWA,MAAa,mBAAkC,OAAO,kBAAkB"}
@@ -4,7 +4,7 @@ import { ModelRequest } from "../nodes/types.cjs";
4
4
  import { AIMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
5
5
  import { ClientTool, ServerTool } from "@langchain/core/tools";
6
6
  import { InferInteropZodInput, InferInteropZodOutput, InteropZodDefault, InteropZodObject, InteropZodOptional } from "@langchain/core/utils/types";
7
- import { AnnotationRoot, Command, InferStateSchemaUpdate, StateDefinitionInit, StateSchema } from "@langchain/langgraph";
7
+ import { AnnotationRoot, Command, InferStateSchemaUpdate, InferStateSchemaValue, StateDefinitionInit, StateSchema } from "@langchain/langgraph";
8
8
  import { ToolCall as ToolCall$1 } from "@langchain/core/messages/tool";
9
9
  import { InteropZodToStateDefinition } from "@langchain/langgraph/zod";
10
10
 
@@ -54,7 +54,10 @@ interface MiddlewareTypeConfig<TSchema extends StateDefinitionInit | undefined =
54
54
  * Used when no explicit type parameters are provided.
55
55
  */
56
56
  type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;
57
- 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;
57
+ type InferSchemaValueType<TSchema> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends StateSchema<infer TFields> ? InferStateSchemaValue<TFields> & AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaValue<TSchema> & AgentBuiltInState : AgentBuiltInState;
58
+ type InferSchemaUpdateType<TSchema> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> & AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodInput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaInput<TSchema> & AgentBuiltInState : AgentBuiltInState;
59
+ type NormalizedSchemaInput<TSchema extends StateDefinitionInit | undefined | never = any> = InferSchemaValueType<TSchema>;
60
+ type NormalizedSchemaUpdate<TSchema extends StateDefinitionInit | undefined | never = any> = InferSchemaUpdateType<TSchema>;
58
61
  /**
59
62
  * Result type for middleware functions.
60
63
  */
@@ -147,14 +150,14 @@ type WrapModelCallHook<TSchema extends StateDefinitionInit | undefined = undefin
147
150
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
148
151
  * @returns A middleware result containing partial state updates or undefined to pass through
149
152
  */
150
- type BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
153
+ type BeforeAgentHandler<TSchema, TContext> = (state: InferSchemaValueType<TSchema>, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;
151
154
  /**
152
155
  * Hook type for the beforeAgent lifecycle event.
153
156
  * Can be either a handler function or an object with a handler and optional jump targets.
154
157
  * This hook is called once at the start of the agent invocation.
155
158
  */
156
- type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {
157
- hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
159
+ type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<TSchema, TContext> | {
160
+ hook: BeforeAgentHandler<TSchema, TContext>;
158
161
  canJumpTo?: JumpToTarget[];
159
162
  };
160
163
  /**
@@ -165,14 +168,14 @@ type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined
165
168
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
166
169
  * @returns A middleware result containing partial state updates or undefined to pass through
167
170
  */
168
- type BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
171
+ type BeforeModelHandler<TSchema, TContext> = (state: InferSchemaValueType<TSchema>, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;
169
172
  /**
170
173
  * Hook type for the beforeModel lifecycle event.
171
174
  * Can be either a handler function or an object with a handler and optional jump targets.
172
175
  * This hook is called before each model invocation.
173
176
  */
174
- type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {
175
- hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;
177
+ type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<TSchema, TContext> | {
178
+ hook: BeforeModelHandler<TSchema, TContext>;
176
179
  canJumpTo?: JumpToTarget[];
177
180
  };
178
181
  /**
@@ -184,14 +187,14 @@ type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined
184
187
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
185
188
  * @returns A middleware result containing partial state updates or undefined to pass through
186
189
  */
187
- type AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
190
+ type AfterModelHandler<TSchema, TContext> = (state: InferSchemaValueType<TSchema>, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;
188
191
  /**
189
192
  * Hook type for the afterModel lifecycle event.
190
193
  * Can be either a handler function or an object with a handler and optional jump targets.
191
194
  * This hook is called after each model invocation.
192
195
  */
193
- type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {
194
- hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;
196
+ type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<TSchema, TContext> | {
197
+ hook: AfterModelHandler<TSchema, TContext>;
195
198
  canJumpTo?: JumpToTarget[];
196
199
  };
197
200
  /**
@@ -202,14 +205,14 @@ type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined,
202
205
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
203
206
  * @returns A middleware result containing partial state updates or undefined to pass through
204
207
  */
205
- type AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
208
+ type AfterAgentHandler<TSchema, TContext> = (state: InferSchemaValueType<TSchema>, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<InferSchemaUpdateType<TSchema>>>>;
206
209
  /**
207
210
  * Hook type for the afterAgent lifecycle event.
208
211
  * Can be either a handler function or an object with a handler and optional jump targets.
209
212
  * This hook is called once at the end of the agent invocation.
210
213
  */
211
- type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {
212
- hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
214
+ type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<TSchema, TContext> | {
215
+ hook: AfterAgentHandler<TSchema, TContext>;
213
216
  canJumpTo?: JumpToTarget[];
214
217
  };
215
218
  /**
@@ -441,13 +444,13 @@ type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extend
441
444
  * This filters out private properties (those starting with underscore)
442
445
  * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph
443
446
  */
444
- 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>> : {} : {};
447
+ type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends StateSchema<infer TFields> ? FilterPrivateProps<InferStateSchemaValue<TFields>> : TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaValue<TSchema>> : {} : {};
445
448
  /**
446
449
  * Helper type to infer the input state schema type from a middleware (all properties optional)
447
450
  * This filters out private properties (those starting with underscore)
448
451
  * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph
449
452
  */
450
- 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>> : {} : {};
453
+ type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends StateSchema<infer TFields> ? FilterPrivateProps<InferStateSchemaUpdate<TFields>> : TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};
451
454
  /**
452
455
  * Helper type to infer merged state from an array of middleware (just the middleware states)
453
456
  */
@@ -489,7 +492,8 @@ type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> = T exte
489
492
  */
490
493
  type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>["State"] : {};
491
494
  type ToAnnotationRoot<A extends StateDefinitionInit> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? InteropZodToStateDefinition<A> : never;
492
- type InferSchemaInput<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> : A extends InteropZodObject ? InferInteropZodOutput<A> : A extends AnyAnnotationRoot ? A["State"] : {};
495
+ type InferSchemaValue<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaValue<TFields> : A extends InteropZodObject ? InferInteropZodOutput<A> : A extends AnyAnnotationRoot ? A["State"] : {};
496
+ type InferSchemaInput<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> : A extends InteropZodObject ? InferInteropZodInput<A> : A extends AnyAnnotationRoot ? A["Update"] : {};
493
497
  //#endregion
494
- export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
498
+ export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
495
499
  //# sourceMappingURL=types.d.cts.map
@@ -1 +1 @@
1
- {"version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