langchain 1.4.1 → 1.4.4

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 (104) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/agents/ReactAgent.cjs +15 -1
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.d.cts +2 -2
  5. package/dist/agents/ReactAgent.d.cts.map +1 -1
  6. package/dist/agents/ReactAgent.d.ts +2 -2
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +16 -2
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/annotation.cjs.map +1 -1
  11. package/dist/agents/annotation.js.map +1 -1
  12. package/dist/agents/index.cjs.map +1 -1
  13. package/dist/agents/index.d.cts +28 -28
  14. package/dist/agents/index.d.cts.map +1 -1
  15. package/dist/agents/index.d.ts +28 -28
  16. package/dist/agents/index.d.ts.map +1 -1
  17. package/dist/agents/index.js.map +1 -1
  18. package/dist/agents/middleware/contextEditing.d.cts +1 -1
  19. package/dist/agents/middleware/contextEditing.d.ts +1 -1
  20. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +1 -1
  21. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +1 -1
  22. package/dist/agents/middleware/hitl.d.cts +1 -1
  23. package/dist/agents/middleware/hitl.d.ts +1 -1
  24. package/dist/agents/middleware/llmToolSelector.d.cts +1 -1
  25. package/dist/agents/middleware/llmToolSelector.d.ts +1 -1
  26. package/dist/agents/middleware/modelCallLimit.d.cts +1 -1
  27. package/dist/agents/middleware/modelCallLimit.d.ts +1 -1
  28. package/dist/agents/middleware/modelFallback.d.cts +1 -1
  29. package/dist/agents/middleware/modelFallback.d.ts +1 -1
  30. package/dist/agents/middleware/modelRetry.d.cts +1 -1
  31. package/dist/agents/middleware/modelRetry.d.ts +1 -1
  32. package/dist/agents/middleware/pii.d.cts +1 -1
  33. package/dist/agents/middleware/pii.d.ts +1 -1
  34. package/dist/agents/middleware/piiRedaction.d.cts +1 -1
  35. package/dist/agents/middleware/piiRedaction.d.ts +1 -1
  36. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +1 -1
  37. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +1 -1
  38. package/dist/agents/middleware/summarization.d.cts +1 -1
  39. package/dist/agents/middleware/summarization.d.ts +1 -1
  40. package/dist/agents/middleware/todoListMiddleware.cjs +3 -1
  41. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  42. package/dist/agents/middleware/todoListMiddleware.d.cts +1 -1
  43. package/dist/agents/middleware/todoListMiddleware.d.ts +1 -1
  44. package/dist/agents/middleware/todoListMiddleware.js +3 -1
  45. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  46. package/dist/agents/middleware/toolCallLimit.d.cts +1 -1
  47. package/dist/agents/middleware/toolCallLimit.d.ts +1 -1
  48. package/dist/agents/middleware/toolEmulator.d.cts +1 -1
  49. package/dist/agents/middleware/toolEmulator.d.ts +1 -1
  50. package/dist/agents/middleware/toolRetry.d.cts +1 -1
  51. package/dist/agents/middleware/toolRetry.d.ts +1 -1
  52. package/dist/agents/middleware/types.cjs.map +1 -1
  53. package/dist/agents/middleware/types.d.cts +41 -18
  54. package/dist/agents/middleware/types.d.cts.map +1 -1
  55. package/dist/agents/middleware/types.d.ts +41 -18
  56. package/dist/agents/middleware/types.d.ts.map +1 -1
  57. package/dist/agents/middleware/types.js.map +1 -1
  58. package/dist/agents/middleware.cjs +4 -1
  59. package/dist/agents/middleware.cjs.map +1 -1
  60. package/dist/agents/middleware.d.cts +10 -3
  61. package/dist/agents/middleware.d.cts.map +1 -1
  62. package/dist/agents/middleware.d.ts +10 -3
  63. package/dist/agents/middleware.d.ts.map +1 -1
  64. package/dist/agents/middleware.js +4 -1
  65. package/dist/agents/middleware.js.map +1 -1
  66. package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
  67. package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
  68. package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
  69. package/dist/agents/nodes/AfterModelNode.js.map +1 -1
  70. package/dist/agents/nodes/AgentNode.cjs +1 -1
  71. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  72. package/dist/agents/nodes/AgentNode.js +1 -1
  73. package/dist/agents/nodes/AgentNode.js.map +1 -1
  74. package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
  75. package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
  76. package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
  77. package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
  78. package/dist/agents/nodes/middleware.cjs +2 -2
  79. package/dist/agents/nodes/middleware.cjs.map +1 -1
  80. package/dist/agents/nodes/middleware.js +3 -3
  81. package/dist/agents/nodes/middleware.js.map +1 -1
  82. package/dist/agents/nodes/utils.cjs +5 -3
  83. package/dist/agents/nodes/utils.cjs.map +1 -1
  84. package/dist/agents/nodes/utils.js +5 -3
  85. package/dist/agents/nodes/utils.js.map +1 -1
  86. package/dist/agents/stream.cjs +27 -1
  87. package/dist/agents/stream.cjs.map +1 -1
  88. package/dist/agents/stream.d.cts.map +1 -1
  89. package/dist/agents/stream.d.ts.map +1 -1
  90. package/dist/agents/stream.js +27 -1
  91. package/dist/agents/stream.js.map +1 -1
  92. package/dist/agents/types.d.cts +24 -12
  93. package/dist/agents/types.d.cts.map +1 -1
  94. package/dist/agents/types.d.ts +24 -12
  95. package/dist/agents/types.d.ts.map +1 -1
  96. package/dist/agents/utils.cjs +22 -0
  97. package/dist/agents/utils.cjs.map +1 -1
  98. package/dist/agents/utils.js +22 -1
  99. package/dist/agents/utils.js.map +1 -1
  100. package/dist/browser.d.cts +3 -3
  101. package/dist/browser.d.ts +3 -3
  102. package/dist/index.d.cts +3 -3
  103. package/dist/index.d.ts +3 -3
  104. package/package.json +6 -6
