@langchain/langgraph 1.1.0 → 1.1.2

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/dist/errors.d.cts.map +1 -1
  2. package/dist/graph/annotation.cjs +3 -0
  3. package/dist/graph/annotation.cjs.map +1 -1
  4. package/dist/graph/annotation.d.cts +1 -0
  5. package/dist/graph/annotation.d.cts.map +1 -1
  6. package/dist/graph/annotation.d.ts +1 -0
  7. package/dist/graph/annotation.d.ts.map +1 -1
  8. package/dist/graph/annotation.js +3 -0
  9. package/dist/graph/annotation.js.map +1 -1
  10. package/dist/graph/graph.cjs +3 -3
  11. package/dist/graph/graph.cjs.map +1 -1
  12. package/dist/graph/graph.js +3 -3
  13. package/dist/graph/graph.js.map +1 -1
  14. package/dist/graph/message.d.cts +2 -2
  15. package/dist/graph/message.d.cts.map +1 -1
  16. package/dist/graph/message.d.ts +2 -2
  17. package/dist/graph/message.d.ts.map +1 -1
  18. package/dist/graph/messages_annotation.d.cts +5 -5
  19. package/dist/graph/messages_annotation.d.cts.map +1 -1
  20. package/dist/graph/messages_annotation.d.ts +5 -5
  21. package/dist/graph/messages_annotation.d.ts.map +1 -1
  22. package/dist/graph/state.cjs +98 -78
  23. package/dist/graph/state.cjs.map +1 -1
  24. package/dist/graph/state.d.cts +68 -35
  25. package/dist/graph/state.d.cts.map +1 -1
  26. package/dist/graph/state.d.ts +68 -35
  27. package/dist/graph/state.d.ts.map +1 -1
  28. package/dist/graph/state.js +99 -79
  29. package/dist/graph/state.js.map +1 -1
  30. package/dist/graph/types.cjs +41 -0
  31. package/dist/graph/types.cjs.map +1 -0
  32. package/dist/graph/types.d.cts +247 -18
  33. package/dist/graph/types.d.cts.map +1 -1
  34. package/dist/graph/types.d.ts +247 -18
  35. package/dist/graph/types.d.ts.map +1 -1
  36. package/dist/graph/types.js +40 -0
  37. package/dist/graph/types.js.map +1 -0
  38. package/dist/graph/zod/meta.cjs +4 -4
  39. package/dist/graph/zod/meta.cjs.map +1 -1
  40. package/dist/graph/zod/meta.js +4 -4
  41. package/dist/graph/zod/meta.js.map +1 -1
  42. package/dist/graph/zod/zod-registry.d.cts.map +1 -1
  43. package/dist/graph/zod/zod-registry.d.ts.map +1 -1
  44. package/dist/hash.cjs +1 -1
  45. package/dist/hash.cjs.map +1 -1
  46. package/dist/hash.js +1 -1
  47. package/dist/hash.js.map +1 -1
  48. package/dist/index.d.cts +3 -3
  49. package/dist/index.d.ts +3 -3
  50. package/dist/prebuilt/agent_executor.d.cts +5 -5
  51. package/dist/prebuilt/agent_executor.d.cts.map +1 -1
  52. package/dist/prebuilt/agent_executor.d.ts +5 -5
  53. package/dist/prebuilt/agent_executor.d.ts.map +1 -1
  54. package/dist/prebuilt/react_agent_executor.cjs +12 -12
  55. package/dist/prebuilt/react_agent_executor.cjs.map +1 -1
  56. package/dist/prebuilt/react_agent_executor.d.cts +3 -3
  57. package/dist/prebuilt/react_agent_executor.d.cts.map +1 -1
  58. package/dist/prebuilt/react_agent_executor.d.ts +3 -3
  59. package/dist/prebuilt/react_agent_executor.d.ts.map +1 -1
  60. package/dist/prebuilt/react_agent_executor.js +12 -12
  61. package/dist/prebuilt/react_agent_executor.js.map +1 -1
  62. package/dist/prebuilt/tool_node.cjs +1 -1
  63. package/dist/prebuilt/tool_node.cjs.map +1 -1
  64. package/dist/prebuilt/tool_node.js +1 -1
  65. package/dist/prebuilt/tool_node.js.map +1 -1
  66. package/dist/pregel/debug.cjs +9 -9
  67. package/dist/pregel/debug.cjs.map +1 -1
  68. package/dist/pregel/debug.js +9 -9
  69. package/dist/pregel/debug.js.map +1 -1
  70. package/dist/pregel/index.cjs +44 -44
  71. package/dist/pregel/index.cjs.map +1 -1
  72. package/dist/pregel/index.js +44 -44
  73. package/dist/pregel/index.js.map +1 -1
  74. package/dist/pregel/loop.cjs +1 -1
  75. package/dist/pregel/loop.cjs.map +1 -1
  76. package/dist/pregel/loop.js +1 -1
  77. package/dist/pregel/loop.js.map +1 -1
  78. package/dist/pregel/utils/subgraph.cjs +2 -2
  79. package/dist/pregel/utils/subgraph.cjs.map +1 -1
  80. package/dist/pregel/utils/subgraph.js +2 -2
  81. package/dist/pregel/utils/subgraph.js.map +1 -1
  82. package/dist/state/schema.cjs +8 -9
  83. package/dist/state/schema.cjs.map +1 -1
  84. package/dist/state/schema.d.cts +18 -22
  85. package/dist/state/schema.d.cts.map +1 -1
  86. package/dist/state/schema.d.ts +18 -22
  87. package/dist/state/schema.d.ts.map +1 -1
  88. package/dist/state/schema.js +8 -9
  89. package/dist/state/schema.js.map +1 -1
  90. package/dist/state/values/reduced.cjs.map +1 -1
  91. package/dist/state/values/reduced.d.cts +1 -1
  92. package/dist/state/values/reduced.d.cts.map +1 -1
  93. package/dist/state/values/reduced.d.ts +1 -1
  94. package/dist/state/values/reduced.d.ts.map +1 -1
  95. package/dist/state/values/reduced.js.map +1 -1
  96. package/dist/state/values/untracked.cjs.map +1 -1
  97. package/dist/state/values/untracked.d.cts +4 -0
  98. package/dist/state/values/untracked.d.cts.map +1 -1
  99. package/dist/state/values/untracked.d.ts +4 -0
  100. package/dist/state/values/untracked.d.ts.map +1 -1
  101. package/dist/state/values/untracked.js.map +1 -1
  102. package/dist/web.d.cts +3 -3
  103. package/dist/web.d.ts +3 -3
  104. package/package.json +6 -6
@@ -1,9 +1,10 @@
1
1
  import { InteropZodToStateDefinition } from "./zod/meta.js";
2
- import { Runtime } from "../pregel/runnable_types.js";
2
+ import { LangGraphRunnableConfig } from "../pregel/runnable_types.js";
3
3
  import { AnnotationRoot, StateDefinition, StateType, UpdateType } from "./annotation.js";
4
4
  import { CommandInstance, END, Send } from "../constants.js";
5
5
  import { AnyStateSchema, StateSchema, StateSchemaFieldsToStateDefinition } from "../state/schema.js";
6
6
  import { InteropZodObject } from "@langchain/core/utils/types";
7
+ import { StandardSchemaV1 } from "@standard-schema/spec";
7
8
 
8
9
  //#region src/graph/types.d.ts
9
10
 
@@ -12,13 +13,72 @@ import { InteropZodObject } from "@langchain/core/utils/types";
12
13
  *
13
14
  * @internal
14
15
  */
15
- type ToStateDefinition<T> = T extends StateSchema<infer TInit> ? StateSchemaFieldsToStateDefinition<TInit> : T extends InteropZodObject ? InteropZodToStateDefinition<T> : T extends StateDefinition ? T : never;
16
+ type ToStateDefinition<T> = T extends StateSchema<infer TInit> ? StateSchemaFieldsToStateDefinition<TInit> : T extends AnnotationRoot<infer SD> ? SD : T extends InteropZodObject ? InteropZodToStateDefinition<T> : T extends StateDefinition ? T : never;
16
17
  /**
17
18
  * Type for schema types that can be used to initialize state.
19
+ * Supports all valid schema types: StateDefinition, Zod objects, StateSchema, and AnnotationRoot.
18
20
  *
19
21
  * @internal
20
22
  */
21
- type StateDefinitionInit = StateDefinition | InteropZodObject | AnyStateSchema;
23
+ type StateDefinitionInit = StateDefinition | InteropZodObject | AnyStateSchema | AnnotationRoot<any>;
24
+ /**
25
+ * Check if a value is a valid StateDefinitionInit type.
26
+ * Supports: StateSchema, InteropZodObject (Zod), AnnotationRoot, StateDefinition
27
+ *
28
+ * @internal
29
+ */
30
+
31
+ /**
32
+ * Valid types for context schema.
33
+ * Context doesn't have channels/reducers, so StateSchema is NOT supported.
34
+ * Supports StandardSchemaV1 (Zod, Valibot, etc.) and AnnotationRoot (backward compat).
35
+ *
36
+ * @internal
37
+ */
38
+ type ContextSchemaInit = StandardSchemaV1 | AnnotationRoot<StateDefinition>;
39
+ /**
40
+ * Initialization options for StateGraph.
41
+ * Accepts any combination of schema types for state/input/output.
42
+ *
43
+ * Supports both `state` and `stateSchema` as aliases for backward compatibility.
44
+ * If only `input` is provided (no state/stateSchema), `input` is used as the state schema.
45
+ *
46
+ * @template SD - State definition type
47
+ * @template I - Input definition type (defaults to undefined)
48
+ * @template O - Output definition type (defaults to undefined)
49
+ * @template C - Context schema type (defaults to undefined)
50
+ * @template N - Node name union type (defaults to string)
51
+ * @template InterruptType - Interrupt type (defaults to unknown)
52
+ * @template WriterType - Writer type (defaults to unknown)
53
+ */
54
+ type StateGraphInit<SD extends StateDefinitionInit = StateDefinitionInit, I extends StateDefinitionInit | undefined = undefined, O extends StateDefinitionInit | undefined = undefined, C extends StateDefinitionInit | undefined = undefined, N extends string = string, InterruptType = unknown, WriterType = unknown> = {
55
+ /** Primary key for state schema */
56
+ state?: SD;
57
+ /**
58
+ * @deprecated Use `state` instead. Will be removed in a future version.
59
+ */
60
+ stateSchema?: SD;
61
+ input?: I;
62
+ output?: O;
63
+ /** Context schema for runtime configuration validation. Does not support StateSchema. */
64
+ context?: C;
65
+ interrupt?: InterruptType;
66
+ writer?: WriterType;
67
+ nodes?: N[];
68
+ };
69
+ /**
70
+ * Options for the second argument when passing a direct schema.
71
+ * Excludes `state` and `stateSchema` since those come from the first arg.
72
+ *
73
+ * @internal
74
+ */
75
+ type StateGraphOptions<I extends StateDefinitionInit | undefined = undefined, O extends StateDefinitionInit | undefined = undefined, C extends StateDefinitionInit | undefined = undefined, N extends string = string, InterruptType = unknown, WriterType = unknown> = Omit<StateGraphInit<StateDefinitionInit, I, O, C, N, InterruptType, WriterType>, "state" | "stateSchema">;
76
+ /**
77
+ * Check if a value is a StateGraphInit object (has state, stateSchema, or input with valid schema).
78
+ *
79
+ * @internal
80
+ */
81
+
22
82
  /**
23
83
  * Extract the State type from any supported schema type.
24
84
  *
@@ -48,9 +108,88 @@ type ExtractStateType<Schema, Fallback = Schema> = Schema extends AnnotationRoot
48
108
  * @template FallbackBase - Base type for fallback (will be partialized), defaults to Schema
49
109
  */
50
110
  type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends AnnotationRoot<infer SD> ? UpdateType<SD> : UpdateType<ToStateDefinition<Schema>> extends infer U ? [U] extends [never] ? Partial<FallbackBase> : U : Partial<FallbackBase>;
