langchain 1.1.6-dev-1765433794876 → 1.2.0

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 (82) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +2 -1
  3. package/chat_models/universal.cjs +1 -0
  4. package/chat_models/universal.d.cts +1 -0
  5. package/chat_models/universal.d.ts +1 -0
  6. package/chat_models/universal.js +1 -0
  7. package/dist/agents/index.cjs +1 -0
  8. package/dist/agents/index.cjs.map +1 -1
  9. package/dist/agents/index.d.cts +1 -1
  10. package/dist/agents/index.d.cts.map +1 -1
  11. package/dist/agents/index.d.ts +1 -1
  12. package/dist/agents/index.d.ts.map +1 -1
  13. package/dist/agents/index.js +1 -0
  14. package/dist/agents/index.js.map +1 -1
  15. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  16. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  17. package/dist/agents/middleware/summarization.cjs +10 -2
  18. package/dist/agents/middleware/summarization.cjs.map +1 -1
  19. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  20. package/dist/agents/middleware/summarization.js +10 -2
  21. package/dist/agents/middleware/summarization.js.map +1 -1
  22. package/dist/agents/middleware/types.cjs +12 -0
  23. package/dist/agents/middleware/types.cjs.map +1 -0
  24. package/dist/agents/middleware/types.d.cts +12 -1
  25. package/dist/agents/middleware/types.d.cts.map +1 -1
  26. package/dist/agents/middleware/types.d.ts +12 -1
  27. package/dist/agents/middleware/types.d.ts.map +1 -1
  28. package/dist/agents/middleware/types.js +11 -0
  29. package/dist/agents/middleware/types.js.map +1 -0
  30. package/dist/agents/middleware.cjs +2 -0
  31. package/dist/agents/middleware.cjs.map +1 -1
  32. package/dist/agents/middleware.d.cts.map +1 -1
  33. package/dist/agents/middleware.d.ts.map +1 -1
  34. package/dist/agents/middleware.js +3 -0
  35. package/dist/agents/middleware.js.map +1 -1
  36. package/dist/agents/nodes/AgentNode.cjs +3 -2
  37. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  38. package/dist/agents/nodes/AgentNode.js +3 -2
  39. package/dist/agents/nodes/AgentNode.js.map +1 -1
  40. package/dist/agents/responses.cjs +94 -14
  41. package/dist/agents/responses.cjs.map +1 -1
  42. package/dist/agents/responses.d.cts +67 -6
  43. package/dist/agents/responses.d.cts.map +1 -1
  44. package/dist/agents/responses.d.ts +67 -6
  45. package/dist/agents/responses.d.ts.map +1 -1
  46. package/dist/agents/responses.js +94 -14
  47. package/dist/agents/responses.js.map +1 -1
  48. package/dist/agents/tests/utils.cjs.map +1 -1
  49. package/dist/agents/tests/utils.js.map +1 -1
  50. package/dist/index.cjs +3 -0
  51. package/dist/index.d.cts +2 -2
  52. package/dist/index.d.ts +2 -2
  53. package/dist/index.js +3 -1
  54. package/hub/node.cjs +1 -0
  55. package/hub/node.d.cts +1 -0
  56. package/hub/node.d.ts +1 -0
  57. package/hub/node.js +1 -0
  58. package/hub.cjs +1 -0
  59. package/hub.d.cts +1 -0
  60. package/hub.d.ts +1 -0
  61. package/hub.js +1 -0
  62. package/load/serializable.cjs +1 -0
  63. package/load/serializable.d.cts +1 -0
  64. package/load/serializable.d.ts +1 -0
  65. package/load/serializable.js +1 -0
  66. package/load.cjs +1 -0
  67. package/load.d.cts +1 -0
  68. package/load.d.ts +1 -0
  69. package/load.js +1 -0
  70. package/package.json +5 -5
  71. package/storage/encoder_backed.cjs +1 -0
  72. package/storage/encoder_backed.d.cts +1 -0
  73. package/storage/encoder_backed.d.ts +1 -0
  74. package/storage/encoder_backed.js +1 -0
  75. package/storage/file_system.cjs +1 -0
  76. package/storage/file_system.d.cts +1 -0
  77. package/storage/file_system.d.ts +1 -0
  78. package/storage/file_system.js +1 -0
  79. package/storage/in_memory.cjs +1 -0
  80. package/storage/in_memory.d.cts +1 -0
  81. package/storage/in_memory.d.ts +1 -0
  82. package/storage/in_memory.js +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"summarization.js","names":["input: BaseLanguageModel","options: SummarizationMiddlewareConfig","z4","trigger: ContextSize | ContextSize[] | undefined","keep: ContextSize","triggerConditions: ContextSize[]","uuid","messages: BaseMessage[]","systemPrompt: SystemMessage | undefined","conversationMessages: BaseMessage[]","cutoffIndex: number","totalTokens: number","model: BaseLanguageModel","tokenCounter: TokenCounter","targetTokenCount: number","messagesToKeep: number","aiMessage: AIMessage","aiMessageIndex: number","toolCallIds: Set<string>","messagesToSummarize: BaseMessage[]","summaryPrompt: string","trimTokensToSummarize: number | undefined"],"sources":["../../../src/agents/middleware/summarization.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4 } from \"zod/v4\";\nimport { v4 as uuid } from \"uuid\";\nimport {\n BaseMessage,\n AIMessage,\n SystemMessage,\n ToolMessage,\n RemoveMessage,\n trimMessages,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport {\n BaseLanguageModel,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport {\n interopSafeParse,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { countTokensApproximately } from \"./utils.js\";\nimport { hasToolCalls } from \"../utils.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\n\nexport const DEFAULT_SUMMARY_PROMPT = `<role>\nContext Extraction Assistant\n</role>\n\n<primary_objective>\nYour sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.\n</primary_objective>\n\n<objective_information>\nYou're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.\nThis context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.\n</objective_information>\n\n<instructions>\nThe conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.\nYou want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.\n</instructions>\n\nThe user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:\n\nWith all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.\nRespond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.\n\n<messages>\nMessages to summarize:\n{messages}\n</messages>`;\n\nconst DEFAULT_MESSAGES_TO_KEEP = 20;\nconst DEFAULT_TRIM_TOKEN_LIMIT = 4000;\nconst DEFAULT_FALLBACK_MESSAGE_COUNT = 15;\nconst SEARCH_RANGE_FOR_TOOL_PAIRS = 5;\n\nconst tokenCounterSchema = z\n .function()\n .args(z.array(z.custom<BaseMessage>()))\n .returns(z.union([z.number(), z.promise(z.number())]));\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\nexport const contextSizeSchema = z\n .object({\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z\n .number()\n .gt(0, \"Fraction must be greater than 0\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.number().positive(\"Tokens must be greater than 0\").optional(),\n /**\n * Number of messages to use as the trigger\n */\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .positive(\"Messages must be greater than 0\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count >= 1;\n },\n {\n message: \"At least one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\n\nexport const keepSchema = z\n .object({\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z\n .number()\n .min(0, \"Messages must be non-negative\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to keep\n */\n tokens: z\n .number()\n .min(0, \"Tokens must be greater than or equal to 0\")\n .optional(),\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .min(0, \"Messages must be non-negative\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count === 1;\n },\n {\n message: \"Exactly one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type KeepSize = z.infer<typeof keepSchema>;\n\nconst contextSchema = z.object({\n /**\n * Model to use for summarization\n */\n model: z.custom<string | BaseLanguageModel>(),\n /**\n * Trigger conditions for summarization.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 5000 AND messages >= 3\n * trigger: { tokens: 5000, messages: 3 }\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 }\n * ]\n * ```\n */\n trigger: z.union([contextSizeSchema, z.array(contextSizeSchema)]).optional(),\n /**\n * Keep conditions for summarization\n */\n keep: keepSchema.optional(),\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: tokenCounterSchema.optional(),\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.string().default(DEFAULT_SUMMARY_PROMPT),\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.number().optional(),\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.string().optional(),\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.number().optional(),\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.number().optional(),\n});\n\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nexport function getProfileLimits(input: BaseLanguageModel): number | undefined {\n // Access maxInputTokens on the model profile directly if available\n if (\n \"profile\" in input &&\n typeof input.profile === \"object\" &&\n input.profile &&\n \"maxInputTokens\" in input.profile &&\n (typeof input.profile.maxInputTokens === \"number\" ||\n input.profile.maxInputTokens == null)\n ) {\n return input.profile.maxInputTokens ?? undefined;\n }\n\n // Fallback to using model name if available\n if (\"model\" in input && typeof input.model === \"string\") {\n return getModelContextSize(input.model);\n }\n if (\"modelName\" in input && typeof input.modelName === \"string\") {\n return getModelContextSize(input.modelName);\n }\n\n return undefined;\n}\n\n/**\n * Summarization middleware that automatically summarizes conversation history when token limits are approached.\n *\n * This middleware monitors message token counts and automatically summarizes older\n * messages when a threshold is reached, preserving recent messages and maintaining\n * context continuity by ensuring AI/Tool message pairs remain together.\n *\n * @param options Configuration options for the summarization middleware\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * import { summarizationMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 4000 AND messages >= 10\n * const agent1 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: { tokens: 4000, messages: 10 },\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * const agent2 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 },\n * ],\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * ```\n */\nexport function summarizationMiddleware(\n options: SummarizationMiddlewareConfig\n) {\n /**\n * Parse user options to get their explicit values\n */\n const { data: userOptions, error } = interopSafeParse(contextSchema, options);\n if (error) {\n throw new Error(\n `Invalid summarization middleware options: ${z4.prettifyError(error)}`\n );\n }\n\n return createMiddleware({\n name: \"SummarizationMiddleware\",\n contextSchema: contextSchema.extend({\n /**\n * `model` should be required when initializing the middleware,\n * but can be omitted within context when invoking the middleware.\n */\n model: z.custom<BaseLanguageModel>().optional(),\n }),\n beforeModel: async (state, runtime) => {\n let trigger: ContextSize | ContextSize[] | undefined =\n userOptions.trigger;\n let keep: ContextSize = userOptions.keep as InferInteropZodOutput<\n typeof keepSchema\n >;\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.maxTokensBeforeSummary !== undefined) {\n console.warn(\n \"maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead.\"\n );\n if (trigger === undefined) {\n trigger = { tokens: userOptions.maxTokensBeforeSummary };\n }\n }\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.messagesToKeep !== undefined) {\n console.warn(\n \"messagesToKeep is deprecated. Use `keep: { messages: value }` instead.\"\n );\n if (\n !keep ||\n (keep &&\n \"messages\" in keep &&\n keep.messages === DEFAULT_MESSAGES_TO_KEEP)\n ) {\n keep = { messages: userOptions.messagesToKeep };\n }\n }\n\n /**\n * Merge context with user options\n */\n const resolvedTrigger =\n runtime.context?.trigger !== undefined\n ? runtime.context.trigger\n : trigger;\n const resolvedKeep =\n runtime.context?.keep !== undefined\n ? runtime.context.keep\n : keep ?? { messages: DEFAULT_MESSAGES_TO_KEEP };\n\n const validatedKeep = keepSchema.parse(resolvedKeep);\n\n /**\n * Validate trigger conditions\n */\n let triggerConditions: ContextSize[] = [];\n if (resolvedTrigger === undefined) {\n triggerConditions = [];\n } else if (Array.isArray(resolvedTrigger)) {\n /**\n * It's an array of ContextSize objects\n */\n triggerConditions = (resolvedTrigger as ContextSize[]).map((t) =>\n contextSizeSchema.parse(t)\n );\n } else {\n /**\n * Single ContextSize object - all properties must be satisfied (AND logic)\n */\n triggerConditions = [contextSizeSchema.parse(resolvedTrigger)];\n }\n\n /**\n * Check if profile is required\n */\n const requiresProfile =\n triggerConditions.some((c) => \"fraction\" in c) ||\n \"fraction\" in validatedKeep;\n\n const model =\n typeof userOptions.model === \"string\"\n ? await initChatModel(userOptions.model)\n : userOptions.model;\n\n if (requiresProfile && !getProfileLimits(model)) {\n throw new Error(\n \"Model profile information is required to use fractional token limits. \" +\n \"Use absolute token counts instead.\"\n );\n }\n\n const summaryPrompt =\n runtime.context?.summaryPrompt === DEFAULT_SUMMARY_PROMPT\n ? userOptions.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT\n : runtime.context?.summaryPrompt ??\n userOptions.summaryPrompt ??\n DEFAULT_SUMMARY_PROMPT;\n const trimTokensToSummarize =\n runtime.context?.trimTokensToSummarize !== undefined\n ? runtime.context.trimTokensToSummarize\n : userOptions.trimTokensToSummarize ?? DEFAULT_TRIM_TOKEN_LIMIT;\n\n /**\n * Ensure all messages have IDs\n */\n ensureMessageIds(state.messages);\n\n const tokenCounter =\n runtime.context?.tokenCounter !== undefined\n ? runtime.context.tokenCounter\n : userOptions.tokenCounter ?? countTokensApproximately;\n const totalTokens = await tokenCounter(state.messages);\n const doSummarize = await shouldSummarize(\n state.messages,\n totalTokens,\n triggerConditions,\n model\n );\n\n if (!doSummarize) {\n return;\n }\n\n const { systemPrompt, conversationMessages } = splitSystemMessage(\n state.messages\n );\n const cutoffIndex = await determineCutoffIndex(\n conversationMessages,\n validatedKeep,\n tokenCounter,\n model\n );\n\n if (cutoffIndex <= 0) {\n return;\n }\n\n const { messagesToSummarize, preservedMessages } = partitionMessages(\n systemPrompt,\n conversationMessages,\n cutoffIndex\n );\n\n const summary = await createSummary(\n messagesToSummarize,\n model,\n summaryPrompt,\n tokenCounter,\n trimTokensToSummarize\n );\n\n const summaryMessage = new HumanMessage({\n content: `Here is a summary of the conversation to date:\\n\\n${summary}`,\n id: uuid(),\n });\n\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n summaryMessage,\n ...preservedMessages,\n ],\n };\n },\n });\n}\n\n/**\n * Ensure all messages have unique IDs\n */\nfunction ensureMessageIds(messages: BaseMessage[]): void {\n for (const msg of messages) {\n if (!msg.id) {\n msg.id = uuid();\n }\n }\n}\n\n/**\n * Separate system message from conversation messages\n */\nfunction splitSystemMessage(messages: BaseMessage[]): {\n systemPrompt?: SystemMessage;\n conversationMessages: BaseMessage[];\n} {\n if (messages.length > 0 && SystemMessage.isInstance(messages[0])) {\n return {\n systemPrompt: messages[0] as SystemMessage,\n conversationMessages: messages.slice(1),\n };\n }\n return {\n conversationMessages: messages,\n };\n}\n\n/**\n * Partition messages into those to summarize and those to preserve\n */\nfunction partitionMessages(\n systemPrompt: SystemMessage | undefined,\n conversationMessages: BaseMessage[],\n cutoffIndex: number\n): { messagesToSummarize: BaseMessage[]; preservedMessages: BaseMessage[] } {\n const messagesToSummarize = conversationMessages.slice(0, cutoffIndex);\n const preservedMessages = conversationMessages.slice(cutoffIndex);\n\n // Include system message in messages to summarize to capture previous summaries\n if (systemPrompt) {\n messagesToSummarize.unshift(systemPrompt);\n }\n\n return { messagesToSummarize, preservedMessages };\n}\n\n/**\n * Determine whether summarization should run for the current token usage\n *\n * @param messages - Current messages in the conversation\n * @param totalTokens - Total token count for all messages\n * @param triggerConditions - Array of trigger conditions. Returns true if ANY condition is satisfied (OR logic).\n * Within each condition, ALL specified properties must be satisfied (AND logic).\n * @param model - The language model being used\n * @returns true if summarization should be triggered\n */\nasync function shouldSummarize(\n messages: BaseMessage[],\n totalTokens: number,\n triggerConditions: ContextSize[],\n model: BaseLanguageModel\n): Promise<boolean> {\n if (triggerConditions.length === 0) {\n return false;\n }\n\n /**\n * Check each condition (OR logic between conditions)\n */\n for (const trigger of triggerConditions) {\n /**\n * Within a single condition, all specified properties must be satisfied (AND logic)\n */\n let conditionMet = true;\n let hasAnyProperty = false;\n\n if (trigger.messages !== undefined) {\n hasAnyProperty = true;\n if (messages.length < trigger.messages) {\n conditionMet = false;\n }\n }\n\n if (trigger.tokens !== undefined) {\n hasAnyProperty = true;\n if (totalTokens < trigger.tokens) {\n conditionMet = false;\n }\n }\n\n if (trigger.fraction !== undefined) {\n hasAnyProperty = true;\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens === \"number\") {\n const threshold = Math.floor(maxInputTokens * trigger.fraction);\n if (totalTokens < threshold) {\n conditionMet = false;\n }\n } else {\n /**\n * If fraction is specified but we can't get model limits, skip this condition\n */\n conditionMet = false;\n }\n }\n\n /**\n * If condition has at least one property and all properties are satisfied, trigger summarization\n */\n if (hasAnyProperty && conditionMet) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine cutoff index respecting retention configuration\n */\nasync function determineCutoffIndex(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number> {\n if (\"tokens\" in keep || \"fraction\" in keep) {\n const tokenBasedCutoff = await findTokenBasedCutoff(\n messages,\n keep,\n tokenCounter,\n model\n );\n if (typeof tokenBasedCutoff === \"number\") {\n return tokenBasedCutoff;\n }\n /**\n * Fallback to message count if token-based fails\n */\n return findSafeCutoff(messages, DEFAULT_MESSAGES_TO_KEEP);\n }\n /**\n * find cutoff index based on message count\n */\n return findSafeCutoff(messages, keep.messages ?? DEFAULT_MESSAGES_TO_KEEP);\n}\n\n/**\n * Find cutoff index based on target token retention\n */\nasync function findTokenBasedCutoff(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number | undefined> {\n if (messages.length === 0) {\n return 0;\n }\n\n let targetTokenCount: number;\n\n if (\"fraction\" in keep && keep.fraction !== undefined) {\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens !== \"number\") {\n return;\n }\n targetTokenCount = Math.floor(maxInputTokens * keep.fraction);\n } else if (\"tokens\" in keep && keep.tokens !== undefined) {\n targetTokenCount = Math.floor(keep.tokens);\n } else {\n return;\n }\n\n if (targetTokenCount <= 0) {\n targetTokenCount = 1;\n }\n\n const totalTokens = await tokenCounter(messages);\n if (totalTokens <= targetTokenCount) {\n return 0;\n }\n\n /**\n * Use binary search to identify the earliest message index that keeps the\n * suffix within the token budget.\n */\n let left = 0;\n let right = messages.length;\n let cutoffCandidate = messages.length;\n const maxIterations = Math.floor(Math.log2(messages.length)) + 1;\n\n for (let i = 0; i < maxIterations; i++) {\n if (left >= right) {\n break;\n }\n\n const mid = Math.floor((left + right) / 2);\n const suffixTokens = await tokenCounter(messages.slice(mid));\n if (suffixTokens <= targetTokenCount) {\n cutoffCandidate = mid;\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n if (cutoffCandidate === messages.length) {\n cutoffCandidate = left;\n }\n\n if (cutoffCandidate >= messages.length) {\n if (messages.length === 1) {\n return 0;\n }\n cutoffCandidate = messages.length - 1;\n }\n\n /**\n * Find safe cutoff point that preserves tool pairs\n */\n for (let i = cutoffCandidate; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Find safe cutoff point that preserves AI/Tool message pairs\n */\nfunction findSafeCutoff(\n messages: BaseMessage[],\n messagesToKeep: number\n): number {\n if (messages.length <= messagesToKeep) {\n return 0;\n }\n\n const targetCutoff = messages.length - messagesToKeep;\n\n for (let i = targetCutoff; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Check if cutting at index would separate AI/Tool message pairs\n */\nfunction isSafeCutoffPoint(\n messages: BaseMessage[],\n cutoffIndex: number\n): boolean {\n if (cutoffIndex >= messages.length) {\n return true;\n }\n\n /**\n * Prevent preserved messages from starting with AI message containing tool calls\n */\n if (\n cutoffIndex < messages.length &&\n AIMessage.isInstance(messages[cutoffIndex]) &&\n hasToolCalls(messages[cutoffIndex])\n ) {\n return false;\n }\n\n const searchStart = Math.max(0, cutoffIndex - SEARCH_RANGE_FOR_TOOL_PAIRS);\n const searchEnd = Math.min(\n messages.length,\n cutoffIndex + SEARCH_RANGE_FOR_TOOL_PAIRS\n );\n\n for (let i = searchStart; i < searchEnd; i++) {\n if (!hasToolCalls(messages[i])) {\n continue;\n }\n\n const toolCallIds = extractToolCallIds(messages[i] as AIMessage);\n if (cutoffSeparatesToolPair(messages, i, cutoffIndex, toolCallIds)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Extract tool call IDs from an AI message\n */\nfunction extractToolCallIds(aiMessage: AIMessage): Set<string> {\n const toolCallIds = new Set<string>();\n if (aiMessage.tool_calls) {\n for (const toolCall of aiMessage.tool_calls) {\n const id =\n typeof toolCall === \"object\" && \"id\" in toolCall ? toolCall.id : null;\n if (id) {\n toolCallIds.add(id);\n }\n }\n }\n return toolCallIds;\n}\n\n/**\n * Check if cutoff separates an AI message from its corresponding tool messages\n */\nfunction cutoffSeparatesToolPair(\n messages: BaseMessage[],\n aiMessageIndex: number,\n cutoffIndex: number,\n toolCallIds: Set<string>\n): boolean {\n for (let j = aiMessageIndex + 1; j < messages.length; j++) {\n const message = messages[j];\n if (\n ToolMessage.isInstance(message) &&\n toolCallIds.has(message.tool_call_id)\n ) {\n const aiBeforeCutoff = aiMessageIndex < cutoffIndex;\n const toolBeforeCutoff = j < cutoffIndex;\n if (aiBeforeCutoff !== toolBeforeCutoff) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Generate summary for the given messages\n */\nasync function createSummary(\n messagesToSummarize: BaseMessage[],\n model: BaseLanguageModel,\n summaryPrompt: string,\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<string> {\n if (!messagesToSummarize.length) {\n return \"No previous conversation history.\";\n }\n\n const trimmedMessages = await trimMessagesForSummary(\n messagesToSummarize,\n tokenCounter,\n trimTokensToSummarize\n );\n\n if (!trimmedMessages.length) {\n return \"Previous conversation was too long to summarize.\";\n }\n\n try {\n const formattedPrompt = summaryPrompt.replace(\n \"{messages}\",\n JSON.stringify(trimmedMessages, null, 2)\n );\n const response = await model.invoke(formattedPrompt);\n const content = response.content;\n /**\n * Handle both string content and MessageContent array\n */\n if (typeof content === \"string\") {\n return content.trim();\n } else if (Array.isArray(content)) {\n /**\n * Extract text from MessageContent array\n */\n const textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n return (item as { text: string }).text;\n }\n return \"\";\n })\n .join(\"\");\n return textContent.trim();\n }\n return \"Error generating summary: Invalid response format\";\n } catch (e) {\n return `Error generating summary: ${e}`;\n }\n}\n\n/**\n * Trim messages to fit within summary generation limits\n */\nasync function trimMessagesForSummary(\n messages: BaseMessage[],\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<BaseMessage[]> {\n if (trimTokensToSummarize === undefined) {\n return messages;\n }\n\n try {\n return await trimMessages(messages, {\n maxTokens: trimTokensToSummarize,\n tokenCounter: async (msgs) => tokenCounter(msgs),\n strategy: \"last\",\n allowPartial: true,\n includeSystem: true,\n });\n } catch {\n /**\n * Fallback to last N messages if trimming fails\n */\n return messages.slice(-DEFAULT_FALLBACK_MESSAGE_COUNT);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBAAyB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0B5B,CAAC;AAEZ,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,iCAAiC;AACvC,MAAM,8BAA8B;AAEpC,MAAM,qBAAqB,EACxB,UAAU,CACV,KAAK,EAAE,MAAM,EAAE,QAAqB,CAAC,CAAC,CACtC,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,AAAC,EAAC,CAAC;AAKxD,MAAa,oBAAoB,EAC9B,OAAO;CAIN,UAAU,EACP,QAAQ,CACR,GAAG,GAAG,kCAAkC,CACxC,IAAI,GAAG,2CAA2C,CAClD,UAAU;CAIb,QAAQ,EAAE,QAAQ,CAAC,SAAS,gCAAgC,CAAC,UAAU;CAIvE,UAAU,EACP,QAAQ,CACR,IAAI,8BAA8B,CAClC,SAAS,kCAAkC,CAC3C,UAAU;AACd,EAAC,CACD,OACC,CAAC,SAAS;CACR,MAAM,QAAQ;EAAC,KAAK;EAAU,KAAK;EAAQ,KAAK;CAAS,EAAC,O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oB,OACvB,QAAO;CAGT,MAAM,kBAAkB,MAAM,uBAC5B,qBACA,cACA,sBACD;AAED,KAAI,CAAC,gBAAgB,OACnB,QAAO;AAGT,KAAI;EACF,MAAM,kBAAkB,cAAc,QACpC,cACA,KAAK,UAAU,iBAAiB,MAAM,EAAE,CACzC;EACD,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EACpD,MAAM,UAAU,SAAS;;;;AAIzB,MAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;WACZ,MAAM,QAAQ,QAAQ,EAAE;;;;GAIjC,MAAM,cAAc,QACjB,IAAI,CAAC,SAAS;AACb,QAAI,OAAO,SAAS,SAAU,QAAO;AACrC,QAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,KACzD,QAAQ,KAA0B;AAEpC,WAAO;GACR,EAAC,CACD,KAAK,GAAG;AACX,UAAO,YAAY,MAAM;EAC1B;AACD,SAAO;CACR,SAAQ,GAAG;AACV,SAAO,CAAC,0BAA0B,EAAE,GAAG;CACxC;AACF;;;;AAKD,eAAe,uBACbd,UACAM,cACAQ,uBACwB;AACxB,KAAI,0BAA0B,OAC5B,QAAO;AAGT,KAAI;AACF,SAAO,MAAM,aAAa,UAAU;GAClC,WAAW;GACX,cAAc,OAAO,SAAS,aAAa,KAAK;GAChD,UAAU;GACV,cAAc;GACd,eAAe;EAChB,EAAC;CACH,QAAO;;;;AAIN,SAAO,SAAS,MAAM,CAAC,+BAA+B;CACvD;AACF"}