@@ -1,7 +1,7 @@
1
1
  import { AgentLanguageModelLike } from "./model.js";
2
2
  import { ResponseFormatInput, ResponseFormatUndefined } from "./responses.js";
3
3
  import { JumpToTarget } from "./constants.js";
4
- import { AgentMiddleware, AnyAnnotationRoot, InferMiddlewareContexts, InferMiddlewareStates, InferSchemaInput, InferSchemaValue } from "./middleware/types.js";
4
+ import { AgentMiddleware, AnyAgentMiddleware, AnyAnnotationRoot, InferMiddlewareContexts, InferMiddlewareStates, InferSchemaInput, InferSchemaValue } from "./middleware/types.js";
5
5
  import { BaseMessage, MessageStructure, MessageToolDefinition, SystemMessage } from "@langchain/core/messages";
6
6
  import { ClientTool, DynamicStructuredTool, ServerTool, StructuredToolInterface } from "@langchain/core/tools";
7
7
  import { END, START, StateDefinitionInit, StateGraph, StreamTransformer } from "@langchain/langgraph";
@@ -34,10 +34,10 @@ import { Messages } from "@langchain/langgraph/";
34
34
  * @typeParam TTools - The combined tools type from both `createAgent` tools parameter
35
35
  * and middleware tools. This is a readonly array of `ClientTool | ServerTool`.
36
36
  *
37
- * @typeParam TStreamTransformers - The tuple of user-supplied stream transformer
38
- * factories registered at `createAgent({ streamTransformers })`. Used to type
39
- * `run.extensions` on the stream returned from
40
- * `streamEvents(..., { version: "v3" })`.
37
+ * @typeParam TStreamTransformers - The combined tuple of stream transformer
38
+ * factories from `createAgent({ streamTransformers })` and middleware
39
+ * `streamTransformers`. Used to type `run.extensions` on the stream returned
40
+ * from `streamEvents(..., { version: "v3" })`.
41
41
  *
42
42
  * @example
43
43
  * ```typescript
@@ -55,7 +55,7 @@ import { Messages } from "@langchain/langgraph/";
55
55
  * const agent: ReactAgent<MyAgentTypes> = createAgent({ ... });
56
56
  * ```
57
57
  */
58
- interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = ReadonlyArray<() => StreamTransformer<any>>> {
58
+ interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AnyAgentMiddleware[] = readonly AnyAgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = ReadonlyArray<() => StreamTransformer<any>>> {
59
59
  /** The structured response type when using `responseFormat` */
60
60
  Response: TResponse;
61
61
  /** The custom state schema type */
@@ -82,7 +82,7 @@ interface DefaultAgentTypeConfig extends AgentTypeConfig {
82
82
  Response: Record<string, any>;
83
83
  State: undefined;
84
84
  Context: AnyAnnotationRoot;
85
- Middleware: readonly AgentMiddleware[];
85
+ Middleware: readonly AnyAgentMiddleware[];
86
86
  Tools: readonly (ClientTool | ServerTool)[];
87
87
  StreamTransformers: readonly [];
88
88
  }
@@ -90,16 +90,28 @@ interface DefaultAgentTypeConfig extends AgentTypeConfig {
90
90
  * Helper type to infer tools from a single middleware instance.
91
91
  * Extracts the TTools type parameter from AgentMiddleware.
92
92
  */
93
- type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];
93
+ type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools, any> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];
94
+ /**
95
+ * Helper type to infer stream transformers from a single middleware instance.
96
+ */
97
+ type InferMiddlewareStreamTransformers<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, any, infer TStreamTransformers> ? [TStreamTransformers] extends [readonly []] ? readonly [] : TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> ? TStreamTransformers : readonly [] : readonly [];
94
98
  /**
95
99
  * Helper type to infer and merge tools from an array of middleware.
96
100
  * Recursively extracts tools from each middleware and combines them into a single tuple.
97
101
  */
98
- type InferMiddlewareToolsArray<T extends readonly AgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? readonly [...InferMiddlewareTools<First>, ...InferMiddlewareToolsArray<Rest>] : InferMiddlewareTools<First> : readonly [] : readonly [];
102
+ type InferMiddlewareToolsArray<T extends readonly AnyAgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AnyAgentMiddleware[] ? readonly [...InferMiddlewareTools<First>, ...InferMiddlewareToolsArray<Rest>] : InferMiddlewareTools<First> : readonly [] : readonly [];
99
103
  /**
100
104
  * Helper type to combine agent tools with middleware tools into a single readonly array.
101
105
  */
102
- type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];
106
+ type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AnyAgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];
107
+ /**
108
+ * Helper type to infer and merge stream transformers from an array of middleware.
109
+ */
110
+ type InferMiddlewareStreamTransformersArray<T extends readonly AnyAgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AnyAgentMiddleware[] ? readonly [...InferMiddlewareStreamTransformers<First>, ...InferMiddlewareStreamTransformersArray<Rest>] : InferMiddlewareStreamTransformers<First> : readonly [] : readonly [];
111
+ /**
112
+ * Helper type to combine agent stream transformers with middleware stream transformers.
113
+ */
114
+ type CombineStreamTransformers<TAgentStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>>, TMiddleware extends readonly AnyAgentMiddleware[]> = readonly [...TAgentStreamTransformers, ...InferMiddlewareStreamTransformersArray<TMiddleware>];
103
115
  /**
104
116
  * Helper type to extract the tool name, input type, and output type from a tool.
105
117
  * Converts a single tool to a MessageToolDefinition entry.
@@ -650,7 +662,7 @@ type CreateAgentParams<StructuredResponseType extends Record<string, any> = Reco
650
662
  *
651
663
  * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}
652
664
  */