111
+ /**
112
+ * Extract the input type from a type bag, using ExtractStateType on the InputSchema.
113
+ * Falls back to Default if InputSchema is not provided.
114
+ * @internal
115
+ */
116
+ type ExtractBagInput<Bag, Default> = Bag extends {
117
+ InputSchema: infer I;
118
+ } ? ExtractStateType<I> : Default;
119
+ /**
120
+ * Extract the output type from a type bag, using ExtractUpdateType on the OutputSchema.
121
+ * Falls back to Default if OutputSchema is not provided.
122
+ * @internal
123
+ */
124
+ type ExtractBagOutput<Bag, Default> = Bag extends {
125
+ OutputSchema: infer O;
126
+ } ? ExtractUpdateType<O> : Default;
127
+ /**
128
+ * Extract the context type from a type bag, using ExtractStateType on the ContextSchema.
129
+ * Falls back to Default if ContextSchema is not provided.
130
+ * Ensures result extends Record<string, unknown> for LangGraphRunnableConfig compatibility.
131
+ * @internal
132
+ */
133
+ type ExtractBagContext<Bag, Default extends Record<string, unknown>> = Bag extends {
134
+ ContextSchema: infer C;
135
+ } ? ExtractStateType<C> extends infer Ctx ? Ctx extends Record<string, unknown> ? Ctx : Default : Default : Default;
136
+ /**
137
+ * Extract the Nodes type from a type bag.
138
+ * Falls back to Default if Nodes is not provided.
139
+ * @internal
140
+ */
141
+ type ExtractBagNodes<Bag, Default extends string> = Bag extends {
142
+ Nodes: infer N extends string;
143
+ } ? N : Default;
144
+ /**
145
+ * Type bag for GraphNode that accepts schema types.
146
+ * All fields are optional - unspecified fields use defaults.
147
+ *
148
+ * This enables separate input/output schemas for nodes, which is useful when
149
+ * a node receives a subset of state fields and returns different fields.
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const node: GraphNode<{
154
+ * InputSchema: typeof NodeInputSchema;
155
+ * OutputSchema: typeof NodeOutputSchema;
156
+ * ContextSchema: typeof ContextSchema;
157
+ * Nodes: "agent" | "tool";
158
+ * }> = (state, runtime) => {
159
+ * return { answer: `Response to: ${state.query}` };
160
+ * };
161
+ * ```
162
+ */
163
+ interface GraphNodeTypes<InputSchema = unknown, OutputSchema = unknown, ContextSchema = unknown, Nodes extends string = string> {
164
+ /** Schema for node input state (uses ExtractStateType) */
165
+ InputSchema?: InputSchema;
166
+ /** Schema for node output/update (uses ExtractUpdateType) */
167
+ OutputSchema?: OutputSchema;
168
+ /** Schema for runtime context (uses ExtractStateType) */
169
+ ContextSchema?: ContextSchema;
170
+ /** Union of valid node names for Command.goto */
171
+ Nodes?: Nodes;
172
+ }
173
+ /**
174
+ * Detect if T is a type bag (has InputSchema or OutputSchema) or a direct schema.
175
+ * @internal
176
+ */
177
+ type IsGraphNodeTypeBag<T> = T extends {
178
+ InputSchema: unknown;
179
+ } ? true : T extends {
180
+ OutputSchema: unknown;
181
+ } ? true : false;
182
+ /**
183
+ * Return value type for GraphNode functions.
184
+ * Nodes can return an update object, a Command, or a Promise of either.
185
+ *
186
+ * @template Update - The update type (what fields can be returned)
187
+ * @template Nodes - Union of valid node names for Command.goto
188
+ */
189
+ type GraphNodeReturnValue<Update, Nodes extends string = string> = Update | CommandInstance<unknown, Update, Nodes> | Promise<Update | CommandInstance<unknown, Update, Nodes>>;
51
190
  /**
52
191
  * Strongly-typed utility for authoring graph nodes outside of the StateGraph builder,
53
- * supporting inference for both state (from Schema) and runtime context (from ContextType).
192
+ * supporting inference for both state (from Schema) and config context (from Context type).
54
193
  *
55
194
  * This type enables you to define graph node functions with full type safety—both
56
195
  * for the evolving state and for additional context that may be passed in at runtime.
@@ -59,11 +198,19 @@ type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends Annotatio
59
198
  * Works with StateSchema, AnnotationRoot, and Zod object schemas for state, and
60
199
  * with a user-defined object shape for context.
61
200
  *
62
- * @template Schema - The state schema type (StateSchema, AnnotationRoot, or InteropZodObject)
63
- * @template Context - The type of the runtime context injected into this node (default: Record<string, unknown>)
201
+ * **Supports two patterns:**
202
+ *
203
+ * 1. **Single schema usage** - Single schema for both input and output:
204
+ * `GraphNode<Schema, Context, Nodes>`
205
+ *
206
+ * 2. **Type bag pattern** - Separate schemas for input, output, context:
207
+ * `GraphNode<{ InputSchema; OutputSchema; ContextSchema; Nodes }>`
208
+ *
209
+ * @template Schema - The state schema type (StateSchema, AnnotationRoot, InteropZodObject) OR a type bag
210
+ * @template Context - The type of the context passed into this node (default: Record<string, unknown>)
64
211
  * @template Nodes - An optional union of valid node names for Command.goto, used for type-safe routing (default: string)
65
212
  *
66
- * @example
213
+ * @example Single schema usage
67
214
  * ```typescript
68
215
  * import { StateSchema, GraphNode } from "@langchain/langgraph";
69
216
  * import { z } from "zod/v4";
@@ -76,14 +223,14 @@ type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends Annotatio
76
223
  * // Context shape for custom node logic (optional)
77
224
  * type MyContext = { userId: string };
78
225
  *
79
- * // Node receiving state and context
80
- * const processNode: GraphNode<typeof AgentState, MyContext> = (state, runtime) => {
81
- * const { userId } = runtime; // type-safe context access
226
+ * // Node receiving state and config
227
+ * const processNode: GraphNode<typeof AgentState, MyContext> = (state, config) => {
228
+ * const userId = config.configurable?.userId; // type-safe context access
82
229
  * return { step: state.step + 1 };
83
230
  * };
84
231
  *
85
232
  * // Node with type-safe graph routing
86
- * const routerNode: GraphNode<typeof AgentState, MyContext, "agent" | "tool"> = (state, runtime) => {
233
+ * const routerNode: GraphNode<typeof AgentState, MyContext, "agent" | "tool"> = (state, config) => {
87
234
  * if (state.needsTool) {
88
235
  * return new Command({ goto: "tool", update: { step: state.step + 1 } });
89
236
  * }
@@ -96,32 +243,114 @@ type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends Annotatio
96
243
  * .addNode("router", routerNode)
97
244
  * .compile();
98
245
  * ```
246
+ *
247
+ * @example Type bag pattern - separate input/output schemas
248
+ * ```typescript
249
+ * const InputSchema = new StateSchema({
250
+ * messages: z.array(z.string()),
251
+ * query: z.string(),
252
+ * });
253
+ *
254
+ * const OutputSchema = new StateSchema({
255
+ * answer: z.string(),
256
+ * });
257
+ *
258
+ * const ContextSchema = z.object({ userId: z.string() });
259
+ *
260
+ * const node: GraphNode<{
261
+ * InputSchema: typeof InputSchema;
262
+ * OutputSchema: typeof OutputSchema;
263
+ * ContextSchema: typeof ContextSchema;
264
+ * Nodes: "agent" | "tool";
265
+ * }> = (state, config) => {
266
+ * // state is { messages: string[]; query: string }
267
+ * // config.configurable is { userId: string } | undefined
268
+ * return { answer: `Response to: ${state.query}` };
269
+ * };
270
+ * ```
99
271
  */
100
- type GraphNode<Schema, Context = Record<string, unknown>, Nodes extends string = string> = (state: ExtractStateType<Schema>, runtime: Runtime<Context>) => ExtractUpdateType<Schema> | CommandInstance<unknown, ExtractUpdateType<Schema>, Nodes> | Promise<ExtractUpdateType<Schema> | CommandInstance<unknown, ExtractUpdateType<Schema>, Nodes>>;
272
+ type GraphNode<Schema, Context extends Record<string, any> = Record<string, any>, Nodes extends string = string> = IsGraphNodeTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>) => GraphNodeReturnValue<ExtractBagOutput<Schema, Partial<ExtractBagInput<Schema, unknown>>>, ExtractBagNodes<Schema, string>> : (state: ExtractStateType<Schema>, config: LangGraphRunnableConfig<Context>) => GraphNodeReturnValue<ExtractUpdateType<Schema>, Nodes>;
273
+ /**
274
+ * Type bag for ConditionalEdgeRouter that accepts schema types.
275
+ * Unlike GraphNodeTypes, conditional edges don't have separate input/output -
276
+ * they just read state and return routing decisions.
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * const router: ConditionalEdgeRouter<{
281
+ * Schema: typeof StateSchema;
282
+ * ContextSchema: typeof ContextSchema;
283
+ * Nodes: "agent" | "tool";
284
+ * }> = (state, config) => {
285
+ * return state.done ? END : "agent";
286
+ * };
287
+ * ```
288
+ */
289
+ interface ConditionalEdgeRouterTypes<InputSchema = unknown, ContextSchema = unknown, Nodes extends string = string> {
290
+ /** Schema for router state (uses ExtractStateType) */
291
+ InputSchema?: InputSchema;
292
+ /** Schema for runtime context (uses ExtractStateType) */
293
+ ContextSchema?: ContextSchema;
294
+ /** Union of valid node names that can be routed to */
295
+ Nodes?: Nodes;
296
+ }
297
+ /**
298
+ * Detect if T is a ConditionalEdgeRouterTypes bag.
299
+ * @internal
300
+ */
301
+ type IsConditionalEdgeRouterTypeBag<T> = T extends {
302
+ InputSchema: unknown;
303
+ } ? true : T extends {
304
+ ContextSchema: unknown;
305
+ } ? true : false;
306
+ /**
307
+ * Return type for conditional edge routing functions.
308
+ */
309
+ type ConditionalEdgeRouterReturnValue<Nodes extends string, State> = Nodes | typeof END | Send<Nodes, State> | Array<Nodes | Send<Nodes, State>>;
101
310
  /**
102
311
  * Type for conditional edge routing functions.
103
312
  *
104
313
  * Use this to type functions passed to `addConditionalEdges` for
105
314
  * full type safety on state, runtime context, and return values.
106
315
  *
107
- * @template Schema - The state schema type
316
+ * **Supports two patterns:**
317
+ *
318
+ * 1. **Single schema pattern** - Single schema:
319
+ * `ConditionalEdgeRouter<Schema, Context, Nodes>`
320
+ *
321
+ * 2. **Type bag pattern** - Separate schemas for state, context:
322
+ * `ConditionalEdgeRouter<{ Schema; ContextSchema; Nodes }>`
323
+ *
324
+ * @template Schema - The state schema type OR a type bag
108
325
  * @template Context - The runtime context type available to node logic
109
326
  * @template Nodes - Union of valid node names that can be routed to
110
327
  *
111
- * @example
328
+ * @example Single schema pattern
112
329
  * ```typescript
113
330
  * type MyContext = { userId: string };
114
331
  * const router: ConditionalEdgeRouter<typeof AgentState, MyContext, "agent" | "tool"> =
115
- * (state, runtime) => {
116
- * // Access runtime context as type-safe: runtime.userId
332
+ * (state, config) => {
333
+ * const userId = config.context?.userId;
117
334
  * if (state.done) return END;
118
335
  * return state.needsTool ? "tool" : "agent";
119
336
  * };
120
337
  *
121
338
  * graph.addConditionalEdges("router", router, ["agent", "tool"]);
122
339
  * ```
340
+ *
341
+ * @example Type bag pattern
342
+ * ```typescript
343
+ * const router: ConditionalEdgeRouter<{
344
+ * Schema: typeof StateSchema;
345
+ * ContextSchema: typeof ContextSchema;
346
+ * Nodes: "agent" | "tool";
347
+ * }> = (state, config) => {
348
+ * if (state.done) return END;
349
+ * return "agent";
350
+ * };
351
+ * ```
123
352
  */