1
+ {"version":3,"file":"summarization.js","names":["input: BaseLanguageModel","options: SummarizationMiddlewareConfig","z4","trigger: ContextSize | ContextSize[] | undefined","keep: ContextSize","triggerConditions: ContextSize[]","uuid","messages: BaseMessage[]","systemPrompt: SystemMessage | undefined","conversationMessages: BaseMessage[]","cutoffIndex: number","totalTokens: number","model: BaseLanguageModel","tokenCounter: TokenCounter","targetTokenCount: number","messagesToKeep: number","aiMessage: AIMessage","aiMessageIndex: number","toolCallIds: Set<string>","messagesToSummarize: BaseMessage[]","summaryPrompt: string","trimTokensToSummarize: number | undefined"],"sources":["../../../src/agents/middleware/summarization.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4 } from \"zod/v4\";\nimport { v4 as uuid } from \"uuid\";\nimport {\n BaseMessage,\n AIMessage,\n SystemMessage,\n ToolMessage,\n RemoveMessage,\n trimMessages,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport {\n BaseLanguageModel,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport {\n interopSafeParse,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { countTokensApproximately } from \"./utils.js\";\nimport { hasToolCalls } from \"../utils.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\n\nexport const DEFAULT_SUMMARY_PROMPT = `<role>\nContext Extraction Assistant\n</role>\n\n<primary_objective>\nYour sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.\n</primary_objective>\n\n<objective_information>\nYou're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.\nThis context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.\n</objective_information>\n\n<instructions>\nThe conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.\nYou want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.\n</instructions>\n\nThe user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:\n\nWith all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.\nRespond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.\n\n<messages>\nMessages to summarize:\n{messages}\n</messages>`;\n\nconst DEFAULT_SUMMARY_PREFIX = \"Here is a summary of the conversation to date:\";\nconst DEFAULT_MESSAGES_TO_KEEP = 20;\nconst DEFAULT_TRIM_TOKEN_LIMIT = 4000;\nconst DEFAULT_FALLBACK_MESSAGE_COUNT = 15;\nconst SEARCH_RANGE_FOR_TOOL_PAIRS = 5;\n\nconst tokenCounterSchema = z\n .function()\n .args(z.array(z.custom<BaseMessage>()))\n .returns(z.union([z.number(), z.promise(z.number())]));\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\nexport const contextSizeSchema = z\n .object({\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z\n .number()\n .gt(0, \"Fraction must be greater than 0\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.number().positive(\"Tokens must be greater than 0\").optional(),\n /**\n * Number of messages to use as the trigger\n */\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .positive(\"Messages must be greater than 0\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count >= 1;\n },\n {\n message: \"At least one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\n\nexport const keepSchema = z\n .object({\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z\n .number()\n .min(0, \"Messages must be non-negative\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to keep\n */\n tokens: z\n .number()\n .min(0, \"Tokens must be greater than or equal to 0\")\n .optional(),\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .min(0, \"Messages must be non-negative\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count === 1;\n },\n {\n message: \"Exactly one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type KeepSize = z.infer<typeof keepSchema>;\n\nconst contextSchema = z.object({\n /**\n * Model to use for summarization\n */\n model: z.custom<string | BaseLanguageModel>(),\n /**\n * Trigger conditions for summarization.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 5000 AND messages >= 3\n * trigger: { tokens: 5000, messages: 3 }\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 }\n * ]\n * ```\n */\n trigger: z.union([contextSizeSchema, z.array(contextSizeSchema)]).optional(),\n /**\n * Keep conditions for summarization\n */\n keep: keepSchema.optional(),\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: tokenCounterSchema.optional(),\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.string().default(DEFAULT_SUMMARY_PROMPT),\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.number().optional(),\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.string().optional(),\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.number().optional(),\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.number().optional(),\n});\n\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nexport function getProfileLimits(input: BaseLanguageModel): number | undefined {\n // Access maxInputTokens on the model profile directly if available\n if (\n \"profile\" in input &&\n typeof input.profile === \"object\" &&\n input.profile &&\n \"maxInputTokens\" in input.profile &&\n (typeof input.profile.maxInputTokens === \"number\" ||\n input.profile.maxInputTokens == null)\n ) {\n return input.profile.maxInputTokens ?? undefined;\n }\n\n // Fallback to using model name if available\n if (\"model\" in input && typeof input.model === \"string\") {\n return getModelContextSize(input.model);\n }\n if (\"modelName\" in input && typeof input.modelName === \"string\") {\n return getModelContextSize(input.modelName);\n }\n\n return undefined;\n}\n\n/**\n * Summarization middleware that automatically summarizes conversation history when token limits are approached.\n *\n * This middleware monitors message token counts and automatically summarizes older\n * messages when a threshold is reached, preserving recent messages and maintaining\n * context continuity by ensuring AI/Tool message pairs remain together.\n *\n * @param options Configuration options for the summarization middleware\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * import { summarizationMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 4000 AND messages >= 10\n * const agent1 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: { tokens: 4000, messages: 10 },\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * const agent2 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 },\n * ],\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * ```\n */\nexport function summarizationMiddleware(\n options: SummarizationMiddlewareConfig\n) {\n /**\n * Parse user options to get their explicit values\n */\n const { data: userOptions, error } = interopSafeParse(contextSchema, options);\n if (error) {\n throw new Error(\n `Invalid summarization middleware options: ${z4.prettifyError(error)}`\n );\n }\n\n return createMiddleware({\n name: \"SummarizationMiddleware\",\n contextSchema: contextSchema.extend({\n /**\n * `model` should be required when initializing the middleware,\n * but can be omitted within context when invoking the middleware.\n */\n model: z.custom<BaseLanguageModel>().optional(),\n }),\n beforeModel: async (state, runtime) => {\n let trigger: ContextSize | ContextSize[] | undefined =\n userOptions.trigger;\n let keep: ContextSize = userOptions.keep as InferInteropZodOutput<\n typeof keepSchema\n >;\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.maxTokensBeforeSummary !== undefined) {\n console.warn(\n \"maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead.\"\n );\n if (trigger === undefined) {\n trigger = { tokens: userOptions.maxTokensBeforeSummary };\n }\n }\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.messagesToKeep !== undefined) {\n console.warn(\n \"messagesToKeep is deprecated. Use `keep: { messages: value }` instead.\"\n );\n if (\n !keep ||\n (keep &&\n \"messages\" in keep &&\n keep.messages === DEFAULT_MESSAGES_TO_KEEP)\n ) {\n keep = { messages: userOptions.messagesToKeep };\n }\n }\n\n /**\n * Merge context with user options\n */\n const resolvedTrigger =\n runtime.context?.trigger !== undefined\n ? runtime.context.trigger\n : trigger;\n const resolvedKeep =\n runtime.context?.keep !== undefined\n ? runtime.context.keep\n : keep ?? { messages: DEFAULT_MESSAGES_TO_KEEP };\n\n const validatedKeep = keepSchema.parse(resolvedKeep);\n\n /**\n * Validate trigger conditions\n */\n let triggerConditions: ContextSize[] = [];\n if (resolvedTrigger === undefined) {\n triggerConditions = [];\n } else if (Array.isArray(resolvedTrigger)) {\n /**\n * It's an array of ContextSize objects\n */\n triggerConditions = (resolvedTrigger as ContextSize[]).map((t) =>\n contextSizeSchema.parse(t)\n );\n } else {\n /**\n * Single ContextSize object - all properties must be satisfied (AND logic)\n */\n triggerConditions = [contextSizeSchema.parse(resolvedTrigger)];\n }\n\n /**\n * Check if profile is required\n */\n const requiresProfile =\n triggerConditions.some((c) => \"fraction\" in c) ||\n \"fraction\" in validatedKeep;\n\n const model =\n typeof userOptions.model === \"string\"\n ? await initChatModel(userOptions.model)\n : userOptions.model;\n\n if (requiresProfile && !getProfileLimits(model)) {\n throw new Error(\n \"Model profile information is required to use fractional token limits. \" +\n \"Use absolute token counts instead.\"\n );\n }\n\n const summaryPrompt =\n runtime.context?.summaryPrompt === DEFAULT_SUMMARY_PROMPT\n ? userOptions.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT\n : runtime.context?.summaryPrompt ??\n userOptions.summaryPrompt ??\n DEFAULT_SUMMARY_PROMPT;\n const summaryPrefix =\n runtime.context.summaryPrefix ??\n userOptions.summaryPrefix ??\n DEFAULT_SUMMARY_PREFIX;\n const trimTokensToSummarize =\n runtime.context?.trimTokensToSummarize !== undefined\n ? runtime.context.trimTokensToSummarize\n : userOptions.trimTokensToSummarize ?? DEFAULT_TRIM_TOKEN_LIMIT;\n\n /**\n * Ensure all messages have IDs\n */\n ensureMessageIds(state.messages);\n\n const tokenCounter =\n runtime.context?.tokenCounter !== undefined\n ? runtime.context.tokenCounter\n : userOptions.tokenCounter ?? countTokensApproximately;\n const totalTokens = await tokenCounter(state.messages);\n const doSummarize = await shouldSummarize(\n state.messages,\n totalTokens,\n triggerConditions,\n model\n );\n\n if (!doSummarize) {\n return;\n }\n\n const { systemPrompt, conversationMessages } = splitSystemMessage(\n state.messages\n );\n const cutoffIndex = await determineCutoffIndex(\n conversationMessages,\n validatedKeep,\n tokenCounter,\n model\n );\n\n if (cutoffIndex <= 0) {\n return;\n }\n\n const { messagesToSummarize, preservedMessages } = partitionMessages(\n systemPrompt,\n conversationMessages,\n cutoffIndex\n );\n\n const summary = await createSummary(\n messagesToSummarize,\n model,\n summaryPrompt,\n tokenCounter,\n trimTokensToSummarize\n );\n\n const summaryMessage = new HumanMessage({\n content: `${summaryPrefix}\\n\\n${summary}`,\n id: uuid(),\n });\n\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n summaryMessage,\n ...preservedMessages,\n ],\n };\n },\n });\n}\n\n/**\n * Ensure all messages have unique IDs\n */\nfunction ensureMessageIds(messages: BaseMessage[]): void {\n for (const msg of messages) {\n if (!msg.id) {\n msg.id = uuid();\n }\n }\n}\n\n/**\n * Separate system message from conversation messages\n */\nfunction splitSystemMessage(messages: BaseMessage[]): {\n systemPrompt?: SystemMessage;\n conversationMessages: BaseMessage[];\n} {\n if (messages.length > 0 && SystemMessage.isInstance(messages[0])) {\n return {\n systemPrompt: messages[0] as SystemMessage,\n conversationMessages: messages.slice(1),\n };\n }\n return {\n conversationMessages: messages,\n };\n}\n\n/**\n * Partition messages into those to summarize and those to preserve\n */\nfunction partitionMessages(\n systemPrompt: SystemMessage | undefined,\n conversationMessages: BaseMessage[],\n cutoffIndex: number\n): { messagesToSummarize: BaseMessage[]; preservedMessages: BaseMessage[] } {\n const messagesToSummarize = conversationMessages.slice(0, cutoffIndex);\n const preservedMessages = conversationMessages.slice(cutoffIndex);\n\n // Include system message in messages to summarize to capture previous summaries\n if (systemPrompt) {\n messagesToSummarize.unshift(systemPrompt);\n }\n\n return { messagesToSummarize, preservedMessages };\n}\n\n/**\n * Determine whether summarization should run for the current token usage\n *\n * @param messages - Current messages in the conversation\n * @param totalTokens - Total token count for all messages\n * @param triggerConditions - Array of trigger conditions. Returns true if ANY condition is satisfied (OR logic).\n * Within each condition, ALL specified properties must be satisfied (AND logic).\n * @param model - The language model being used\n * @returns true if summarization should be triggered\n */\nasync function shouldSummarize(\n messages: BaseMessage[],\n totalTokens: number,\n triggerConditions: ContextSize[],\n model: BaseLanguageModel\n): Promise<boolean> {\n if (triggerConditions.length === 0) {\n return false;\n }\n\n /**\n * Check each condition (OR logic between conditions)\n */\n for (const trigger of triggerConditions) {\n /**\n * Within a single condition, all specified properties must be satisfied (AND logic)\n */\n let conditionMet = true;\n let hasAnyProperty = false;\n\n if (trigger.messages !== undefined) {\n hasAnyProperty = true;\n if (messages.length < trigger.messages) {\n conditionMet = false;\n }\n }\n\n if (trigger.tokens !== undefined) {\n hasAnyProperty = true;\n if (totalTokens < trigger.tokens) {\n conditionMet = false;\n }\n }\n\n if (trigger.fraction !== undefined) {\n hasAnyProperty = true;\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens === \"number\") {\n const threshold = Math.floor(maxInputTokens * trigger.fraction);\n if (totalTokens < threshold) {\n conditionMet = false;\n }\n } else {\n /**\n * If fraction is specified but we can't get model limits, skip this condition\n */\n conditionMet = false;\n }\n }\n\n /**\n * If condition has at least one property and all properties are satisfied, trigger summarization\n */\n if (hasAnyProperty && conditionMet) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine cutoff index respecting retention configuration\n */\nasync function determineCutoffIndex(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number> {\n if (\"tokens\" in keep || \"fraction\" in keep) {\n const tokenBasedCutoff = await findTokenBasedCutoff(\n messages,\n keep,\n tokenCounter,\n model\n );\n if (typeof tokenBasedCutoff === \"number\") {\n return tokenBasedCutoff;\n }\n /**\n * Fallback to message count if token-based fails\n */\n return findSafeCutoff(messages, DEFAULT_MESSAGES_TO_KEEP);\n }\n /**\n * find cutoff index based on message count\n */\n return findSafeCutoff(messages, keep.messages ?? DEFAULT_MESSAGES_TO_KEEP);\n}\n\n/**\n * Find cutoff index based on target token retention\n */\nasync function findTokenBasedCutoff(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number | undefined> {\n if (messages.length === 0) {\n return 0;\n }\n\n let targetTokenCount: number;\n\n if (\"fraction\" in keep && keep.fraction !== undefined) {\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens !== \"number\") {\n return;\n }\n targetTokenCount = Math.floor(maxInputTokens * keep.fraction);\n } else if (\"tokens\" in keep && keep.tokens !== undefined) {\n targetTokenCount = Math.floor(keep.tokens);\n } else {\n return;\n }\n\n if (targetTokenCount <= 0) {\n targetTokenCount = 1;\n }\n\n const totalTokens = await tokenCounter(messages);\n if (totalTokens <= targetTokenCount) {\n return 0;\n }\n\n /**\n * Use binary search to identify the earliest message index that keeps the\n * suffix within the token budget.\n */\n let left = 0;\n let right = messages.length;\n let cutoffCandidate = messages.length;\n const maxIterations = Math.floor(Math.log2(messages.length)) + 1;\n\n for (let i = 0; i < maxIterations; i++) {\n if (left >= right) {\n break;\n }\n\n const mid = Math.floor((left + right) / 2);\n const suffixTokens = await tokenCounter(messages.slice(mid));\n if (suffixTokens <= targetTokenCount) {\n cutoffCandidate = mid;\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n if (cutoffCandidate === messages.length) {\n cutoffCandidate = left;\n }\n\n if (cutoffCandidate >= messages.length) {\n if (messages.length === 1) {\n return 0;\n }\n cutoffCandidate = messages.length - 1;\n }\n\n /**\n * Find safe cutoff point that preserves tool pairs\n */\n for (let i = cutoffCandidate; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Find safe cutoff point that preserves AI/Tool message pairs\n */\nfunction findSafeCutoff(\n messages: BaseMessage[],\n messagesToKeep: number\n): number {\n if (messages.length <= messagesToKeep) {\n return 0;\n }\n\n const targetCutoff = messages.length - messagesToKeep;\n\n for (let i = targetCutoff; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Check if cutting at index would separate AI/Tool message pairs\n */\nfunction isSafeCutoffPoint(\n messages: BaseMessage[],\n cutoffIndex: number\n): boolean {\n if (cutoffIndex >= messages.length) {\n return true;\n }\n\n /**\n * Prevent preserved messages from starting with AI message containing tool calls\n */\n if (\n cutoffIndex < messages.length &&\n AIMessage.isInstance(messages[cutoffIndex]) &&\n hasToolCalls(messages[cutoffIndex])\n ) {\n return false;\n }\n\n const searchStart = Math.max(0, cutoffIndex - SEARCH_RANGE_FOR_TOOL_PAIRS);\n const searchEnd = Math.min(\n messages.length,\n cutoffIndex + SEARCH_RANGE_FOR_TOOL_PAIRS\n );\n\n for (let i = searchStart; i < searchEnd; i++) {\n if (!hasToolCalls(messages[i])) {\n continue;\n }\n\n const toolCallIds = extractToolCallIds(messages[i] as AIMessage);\n if (cutoffSeparatesToolPair(messages, i, cutoffIndex, toolCallIds)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Extract tool call IDs from an AI message\n */\nfunction extractToolCallIds(aiMessage: AIMessage): Set<string> {\n const toolCallIds = new Set<string>();\n if (aiMessage.tool_calls) {\n for (const toolCall of aiMessage.tool_calls) {\n const id =\n typeof toolCall === \"object\" && \"id\" in toolCall ? toolCall.id : null;\n if (id) {\n toolCallIds.add(id);\n }\n }\n }\n return toolCallIds;\n}\n\n/**\n * Check if cutoff separates an AI message from its corresponding tool messages\n */\nfunction cutoffSeparatesToolPair(\n messages: BaseMessage[],\n aiMessageIndex: number,\n cutoffIndex: number,\n toolCallIds: Set<string>\n): boolean {\n for (let j = aiMessageIndex + 1; j < messages.length; j++) {\n const message = messages[j];\n if (\n ToolMessage.isInstance(message) &&\n toolCallIds.has(message.tool_call_id)\n ) {\n const aiBeforeCutoff = aiMessageIndex < cutoffIndex;\n const toolBeforeCutoff = j < cutoffIndex;\n if (aiBeforeCutoff !== toolBeforeCutoff) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Generate summary for the given messages\n */\nasync function createSummary(\n messagesToSummarize: BaseMessage[],\n model: BaseLanguageModel,\n summaryPrompt: string,\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<string> {\n if (!messagesToSummarize.length) {\n return \"No previous conversation history.\";\n }\n\n const trimmedMessages = await trimMessagesForSummary(\n messagesToSummarize,\n tokenCounter,\n trimTokensToSummarize\n );\n\n if (!trimmedMessages.length) {\n return \"Previous conversation was too long to summarize.\";\n }\n\n try {\n const formattedPrompt = summaryPrompt.replace(\n \"{messages}\",\n JSON.stringify(trimmedMessages, null, 2)\n );\n /**\n * Invoke the model with an empty callbacks array to prevent the internal\n * summarization call from being streamed to the UI. This ensures the\n * summarization is an internal housekeeping step that doesn't leak\n * assistant messages or streaming events.\n */\n const response = await model.invoke(formattedPrompt, { callbacks: [] });\n const content = response.content;\n /**\n * Handle both string content and MessageContent array\n */\n if (typeof content === \"string\") {\n return content.trim();\n } else if (Array.isArray(content)) {\n /**\n * Extract text from MessageContent array\n */\n const textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n return (item as { text: string }).text;\n }\n return \"\";\n })\n .join(\"\");\n return textContent.trim();\n }\n return \"Error generating summary: Invalid response format\";\n } catch (e) {\n return `Error generating summary: ${e}`;\n }\n}\n\n/**\n * Trim messages to fit within summary generation limits\n */\nasync function trimMessagesForSummary(\n messages: BaseMessage[],\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<BaseMessage[]> {\n if (trimTokensToSummarize === undefined) {\n return messages;\n }\n\n try {\n return await trimMessages(messages, {\n maxTokens: trimTokensToSummarize,\n tokenCounter: async (msgs) => tokenCounter(msgs),\n strategy: \"last\",\n allowPartial: true,\n includeSystem: true,\n });\n } catch {\n /**\n * Fallback to last N messages if trimming fails\n */\n return messages.slice(-DEFAULT_FALLBACK_MESSAGE_COUNT);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBAAyB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0B5B,CAAC;AAEZ,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,iCAAiC;AACvC,MAAM,8BAA8B;AAEpC,MAAM,qBAAqB,EACxB,UAAU,CACV,KAAK,EAAE,MAAM,EAAE,QAAqB,CAAC,CAAC,CACtC,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,AAAC,EAAC,CAAC;AAKxD,MAAa,oBAAoB,EAC9B,OAAO;CAIN,UAAU,EACP,QAAQ,CACR,GAAG,GAAG,kCAAkC,CACxC,IAAI,GAAG,2CAA2C,CAClD,UAAU;CAIb,QAAQ,EAAE,QAAQ,CAAC,SAAS,gCAAgC,CAAC,UAAU;CAIvE,UAAU,EACP,QAAQ,CACR,IAAI,8BAA8B,CAClC,SAAS,kCAAkC,CAC3C,UAAU;AACd,EAAC,CACD,OACC,CAAC,SAAS;CACR,MAAM,QAAQ;EAAC,KAAK;EAAU,KAAK;EAAQ,KAAK;CAAS,EAAC,OACxD,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,OACAQ,eACAP,cACAQ,uBACiB;AACjB,KAAI,CAAC,oBAAoB,OACvB,QAAO;CAGT,MAAM,kBAAkB,MAAM,uBAC5B,qBACA,cACA,sBACD;AAED,KAAI,CAAC,gBAAgB,OACnB,QAAO;AAGT,KAAI;EACF,MAAM,kBAAkB,cAAc,QACpC,cACA,KAAK,UAAU,iBAAiB,MAAM,EAAE,CACzC;;;;;;;EAOD,MAAM,WAAW,MAAM,MAAM,OAAO,iBAAiB,EAAE,WAAW,CAAE,EAAE,EAAC;EACvE,MAAM,UAAU,SAAS;;;;AAIzB,MAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;WACZ,MAAM,QAAQ,QAAQ,EAAE;;;;GAIjC,MAAM,cAAc,QACjB,IAAI,CAAC,SAAS;AACb,QAAI,OAAO,SAAS,SAAU,QAAO;AACrC,QAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,KACzD,QAAQ,KAA0B;AAEpC,WAAO;GACR,EAAC,CACD,KAAK,GAAG;AACX,UAAO,YAAY,MAAM;EAC1B;AACD,SAAO;CACR,SAAQ,GAAG;AACV,SAAO,CAAC,0BAA0B,EAAE,GAAG;CACxC;AACF;;;;AAKD,eAAe,uBACbd,UACAM,cACAQ,uBACwB;AACxB,KAAI,0BAA0B,OAC5B,QAAO;AAGT,KAAI;AACF,SAAO,MAAM,aAAa,UAAU;GAClC,WAAW;GACX,cAAc,OAAO,SAAS,aAAa,KAAK;GAChD,UAAU;GACV,cAAc;GACd,eAAe;EAChB,EAAC;CACH,QAAO;;;;AAIN,SAAO,SAAS,MAAM,CAAC,+BAA+B;CACvD;AACF"}
@@ -0,0 +1,12 @@
1
+
2
+ //#region src/agents/middleware/types.ts
3
+ /**
4
+ * Unique symbol used to brand middleware instances.
5
+ * This prevents functions from being accidentally assignable to AgentMiddleware
6
+ * since functions have a 'name' property that would otherwise make them structurally compatible.
7
+ */
8
+ const MIDDLEWARE_BRAND = Symbol("AgentMiddleware");
9
+
10
+ //#endregion
11
+ exports.MIDDLEWARE_BRAND = MIDDLEWARE_BRAND;
12
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.cjs","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot } 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\nexport type NormalizedSchemaInput<\n TSchema extends InteropZodObject | undefined | never = any\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends Record<string, unknown>\n ? 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 tool: ClientTool | ServerTool;\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 InteropZodObject | 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 InteropZodObject | 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 InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends InteropZodObject | 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 InteropZodObject | 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 InteropZodObject | 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 InteropZodObject | 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 */\nexport interface AgentMiddleware<\n TSchema extends InteropZodObject | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any\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 * 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\n * - A Zod optional object\n * - A Zod default object\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?: (ClientTool | ServerTool)[];\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\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 */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer S, any, any>\n ? S extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<S>>\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 */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer S, any, any>\n ? S extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<S>>\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 = AgentMiddleware[]> = 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 C, any>\n ? C extends InteropZodObject\n ? InferInteropZodInput<C>\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 C, any>\n ? C extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : C extends InteropZodObject\n ? InferInteropZodInput<C>\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 AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\nexport type InferSchemaInput<\n A extends AnyAnnotationRoot | InteropZodObject | undefined\n> = A extends AnyAnnotationRoot | InteropZodObject\n ? ToAnnotationRoot<A>[\"State\"]\n : {};\n"],"mappings":";;;;;;;AA+PA,MAAaA,mBAAkC,OAAO,kBAAkB"}
@@ -153,10 +153,21 @@ type AfterAgentHook<TSchema extends InteropZodObject | undefined = undefined, TC
153
153
  hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