653
- middleware?: readonly AgentMiddleware[];
665
+ middleware?: readonly AnyAgentMiddleware[];
654
666
  /**
655
667
  * An optional name for the agent.
656
668
  */
@@ -734,5 +746,5 @@ type CreateAgentParams<StructuredResponseType extends Record<string, any> = Reco
734
746
  type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;
735
747
  type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;
736
748
  //#endregion
737
- export { AgentTypeConfig, BuiltInState, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall$1 as ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes };
749
+ export { AgentTypeConfig, BuiltInState, CombineStreamTransformers, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall$1 as ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes };
738
750
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/agents/types.ts"],"mappings":";;;;;;;;;;;;;;AA0FA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAAiB,eAAA,mBACG,MAAA,gBAAsB,uBAAA,GACpC,MAAA,gBACA,uBAAA,iBACW,mBAAA,eACX,mBAAA,+BAEa,iBAAA,GAAoB,gBAAA,GACjC,iBAAA,GACA,gBAAA,+BACyB,eAAA,cAA6B,eAAA,6BACjC,UAAA,GAAa,UAAA,gBAClC,UAAA,GACA,UAAA,iCAEwB,aAAA,OAAoB,iBAAA,SAC9C,aAAA,OAAoB,iBAAA;EANtB;EASA,QAAA,EAAU,SAAA;EATgD;EAW1D,KAAA,EAAO,MAAA;EAVkB;EAYzB,OAAA,EAAS,QAAA;EAXL;EAaJ,UAAA,EAAY,WAAA;EAVZ;EAYA,KAAA,EAAO,MAAA;EAZyC;;;;;;EAmBhD,kBAAA,EAAoB,mBAAA;AAAA;;;;;UAOL,sBAAA,SAA+B,eAAA;EAC9C,QAAA,EAAU,MAAA;EACV,KAAA;EACA,OAAA,EAAS,iBAAA;EACT,UAAA,WAAqB,eAAA;EACrB,KAAA,YAAiB,UAAA,GAAa,UAAA;EAC9B,kBAAA;AAAA;;;;;KAOU,oBAAA,WAA+B,eAAA,IACzC,CAAA,SAAU,eAAA,gCACN,MAAA,mBAAyB,UAAA,GAAa,UAAA,MACpC,MAAA;;;;;KAQI,yBAAA,oBAA6C,eAAA,MACvD,CAAA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ASA;;;;;;;;;;EAgME,YAAA,YAAwB,aAAA;EA5KnB;AAMP;;;;;;;;;AAkBA;;;;;AAKA;;;;;;;;;;;AAmBA;;;;;;;;;;;;;;;;;;EA0KE,WAAA,GAAc,YAAA;EAkGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAhEjB,aAAA,GAAgB,aAAA;EAgEhB;;;;EA3DA,YAAA,GAAe,mBAAA;EA8Ef;;;;EAzEA,KAAA,GAAQ,SAAA;EAgJR;;;;;AAMF;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;EAvGE,cAAA,GAAiB,kBAAA;EA4GT;;;;;;EApGR,UAAA,YAAsB,kBAAA;EAyGA;;;EApGtB,IAAA;EAoGmC;;;;EA9FnC,WAAA;;;;;;;EAQA,gBAAA;;;;EAKA,MAAA,GAAS,WAAA;;;;;;;;;;;;;;;;;;;;EAqBT,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqCA,kBAAA,GAAqB,aAAA,OAAoB,iBAAA;AAAA;;;;KAM/B,oBAAA,oBAAwC,cAAA,WAClD,CAAA,mBAAoB,cAAA,4BAChB,IAAA,kBAAsB,cAAA,UACpB,CAAA,GAAI,oBAAA,CAAqB,IAAA,IACzB,CAAA;AAAA,KAGI,mBAAA,4BACV,KAAA,SAAc,UAAA,mEASV,UAAA,CAAW,EAAA,EAAI,CAAA,EAAG,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA"}
@@ -380,6 +380,27 @@ function wrapToolCall(middleware) {
380
380
  return wrappedHandler;
381
381
  }));