124
- type ConditionalEdgeRouter<Schema, Context = Record<string, unknown>, Nodes extends string = string> = (state: ExtractStateType<Schema>, runtime: Runtime<Context>) => Nodes | typeof END | Send<Nodes, ExtractStateType<Schema>> | Array<Nodes | Send<Nodes, ExtractStateType<Schema>>>;
353
+ type ConditionalEdgeRouter<Schema, Context extends Record<string, any> = Record<string, any>, Nodes extends string = string> = IsConditionalEdgeRouterTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>) => ConditionalEdgeRouterReturnValue<ExtractBagNodes<Schema, string>, ExtractBagInput<Schema, unknown>> | Promise<ConditionalEdgeRouterReturnValue<ExtractBagNodes<Schema, string>, ExtractBagInput<Schema, unknown>>> : (state: ExtractStateType<Schema>, config: LangGraphRunnableConfig<Context>) => ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>> | Promise<ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>>>;
125
354
  //#endregion
126
- export { ConditionalEdgeRouter, ExtractStateType, ExtractUpdateType, GraphNode, StateDefinitionInit, ToStateDefinition };
355
+ export { ConditionalEdgeRouter, ConditionalEdgeRouterTypes, ContextSchemaInit, ExtractStateType, ExtractUpdateType, GraphNode, GraphNodeReturnValue, GraphNodeTypes, StateDefinitionInit, StateGraphInit, StateGraphOptions, ToStateDefinition };
127
356
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":["InteropZodObject","Runtime","CommandInstance","Send","END","AnnotationRoot","StateDefinition","StateType","UpdateType","AnnotationUpdateType","AnyStateSchema","StateSchema","StateSchemaFieldsToStateDefinition","InteropZodToStateDefinition","ToStateDefinition","T","TInit","StateDefinitionInit","ExtractStateType","Schema","SD","S","Fallback","ExtractUpdateType","U","FallbackBase","Partial","GraphNode","Record","Context","Nodes","Promise","ConditionalEdgeRouter","Array"],"sources":["../../src/graph/types.d.ts"],"sourcesContent":["import type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type { Runtime } from \"../pregel/runnable_types.js\";\nimport type { CommandInstance, Send } from \"../constants.js\";\nimport { END } from \"../constants.js\";\nimport type { AnnotationRoot, StateDefinition, StateType, UpdateType as AnnotationUpdateType } from \"./annotation.js\";\nimport type { AnyStateSchema, StateSchema, StateSchemaFieldsToStateDefinition } from \"../state/schema.js\";\nimport type { InteropZodToStateDefinition } from \"./zod/meta.js\";\nexport { END };\n/**\n * Convert any supported schema type to a StateDefinition.\n *\n * @internal\n */\nexport type ToStateDefinition<T> = T extends StateSchema<infer TInit> ? StateSchemaFieldsToStateDefinition<TInit> : T extends InteropZodObject ? InteropZodToStateDefinition<T> : T extends StateDefinition ? T : never;\n/**\n * Type for schema types that can be used to initialize state.\n *\n * @internal\n */\nexport type StateDefinitionInit = StateDefinition | InteropZodObject | AnyStateSchema;\n/**\n * Extract the State type from any supported schema type.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract state from\n * @template Fallback - Type to return if schema doesn't match (default: never)\n */\nexport type ExtractStateType<Schema, Fallback = Schema> = Schema extends AnnotationRoot<infer SD> ? StateType<SD> : StateType<ToStateDefinition<Schema>> extends infer S ? [S] extends [never] ? Fallback : S : Fallback;\n/**\n * Extract the Update type from any supported schema type.\n *\n * The Update type represents what a node can return to update the state.\n * All fields are optional since nodes only need to return the fields they modify.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract update type from\n * @template FallbackBase - Base type for fallback (will be partialized), defaults to Schema\n */\nexport type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends AnnotationRoot<infer SD> ? AnnotationUpdateType<SD> : AnnotationUpdateType<ToStateDefinition<Schema>> extends infer U ? [U] extends [never] ? Partial<FallbackBase> : U : Partial<FallbackBase>;\n/**\n * Strongly-typed utility for authoring graph nodes outside of the StateGraph builder,\n * supporting inference for both state (from Schema) and runtime context (from ContextType).\n *\n * This type enables you to define graph node functions with full type safety—both\n * for the evolving state and for additional context that may be passed in at runtime.\n * Typing the context parameter allows for better code organization and precise editor support.\n *\n * Works with StateSchema, AnnotationRoot, and Zod object schemas for state, and\n * with a user-defined object shape for context.\n *\n * @template Schema - The state schema type (StateSchema, AnnotationRoot, or InteropZodObject)\n * @template Context - The type of the runtime context injected into this node (default: Record<string, unknown>)\n * @template Nodes - An optional union of valid node names for Command.goto, used for type-safe routing (default: string)\n *\n * @example\n * ```typescript\n * import { StateSchema, GraphNode } from \"@langchain/langgraph\";\n * import { z } from \"zod/v4\";\n *\n * const AgentState = new StateSchema({\n * messages: MessagesValue,\n * step: z.number().default(0),\n * });\n *\n * // Context shape for custom node logic (optional)\n * type MyContext = { userId: string };\n *\n * // Node receiving state and context\n * const processNode: GraphNode<typeof AgentState, MyContext> = (state, runtime) => {\n * const { userId } = runtime; // type-safe context access\n * return { step: state.step + 1 };\n * };\n *\n * // Node with type-safe graph routing\n * const routerNode: GraphNode<typeof AgentState, MyContext, \"agent\" | \"tool\"> = (state, runtime) => {\n * if (state.needsTool) {\n * return new Command({ goto: \"tool\", update: { step: state.step + 1 } });\n * }\n * return new Command({ goto: \"agent\" });\n * };\n *\n * // Use in graph\n * const graph = new StateGraph(AgentState)\n * .addNode(\"process\", processNode)\n * .addNode(\"router\", routerNode)\n * .compile();\n * ```\n */\nexport type GraphNode<Schema, Context = Record<string, unknown>, Nodes extends string = string> = (state: ExtractStateType<Schema>, runtime: Runtime<Context>) => ExtractUpdateType<Schema> | CommandInstance<unknown, ExtractUpdateType<Schema>, Nodes> | Promise<ExtractUpdateType<Schema> | CommandInstance<unknown, ExtractUpdateType<Schema>, Nodes>>;\n/**\n * Type for conditional edge routing functions.\n *\n * Use this to type functions passed to `addConditionalEdges` for\n * full type safety on state, runtime context, and return values.\n *\n * @template Schema - The state schema type\n * @template Context - The runtime context type available to node logic\n * @template Nodes - Union of valid node names that can be routed to\n *\n * @example\n * ```typescript\n * type MyContext = { userId: string };\n * const router: ConditionalEdgeRouter<typeof AgentState, MyContext, \"agent\" | \"tool\"> =\n * (state, runtime) => {\n * // Access runtime context as type-safe: runtime.userId\n * if (state.done) return END;\n * return state.needsTool ? \"tool\" : \"agent\";\n * };\n *\n * graph.addConditionalEdges(\"router\", router, [\"agent\", \"tool\"]);\n * ```\n */\nexport type ConditionalEdgeRouter<Schema, Context = Record<string, unknown>, Nodes extends string = string> = (state: ExtractStateType<Schema>, runtime: Runtime<Context>) => Nodes | typeof END | Send<Nodes, ExtractStateType<Schema>> | Array<Nodes | Send<Nodes, ExtractStateType<Schema>>>;\n"],"mappings":";;;;;;;;;AAaA;;;;;AAAwEY,KAA5DE,iBAA4DF,CAAAA,CAAAA,CAAAA,GAArCG,CAAqCH,SAA3BD,WAA2BC,CAAAA,KAAAA,MAAAA,CAAAA,GAAAA,kCAAAA,CAAmCI,KAAnCJ,CAAAA,GAA4CG,CAA5CH,SAAsDZ,gBAAtDY,GAAyEC,2BAAzED,CAAqGG,CAArGH,CAAAA,GAA0GG,CAA1GH,SAAoHN,eAApHM,GAAsIG,CAAtIH,GAAAA,KAAAA;;;;;;AAAoHN,KAMhLW,mBAAAA,GAAsBX,eAN0JA,GAMxIN,gBANwIM,GAMrHI,cANqHJ;;;AAM5L;;;;;;AAaA;;;;AAAyED,KAA7Da,gBAA6Db,CAAAA,MAAAA,EAAAA,WAAzBc,MAAyBd,CAAAA,GAAfc,MAAed,SAAAA,cAAAA,CAAAA,KAAAA,GAAAA,CAAAA,GAA2BE,SAA3BF,CAAqCe,EAArCf,CAAAA,GAA2CE,SAA3CF,CAAqDS,iBAArDT,CAAuEc,MAAvEd,CAAAA,CAAAA,SAAAA,KAAAA,EAAAA,GAAAA,CAAmGgB,CAAnGhB,CAAAA,SAAAA,CAAAA,KAAAA,CAAAA,GAAwHiB,QAAxHjB,GAAmIgB,CAAnIhB,GAAuIiB,QAAvIjB;;;;;;;;;;;AAgBzE;;;;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eAAe1B,MAAMD,KAAK2B,OAAOZ,iBAAiBC,WAAWc,MAAMH,QAAQ3B,KAAK2B,OAAOZ,iBAAiBC"}
1
+ {"version":3,"file":"types.d.ts","names":["InteropZodObject","StandardSchemaV1","LangGraphRunnableConfig","CommandInstance","Send","END","AnnotationRoot","StateDefinition","StateType","UpdateType","AnnotationUpdateType","AnyStateSchema","StateSchema","StateSchemaFieldsToStateDefinition","InteropZodToStateDefinition","ToStateDefinition","T","TInit","SD","StateDefinitionInit","isStateDefinitionInit","ContextSchemaInit","StateGraphInit","I","O","C","InterruptType","WriterType","N","StateGraphOptions","Omit","isStateGraphInit","ExtractStateType","Schema","S","Fallback","ExtractUpdateType","U","FallbackBase","Partial","ExtractBagInput","Bag","Default","ExtractBagOutput","ExtractBagContext","Record","Ctx","ExtractBagNodes","GraphNodeTypes","InputSchema","OutputSchema","ContextSchema","Nodes","IsGraphNodeTypeBag","GraphNodeReturnValue","Update","Promise","GraphNode","Context","ConditionalEdgeRouterTypes","IsConditionalEdgeRouterTypeBag","ConditionalEdgeRouterReturnValue","State","Array","ConditionalEdgeRouter"],"sources":["../../src/graph/types.d.ts"],"sourcesContent":["import { type InteropZodObject } from \"@langchain/core/utils/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport type { CommandInstance, Send } from \"../constants.js\";\nimport { END } from \"../constants.js\";\nimport type { AnnotationRoot, StateDefinition, StateType, UpdateType as AnnotationUpdateType } from \"./annotation.js\";\nimport { AnyStateSchema, StateSchema, StateSchemaFieldsToStateDefinition } from \"../state/schema.js\";\nimport type { InteropZodToStateDefinition } from \"./zod/meta.js\";\nexport { END };\n/**\n * Convert any supported schema type to a StateDefinition.\n *\n * @internal\n */\nexport type ToStateDefinition<T> = T extends StateSchema<infer TInit> ? StateSchemaFieldsToStateDefinition<TInit> : T extends AnnotationRoot<infer SD> ? SD : T extends InteropZodObject ? InteropZodToStateDefinition<T> : T extends StateDefinition ? T : never;\n/**\n * Type for schema types that can be used to initialize state.\n * Supports all valid schema types: StateDefinition, Zod objects, StateSchema, and AnnotationRoot.\n *\n * @internal\n */\nexport type StateDefinitionInit = StateDefinition | InteropZodObject | AnyStateSchema | AnnotationRoot<any>;\n/**\n * Check if a value is a valid StateDefinitionInit type.\n * Supports: StateSchema, InteropZodObject (Zod), AnnotationRoot, StateDefinition\n *\n * @internal\n */\nexport declare function isStateDefinitionInit(value: unknown): value is StateDefinitionInit;\n/**\n * Valid types for context schema.\n * Context doesn't have channels/reducers, so StateSchema is NOT supported.\n * Supports StandardSchemaV1 (Zod, Valibot, etc.) and AnnotationRoot (backward compat).\n *\n * @internal\n */\nexport type ContextSchemaInit = StandardSchemaV1 | AnnotationRoot<StateDefinition>;\n/**\n * Initialization options for StateGraph.\n * Accepts any combination of schema types for state/input/output.\n *\n * Supports both `state` and `stateSchema` as aliases for backward compatibility.\n * If only `input` is provided (no state/stateSchema), `input` is used as the state schema.\n *\n * @template SD - State definition type\n * @template I - Input definition type (defaults to undefined)\n * @template O - Output definition type (defaults to undefined)\n * @template C - Context schema type (defaults to undefined)\n * @template N - Node name union type (defaults to string)\n * @template InterruptType - Interrupt type (defaults to unknown)\n * @template WriterType - Writer type (defaults to unknown)\n */\nexport type StateGraphInit<SD extends StateDefinitionInit = StateDefinitionInit, I extends StateDefinitionInit | undefined = undefined, O extends StateDefinitionInit | undefined = undefined, C extends StateDefinitionInit | undefined = undefined, N extends string = string, InterruptType = unknown, WriterType = unknown> = {\n /** Primary key for state schema */\n state?: SD;\n /**\n * @deprecated Use `state` instead. Will be removed in a future version.\n */\n stateSchema?: SD;\n input?: I;\n output?: O;\n /** Context schema for runtime configuration validation. Does not support StateSchema. */\n context?: C;\n interrupt?: InterruptType;\n writer?: WriterType;\n nodes?: N[];\n};\n/**\n * Options for the second argument when passing a direct schema.\n * Excludes `state` and `stateSchema` since those come from the first arg.\n *\n * @internal\n */\nexport type StateGraphOptions<I extends StateDefinitionInit | undefined = undefined, O extends StateDefinitionInit | undefined = undefined, C extends StateDefinitionInit | undefined = undefined, N extends string = string, InterruptType = unknown, WriterType = unknown> = Omit<StateGraphInit<StateDefinitionInit, I, O, C, N, InterruptType, WriterType>, \"state\" | \"stateSchema\">;\n/**\n * Check if a value is a StateGraphInit object (has state, stateSchema, or input with valid schema).\n *\n * @internal\n */\nexport declare function isStateGraphInit(value: unknown): value is StateGraphInit<StateDefinitionInit>;\n/**\n * Extract the State type from any supported schema type.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract state from\n * @template Fallback - Type to return if schema doesn't match (default: never)\n */\nexport type ExtractStateType<Schema, Fallback = Schema> = Schema extends AnnotationRoot<infer SD> ? StateType<SD> : StateType<ToStateDefinition<Schema>> extends infer S ? [S] extends [never] ? Fallback : S : Fallback;\n/**\n * Extract the Update type from any supported schema type.\n *\n * The Update type represents what a node can return to update the state.\n * All fields are optional since nodes only need to return the fields they modify.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract update type from\n * @template FallbackBase - Base type for fallback (will be partialized), defaults to Schema\n */\nexport type ExtractUpdateType<Schema, FallbackBase = Schema> = Schema extends AnnotationRoot<infer SD> ? AnnotationUpdateType<SD> : AnnotationUpdateType<ToStateDefinition<Schema>> extends infer U ? [U] extends [never] ? Partial<FallbackBase> : U : Partial<FallbackBase>;\n/**\n * Extract the input type from a type bag, using ExtractStateType on the InputSchema.\n * Falls back to Default if InputSchema is not provided.\n * @internal\n */\ntype ExtractBagInput<Bag, Default> = Bag extends {\n InputSchema: infer I;\n} ? ExtractStateType<I> : Default;\n/**\n * Extract the output type from a type bag, using ExtractUpdateType on the OutputSchema.\n * Falls back to Default if OutputSchema is not provided.\n * @internal\n */\ntype ExtractBagOutput<Bag, Default> = Bag extends {\n OutputSchema: infer O;\n} ? ExtractUpdateType<O> : Default;\n/**\n * Extract the context type from a type bag, using ExtractStateType on the ContextSchema.\n * Falls back to Default if ContextSchema is not provided.\n * Ensures result extends Record<string, unknown> for LangGraphRunnableConfig compatibility.\n * @internal\n */\ntype ExtractBagContext<Bag, Default extends Record<string, unknown>> = Bag extends {\n ContextSchema: infer C;\n} ? ExtractStateType<C> extends infer Ctx ? Ctx extends Record<string, unknown> ? Ctx : Default : Default : Default;\n/**\n * Extract the Nodes type from a type bag.\n * Falls back to Default if Nodes is not provided.\n * @internal\n */\ntype ExtractBagNodes<Bag, Default extends string> = Bag extends {\n Nodes: infer N extends string;\n} ? N : Default;\n/**\n * Type bag for GraphNode that accepts schema types.\n * All fields are optional - unspecified fields use defaults.\n *\n * This enables separate input/output schemas for nodes, which is useful when\n * a node receives a subset of state fields and returns different fields.\n *\n * @example\n * ```typescript\n * const node: GraphNode<{\n * InputSchema: typeof NodeInputSchema;\n * OutputSchema: typeof NodeOutputSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, runtime) => {\n * return { answer: `Response to: ${state.query}` };\n * };\n * ```\n */\nexport interface GraphNodeTypes<InputSchema = unknown, OutputSchema = unknown, ContextSchema = unknown, Nodes extends string = string> {\n /** Schema for node input state (uses ExtractStateType) */\n InputSchema?: InputSchema;\n /** Schema for node output/update (uses ExtractUpdateType) */\n OutputSchema?: OutputSchema;\n /** Schema for runtime context (uses ExtractStateType) */\n ContextSchema?: ContextSchema;\n /** Union of valid node names for Command.goto */\n Nodes?: Nodes;\n}\n/**\n * Detect if T is a type bag (has InputSchema or OutputSchema) or a direct schema.\n * @internal\n */\ntype IsGraphNodeTypeBag<T> = T extends {\n InputSchema: unknown;\n} ? true : T extends {\n OutputSchema: unknown;\n} ? true : false;\n/**\n * Return value type for GraphNode functions.\n * Nodes can return an update object, a Command, or a Promise of either.\n *\n * @template Update - The update type (what fields can be returned)\n * @template Nodes - Union of valid node names for Command.goto\n */\nexport type GraphNodeReturnValue<Update, Nodes extends string = string> = Update | CommandInstance<unknown, Update, Nodes> | Promise<Update | CommandInstance<unknown, Update, Nodes>>;\n/**\n * Strongly-typed utility for authoring graph nodes outside of the StateGraph builder,\n * supporting inference for both state (from Schema) and config context (from Context type).\n *\n * This type enables you to define graph node functions with full type safety—both\n * for the evolving state and for additional context that may be passed in at runtime.\n * Typing the context parameter allows for better code organization and precise editor support.\n *\n * Works with StateSchema, AnnotationRoot, and Zod object schemas for state, and\n * with a user-defined object shape for context.\n *\n * **Supports two patterns:**\n *\n * 1. **Single schema usage** - Single schema for both input and output:\n * `GraphNode<Schema, Context, Nodes>`\n *\n * 2. **Type bag pattern** - Separate schemas for input, output, context:\n * `GraphNode<{ InputSchema; OutputSchema; ContextSchema; Nodes }>`\n *\n * @template Schema - The state schema type (StateSchema, AnnotationRoot, InteropZodObject) OR a type bag\n * @template Context - The type of the context passed into this node (default: Record<string, unknown>)\n * @template Nodes - An optional union of valid node names for Command.goto, used for type-safe routing (default: string)\n *\n * @example Single schema usage\n * ```typescript\n * import { StateSchema, GraphNode } from \"@langchain/langgraph\";\n * import { z } from \"zod/v4\";\n *\n * const AgentState = new StateSchema({\n * messages: MessagesValue,\n * step: z.number().default(0),\n * });\n *\n * // Context shape for custom node logic (optional)\n * type MyContext = { userId: string };\n *\n * // Node receiving state and config\n * const processNode: GraphNode<typeof AgentState, MyContext> = (state, config) => {\n * const userId = config.configurable?.userId; // type-safe context access\n * return { step: state.step + 1 };\n * };\n *\n * // Node with type-safe graph routing\n * const routerNode: GraphNode<typeof AgentState, MyContext, \"agent\" | \"tool\"> = (state, config) => {\n * if (state.needsTool) {\n * return new Command({ goto: \"tool\", update: { step: state.step + 1 } });\n * }\n * return new Command({ goto: \"agent\" });\n * };\n *\n * // Use in graph\n * const graph = new StateGraph(AgentState)\n * .addNode(\"process\", processNode)\n * .addNode(\"router\", routerNode)\n * .compile();\n * ```\n *\n * @example Type bag pattern - separate input/output schemas\n * ```typescript\n * const InputSchema = new StateSchema({\n * messages: z.array(z.string()),\n * query: z.string(),\n * });\n *\n * const OutputSchema = new StateSchema({\n * answer: z.string(),\n * });\n *\n * const ContextSchema = z.object({ userId: z.string() });\n *\n * const node: GraphNode<{\n * InputSchema: typeof InputSchema;\n * OutputSchema: typeof OutputSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * // state is { messages: string[]; query: string }\n * // config.configurable is { userId: string } | undefined\n * return { answer: `Response to: ${state.query}` };\n * };\n * ```\n */\nexport type GraphNode<Schema, Context extends Record<string, any> = Record<string, any>, Nodes extends string = string> = IsGraphNodeTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>) => GraphNodeReturnValue<ExtractBagOutput<Schema, Partial<ExtractBagInput<Schema, unknown>>>, ExtractBagNodes<Schema, string>> : (state: ExtractStateType<Schema>, config: LangGraphRunnableConfig<Context>) => GraphNodeReturnValue<ExtractUpdateType<Schema>, Nodes>;\n/**\n * Type bag for ConditionalEdgeRouter that accepts schema types.\n * Unlike GraphNodeTypes, conditional edges don't have separate input/output -\n * they just read state and return routing decisions.\n *\n * @example\n * ```typescript\n * const router: ConditionalEdgeRouter<{\n * Schema: typeof StateSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * return state.done ? END : \"agent\";\n * };\n * ```\n */\nexport interface ConditionalEdgeRouterTypes<InputSchema = unknown, ContextSchema = unknown, Nodes extends string = string> {\n /** Schema for router state (uses ExtractStateType) */\n InputSchema?: InputSchema;\n /** Schema for runtime context (uses ExtractStateType) */\n ContextSchema?: ContextSchema;\n /** Union of valid node names that can be routed to */\n Nodes?: Nodes;\n}\n/**\n * Detect if T is a ConditionalEdgeRouterTypes bag.\n * @internal\n */\ntype IsConditionalEdgeRouterTypeBag<T> = T extends {\n InputSchema: unknown;\n} ? true : T extends {\n ContextSchema: unknown;\n} ? true : false;\n/**\n * Return type for conditional edge routing functions.\n */\ntype ConditionalEdgeRouterReturnValue<Nodes extends string, State> = Nodes | typeof END | Send<Nodes, State> | Array<Nodes | Send<Nodes, State>>;\n/**\n * Type for conditional edge routing functions.\n *\n * Use this to type functions passed to `addConditionalEdges` for\n * full type safety on state, runtime context, and return values.\n *\n * **Supports two patterns:**\n *\n * 1. **Single schema pattern** - Single schema:\n * `ConditionalEdgeRouter<Schema, Context, Nodes>`\n *\n * 2. **Type bag pattern** - Separate schemas for state, context:\n * `ConditionalEdgeRouter<{ Schema; ContextSchema; Nodes }>`\n *\n * @template Schema - The state schema type OR a type bag\n * @template Context - The runtime context type available to node logic\n * @template Nodes - Union of valid node names that can be routed to\n *\n * @example Single schema pattern\n * ```typescript\n * type MyContext = { userId: string };\n * const router: ConditionalEdgeRouter<typeof AgentState, MyContext, \"agent\" | \"tool\"> =\n * (state, config) => {\n * const userId = config.context?.userId;\n * if (state.done) return END;\n * return state.needsTool ? \"tool\" : \"agent\";\n * };\n *\n * graph.addConditionalEdges(\"router\", router, [\"agent\", \"tool\"]);\n * ```\n *\n * @example Type bag pattern\n * ```typescript\n * const router: ConditionalEdgeRouter<{\n * Schema: typeof StateSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * if (state.done) return END;\n * return \"agent\";\n * };\n * ```\n */\nexport type ConditionalEdgeRouter<Schema, Context extends Record<string, any> = Record<string, any>, Nodes extends string = string> = IsConditionalEdgeRouterTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>) => ConditionalEdgeRouterReturnValue<ExtractBagNodes<Schema, string>, ExtractBagInput<Schema, unknown>> | Promise<ConditionalEdgeRouterReturnValue<ExtractBagNodes<Schema, string>, ExtractBagInput<Schema, unknown>>> : (state: ExtractStateType<Schema>, config: LangGraphRunnableConfig<Context>) => ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>> | Promise<ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>>>;\n"],"mappings":";;;;;;;;;;AAcA;;;;;AAAwEa,KAA5DE,iBAA4DF,CAAAA,CAAAA,CAAAA,GAArCG,CAAqCH,SAA3BD,WAA2BC,CAAAA,KAAAA,MAAAA,CAAAA,GAAAA,kCAAAA,CAAmCI,KAAnCJ,CAAAA,GAA4CG,CAA5CH,SAAsDP,cAAtDO,CAAAA,KAAAA,GAAAA,CAAAA,GAAiFK,EAAjFL,GAAsFG,CAAtFH,SAAgGb,gBAAhGa,GAAmHC,2BAAnHD,CAA+IG,CAA/IH,CAAAA,GAAoJG,CAApJH,SAA8JN,eAA9JM,GAAgLG,CAAhLH,GAAAA,KAAAA;;;;;;;AAAmHC,KAO/KK,mBAAAA,GAAsBZ,eAPyJO,GAOvId,gBAPuIc,GAOpHH,cAPoHG,GAOnGR,cAPmGQ,CAAAA,GAAAA,CAAAA;;;;;AAO3L;;;;;;;AAeA;;;AAAkEP,KAAtDc,iBAAAA,GAAoBpB,gBAAkCM,GAAfD,cAAeC,CAAAA,eAAAA,CAAAA;;;AAgBlE;;;;;;;;;;;;;AAYaoB,KAZDL,cAYCK,CAAAA,WAZyBR,mBAYzBQ,GAZ+CR,mBAY/CQ,EAAAA,UAZ8ER,mBAY9EQ,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,UAZqIR,mBAYrIQ,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,UAZ4LR,mBAY5LQ,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,UAAAA,MAAAA,GAAAA,MAAAA,EAAAA,gBAAAA,OAAAA,EAAAA,aAAAA,OAAAA,CAAAA,GAAAA;;EACA,KAAA,CAAA,EAXDT,EAWC;EAQDW;;;aAAmFV,CAAAA,EAf7ED,EAe6EC;OAAuDA,CAAAA,EAd1II,CAc0I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C;;WAE9BA;;;;;;KAMN6C,gEAAgET,eAAe/C,MAAMD,KAAKgD,OAAOU,SAASC,MAAMX,QAAQhD,KAAKgD,OAAOU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4C7HE,8CAA8CnB,sBAAsBA,sDAAsDe,+BAA+B3B,+BAA+BO,gBAAgBP,0BAA0B/B,wBAAwB0C,kBAAkBX,QAAQY,8BAA8BgB,iCAAiCd,gBAAgBd,iBAAiBO,gBAAgBP,oBAAoBuB,QAAQK,iCAAiCd,gBAAgBd,iBAAiBO,gBAAgBP,6BAA6BD,iBAAiBC,iBAAiB/B,wBAAwBwD,aAAaG,iCAAiCT,OAAOpB,iBAAiBC,WAAWuB,QAAQK,iCAAiCT,OAAOpB,iBAAiBC"}
@@ -0,0 +1,40 @@
1
+ import { isBaseChannel } from "../channels/base.js";
2
+ import { END } from "../constants.js";
3
+ import { StateSchema } from "../state/schema.js";
4
+ import { isInteropZodObject } from "@langchain/core/utils/types";
5
+
6
+ //#region src/graph/types.ts
7
+ /**
8
+ * Check if a value is a valid StateDefinitionInit type.
9
+ * Supports: StateSchema, InteropZodObject (Zod), AnnotationRoot, StateDefinition
10
+ *
11
+ * @internal
12
+ */
13
+ function isStateDefinitionInit(value) {
14
+ if (value == null) return false;
15
+ if (StateSchema.isInstance(value)) return true;
16
+ if (isInteropZodObject(value)) return true;
17
+ if (typeof value === "object" && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot") return true;
18
+ if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.values(value).every((v) => typeof v === "function" || isBaseChannel(v))) return true;
19
+ return false;
20
+ }
21
+ /**
22
+ * Check if a value is a StateGraphInit object (has state, stateSchema, or input with valid schema).
23
+ *
24
+ * @internal
25
+ */
26
+ function isStateGraphInit(value) {
27
+ if (typeof value !== "object" || value == null) return false;
28
+ const obj = value;
29
+ const hasState = "state" in obj && isStateDefinitionInit(obj.state);
30
+ const hasStateSchema = "stateSchema" in obj && isStateDefinitionInit(obj.stateSchema);
31
+ const hasInput = "input" in obj && isStateDefinitionInit(obj.input);
32
+ if (!hasState && !hasStateSchema && !hasInput) return false;
33
+ if ("input" in obj && obj.input != null && !isStateDefinitionInit(obj.input)) return false;
34
+ if ("output" in obj && obj.output != null && !isStateDefinitionInit(obj.output)) return false;
35
+ return true;
36
+ }
37
+
38
+ //#endregion
39
+ export { isStateDefinitionInit, isStateGraphInit };
40
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/graph/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n isInteropZodObject,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport type { CommandInstance, Send } from \"../constants.js\";\nimport { END } from \"../constants.js\";\nimport type {\n AnnotationRoot,\n StateDefinition,\n StateType,\n UpdateType as AnnotationUpdateType,\n} from \"./annotation.js\";\nimport {\n AnyStateSchema,\n StateSchema,\n StateSchemaFieldsToStateDefinition,\n} from \"../state/schema.js\";\nimport type { InteropZodToStateDefinition } from \"./zod/meta.js\";\nimport { isBaseChannel } from \"../channels/base.js\";\n\n// Re-export END for use in ConditionalEdgeRouter return types\nexport { END };\n\n/**\n * Convert any supported schema type to a StateDefinition.\n *\n * @internal\n */\nexport type ToStateDefinition<T> = T extends StateSchema<infer TInit>\n ? StateSchemaFieldsToStateDefinition<TInit>\n : T extends AnnotationRoot<infer SD>\n ? SD\n : T extends InteropZodObject\n ? InteropZodToStateDefinition<T>\n : T extends StateDefinition\n ? T\n : never;\n\n/**\n * Type for schema types that can be used to initialize state.\n * Supports all valid schema types: StateDefinition, Zod objects, StateSchema, and AnnotationRoot.\n *\n * @internal\n */\nexport type StateDefinitionInit =\n | StateDefinition\n | InteropZodObject\n | AnyStateSchema\n | AnnotationRoot<any>;\n\n/**\n * Check if a value is a valid StateDefinitionInit type.\n * Supports: StateSchema, InteropZodObject (Zod), AnnotationRoot, StateDefinition\n *\n * @internal\n */\nexport function isStateDefinitionInit(\n value: unknown\n): value is StateDefinitionInit {\n if (value == null) return false;\n\n // StateSchema\n if (StateSchema.isInstance(value)) return true;\n\n // InteropZodObject (Zod v3/v4 object schemas)\n if (isInteropZodObject(value)) return true;\n\n // AnnotationRoot\n if (\n typeof value === \"object\" &&\n \"lc_graph_name\" in value &&\n (value as { lc_graph_name: unknown }).lc_graph_name === \"AnnotationRoot\"\n ) {\n return true;\n }\n\n // StateDefinition (raw channel map)\n if (\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value).length > 0 &&\n Object.values(value).every(\n (v) => typeof v === \"function\" || isBaseChannel(v)\n )\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Valid types for context schema.\n * Context doesn't have channels/reducers, so StateSchema is NOT supported.\n * Supports StandardSchemaV1 (Zod, Valibot, etc.) and AnnotationRoot (backward compat).\n *\n * @internal\n */\nexport type ContextSchemaInit =\n | StandardSchemaV1\n | AnnotationRoot<StateDefinition>;\n\n/**\n * Initialization options for StateGraph.\n * Accepts any combination of schema types for state/input/output.\n *\n * Supports both `state` and `stateSchema` as aliases for backward compatibility.\n * If only `input` is provided (no state/stateSchema), `input` is used as the state schema.\n *\n * @template SD - State definition type\n * @template I - Input definition type (defaults to undefined)\n * @template O - Output definition type (defaults to undefined)\n * @template C - Context schema type (defaults to undefined)\n * @template N - Node name union type (defaults to string)\n * @template InterruptType - Interrupt type (defaults to unknown)\n * @template WriterType - Writer type (defaults to unknown)\n */\nexport type StateGraphInit<\n SD extends StateDefinitionInit = StateDefinitionInit,\n I extends StateDefinitionInit | undefined = undefined,\n O extends StateDefinitionInit | undefined = undefined,\n C extends StateDefinitionInit | undefined = undefined,\n N extends string = string,\n InterruptType = unknown,\n WriterType = unknown\n> = {\n /** Primary key for state schema */\n state?: SD;\n\n /**\n * @deprecated Use `state` instead. Will be removed in a future version.\n */\n stateSchema?: SD;\n\n input?: I;\n output?: O;\n\n /** Context schema for runtime configuration validation. Does not support StateSchema. */\n context?: C;\n\n interrupt?: InterruptType;\n writer?: WriterType;\n nodes?: N[];\n};\n\n/**\n * Options for the second argument when passing a direct schema.\n * Excludes `state` and `stateSchema` since those come from the first arg.\n *\n * @internal\n */\nexport type StateGraphOptions<\n I extends StateDefinitionInit | undefined = undefined,\n O extends StateDefinitionInit | undefined = undefined,\n C extends StateDefinitionInit | undefined = undefined,\n N extends string = string,\n InterruptType = unknown,\n WriterType = unknown\n> = Omit<\n StateGraphInit<StateDefinitionInit, I, O, C, N, InterruptType, WriterType>,\n \"state\" | \"stateSchema\"\n>;\n\n/**\n * Check if a value is a StateGraphInit object (has state, stateSchema, or input with valid schema).\n *\n * @internal\n */\nexport function isStateGraphInit(\n value: unknown\n): value is StateGraphInit<StateDefinitionInit> {\n if (typeof value !== \"object\" || value == null) return false;\n\n const obj = value as Record<string, unknown>;\n\n // Must have at least one of: state, stateSchema, or input\n const hasState = \"state\" in obj && isStateDefinitionInit(obj.state);\n const hasStateSchema =\n \"stateSchema\" in obj && isStateDefinitionInit(obj.stateSchema);\n const hasInput = \"input\" in obj && isStateDefinitionInit(obj.input);\n\n if (!hasState && !hasStateSchema && !hasInput) return false;\n\n // Validate input/output if provided\n if (\"input\" in obj && obj.input != null && !isStateDefinitionInit(obj.input))\n return false;\n if (\n \"output\" in obj &&\n obj.output != null &&\n !isStateDefinitionInit(obj.output)\n )\n return false;\n\n return true;\n}\n\n/**\n * Extract the State type from any supported schema type.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract state from\n * @template Fallback - Type to return if schema doesn't match (default: never)\n */\nexport type ExtractStateType<\n Schema,\n Fallback = Schema\n> = Schema extends AnnotationRoot<infer SD>\n ? StateType<SD>\n : StateType<ToStateDefinition<Schema>> extends infer S\n ? [S] extends [never]\n ? Fallback\n : S\n : Fallback;\n\n/**\n * Extract the Update type from any supported schema type.\n *\n * The Update type represents what a node can return to update the state.\n * All fields are optional since nodes only need to return the fields they modify.\n *\n * Supports:\n * - StateSchema\n * - AnnotationRoot\n * - StateDefinition (internal channel definitions)\n * - InteropZodObject (Zod v3/v4 object schemas)\n *\n * @template Schema - The schema type to extract update type from\n * @template FallbackBase - Base type for fallback (will be partialized), defaults to Schema\n */\nexport type ExtractUpdateType<\n Schema,\n FallbackBase = Schema\n> = Schema extends AnnotationRoot<infer SD>\n ? AnnotationUpdateType<SD>\n : AnnotationUpdateType<ToStateDefinition<Schema>> extends infer U\n ? [U] extends [never]\n ? Partial<FallbackBase>\n : U\n : Partial<FallbackBase>;\n\n/**\n * Extract the input type from a type bag, using ExtractStateType on the InputSchema.\n * Falls back to Default if InputSchema is not provided.\n * @internal\n */\ntype ExtractBagInput<Bag, Default> = Bag extends {\n InputSchema: infer I;\n}\n ? ExtractStateType<I>\n : Default;\n\n/**\n * Extract the output type from a type bag, using ExtractUpdateType on the OutputSchema.\n * Falls back to Default if OutputSchema is not provided.\n * @internal\n */\ntype ExtractBagOutput<Bag, Default> = Bag extends {\n OutputSchema: infer O;\n}\n ? ExtractUpdateType<O>\n : Default;\n\n/**\n * Extract the context type from a type bag, using ExtractStateType on the ContextSchema.\n * Falls back to Default if ContextSchema is not provided.\n * Ensures result extends Record<string, unknown> for LangGraphRunnableConfig compatibility.\n * @internal\n */\ntype ExtractBagContext<\n Bag,\n Default extends Record<string, unknown>\n> = Bag extends {\n ContextSchema: infer C;\n}\n ? ExtractStateType<C> extends infer Ctx\n ? Ctx extends Record<string, unknown>\n ? Ctx\n : Default\n : Default\n : Default;\n\n/**\n * Extract the Nodes type from a type bag.\n * Falls back to Default if Nodes is not provided.\n * @internal\n */\ntype ExtractBagNodes<Bag, Default extends string> = Bag extends {\n Nodes: infer N extends string;\n}\n ? N\n : Default;\n\n/**\n * Type bag for GraphNode that accepts schema types.\n * All fields are optional - unspecified fields use defaults.\n *\n * This enables separate input/output schemas for nodes, which is useful when\n * a node receives a subset of state fields and returns different fields.\n *\n * @example\n * ```typescript\n * const node: GraphNode<{\n * InputSchema: typeof NodeInputSchema;\n * OutputSchema: typeof NodeOutputSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, runtime) => {\n * return { answer: `Response to: ${state.query}` };\n * };\n * ```\n */\nexport interface GraphNodeTypes<\n InputSchema = unknown,\n OutputSchema = unknown,\n ContextSchema = unknown,\n Nodes extends string = string\n> {\n /** Schema for node input state (uses ExtractStateType) */\n InputSchema?: InputSchema;\n /** Schema for node output/update (uses ExtractUpdateType) */\n OutputSchema?: OutputSchema;\n /** Schema for runtime context (uses ExtractStateType) */\n ContextSchema?: ContextSchema;\n /** Union of valid node names for Command.goto */\n Nodes?: Nodes;\n}\n\n/**\n * Detect if T is a type bag (has InputSchema or OutputSchema) or a direct schema.\n * @internal\n */\ntype IsGraphNodeTypeBag<T> = T extends { InputSchema: unknown }\n ? true\n : T extends { OutputSchema: unknown }\n ? true\n : false;\n\n/**\n * Return value type for GraphNode functions.\n * Nodes can return an update object, a Command, or a Promise of either.\n *\n * @template Update - The update type (what fields can be returned)\n * @template Nodes - Union of valid node names for Command.goto\n */\nexport type GraphNodeReturnValue<Update, Nodes extends string = string> =\n | Update\n | CommandInstance<unknown, Update, Nodes>\n | Promise<Update | CommandInstance<unknown, Update, Nodes>>;\n\n/**\n * Strongly-typed utility for authoring graph nodes outside of the StateGraph builder,\n * supporting inference for both state (from Schema) and config context (from Context type).\n *\n * This type enables you to define graph node functions with full type safety—both\n * for the evolving state and for additional context that may be passed in at runtime.\n * Typing the context parameter allows for better code organization and precise editor support.\n *\n * Works with StateSchema, AnnotationRoot, and Zod object schemas for state, and\n * with a user-defined object shape for context.\n *\n * **Supports two patterns:**\n *\n * 1. **Single schema usage** - Single schema for both input and output:\n * `GraphNode<Schema, Context, Nodes>`\n *\n * 2. **Type bag pattern** - Separate schemas for input, output, context:\n * `GraphNode<{ InputSchema; OutputSchema; ContextSchema; Nodes }>`\n *\n * @template Schema - The state schema type (StateSchema, AnnotationRoot, InteropZodObject) OR a type bag\n * @template Context - The type of the context passed into this node (default: Record<string, unknown>)\n * @template Nodes - An optional union of valid node names for Command.goto, used for type-safe routing (default: string)\n *\n * @example Single schema usage\n * ```typescript\n * import { StateSchema, GraphNode } from \"@langchain/langgraph\";\n * import { z } from \"zod/v4\";\n *\n * const AgentState = new StateSchema({\n * messages: MessagesValue,\n * step: z.number().default(0),\n * });\n *\n * // Context shape for custom node logic (optional)\n * type MyContext = { userId: string };\n *\n * // Node receiving state and config\n * const processNode: GraphNode<typeof AgentState, MyContext> = (state, config) => {\n * const userId = config.configurable?.userId; // type-safe context access\n * return { step: state.step + 1 };\n * };\n *\n * // Node with type-safe graph routing\n * const routerNode: GraphNode<typeof AgentState, MyContext, \"agent\" | \"tool\"> = (state, config) => {\n * if (state.needsTool) {\n * return new Command({ goto: \"tool\", update: { step: state.step + 1 } });\n * }\n * return new Command({ goto: \"agent\" });\n * };\n *\n * // Use in graph\n * const graph = new StateGraph(AgentState)\n * .addNode(\"process\", processNode)\n * .addNode(\"router\", routerNode)\n * .compile();\n * ```\n *\n * @example Type bag pattern - separate input/output schemas\n * ```typescript\n * const InputSchema = new StateSchema({\n * messages: z.array(z.string()),\n * query: z.string(),\n * });\n *\n * const OutputSchema = new StateSchema({\n * answer: z.string(),\n * });\n *\n * const ContextSchema = z.object({ userId: z.string() });\n *\n * const node: GraphNode<{\n * InputSchema: typeof InputSchema;\n * OutputSchema: typeof OutputSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * // state is { messages: string[]; query: string }\n * // config.configurable is { userId: string } | undefined\n * return { answer: `Response to: ${state.query}` };\n * };\n * ```\n */\nexport type GraphNode<\n Schema,\n Context extends Record<string, any> = Record<string, any>,\n Nodes extends string = string\n> = IsGraphNodeTypeBag<Schema> extends true\n ? // Type bag pattern - extract types from schemas\n (\n state: ExtractBagInput<Schema, unknown>,\n config: LangGraphRunnableConfig<\n ExtractBagContext<Schema, Record<string, unknown>>\n >\n ) => GraphNodeReturnValue<\n ExtractBagOutput<Schema, Partial<ExtractBagInput<Schema, unknown>>>,\n ExtractBagNodes<Schema, string>\n >\n : // Single schema pattern (backward compatible)\n (\n state: ExtractStateType<Schema>,\n config: LangGraphRunnableConfig<Context>\n ) => GraphNodeReturnValue<ExtractUpdateType<Schema>, Nodes>;\n\n/**\n * Type bag for ConditionalEdgeRouter that accepts schema types.\n * Unlike GraphNodeTypes, conditional edges don't have separate input/output -\n * they just read state and return routing decisions.\n *\n * @example\n * ```typescript\n * const router: ConditionalEdgeRouter<{\n * Schema: typeof StateSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * return state.done ? END : \"agent\";\n * };\n * ```\n */\nexport interface ConditionalEdgeRouterTypes<\n InputSchema = unknown,\n ContextSchema = unknown,\n Nodes extends string = string\n> {\n /** Schema for router state (uses ExtractStateType) */\n InputSchema?: InputSchema;\n /** Schema for runtime context (uses ExtractStateType) */\n ContextSchema?: ContextSchema;\n /** Union of valid node names that can be routed to */\n Nodes?: Nodes;\n}\n\n/**\n * Detect if T is a ConditionalEdgeRouterTypes bag.\n * @internal\n */\ntype IsConditionalEdgeRouterTypeBag<T> = T extends { InputSchema: unknown }\n ? true\n : T extends { ContextSchema: unknown }\n ? true\n : false;\n\n/**\n * Return type for conditional edge routing functions.\n */\ntype ConditionalEdgeRouterReturnValue<Nodes extends string, State> =\n | Nodes\n | typeof END\n | Send<Nodes, State>\n | Array<Nodes | Send<Nodes, State>>;\n\n/**\n * Type for conditional edge routing functions.\n *\n * Use this to type functions passed to `addConditionalEdges` for\n * full type safety on state, runtime context, and return values.\n *\n * **Supports two patterns:**\n *\n * 1. **Single schema pattern** - Single schema:\n * `ConditionalEdgeRouter<Schema, Context, Nodes>`\n *\n * 2. **Type bag pattern** - Separate schemas for state, context:\n * `ConditionalEdgeRouter<{ Schema; ContextSchema; Nodes }>`\n *\n * @template Schema - The state schema type OR a type bag\n * @template Context - The runtime context type available to node logic\n * @template Nodes - Union of valid node names that can be routed to\n *\n * @example Single schema pattern\n * ```typescript\n * type MyContext = { userId: string };\n * const router: ConditionalEdgeRouter<typeof AgentState, MyContext, \"agent\" | \"tool\"> =\n * (state, config) => {\n * const userId = config.context?.userId;\n * if (state.done) return END;\n * return state.needsTool ? \"tool\" : \"agent\";\n * };\n *\n * graph.addConditionalEdges(\"router\", router, [\"agent\", \"tool\"]);\n * ```\n *\n * @example Type bag pattern\n * ```typescript\n * const router: ConditionalEdgeRouter<{\n * Schema: typeof StateSchema;\n * ContextSchema: typeof ContextSchema;\n * Nodes: \"agent\" | \"tool\";\n * }> = (state, config) => {\n * if (state.done) return END;\n * return \"agent\";\n * };\n * ```\n */\nexport type ConditionalEdgeRouter<\n Schema,\n Context extends Record<string, any> = Record<string, any>,\n Nodes extends string = string\n> = IsConditionalEdgeRouterTypeBag<Schema> extends true\n ? // Type bag pattern - extract types from schemas\n (\n state: ExtractBagInput<Schema, unknown>,\n config: LangGraphRunnableConfig<\n ExtractBagContext<Schema, Record<string, unknown>>\n >\n ) =>\n | ConditionalEdgeRouterReturnValue<\n ExtractBagNodes<Schema, string>,\n ExtractBagInput<Schema, unknown>\n >\n | Promise<\n ConditionalEdgeRouterReturnValue<\n ExtractBagNodes<Schema, string>,\n ExtractBagInput<Schema, unknown>\n >\n >\n : // Single schema pattern (backward compatible)\n (\n state: ExtractStateType<Schema>,\n config: LangGraphRunnableConfig<Context>\n ) =>\n | ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>>\n | Promise<\n ConditionalEdgeRouterReturnValue<Nodes, ExtractStateType<Schema>>\n >;\n"],"mappings":";;;;;;;;;;;;AA2DA,SAAgB,sBACd,OAC8B;AAC9B,KAAI,SAAS,KAAM,QAAO;AAG1B,KAAI,YAAY,WAAW,MAAM,CAAE,QAAO;AAG1C,KAAI,mBAAmB,MAAM,CAAE,QAAO;AAGtC,KACE,OAAO,UAAU,YACjB,mBAAmB,SAClB,MAAqC,kBAAkB,iBAExD,QAAO;AAIT,KACE,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAO,KAAK,MAAM,CAAC,SAAS,KAC5B,OAAO,OAAO,MAAM,CAAC,OAClB,MAAM,OAAO,MAAM,cAAc,cAAc,EAAE,CACnD,CAED,QAAO;AAGT,QAAO;;;;;;;AAgFT,SAAgB,iBACd,OAC8C;AAC9C,KAAI,OAAO,UAAU,YAAY,SAAS,KAAM,QAAO;CAEvD,MAAM,MAAM;CAGZ,MAAM,WAAW,WAAW,OAAO,sBAAsB,IAAI,MAAM;CACnE,MAAM,iBACJ,iBAAiB,OAAO,sBAAsB,IAAI,YAAY;CAChE,MAAM,WAAW,WAAW,OAAO,sBAAsB,IAAI,MAAM;AAEnE,KAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,SAAU,QAAO;AAGtD,KAAI,WAAW,OAAO,IAAI,SAAS,QAAQ,CAAC,sBAAsB,IAAI,MAAM,CAC1E,QAAO;AACT,KACE,YAAY,OACZ,IAAI,UAAU,QACd,CAAC,sBAAsB,IAAI,OAAO,CAElC,QAAO;AAET,QAAO"}
@@ -98,11 +98,11 @@ var SchemaMetaRegistry = class {
98
98
  if (cache.has(schema)) return cache.get(schema);
99
99
  let modifiedSchema = schema;
100
100
  if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) {
101
- const newShapeEntries = Object.entries((0, _langchain_core_utils_types.getInteropZodObjectShape)(schema)).map(([key, schema$1]) => {
102
- const meta = this.get(schema$1);
103
- let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1;
101
+ const newShapeEntries = Object.entries((0, _langchain_core_utils_types.getInteropZodObjectShape)(schema)).map(([key, schema]) => {
102
+ const meta = this.get(schema);
103
+ let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema : schema;
104
104
  if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) {
105
- const description = (0, _langchain_core_utils_types.getSchemaDescription)(outputSchema) ?? (0, _langchain_core_utils_types.getSchemaDescription)(schema$1);
105
+ const description = (0, _langchain_core_utils_types.getSchemaDescription)(outputSchema) ?? (0, _langchain_core_utils_types.getSchemaDescription)(schema);
106
106
  const strExtras = JSON.stringify({
107
107
  ...meta.jsonSchemaExtra,
108
108
  description
@@ -1 +1 @@
1
- {"version":3,"file":"meta.cjs","names":["BinaryOperatorAggregate","LastValue","schema"],"sources":["../../../src/graph/zod/meta.ts"],"sourcesContent":["import {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n getInteropZodObjectShape,\n extendInteropZodObject,\n getInteropZodDefaultGetter,\n interopZodObjectPartial,\n InteropZodObjectShape,\n isZodSchemaV3,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport { BaseChannel } from \"../../channels/base.js\";\nimport { BinaryOperatorAggregate } from \"../../channels/binop.js\";\nimport { LastValue } from \"../../channels/last_value.js\";\n\nexport const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\n\n/** @internal */\nexport type ReducedZodChannel<\n T extends InteropZodType,\n TReducerSchema extends InteropZodType\n> = T & {\n lg_reducer_schema: TReducerSchema;\n};\n\n/** @internal */\nexport type InteropZodToStateDefinition<\n T extends InteropZodObject,\n TShape = InteropZodObjectShape<T>\n> = {\n [key in keyof TShape]: TShape[key] extends ReducedZodChannel<\n infer Schema,\n infer ReducerSchema\n >\n ? Schema extends InteropZodType<infer V>\n ? ReducerSchema extends InteropZodType<infer U>\n ? BaseChannel<V, U>\n : never\n : never\n : TShape[key] extends InteropZodType<infer V, infer U>\n ? BaseChannel<V, U>\n : never;\n};\n\nexport type UpdateType<\n T extends InteropZodObject,\n TShape = InteropZodObjectShape<T>\n> = {\n [key in keyof TShape]?: TShape[key] extends ReducedZodChannel<\n infer Schema,\n infer ReducerSchema\n >\n ? Schema extends InteropZodType<unknown>\n ? ReducerSchema extends InteropZodType<infer U>\n ? U\n : never\n : never\n : TShape[key] extends InteropZodType<unknown, infer U>\n ? U\n : never;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SchemaMeta<TValue = any, TUpdate = TValue> {\n jsonSchemaExtra?: {\n langgraph_nodes?: string[];\n langgraph_type?: \"prompt\" | \"messages\";\n [key: string]: unknown;\n };\n reducer?: {\n schema?: InteropZodType<TUpdate>;\n fn: (a: TValue, b: TUpdate) => TValue;\n };\n default?: () => TValue;\n}\n\n/**\n * A registry for storing and managing metadata associated with schemas.\n * This class provides methods to get, extend, remove, and check metadata for a given schema.\n */\nexport class SchemaMetaRegistry {\n /**\n * Internal map storing schema metadata.\n * @internal\n */\n _map = new WeakMap<InteropZodType, SchemaMeta>();\n\n /**\n * Cache for extended schfemas.\n * @internal\n */\n _extensionCache = new Map<string, WeakMap<InteropZodType, InteropZodType>>();\n\n /**\n * Retrieves the metadata associated with a given schema.\n * @template TValue The value type of the schema.\n * @template TUpdate The update type of the schema (defaults to TValue).\n * @param schema The schema to retrieve metadata for.\n * @returns The associated SchemaMeta, or undefined if not present.\n */\n get<TValue, TUpdate = TValue>(\n schema: InteropZodType<TValue>\n ): SchemaMeta<TValue, TUpdate> | undefined {\n return this._map.get(schema);\n }\n\n /**\n * Extends or sets the metadata for a given schema.\n * @template TValue The value type of the schema.\n * @template TUpdate The update type of the schema (defaults to TValue).\n * @param schema The schema to extend metadata for.\n * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata.\n */\n extend<TValue, TUpdate>(\n schema: InteropZodType<TValue>,\n predicate: (\n meta: SchemaMeta<TValue, TUpdate> | undefined\n ) => SchemaMeta<TValue, TUpdate>\n ) {\n const existingMeta = this.get<TValue, TUpdate>(schema);\n this._map.set(schema, predicate(existingMeta));\n }\n\n /**\n * Removes the metadata associated with a given schema.\n * @param schema The schema to remove metadata for.\n * @returns The SchemaMetaRegistry instance (for chaining).\n */\n remove(schema: InteropZodType): this {\n this._map.delete(schema);\n return this;\n }\n\n /**\n * Checks if metadata exists for a given schema.\n * @param schema The schema to check.\n * @returns True if metadata exists, false otherwise.\n */\n has(schema: InteropZodType): boolean {\n return this._map.has(schema);\n }\n\n /**\n * Returns a mapping of channel instances for each property in the schema\n * using the associated metadata in the registry.\n *\n * This is used to create the `channels` object that's passed to the `Graph` constructor.\n *\n * @template T The shape of the schema.\n * @param schema The schema to extract channels from.\n * @returns A mapping from property names to channel instances.\n */\n getChannelsForSchema<T extends InteropZodObject>(\n schema: T\n ): InteropZodToStateDefinition<T> {\n const channels = {} as Record<string, BaseChannel>;\n const shape = getInteropZodObjectShape(schema);\n for (const [key, channelSchema] of Object.entries(shape)) {\n const meta = this.get(channelSchema);\n if (meta?.reducer) {\n channels[key] = new BinaryOperatorAggregate<\n InferInteropZodOutput<typeof channelSchema>\n >(meta.reducer.fn, meta.default);\n } else {\n channels[key] = new LastValue(meta?.default);\n }\n }\n return channels as InteropZodToStateDefinition<T>;\n }\n\n /**\n * Returns a modified schema that introspectively looks at all keys of the provided\n * object schema, and applies the augmentations based on meta provided with those keys\n * in the registry and the selectors provided in the `effects` parameter.\n *\n * This assumes that the passed in schema is the \"root\" schema object for a graph where\n * the keys of the schema are the channels of the graph. Because we need to represent\n * the input of a graph in a couple of different ways, the `effects` parameter allows\n * us to apply those augmentations based on pre determined conditions.\n *\n * @param schema The root schema object to extend.\n * @param effects The effects that are being applied.\n * @returns The extended schema.\n */\n getExtendedChannelSchemas<T extends InteropZodObject>(\n schema: T,\n effects: {\n /**\n * Augments the shape by using the reducer's schema if it exists\n */\n withReducerSchema?: boolean;\n /**\n * Applies the stringified jsonSchemaExtra as a description to the schema.\n */\n withJsonSchemaExtrasAsDescription?: boolean;\n /**\n * Applies the `.partial()` modifier to the schema.\n */\n asPartial?: boolean;\n }\n ): InteropZodObject {\n // If no effects are being applied, return the schema unchanged\n if (Object.keys(effects).length === 0) {\n return schema;\n }\n\n // Cache key is determined by looking at the effects that are being applied\n const cacheKey = Object.entries(effects)\n .filter(([, v]) => v === true)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}:${v}`)\n .join(\"|\");\n\n const cache = this._extensionCache.get(cacheKey) ?? new WeakMap();\n if (cache.has(schema)) return cache.get(schema)! as T;\n\n let modifiedSchema: InteropZodObject = schema;\n\n if (\n effects.withReducerSchema ||\n effects.withJsonSchemaExtrasAsDescription\n ) {\n const newShapeEntries = Object.entries(\n getInteropZodObjectShape(schema)\n ).map(([key, schema]) => {\n const meta = this.get(schema);\n let outputSchema = effects.withReducerSchema\n ? meta?.reducer?.schema ?? schema\n : schema;\n if (\n effects.withJsonSchemaExtrasAsDescription &&\n meta?.jsonSchemaExtra\n ) {\n const description =\n getSchemaDescription(outputSchema) ?? getSchemaDescription(schema);\n const strExtras = JSON.stringify({\n ...meta.jsonSchemaExtra,\n description,\n });\n outputSchema = outputSchema.describe(\n `${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`\n );\n }\n return [key, outputSchema];\n });\n modifiedSchema = extendInteropZodObject(\n schema,\n Object.fromEntries(newShapeEntries)\n );\n if (isZodSchemaV3(modifiedSchema)) {\n modifiedSchema._def.unknownKeys = \"strip\";\n }\n }\n if (effects.asPartial) {\n modifiedSchema = interopZodObjectPartial(modifiedSchema);\n }\n\n cache.set(schema, modifiedSchema);\n this._extensionCache.set(cacheKey, cache);\n return modifiedSchema;\n }\n}\n\nexport const schemaMetaRegistry = new SchemaMetaRegistry();\n\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate> & { reducer?: undefined }\n): TSchema;\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate>\n): ReducedZodChannel<TSchema, InteropZodType<TUpdate>>;\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate>\n): ReducedZodChannel<TSchema, InteropZodType<TUpdate>> | TSchema {\n if (meta.reducer && !meta.default) {\n const defaultValueGetter = getInteropZodDefaultGetter(schema);\n if (defaultValueGetter != null) {\n // eslint-disable-next-line no-param-reassign\n meta.default = defaultValueGetter;\n }\n }\n if (meta.reducer) {\n const schemaWithReducer = Object.assign(schema, {\n lg_reducer_schema: meta.reducer?.schema ?? schema,\n });\n schemaMetaRegistry.extend(schemaWithReducer, () => meta);\n return schemaWithReducer;\n } else {\n schemaMetaRegistry.extend(schema, () => meta);\n return schema;\n }\n}\n"],"mappings":";;;;;AAgBA,MAAa,iCAAiC;;;;;AAiE9C,IAAa,qBAAb,MAAgC;;;;;CAK9B,uBAAO,IAAI,SAAqC;;;;;CAMhD,kCAAkB,IAAI,KAAsD;;;;;;;;CAS5E,IACE,QACyC;AACzC,SAAO,KAAK,KAAK,IAAI,OAAO;;;;;;;;;CAU9B,OACE,QACA,WAGA;EACA,MAAM,eAAe,KAAK,IAAqB,OAAO;AACtD,OAAK,KAAK,IAAI,QAAQ,UAAU,aAAa,CAAC;;;;;;;CAQhD,OAAO,QAA8B;AACnC,OAAK,KAAK,OAAO,OAAO;AACxB,SAAO;;;;;;;CAQT,IAAI,QAAiC;AACnC,SAAO,KAAK,KAAK,IAAI,OAAO;;;;;;;;;;;;CAa9B,qBACE,QACgC;EAChC,MAAM,WAAW,EAAE;EACnB,MAAM,kEAAiC,OAAO;AAC9C,OAAK,MAAM,CAAC,KAAK,kBAAkB,OAAO,QAAQ,MAAM,EAAE;GACxD,MAAM,OAAO,KAAK,IAAI,cAAc;AACpC,OAAI,MAAM,QACR,UAAS,OAAO,IAAIA,sCAElB,KAAK,QAAQ,IAAI,KAAK,QAAQ;OAEhC,UAAS,OAAO,IAAIC,6BAAU,MA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KAAK,SAAS;EACjC,MAAM,iFAAgD,OAAO;AAC7D,MAAI,sBAAsB,KAExB,MAAK,UAAU;;AAGnB,KAAI,KAAK,SAAS;EAChB,MAAM,oBAAoB,OAAO,OAAO,QAAQ,EAC9C,mBAAmB,KAAK,SAAS,UAAU,QAC5C,CAAC;AACF,qBAAmB,OAAO,yBAAyB,KAAK;AACxD,SAAO;QACF;AACL,qBAAmB,OAAO,cAAc,KAAK;AAC7C,SAAO"}
1
+ {"version":3,"file":"meta.cjs","names":["BinaryOperatorAggregate","LastValue"],"sources":["../../../src/graph/zod/meta.ts"],"sourcesContent":["import {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n getInteropZodObjectShape,\n extendInteropZodObject,\n getInteropZodDefaultGetter,\n interopZodObjectPartial,\n InteropZodObjectShape,\n isZodSchemaV3,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport { BaseChannel } from \"../../channels/base.js\";\nimport { BinaryOperatorAggregate } from \"../../channels/binop.js\";\nimport { LastValue } from \"../../channels/last_value.js\";\n\nexport const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\n\n/** @internal */\nexport type ReducedZodChannel<\n T extends InteropZodType,\n TReducerSchema extends InteropZodType\n> = T & {\n lg_reducer_schema: TReducerSchema;\n};\n\n/** @internal */\nexport type InteropZodToStateDefinition<\n T extends InteropZodObject,\n TShape = InteropZodObjectShape<T>\n> = {\n [key in keyof TShape]: TShape[key] extends ReducedZodChannel<\n infer Schema,\n infer ReducerSchema\n >\n ? Schema extends InteropZodType<infer V>\n ? ReducerSchema extends InteropZodType<infer U>\n ? BaseChannel<V, U>\n : never\n : never\n : TShape[key] extends InteropZodType<infer V, infer U>\n ? BaseChannel<V, U>\n : never;\n};\n\nexport type UpdateType<\n T extends InteropZodObject,\n TShape = InteropZodObjectShape<T>\n> = {\n [key in keyof TShape]?: TShape[key] extends ReducedZodChannel<\n infer Schema,\n infer ReducerSchema\n >\n ? Schema extends InteropZodType<unknown>\n ? ReducerSchema extends InteropZodType<infer U>\n ? U\n : never\n : never\n : TShape[key] extends InteropZodType<unknown, infer U>\n ? U\n : never;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SchemaMeta<TValue = any, TUpdate = TValue> {\n jsonSchemaExtra?: {\n langgraph_nodes?: string[];\n langgraph_type?: \"prompt\" | \"messages\";\n [key: string]: unknown;\n };\n reducer?: {\n schema?: InteropZodType<TUpdate>;\n fn: (a: TValue, b: TUpdate) => TValue;\n };\n default?: () => TValue;\n}\n\n/**\n * A registry for storing and managing metadata associated with schemas.\n * This class provides methods to get, extend, remove, and check metadata for a given schema.\n */\nexport class SchemaMetaRegistry {\n /**\n * Internal map storing schema metadata.\n * @internal\n */\n _map = new WeakMap<InteropZodType, SchemaMeta>();\n\n /**\n * Cache for extended schfemas.\n * @internal\n */\n _extensionCache = new Map<string, WeakMap<InteropZodType, InteropZodType>>();\n\n /**\n * Retrieves the metadata associated with a given schema.\n * @template TValue The value type of the schema.\n * @template TUpdate The update type of the schema (defaults to TValue).\n * @param schema The schema to retrieve metadata for.\n * @returns The associated SchemaMeta, or undefined if not present.\n */\n get<TValue, TUpdate = TValue>(\n schema: InteropZodType<TValue>\n ): SchemaMeta<TValue, TUpdate> | undefined {\n return this._map.get(schema);\n }\n\n /**\n * Extends or sets the metadata for a given schema.\n * @template TValue The value type of the schema.\n * @template TUpdate The update type of the schema (defaults to TValue).\n * @param schema The schema to extend metadata for.\n * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata.\n */\n extend<TValue, TUpdate>(\n schema: InteropZodType<TValue>,\n predicate: (\n meta: SchemaMeta<TValue, TUpdate> | undefined\n ) => SchemaMeta<TValue, TUpdate>\n ) {\n const existingMeta = this.get<TValue, TUpdate>(schema);\n this._map.set(schema, predicate(existingMeta));\n }\n\n /**\n * Removes the metadata associated with a given schema.\n * @param schema The schema to remove metadata for.\n * @returns The SchemaMetaRegistry instance (for chaining).\n */\n remove(schema: InteropZodType): this {\n this._map.delete(schema);\n return this;\n }\n\n /**\n * Checks if metadata exists for a given schema.\n * @param schema The schema to check.\n * @returns True if metadata exists, false otherwise.\n */\n has(schema: InteropZodType): boolean {\n return this._map.has(schema);\n }\n\n /**\n * Returns a mapping of channel instances for each property in the schema\n * using the associated metadata in the registry.\n *\n * This is used to create the `channels` object that's passed to the `Graph` constructor.\n *\n * @template T The shape of the schema.\n * @param schema The schema to extract channels from.\n * @returns A mapping from property names to channel instances.\n */\n getChannelsForSchema<T extends InteropZodObject>(\n schema: T\n ): InteropZodToStateDefinition<T> {\n const channels = {} as Record<string, BaseChannel>;\n const shape = getInteropZodObjectShape(schema);\n for (const [key, channelSchema] of Object.entries(shape)) {\n const meta = this.get(channelSchema);\n if (meta?.reducer) {\n channels[key] = new BinaryOperatorAggregate<\n InferInteropZodOutput<typeof channelSchema>\n >(meta.reducer.fn, meta.default);\n } else {\n channels[key] = new LastValue(meta?.default);\n }\n }\n return channels as InteropZodToStateDefinition<T>;\n }\n\n /**\n * Returns a modified schema that introspectively looks at all keys of the provided\n * object schema, and applies the augmentations based on meta provided with those keys\n * in the registry and the selectors provided in the `effects` parameter.\n *\n * This assumes that the passed in schema is the \"root\" schema object for a graph where\n * the keys of the schema are the channels of the graph. Because we need to represent\n * the input of a graph in a couple of different ways, the `effects` parameter allows\n * us to apply those augmentations based on pre determined conditions.\n *\n * @param schema The root schema object to extend.\n * @param effects The effects that are being applied.\n * @returns The extended schema.\n */\n getExtendedChannelSchemas<T extends InteropZodObject>(\n schema: T,\n effects: {\n /**\n * Augments the shape by using the reducer's schema if it exists\n */\n withReducerSchema?: boolean;\n /**\n * Applies the stringified jsonSchemaExtra as a description to the schema.\n */\n withJsonSchemaExtrasAsDescription?: boolean;\n /**\n * Applies the `.partial()` modifier to the schema.\n */\n asPartial?: boolean;\n }\n ): InteropZodObject {\n // If no effects are being applied, return the schema unchanged\n if (Object.keys(effects).length === 0) {\n return schema;\n }\n\n // Cache key is determined by looking at the effects that are being applied\n const cacheKey = Object.entries(effects)\n .filter(([, v]) => v === true)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}:${v}`)\n .join(\"|\");\n\n const cache = this._extensionCache.get(cacheKey) ?? new WeakMap();\n if (cache.has(schema)) return cache.get(schema)! as T;\n\n let modifiedSchema: InteropZodObject = schema;\n\n if (\n effects.withReducerSchema ||\n effects.withJsonSchemaExtrasAsDescription\n ) {\n const newShapeEntries = Object.entries(\n getInteropZodObjectShape(schema)\n ).map(([key, schema]) => {\n const meta = this.get(schema);\n let outputSchema = effects.withReducerSchema\n ? meta?.reducer?.schema ?? schema\n : schema;\n if (\n effects.withJsonSchemaExtrasAsDescription &&\n meta?.jsonSchemaExtra\n ) {\n const description =\n getSchemaDescription(outputSchema) ?? getSchemaDescription(schema);\n const strExtras = JSON.stringify({\n ...meta.jsonSchemaExtra,\n description,\n });\n outputSchema = outputSchema.describe(\n `${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`\n );\n }\n return [key, outputSchema];\n });\n modifiedSchema = extendInteropZodObject(\n schema,\n Object.fromEntries(newShapeEntries)\n );\n if (isZodSchemaV3(modifiedSchema)) {\n modifiedSchema._def.unknownKeys = \"strip\";\n }\n }\n if (effects.asPartial) {\n modifiedSchema = interopZodObjectPartial(modifiedSchema);\n }\n\n cache.set(schema, modifiedSchema);\n this._extensionCache.set(cacheKey, cache);\n return modifiedSchema;\n }\n}\n\nexport const schemaMetaRegistry = new SchemaMetaRegistry();\n\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate> & { reducer?: undefined }\n): TSchema;\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate>\n): ReducedZodChannel<TSchema, InteropZodType<TUpdate>>;\nexport function withLangGraph<\n TValue,\n TUpdate,\n TSchema extends InteropZodType<TValue>\n>(\n schema: TSchema,\n meta: SchemaMeta<TValue, TUpdate>\n): ReducedZodChannel<TSchema, InteropZodType<TUpdate>> | TSchema {\n if (meta.reducer && !meta.default) {\n const defaultValueGetter = getInteropZodDefaultGetter(schema);\n if (defaultValueGetter != null) {\n // eslint-disable-next-line no-param-reassign\n meta.default = defaultValueGetter;\n }\n }\n if (meta.reducer) {\n const schemaWithReducer = Object.assign(schema, {\n lg_reducer_schema: meta.reducer?.schema ?? schema,\n });\n schemaMetaRegistry.extend(schemaWithReducer, () => meta);\n return schemaWithReducer;\n } else {\n schemaMetaRegistry.extend(schema, () => meta);\n return schema;\n }\n}\n"],"mappings":";;;;;AAgBA,MAAa,iCAAiC;;;;;AAiE9C,IAAa,qBAAb,MAAgC;;;;;CAK9B,uBAAO,IAAI,SAAqC;;;;;CAMhD,kCAAkB,IAAI,KAAsD;;;;;;;;CAS5E,IACE,QACyC;AACzC,SAAO,KAAK,KAAK,IAAI,OAAO;;;;;;;;;CAU9B,OACE,QACA,WAGA;EACA,MAAM,eAAe,KAAK,IAAqB,OAAO;AACtD,OAAK,KAAK,IAAI,QAAQ,UAAU,aAAa,CAAC;;;;;;;CAQhD,OAAO,QAA8B;AACnC,OAAK,KAAK,OAAO,OAAO;AACxB,SAAO;;;;;;;CAQT,IAAI,QAAiC;AACnC,SAAO,KAAK,KAAK,IAAI,OAAO;;;;;;;;;;;;CAa9B,qBACE,QACgC;EAChC,MAAM,WAAW,EAAE;EACnB,MAAM,kEAAiC,OAAO;AAC9C,OAAK,MAAM,CAAC,KAAK,kBAAkB,OAAO,QAAQ,MAAM,EAAE;GACxD,MAAM,OAAO,KAAK,IAAI,cAAc;AACpC,OAAI,MAAM,QACR,UAAS,OAAO,IAAIA,sCAElB,KAAK,QAAQ,IAAI,KAAK,QAAQ;OAEhC,UAAS,OAAO,IAAIC,6BAAU,MAAM,QAAQ;;AAGhD,SAAO;;;;;;;;;;;;;;;;CAiBT,0BACE,QACA,SAckB;AAElB,MAAI,OAAO,K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KAAK,SAAS;EAChB,MAAM,oBAAoB,OAAO,OAAO,QAAQ,EAC9C,mBAAmB,KAAK,SAAS,UAAU,QAC5C,CAAC;AACF,qBAAmB,OAAO,yBAAyB,KAAK;AACxD,SAAO;QACF;AACL,qBAAmB,OAAO,cAAc,KAAK;AAC7C,SAAO"}
@@ -98,11 +98,11 @@ var SchemaMetaRegistry = class {
98
98
  if (cache.has(schema)) return cache.get(schema);
99
99
  let modifiedSchema = schema;
100
100
  if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) {
101
- const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema$1]) => {
102
- const meta = this.get(schema$1);
103
- let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1;
101
+ const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema]) => {
102
+ const meta = this.get(schema);
103
+ let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema : schema;
104
104
  if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) {
105
- const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema$1);
105
+ const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema);
106
106
  const strExtras = JSON.stringify({
107
107
  ...meta.jsonSchemaExtra,
108
108
  description