154
154
  canJumpTo?: JumpToTarget[];
155
155
  };
156
+ /**
157
+ * Unique symbol used to brand middleware instances.
158
+ * This prevents functions from being accidentally assignable to AgentMiddleware
159
+ * since functions have a 'name' property that would otherwise make them structurally compatible.
160
+ */
161
+ declare const MIDDLEWARE_BRAND: unique symbol;
156
162
  /**
157
163
  * Base middleware interface.
158
164
  */
159
165
  interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any> {
166
+ /**
167
+ * Brand property to distinguish middleware instances from plain objects or functions.
168
+ * This is required and prevents accidental assignment of functions to middleware arrays.
169
+ */
170
+ readonly [MIDDLEWARE_BRAND]: true;
160
171
  /**
161
172
  * The name of the middleware.
162
173
  */
@@ -368,5 +379,5 @@ type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObjec
368
379
  type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
369
380
  type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>["State"] : {};
370
381
  //#endregion
371
- export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
382
+ export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MIDDLEWARE_BRAND, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
372
383
  //# sourceMappingURL=types.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodInput","InferInteropZodOutput","InteropZodToStateDefinition","AnnotationRoot","AIMessage","SystemMessage","ToolMessage","ToolCall","Command","ClientTool","ServerTool","JumpToTarget","Runtime","AgentBuiltInState","ModelRequest","PromiseOrValue","T","Promise","AnyAnnotationRoot","NormalizedSchemaInput","TSchema","Record","MiddlewareResult","TState","ToolCallRequest","TContext","ToolCallHandler","WrapToolCallHook","WrapModelCallHandler","Omit","WrapModelCallHook","BeforeAgentHandler","Partial","BeforeAgentHook","BeforeModelHandler","BeforeModelHook","AfterModelHandler","AfterModelHook","AfterAgentHandler","AfterAgentHook","AgentMiddleware","TContextSchema","TFullContext","FilterPrivateProps","K","InferChannelType","ToAnnotationRoot","InferMiddlewareState","S","InferMiddlewareInputState","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","C","InferMiddlewareContextInput","Inner","InferMiddlewareContexts","MergeContextTypes","A","B","InferMiddlewareContextInputs","InferContextInput","ContextSchema","InferSchemaInput"],"sources":["../../../src/agents/middleware/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodInput, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot } from \"@langchain/langgraph\";\nimport type { AIMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\ntype PromiseOrValue<T> = T | Promise<T>;\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\nexport type NormalizedSchemaInput<TSchema extends InteropZodObject | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends Record<string, unknown> ? TSchema & AgentBuiltInState : AgentBuiltInState;\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = (TState & {\n jumpTo?: JumpToTarget;\n}) | void;\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<TState extends Record<string, unknown> = Record<string, unknown>, TContext = unknown> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n */\n tool: ClientTool | ServerTool;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, \n/**\n * allow to reset the system prompt or system message\n */\n\"systemPrompt\" | \"systemMessage\"> & {\n systemPrompt?: string;\n systemMessage?: SystemMessage;\n}) => PromiseOrValue<AIMessage>;\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage>;\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Base middleware interface.\n */\nexport interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any> {\n /**\n * The name of the middleware.\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>[\"State\"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer S, any, any> ? S extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<S>> : {} : {};\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 */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer S, any, any> ? S extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<S>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined] ? [B] extends [undefined] ? undefined : B | undefined : [B] extends [undefined] ? A | undefined : [A] extends [B] ? A : [B] extends [A] ? B : A & B;\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? MergeContextTypes<InferMiddlewareContextInput<First>, InferMiddlewareContextInputs<Rest>> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;\nexport type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>[\"State\"] : {};\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;KAUKkB,oBAAoBC,IAAIC,QAAQD;AAAhCD,KACOG,iBAAAA,GAAoBf,cADb,CAAA,GAAA,CAAA;AAAMa,KAEbG,qBAFaH,CAAAA,gBAEyBnB,gBAFzBmB,GAAAA,SAAAA,GAAAA,KAAAA,GAAAA,GAAAA,CAAAA,GAAAA,CAEwEI,OAFxEJ,CAAAA,SAAAA,CAAAA,KAAAA,CAAAA,GAEmGH,iBAFnGG,GAEuHI,OAFvHJ,SAEuInB,gBAFvImB,GAE0Jf,qBAF1Je,CAEgLI,OAFhLJ,CAAAA,GAE2LH,iBAF3LG,GAE+MI,OAF/MJ,SAE+NK,MAF/NL,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,GAEyPI,OAFzPJ,GAEmQH,iBAFnQG,GAEuRH,iBAFvRG;;;AAAW;AACxBE,KAKAI,gBALiB,CAAA,MAAA,CAAGnB,GAAAA,CAKQoB,MALRpB,GAAAA;EACpBgB,MAAAA,CAAAA,EAKCR,YALDQ;CAAsCtB,CAAAA,GAAAA,IAAAA;;;;;AAAuJuB,UAWxLI,eAXwLJ,CAAAA,eAWzJC,MAXyJD,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,GAW/HC,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AAA,CAAAA,GACYA,CADZA,SACsB5C,iBADtB4C,GAC0CjE,gBAD1CiE,GAC6DhB,gBAD7DgB,CAC8EA,CAD9EA,CAAAA,CAAAA,OAAAA,CAAAA,GAAAA,CAAAA,CAAAA"}
1
+ {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodInput","InferInteropZodOutput","InteropZodToStateDefinition","AnnotationRoot","AIMessage","SystemMessage","ToolMessage","ToolCall","Command","ClientTool","ServerTool","JumpToTarget","Runtime","AgentBuiltInState","ModelRequest","PromiseOrValue","T","Promise","AnyAnnotationRoot","NormalizedSchemaInput","TSchema","Record","MiddlewareResult","TState","ToolCallRequest","TContext","ToolCallHandler","WrapToolCallHook","WrapModelCallHandler","Omit","WrapModelCallHook","BeforeAgentHandler","Partial","BeforeAgentHook","BeforeModelHandler","BeforeModelHook","AfterModelHandler","AfterModelHook","AfterAgentHandler","AfterAgentHook","MIDDLEWARE_BRAND","AgentMiddleware","TContextSchema","TFullContext","FilterPrivateProps","K","InferChannelType","ToAnnotationRoot","InferMiddlewareState","S","InferMiddlewareInputState","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","C","InferMiddlewareContextInput","Inner","InferMiddlewareContexts","MergeContextTypes","A","B","InferMiddlewareContextInputs","InferContextInput","ContextSchema","InferSchemaInput"],"sources":["../../../src/agents/middleware/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodInput, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot } from \"@langchain/langgraph\";\nimport type { AIMessage, SystemMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\ntype PromiseOrValue<T> = T | Promise<T>;\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\nexport type NormalizedSchemaInput<TSchema extends InteropZodObject | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends Record<string, unknown> ? TSchema & AgentBuiltInState : AgentBuiltInState;\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = (TState & {\n jumpTo?: JumpToTarget;\n}) | void;\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<TState extends Record<string, unknown> = Record<string, unknown>, TContext = unknown> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n */\n tool: ClientTool | ServerTool;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, \n/**\n * allow to reset the system prompt or system message\n */\n\"systemPrompt\" | \"systemMessage\"> & {\n systemPrompt?: string;\n systemMessage?: SystemMessage;\n}) => PromiseOrValue<AIMessage>;\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage>;\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<TSchema extends InteropZodObject | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n};\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport declare const MIDDLEWARE_BRAND: unique symbol;\n/**\n * Base middleware interface.\n */\nexport interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any> {\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 * The name of the middleware.\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>[\"State\"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer S, any, any> ? S extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<S>> : {} : {};\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 */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer S, any, any> ? S extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<S>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> = InferMiddlewareStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer C, any> ? C extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : C extends InteropZodObject ? InferInteropZodInput<C> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined] ? [B] extends [undefined] ? undefined : B | undefined : [B] extends [undefined] ? A | undefined : [A] extends [B] ? A : [B] extends [A] ? B : A & B;\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? MergeContextTypes<InferMiddlewareContextInput<First>, InferMiddlewareContextInputs<Rest>> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;\nexport type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>[\"State\"] : {};\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;KAUKkB,oBAAoBC,IAAIC,QAAQD;AAAhCD,KACOG,iBAAAA,GAAoBf,cADb,CAAA,GAAA,CAAA;AAAMa,KAEbG,qBAFaH,CAAAA,gBAEyBnB,gBAFzBmB,GAAAA,SAAAA,GAAAA,KAAAA,GAAAA,GAAAA,CAAAA,GAAAA,CAEwEI,OAFxEJ,CAAAA,SAAAA,CAAAA,KAAAA,CAAAA,GAEmGH,iBAFnGG,GAEuHI,OAFvHJ,SAEuInB,gBAFvImB,GAE0Jf,qB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AAAA;;;;AAA6B5D,KADlI+D,iBACkI/D,CAAAA,sBAD1Fe,iBAC0Ff,GADtEN,gBACsEM,CAAAA,GADlDgE,aACkDhE,SAD5BN,gBAC4BM,GADTH,oBACSG,CADYgE,aACZhE,CAAAA,GAD6BgE,aAC7BhE,SADmDe,iBACnDf,GADuE4C,gBACvE5C,CADwFgE,aACxFhE,CAAAA,CAAAA,OAAAA,CAAAA,GAAAA,CAAAA,CAAAA;AAAc,KAAhJ4C,gBAAgJ,CAAA,UAArH7B,iBAAqH,GAAjGrB,gBAAiG,CAAA,GAA7EkE,CAA6E,SAAnE7C,iBAAmE,GAA/C6C,CAA+C,GAA3CA,CAA2C,SAAjClE,gBAAiC,GAAdM,cAAc,CAACD,2BAAD,CAA6B6D,CAA7B,CAAA,CAAA,GAAA,KAAA;AAChJK,KAAAA,gBAAgB,CAAAL,UAAW7C,iBAAX,GAA+BrB,gBAA/B,GAAA,SAAA,CAAA,GAA+DkE,CAA/D,SAAyE7C,iBAAzE,GAA6FrB,gBAA7F,GAAgHkD,gBAAhH,CAAiIgB,CAAjI,CAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA"}
@@ -153,10 +153,21 @@ type AfterAgentHook<TSchema extends InteropZodObject | undefined = undefined, TC
153
153
  hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