382
382
  }
383
+ /**
384
+ * Static LangGraph config keys propagated from ReactAgent defaults onto the
385
+ * compiled inner graph. This ensures values set via `withConfig()` survive
386
+ * LangGraph API loading, which unwraps ReactAgent to `.graph` before execution.
387
+ */
388
+ const GRAPH_DEFAULT_CONFIG_KEYS = [
389
+ "tags",
390
+ "metadata",
391
+ "runName",
392
+ "maxConcurrency",
393
+ "recursionLimit",
394
+ "configurable"
395
+ ];
396
+ function toGraphDefaultConfig(config) {
397
+ const result = {};
398
+ for (const key of GRAPH_DEFAULT_CONFIG_KEYS) {
399
+ const value = config[key];
400
+ if (value !== void 0) result[key] = value;
401
+ }
402
+ return result;
403
+ }
383
404
  //#endregion
384
405
  exports._addInlineAgentName = _addInlineAgentName;
385
406
  exports._removeInlineAgentName = _removeInlineAgentName;
@@ -387,6 +408,7 @@ exports.bindTools = bindTools;
387
408
  exports.hasToolCalls = hasToolCalls;
388
409
  exports.isClientTool = isClientTool;
389
410
  exports.normalizeSystemPrompt = normalizeSystemPrompt;
411
+ exports.toGraphDefaultConfig = toGraphDefaultConfig;
390
412
  exports.validateLLMHasNoBoundTools = validateLLMHasNoBoundTools;
391
413
  exports.wrapToolCall = wrapToolCall;
392
414
 
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["StateSchema","AIMessage","AIMessageChunk","Runnable","isBaseChatModel","RunnableBinding","RunnableSequence","isConfigurableModel","MultipleToolsBoundError","SystemMessage","ToolMessage","MiddlewareError"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n isBaseChatModel,\n isConfigurableModel,\n type AgentLanguageModelLike as LanguageModelLike,\n} from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACP,aACA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E;MACP;KACF,EACD,oBACD;;;;AAKD,QAAI,CAACI,yBAAAA,YAAY,WAAW,OAAO,IAAI,EAAA,GAAA,qBAAA,WAAW,OAAO,CACvD,OAAM,IAAI,MACR,uDAAuD,EAAE,KAAK,0CACpB,OAAO,SAClD;AAGH,WAAO;YACA,OAAO;AACd,UAAMC,eAAAA,gBAAgB,KAAK,OAAO,EAAE,KAAK;;;AAG7C,SAAO;GACP,CACH"}
1
+ {"version":3,"file":"utils.cjs","names":["StateSchema","AIMessage","AIMessageChunk","Runnable","isBaseChatModel","RunnableBinding","RunnableSequence","isConfigurableModel","MultipleToolsBoundError","SystemMessage","ToolMessage","MiddlewareError"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n isBaseChatModel,\n isConfigurableModel,\n type AgentLanguageModelLike as LanguageModelLike,\n} from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AnyAgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(middleware: readonly AnyAgentMiddleware[]) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n\n/**\n * Static LangGraph config keys propagated from ReactAgent defaults onto the\n * compiled inner graph. This ensures values set via `withConfig()` survive\n * LangGraph API loading, which unwraps ReactAgent to `.graph` before execution.\n */\nconst GRAPH_DEFAULT_CONFIG_KEYS = [\n \"tags\",\n \"metadata\",\n \"runName\",\n \"maxConcurrency\",\n \"recursionLimit\",\n \"configurable\",\n] as const satisfies readonly (keyof RunnableConfig)[];\n\nexport function toGraphDefaultConfig(\n config: RunnableConfig\n): Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\"> {\n const result: Record<string, unknown> = {};\n for (const key of GRAPH_DEFAULT_CONFIG_KEYS) {\n const value = config[key];\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result as Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\">;\n}\n"],"mappings":";;;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACP,aACA,OACyB;AAEzB,KAAIA,qBAAAA,YAAY,WAAW,YAAY,EAAE;EACvC,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,YAAY,OAAO,CAC/C,KAAI,OAAO,MACT,QAAO,OAAO,MAAM;AAGxB,SAAO;;AAIT,MAAA,GAAA,4BAAA,oBAAuB,YAAY,CACjC,SAAA,GAAA,4BAAA,cAAoB,aAAiC,MAAM;AAG7D,OAAM,IAAI,MAAM,8BAA8B,OAAO,cAAc;;;;;;;;;;;;;;;;AAmBrE,SAAgB,oBACd,SACe;AACf,KAAI,CAACC,yBAAAA,UAAU,WAAW,QAAQ,IAAIC,yBAAAA,eAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,SAAS;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,yBAAAA,UAAU;EACnB,GAAG,QAAQ;EACX,SAAS,SAAS,KAAK,kBAAkB,QAAQ,QAAQ;EACzD,MAAM,KAAA;EACP,CAAC;CAGJ,MAAM,iBAAiB,EAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;AACpC,oBAAkB;AAClB,iBAAe,KACb,SAAS,KAAK,kBAAkB,aAAa,YAC9C;YAED,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;AACA,oBAAkB;AAClB,iBAAe,KAAK;GAClB,GAAG;GACH,MAAM,SAAS,KAAK,kBAAkB,aAAa,KAAK;GACzD,CAAC;OAEF,gBAAe,KAAK,aAAa;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O,QAAQ;KACb,GAAG;KACH,OAAO;KACR,CAAC;;AAGJ,OAAI;IACF,MAAM,SAAS,MAAM,gBACnB;KACE,GAAG;KAIH,OAAO;MACL,UAAU,cAAc;MACxB,GAAI,EAAE,cACF,qBAAqB,EAAE,aAAa,EAAE,GAAG,eAAe,CAAC,GACzD,EAAE;MACP;KACF,EACD,oBACD;;;;AAKD,QAAI,CAACI,yBAAAA,YAAY,WAAW,OAAO,IAAI,EAAA,GAAA,qBAAA,WAAW,OAAO,CACvD,OAAM,IAAI,MACR,uDAAuD,EAAE,KAAK,0CACpB,OAAO,SAClD;AAGH,WAAO;YACA,OAAO;AACd,UAAMC,eAAAA,gBAAgB,KAAK,OAAO,EAAE,KAAK;;;AAG7C,SAAO;GACP,CACH;;;;;;;AAQH,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAgB,qBACd,QACwD;CACxD,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,OAAO,2BAA2B;EAC3C,MAAM,QAAQ,OAAO;AACrB,MAAI,UAAU,KAAA,EACZ,QAAO,OAAO;;AAGlB,QAAO"}
@@ -379,7 +379,28 @@ function wrapToolCall(middleware) {
379
379
  return wrappedHandler;
380
380
  }));
381
381
  }
382
+ /**
383
+ * Static LangGraph config keys propagated from ReactAgent defaults onto the
384
+ * compiled inner graph. This ensures values set via `withConfig()` survive
385
+ * LangGraph API loading, which unwraps ReactAgent to `.graph` before execution.
386
+ */
387
+ const GRAPH_DEFAULT_CONFIG_KEYS = [
388
+ "tags",
389
+ "metadata",
390
+ "runName",
391
+ "maxConcurrency",
392
+ "recursionLimit",
393
+ "configurable"
394
+ ];
395
+ function toGraphDefaultConfig(config) {
396
+ const result = {};
397
+ for (const key of GRAPH_DEFAULT_CONFIG_KEYS) {
398
+ const value = config[key];
399
+ if (value !== void 0) result[key] = value;
400
+ }
401
+ return result;
402
+ }
382
403
  //#endregion
383
- export { _addInlineAgentName, _removeInlineAgentName, bindTools, hasToolCalls, isClientTool, normalizeSystemPrompt, validateLLMHasNoBoundTools, wrapToolCall };
404
+ export { _addInlineAgentName, _removeInlineAgentName, bindTools, hasToolCalls, isClientTool, normalizeSystemPrompt, toGraphDefaultConfig, validateLLMHasNoBoundTools, wrapToolCall };
384
405
 