154
154
  canJumpTo?: JumpToTarget[];
155
155
  };
156
+ /**
157
+ * Unique symbol used to brand middleware instances.
158
+ * This prevents functions from being accidentally assignable to AgentMiddleware
159
+ * since functions have a 'name' property that would otherwise make them structurally compatible.
160
+ */
161
+ declare const MIDDLEWARE_BRAND: unique symbol;
156
162
  /**
157
163
  * Base middleware interface.
158
164
  */
159
165
  interface AgentMiddleware<TSchema extends InteropZodObject | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any> {
166
+ /**
167
+ * Brand property to distinguish middleware instances from plain objects or functions.
168
+ * This is required and prevents accidental assignment of functions to middleware arrays.
169
+ */
170
+ readonly [MIDDLEWARE_BRAND]: true;
160
171
  /**
161
172
  * The name of the middleware.
162
173
  */
@@ -368,5 +379,5 @@ type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObjec
368
379
  type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
369
380
  type InferSchemaInput<A extends AnyAnnotationRoot | InteropZodObject | undefined> = A extends AnyAnnotationRoot | InteropZodObject ? ToAnnotationRoot<A>["State"] : {};
370
381
  //#endregion
371
- export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
382
+ export { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, MIDDLEWARE_BRAND, MiddlewareResult, NormalizedSchemaInput, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook };
372
383
  //# sourceMappingURL=types.d.ts.map