385
406
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n isBaseChatModel,\n isConfigurableModel,\n type AgentLanguageModelLike as LanguageModelLike,\n} from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(\n middleware: readonly AgentMiddleware<InteropZodObject | undefined>[]\n) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n"],"mappings":";;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACP,aACA,OACyB;AAEzB,KAAI,YAAY,WAAW,YAAY,EAAE;EACvC,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,YAAY,OAAO,CAC/C,KAAI,OAAO,MACT,QAAO,OAAO,MAAM;AAGxB,SAAO;;AAIT,KAAI,mBAAmB,YAAY,CACjC,QAAO,aAAa,aAAiC,MAAM;AAG7D,OAAM,IAAI,MAAM,8BAA8B,OAAO,cAAc;;;;;;;;;;;;;;;;AAmBrE,SAAgB,oBACd,SACe;AACf,KAAI,CAAC,UAAU,WAAW,QAAQ,IAAI,eAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAA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AE3E,KAAI,2BAA2B,WAAW,EACxC;AAGF,QAAO,sBACL,2BAA2B,KAAK,MAAM;EACpC,MAAM,kBAAkB,EAAE;;;;EAI1B,MAAM,iBAAmC,OAAO,SAAS,YAAY;;;;;;;GAOnE,MAAM,gBAAgB,QAAQ;;;;;GAM9B,MAAM,sBAAuC,OAAO,kBAAkB;;;;;;IAMpE,MAAM,cAAc;KAClB,GAAG;KACH,GAAG,cAAc;KAClB;AACD,WAAO,QAAQ;KACb,GAAG;KACH,OAAO;KACR,CAAC;;AAGJ,OAAI;IACF,MAAM,SAAS,MAAM,gBACnB;KACE,GAAG;KAIH,OAAO;MACL,UAAU,cAAc;MACxB,GAAI,EAAE,cACF,qBAAqB,EAAE,aAAa,EAAE,GAAG,eAAe,CAAC,GACzD,EAAE;MACP;KACF,EACD,oBACD;;;;AAKD,QAAI,CAAC,YAAY,WAAW,OAAO,IAAI,CAAC,UAAU,OAAO,CACvD,OAAM,IAAI,MACR,uDAAuD,EAAE,KAAK,0CACpB,OAAO,SAClD;AAGH,WAAO;YACA,OAAO;AACd,UAAM,gBAAgB,KAAK,OAAO,EAAE,KAAK;;;AAG7C,SAAO;GACP,CACH"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { isCommand, StateSchema } from \"@langchain/langgraph\";\nimport {\n type InteropZodObject,\n interopParse,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n BaseChatModel,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport { BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n isBaseChatModel,\n isConfigurableModel,\n type AgentLanguageModelLike as LanguageModelLike,\n} from \"./model.js\";\nimport { MultipleToolsBoundError, MiddlewareError } from \"./errors.js\";\nimport type { AgentBuiltInState } from \"./runtime.js\";\nimport type {\n ToolCallHandler,\n AnyAgentMiddleware,\n ToolCallRequest,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\n/**\n * Parse middleware state from the full agent state based on the middleware's stateSchema.\n *\n * Handles two types of state schemas:\n * 1. Zod schemas (v3 or v4) - parsed using interopParse\n * 2. LangGraph StateSchema - extracts only the keys defined in `fields`\n *\n * @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema)\n * @param state - The full agent state to parse from\n * @returns Parsed state containing only the keys defined in the schema\n */\nfunction parseMiddlewareState(\n stateSchema: unknown,\n state: Record<string, unknown>\n): Record<string, unknown> {\n // Handle LangGraph StateSchema (has `fields` property)\n if (StateSchema.isInstance(stateSchema)) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(stateSchema.fields)) {\n if (key in state) {\n result[key] = state[key];\n }\n }\n return result;\n }\n\n // Handle Zod schemas using interopParse\n if (isInteropZodSchema(stateSchema)) {\n return interopParse(stateSchema as InteropZodObject, state);\n }\n\n throw new Error(`Invalid state schema type: ${typeof stateSchema}`);\n}\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\n/**\n * Helper function to check if a language model has a bindTools method.\n * @param llm - The language model to check if it has a bindTools method.\n * @returns True if the language model has a bindTools method, false otherwise.\n */\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(message?: BaseMessage): boolean {\n return Boolean(\n AIMessage.isInstance(message) &&\n message.tool_calls &&\n message.tool_calls.length > 0\n );\n}\n\n/**\n * Normalizes a system prompt to a SystemMessage object.\n * If it's already a SystemMessage, returns it as-is.\n * If it's a string, converts it to a SystemMessage.\n * If it's undefined, creates an empty system message so it is easier to append to it later.\n */\nexport function normalizeSystemPrompt(\n systemPrompt?: string | SystemMessage\n): SystemMessage {\n if (systemPrompt == null) {\n return new SystemMessage(\"\");\n }\n if (SystemMessage.isInstance(systemPrompt)) {\n return systemPrompt;\n }\n if (typeof systemPrompt === \"string\") {\n return new SystemMessage({\n content: [{ type: \"text\", text: systemPrompt }],\n });\n }\n throw new Error(\n `Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`\n );\n}\n\n/**\n * Helper function to bind tools to a language model.\n * @param llm - The language model to bind tools to.\n * @param toolClasses - The tools to bind to the language model.\n * @param options - The options to pass to the language model.\n * @returns The language model with the tools bound to it.\n */\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(\n await llm._getModelInstance(),\n toolClasses,\n options\n );\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Compose multiple wrapToolCall handlers into a single middleware stack.\n *\n * Composes handlers so the first in the list becomes the outermost layer.\n * Each handler receives a handler callback to execute inner layers.\n *\n * @param handlers - List of handlers. First handler wraps all others.\n * @returns Composed handler, or undefined if handlers array is empty.\n *\n * @example\n * ```typescript\n * // handlers=[auth, retry] means: auth wraps retry\n * // Flow: auth calls retry, retry calls base handler\n * const auth: ToolCallWrapper = async (request, handler) => {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (error.message === \"Unauthorized\") {\n * await refreshToken();\n * return await handler(request);\n * }\n * throw error;\n * }\n * };\n *\n * const retry: ToolCallWrapper = async (request, handler) => {\n * for (let attempt = 0; attempt < 3; attempt++) {\n * try {\n * return await handler(request);\n * } catch (error) {\n * if (attempt === 2) throw error;\n * }\n * }\n * throw new Error(\"Unreachable\");\n * };\n *\n * const composedHandler = chainToolCallHandlers([auth, retry]);\n * ```\n */\nfunction chainToolCallHandlers(\n handlers: WrapToolCallHook[]\n): WrapToolCallHook | undefined {\n if (handlers.length === 0) {\n return undefined;\n }\n\n if (handlers.length === 1) {\n return handlers[0];\n }\n\n // Compose two handlers where outer wraps inner\n // The key is to properly propagate request modifications through the chain\n function composeTwo(\n outer: WrapToolCallHook,\n inner: WrapToolCallHook\n ): WrapToolCallHook {\n return async (request, handler) => {\n // Create a wrapper that calls inner with the base handler\n // The innerHandler receives the (possibly modified) request from outer\n // and passes it to inner, which then calls the base handler\n const innerHandler: ToolCallHandler = async (passedRequest) => {\n // inner receives the request passed by outer (which may be modified)\n return inner(passedRequest, handler);\n };\n\n // Call outer with the wrapped inner as its handler\n return outer(request, innerHandler);\n };\n }\n\n // Compose right-to-left: outer(inner(innermost(handler)))\n let result = handlers[handlers.length - 1];\n for (let i = handlers.length - 2; i >= 0; i--) {\n result = composeTwo(handlers[i], result);\n }\n\n return result;\n}\n\n/**\n * Wrapping `wrapToolCall` invocation so we can inject middleware name into\n * the error message.\n *\n * @param middleware list of middleware passed to the agent\n * @param state state of the agent\n * @returns single wrap function\n */\nexport function wrapToolCall(middleware: readonly AnyAgentMiddleware[]) {\n const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall);\n\n if (middlewareWithWrapToolCall.length === 0) {\n return;\n }\n\n return chainToolCallHandlers(\n middlewareWithWrapToolCall.map((m) => {\n const originalHandler = m.wrapToolCall!;\n /**\n * Wrap with error handling and validation\n */\n const wrappedHandler: WrapToolCallHook = async (request, handler) => {\n /**\n * Capture the original state for this middleware's schema parsing.\n * This is important because the request may be modified (via override)\n * as it passes through the middleware chain, but each middleware\n * should always see the full original state for its schema parsing.\n */\n const originalState = request.state;\n\n /**\n * Create a handler that preserves state parsing for this middleware\n * while allowing tool/toolCall/state modifications from inner middleware\n */\n const wrappedInnerHandler: ToolCallHandler = async (passedRequest) => {\n /**\n * Merge the passed request with the original state for parsing.\n * This ensures middleware can override tool/toolCall while\n * maintaining proper state parsing for each middleware in the chain.\n */\n const mergedState = {\n ...originalState,\n ...passedRequest.state,\n };\n return handler({\n ...passedRequest,\n state: mergedState,\n });\n };\n\n try {\n const result = await originalHandler(\n {\n ...request,\n /**\n * override state with the state from the specific middleware\n */\n state: {\n messages: originalState.messages,\n ...(m.stateSchema\n ? parseMiddlewareState(m.stateSchema, { ...originalState })\n : {}),\n },\n } as ToolCallRequest<AgentBuiltInState, unknown>,\n wrappedInnerHandler\n );\n\n /**\n * Validate return type\n */\n if (!ToolMessage.isInstance(result) && !isCommand(result)) {\n throw new Error(\n `Invalid response from \"wrapToolCall\" in middleware \"${m.name}\": ` +\n `expected ToolMessage or Command, got ${typeof result}`\n );\n }\n\n return result;\n } catch (error) {\n throw MiddlewareError.wrap(error, m.name);\n }\n };\n return wrappedHandler;\n })\n );\n}\n\n/**\n * Static LangGraph config keys propagated from ReactAgent defaults onto the\n * compiled inner graph. This ensures values set via `withConfig()` survive\n * LangGraph API loading, which unwraps ReactAgent to `.graph` before execution.\n */\nconst GRAPH_DEFAULT_CONFIG_KEYS = [\n \"tags\",\n \"metadata\",\n \"runName\",\n \"maxConcurrency\",\n \"recursionLimit\",\n \"configurable\",\n] as const satisfies readonly (keyof RunnableConfig)[];\n\nexport function toGraphDefaultConfig(\n config: RunnableConfig\n): Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\"> {\n const result: Record<string, unknown> = {};\n for (const key of GRAPH_DEFAULT_CONFIG_KEYS) {\n const value = config[key];\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result as Omit<RunnableConfig, \"store\" | \"writer\" | \"interrupt\">;\n}\n"],"mappings":";;;;;;;AA2CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;AAaxB,SAAS,qBACP,aACA,OACyB;AAEzB,KAAI,YAAY,WAAW,YAAY,EAAE;EACvC,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,YAAY,OAAO,CAC/C,KAAI,OAAO,MACT,QAAO,OAAO,MAAM;AAGxB,SAAO;;AAIT,KAAI,mBAAmB,YAAY,CACjC,QAAO,aAAa,aAAiC,MAAM;AAG7D,OAAM,IAAI,MAAM,8BAA8B,OAAO,cAAc;;;;;;;;;;;;;;;;AAmBrE,SAAgB,oBACd,SACe;AACf,KAAI,CAAC,UAAU,WAAW,QAAQ,IAAI,eAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,SAAS;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAI,UAAU;EACnB,GAAG,QAAQ;EACX,SAAS,SAAS,KAAK,kBAAkB,QAAQ,QAAQ;EACzD,MAAM,KAAA;EACP,CAAC;CAGJ,MAAM,iBAAiB,EAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,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cAAc;KAClB,GAAG;KACH,GAAG,cAAc;KAClB;AACD,WAAO,QAAQ;KACb,GAAG;KACH,OAAO;KACR,CAAC;;AAGJ,OAAI;IACF,MAAM,SAAS,MAAM,gBACnB;KACE,GAAG;KAIH,OAAO;MACL,UAAU,cAAc;MACxB,GAAI,EAAE,cACF,qBAAqB,EAAE,aAAa,EAAE,GAAG,eAAe,CAAC,GACzD,EAAE;MACP;KACF,EACD,oBACD;;;;AAKD,QAAI,CAAC,YAAY,WAAW,OAAO,IAAI,CAAC,UAAU,OAAO,CACvD,OAAM,IAAI,MACR,uDAAuD,EAAE,KAAK,0CACpB,OAAO,SAClD;AAGH,WAAO;YACA,OAAO;AACd,UAAM,gBAAgB,KAAK,OAAO,EAAE,KAAK;;;AAG7C,SAAO;GACP,CACH;;;;;;;AAQH,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAgB,qBACd,QACwD;CACxD,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,OAAO,2BAA2B;EAC3C,MAAM,QAAQ,OAAO;AACrB,MAAI,UAAU,KAAA,EACZ,QAAO,OAAO;;AAGlB,QAAO"}
@@ -5,8 +5,8 @@ import { ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy
5
5
  import { JumpToTarget } from "./agents/constants.cjs";
6
6
  import { Runtime } from "./agents/runtime.cjs";
7
7
  import { ModelRequest } from "./agents/nodes/types.cjs";
8
- import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.cjs";
9
- import { AgentTypeConfig, BuiltInState, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.cjs";
8
+ import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.cjs";
9
+ import { AgentTypeConfig, BuiltInState, CombineStreamTransformers, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.cjs";
10
10
  import { AgentRunStream, ToolCallStreamUnion, createToolCallTransformer } from "./agents/stream.cjs";
11
11
  import { ReactAgent } from "./agents/ReactAgent.cjs";
12
12
  import { createMiddleware } from "./agents/middleware.cjs";
@@ -35,4 +35,4 @@ import { context } from "@langchain/core/utils/context";
35
35
  import { InMemoryStore } from "@langchain/core/stores";
36
36
  import { Document, DocumentInput } from "@langchain/core/documents";
37
37
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
38
- export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
38
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/browser.d.ts CHANGED
@@ -5,8 +5,8 @@ import { ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy
5
5
  import { JumpToTarget } from "./agents/constants.js";
6
6
  import { Runtime } from "./agents/runtime.js";
7
7
  import { ModelRequest } from "./agents/nodes/types.js";
8
- import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.js";
9
- import { AgentTypeConfig, BuiltInState, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.js";
8
+ import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.js";
9
+ import { AgentTypeConfig, BuiltInState, CombineStreamTransformers, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.js";
10
10
  import { AgentRunStream, ToolCallStreamUnion, createToolCallTransformer } from "./agents/stream.js";
11
11
  import { ReactAgent } from "./agents/ReactAgent.js";
12
12
  import { createMiddleware } from "./agents/middleware.js";
@@ -35,4 +35,4 @@ import { context } from "@langchain/core/utils/context";
35
35
  import { InMemoryStore } from "@langchain/core/stores";
36
36
  import { Document, DocumentInput } from "@langchain/core/documents";
37
37
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
38
- export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
38
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/index.d.cts CHANGED
@@ -5,8 +5,8 @@ import { ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy
5
5
  import { JumpToTarget } from "./agents/constants.cjs";
6
6
  import { Runtime } from "./agents/runtime.cjs";
7
7
  import { ModelRequest } from "./agents/nodes/types.cjs";
8
- import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.cjs";
9
- import { AgentTypeConfig, BuiltInState, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.cjs";
8
+ import { AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAgentMiddleware, AnyAnnotationRoot, BeforeAgentHook, BeforeModelHook, DefaultMiddlewareTypeConfig, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, MIDDLEWARE_BRAND, MiddlewareResult, MiddlewareTypeConfig, NormalizedSchemaInput, NormalizedSchemaUpdate, ResolveMiddlewareTypeConfig, ToAnnotationRoot, ToolCallHandler, ToolCallRequest, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook } from "./agents/middleware/types.cjs";
9
+ import { AgentTypeConfig, BuiltInState, CombineStreamTransformers, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes } from "./agents/types.cjs";
10
10
  import { AgentRunStream, ToolCallStreamUnion, createToolCallTransformer } from "./agents/stream.cjs";
11
11
  import { ReactAgent } from "./agents/ReactAgent.cjs";
12
12
  import { createMiddleware } from "./agents/middleware.cjs";
@@ -35,4 +35,4 @@ import { context } from "@langchain/core/utils/context";
35
35
  import { InMemoryStore } from "@langchain/core/stores";
36
36
  import { Document, DocumentInput } from "@langchain/core/documents";
37
37
  import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
38
- export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
38
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AgentRunStream, AgentTypeConfig, AnyAgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContextSchema, InferMiddlewareContexts, InferMiddlewareFullContext, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareSchema, InferMiddlewareState, InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, InferMiddlewareToolsFromConfig, InferMiddlewareType, InferSchemaInput, InferSchemaUpdateType, InferSchemaValue, InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, MiddlewareResult, MiddlewareTypeConfig, ModelCallLimitMiddlewareConfig, ModelRequest, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, NormalizedSchemaUpdate, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, ResolveMiddlewareTypeConfig, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, Todo, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolCallStreamUnion, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, TypedToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };