@langchain/langgraph 1.4.19 → 1.4.21
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.
- package/dist/channels/base.cjs +41 -9
- package/dist/channels/base.cjs.map +1 -1
- package/dist/channels/base.d.cts +11 -4
- package/dist/channels/base.d.cts.map +1 -1
- package/dist/channels/base.d.ts +11 -4
- package/dist/channels/base.d.ts.map +1 -1
- package/dist/channels/base.js +40 -10
- package/dist/channels/base.js.map +1 -1
- package/dist/constants.cjs +2 -2
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.js +2 -2
- package/dist/constants.js.map +1 -1
- package/dist/pregel/index.cjs +28 -14
- package/dist/pregel/index.cjs.map +1 -1
- package/dist/pregel/index.d.cts.map +1 -1
- package/dist/pregel/index.d.ts.map +1 -1
- package/dist/pregel/index.js +29 -15
- package/dist/pregel/index.js.map +1 -1
- package/dist/pregel/loop.cjs +16 -4
- package/dist/pregel/loop.cjs.map +1 -1
- package/dist/pregel/loop.js +17 -5
- package/dist/pregel/loop.js.map +1 -1
- package/package.json +4 -4
package/dist/channels/base.cjs
CHANGED
|
@@ -105,15 +105,19 @@ function exitDeltaTaskId(step, taskId) {
|
|
|
105
105
|
*
|
|
106
106
|
* A channel snapshots when EITHER its accumulated update count reaches
|
|
107
107
|
* `snapshotFrequency` OR the total supersteps since its last snapshot reaches
|
|
108
|
-
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`.
|
|
108
|
+
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel
|
|
109
|
+
* without a version is skipped: it was never written on this branch, so it
|
|
110
|
+
* has nothing to snapshot. Pass `undefined` on a branch without
|
|
111
|
+
* {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes
|
|
112
|
+
* and this snapshot is what bounds its walk. Pure predicate, no mutation.
|
|
109
113
|
*/
|
|
110
|
-
function deltaChannelsToSnapshot(channels, countersSinceDeltaSnapshot) {
|
|
114
|
+
function deltaChannelsToSnapshot(channels, countersSinceDeltaSnapshot, channelVersions) {
|
|
111
115
|
const result = /* @__PURE__ */ new Set();
|
|
112
116
|
const maxSupersteps = require_constants.getDeltaMaxSuperstepsSinceSnapshot();
|
|
113
117
|
for (const name in channels) {
|
|
114
118
|
if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;
|
|
115
119
|
const ch = channels[name];
|
|
116
|
-
if (!isDeltaChannel(ch) || !ch.isAvailable()) continue;
|
|
120
|
+
if (!isDeltaChannel(ch) || !ch.isAvailable() || channelVersions !== void 0 && channelVersions[name] === void 0) continue;
|
|
117
121
|
const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];
|
|
118
122
|
if (updates >= ch.snapshotFrequency || supersteps >= maxSupersteps) result.add(name);
|
|
119
123
|
}
|
|
@@ -154,6 +158,34 @@ function createCheckpoint(checkpoint, channels, step, options) {
|
|
|
154
158
|
};
|
|
155
159
|
}
|
|
156
160
|
/**
|
|
161
|
+
* Checkpoint metadata key, `true` when every DeltaChannel write on the
|
|
162
|
+
* checkpoint's branch carries a version. A delta channel with no version there
|
|
163
|
+
* was never written, so it needs no walk. Branches started before this key
|
|
164
|
+
* existed never get it: an older `updateState` stored a delta channel's first
|
|
165
|
+
* write without a version, and only the walk finds such a write.
|
|
166
|
+
*/
|
|
167
|
+
const DELTA_WRITES_VERSIONED = "delta_writes_versioned";
|
|
168
|
+
function isDeltaWritesVersioned(metadata) {
|
|
169
|
+
return metadata?.[DELTA_WRITES_VERSIONED] === true;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Delta channels whose value at `checkpoint` the ancestor walk rebuilds.
|
|
173
|
+
*
|
|
174
|
+
* A {@link DeltaSnapshot} or a migrated plain value in `channel_values`
|
|
175
|
+
* resolves directly, so only a channel with nothing stored there needs the
|
|
176
|
+
* walk. With `versionedOnly`, a channel with no version was never written, so
|
|
177
|
+
* it is empty without one; a walk for it would find no snapshot to stop at and
|
|
178
|
+
* read every ancestor, every time the thread is loaded.
|
|
179
|
+
*/
|
|
180
|
+
function deltaChannelsToReplay(specs, checkpoint, versionedOnly) {
|
|
181
|
+
const keys = [];
|
|
182
|
+
for (const k in specs) {
|
|
183
|
+
if (!Object.prototype.hasOwnProperty.call(specs, k)) continue;
|
|
184
|
+
if (isDeltaChannel(specs[k]) && (!versionedOnly || checkpoint.channel_versions[k] !== void 0) && !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)) keys.push(k);
|
|
185
|
+
}
|
|
186
|
+
return keys;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
157
189
|
* Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}
|
|
158
190
|
* whose value is absent from `channel_values` by replaying ancestor writes.
|
|
159
191
|
*
|
|
@@ -163,17 +195,15 @@ function createCheckpoint(checkpoint, channels, step, options) {
|
|
|
163
195
|
* from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`
|
|
164
196
|
* finds the nearest seed and accumulates the writes between it and the
|
|
165
197
|
* target. All delta channels needing replay are batched into a single saver
|
|
166
|
-
* call.
|
|
198
|
+
* call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries
|
|
199
|
+
* {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are
|
|
200
|
+
* left empty instead of walked.
|
|
167
201
|
*/
|
|
168
202
|
async function channelsFromCheckpoint(specs, checkpoint, options) {
|
|
169
203
|
const channels = emptyChannels(specs, checkpoint);
|
|
170
204
|
const { saver, config } = options ?? {};
|
|
171
205
|
const filteredSpecs = getOnlyChannels(specs);
|
|
172
|
-
const deltaKeys =
|
|
173
|
-
for (const k in filteredSpecs) {
|
|
174
|
-
if (!Object.prototype.hasOwnProperty.call(filteredSpecs, k)) continue;
|
|
175
|
-
if (isDeltaChannel(filteredSpecs[k]) && !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)) deltaKeys.push(k);
|
|
176
|
-
}
|
|
206
|
+
const deltaKeys = deltaChannelsToReplay(filteredSpecs, checkpoint, options?.deltaWritesVersioned ?? false);
|
|
177
207
|
const written = deltaKeys.filter((k) => checkpoint.channel_versions[k] !== void 0);
|
|
178
208
|
if ((saver === void 0 || config === void 0) && written.length > 0) throw new Error(`DeltaChannel ${written.join(", ")} has history to replay but no checkpointer or config was passed to read it`);
|
|
179
209
|
if (deltaKeys.length === 0 || saver === void 0 || config === void 0) return channels;
|
|
@@ -192,6 +222,7 @@ async function channelsFromCheckpoint(specs, checkpoint, options) {
|
|
|
192
222
|
}
|
|
193
223
|
//#endregion
|
|
194
224
|
exports.BaseChannel = BaseChannel;
|
|
225
|
+
exports.DELTA_WRITES_VERSIONED = DELTA_WRITES_VERSIONED;
|
|
195
226
|
exports.channelsFromCheckpoint = channelsFromCheckpoint;
|
|
196
227
|
exports.createCheckpoint = createCheckpoint;
|
|
197
228
|
exports.deltaChannelsToSnapshot = deltaChannelsToSnapshot;
|
|
@@ -200,5 +231,6 @@ exports.exitDeltaTaskId = exitDeltaTaskId;
|
|
|
200
231
|
exports.getOnlyChannels = getOnlyChannels;
|
|
201
232
|
exports.isBaseChannel = isBaseChannel;
|
|
202
233
|
exports.isDeltaChannel = isDeltaChannel;
|
|
234
|
+
exports.isDeltaWritesVersioned = isDeltaWritesVersioned;
|
|
203
235
|
|
|
204
236
|
//# sourceMappingURL=base.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["EmptyChannelError","getDeltaMaxSuperstepsSinceSnapshot","DeltaSnapshot"],"sources":["../../src/channels/base.ts"],"sourcesContent":["import {\n ReadonlyCheckpoint,\n uuid6,\n Checkpoint,\n DeltaSnapshot,\n type BaseCheckpointSaver,\n type DeltaChannelHistory,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { EmptyChannelError } from \"../errors.js\";\nimport { getDeltaMaxSuperstepsSinceSnapshot } from \"../constants.js\";\n\n/** Matches Postgres `uuid` / Python `uuid.UUID` (128-bit, 8-4-4-4-12 hex). */\nconst STRUCTURED_UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Structural check for a {@link DeltaChannel} without importing it (avoids an\n * import cycle: `delta.ts` imports `base.ts`).\n */\nexport function isDeltaChannel(channel: BaseChannel): boolean {\n return channel != null && channel.lc_graph_name === \"DeltaChannel\";\n}\n\nexport function isBaseChannel(obj: unknown): obj is BaseChannel {\n return obj != null && (obj as BaseChannel).lg_is_channel === true;\n}\n\n/** @internal */\nexport abstract class BaseChannel<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown,\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n abstract lc_graph_name: string;\n\n /** @ignore */\n lg_is_channel = true;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @param {CheckpointType | undefined} initialValue\n * @returns {this}\n */\n abstract fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n * This method is called by Pregel for all channels at the end of each step.\n * If there are no updates, it is called with an empty sequence.\n *\n * Raises InvalidUpdateError if the sequence of updates is invalid.\n * Returns True if the channel was updated, False otherwise.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n abstract update(values: UpdateType[]): boolean;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n abstract get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n abstract checkpoint(): CheckpointType | undefined;\n\n /**\n * Mark the current value of the channel as consumed. By default, no-op.\n * A channel can use this method to modify its state, preventing the value\n * from being consumed again.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n consume(): boolean {\n return false;\n }\n\n /**\n * Notify the channel that the Pregel run is finishing. By default, no-op.\n * A channel can use this method to modify its state, preventing finish.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n finish(): boolean {\n return false;\n }\n\n /**\n * Return True if the channel is available (not empty), False otherwise.\n * Subclasses should override this method to provide a more efficient\n * implementation than calling get() and catching EmptyChannelError.\n */\n isAvailable(): boolean {\n try {\n this.get();\n return true;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Compare this channel with another channel for equality.\n * Used to determine if two channels with the same key are semantically equivalent.\n * Subclasses should override this method to provide a meaningful comparison.\n *\n * @param {BaseChannel} other - The other channel to compare with.\n * @returns {boolean} True if the channels are equal, false otherwise.\n */\n equals(other: BaseChannel): boolean {\n return this === other;\n }\n}\n\nconst IS_ONLY_BASE_CHANNEL = Symbol.for(\"LG_IS_ONLY_BASE_CHANNEL\");\nexport function getOnlyChannels(\n channels: Record<string, BaseChannel>\n): Record<string, BaseChannel> {\n // @ts-expect-error - we know it's a record of base channels\n if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels;\n\n const newChannels = {} as Record<string, BaseChannel>;\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const value = channels[k];\n if (isBaseChannel(value)) newChannels[k] = value;\n }\n\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\nexport function emptyChannels<Cc extends Record<string, BaseChannel>>(\n channels: Cc,\n checkpoint: ReadonlyCheckpoint\n): Cc {\n const filteredChannels = getOnlyChannels(channels) as Cc;\n\n const newChannels = {} as Cc;\n for (const k in filteredChannels) {\n if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue;\n const channelValue = checkpoint.channel_values[k];\n newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue);\n }\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\n/**\n * Minimal structural view of a {@link DeltaChannel}, used by helpers in this\n * module that must not import the concrete class (import-cycle avoidance).\n */\ninterface DeltaChannelLike extends BaseChannel {\n snapshotFrequency: number;\n replayWrites(writes: DeltaChannelHistory[\"writes\"]): void;\n}\n\n/**\n * Synthetic task id for exit-mode DeltaChannel writes.\n *\n * Embeds the superstep in the first UUID group so `ORDER BY task_id, idx`\n * preserves chronological order while remaining a valid RFC UUID (required by\n * Postgres `checkpoint_writes.task_id uuid` columns).\n */\nexport function exitDeltaTaskId(step: number, taskId: string): string {\n if (!STRUCTURED_UUID.test(taskId)) {\n throw new TypeError(`Invalid task id for exit delta: ${taskId}`);\n }\n const parts = taskId.toLowerCase().split(\"-\");\n const stepPart = String(step).padStart(8, \"0\");\n return `${stepPart}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`;\n}\n\n/**\n * Return the set of {@link DeltaChannel} names that should snapshot now.\n *\n * A channel snapshots when EITHER its accumulated update count reaches\n * `snapshotFrequency` OR the total supersteps since its last snapshot reaches\n * `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Pure predicate — no mutation.\n */\nexport function deltaChannelsToSnapshot(\n channels: Record<string, BaseChannel>,\n countersSinceDeltaSnapshot: Record<string, [number, number]>\n): Set<string> {\n const result = new Set<string>();\n const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot();\n for (const name in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;\n const ch = channels[name];\n if (!isDeltaChannel(ch) || !ch.isAvailable()) continue;\n const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];\n if (\n updates >= (ch as DeltaChannelLike).snapshotFrequency ||\n supersteps >= maxSupersteps\n ) {\n result.add(name);\n }\n }\n return result;\n}\n\nexport function createCheckpoint<ValueType>(\n checkpoint: ReadonlyCheckpoint,\n channels: Record<string, BaseChannel<ValueType>> | undefined,\n step: number,\n options?: {\n id?: string;\n channelsToSnapshot?: Set<string>;\n updatedChannels?: Set<string>;\n getNextVersion?: (current: number | string | undefined) => number | string;\n }\n): Checkpoint {\n const channelsToSnapshot = options?.channelsToSnapshot ?? new Set<string>();\n const { updatedChannels, getNextVersion } = options ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let values: Record<string, any>;\n let channelVersions: Record<string, number | string> =\n checkpoint.channel_versions;\n if (channels === undefined) {\n values = checkpoint.channel_values;\n } else {\n values = {};\n channelVersions = { ...checkpoint.channel_versions };\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const channel = channels[k];\n if (channelsToSnapshot.has(k)) {\n // Snapshot a DeltaChannel: store the materialized value directly. In\n // exit/deferred modes the channel may have reached its snapshot\n // threshold over several supersteps without the LAST superstep\n // writing to it, so its version wouldn't be bumped by applyWrites —\n // bump it here so the saver includes the snapshot blob.\n if (\n getNextVersion !== undefined &&\n (updatedChannels === undefined || !updatedChannels.has(k))\n ) {\n channelVersions[k] = getNextVersion(channelVersions[k]);\n }\n values[k] = new DeltaSnapshot(channel.get());\n continue;\n }\n if (isDeltaChannel(channel)) {\n // Omitted from channel_values; reconstructed from ancestor writes.\n continue;\n }\n try {\n values[k] = channel.checkpoint();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n // no-op\n } else {\n throw error; // Rethrow unexpected errors\n }\n }\n }\n }\n\n return {\n v: 4,\n id: options?.id ?? uuid6(step),\n ts: new Date().toISOString(),\n channel_values: values,\n channel_versions: channelVersions,\n versions_seen: checkpoint.versions_seen,\n };\n}\n\n/**\n * Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}\n * whose value is absent from `channel_values` by replaying ancestor writes.\n *\n * For most channels (and for delta channels with a {@link DeltaSnapshot} or a\n * migrated plain value in `channel_values`), {@link emptyChannels} is\n * sufficient and no saver access is required. When a delta channel is absent\n * from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`\n * finds the nearest seed and accumulates the writes between it and the\n * target. All delta channels needing replay are batched into a single saver\n * call.\n */\nexport async function channelsFromCheckpoint<\n Cc extends Record<string, BaseChannel>,\n>(\n specs: Cc,\n checkpoint: ReadonlyCheckpoint,\n options?: { saver?: BaseCheckpointSaver; config?: RunnableConfig }\n): Promise<Cc> {\n const channels = emptyChannels(specs, checkpoint);\n const { saver, config } = options ?? {};\n\n const filteredSpecs = getOnlyChannels(specs);\n const deltaKeys: string[] = [];\n for (const k in filteredSpecs) {\n if (!Object.prototype.hasOwnProperty.call(filteredSpecs, k)) continue;\n if (\n isDeltaChannel(filteredSpecs[k]) &&\n !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)\n ) {\n deltaKeys.push(k);\n }\n }\n\n const written = deltaKeys.filter(\n (k) => checkpoint.channel_versions[k] !== undefined\n );\n if ((saver === undefined || config === undefined) && written.length > 0) {\n throw new Error(\n `DeltaChannel ${written.join(\", \")} has history to replay but no checkpointer or config was passed to read it`\n );\n }\n if (deltaKeys.length === 0 || saver === undefined || config === undefined) {\n return channels;\n }\n\n const histories = await saver.getDeltaChannelHistory({\n config,\n channels: deltaKeys,\n });\n for (const k of deltaKeys) {\n const history = histories[k];\n if (history === undefined) continue;\n const replayCh = filteredSpecs[k].fromCheckpoint(\n history.seed\n ) as unknown as DeltaChannelLike;\n replayCh.replayWrites(history.writes);\n (channels as Record<string, BaseChannel>)[k] = replayCh;\n }\n return channels;\n}\n"],"mappings":";;;;;AAaA,MAAM,kBACJ;;;;;AAMF,SAAgB,eAAe,SAA+B;AAC5D,QAAO,WAAW,QAAQ,QAAQ,kBAAkB;;AAGtD,SAAgB,cAAc,KAAkC;AAC9D,QAAO,OAAO,QAAS,IAAoB,kBAAkB;;;AAI/D,IAAsB,cAAtB,MAIE;CACA;CAE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AO;EACL,GAAG;EACH,IAAI,SAAS,OAAA,GAAA,gCAAA,OAAY,KAAK;EAC9B,qBAAI,IAAI,MAAM,EAAC,aAAa;EAC5B,gBAAgB;EAChB,kBAAkB;EAClB,eAAe,WAAW;EAC3B;;;;;;;;;;;;;;AAeH,eAAsB,uBAGpB,OACA,YACA,SACa;CACb,MAAM,WAAW,cAAc,OAAO,WAAW;CACjD,MAAM,EAAE,OAAO,WAAW,WAAW,EAAE;CAEvC,MAAM,gBAAgB,gBAAgB,MAAM;CAC5C,MAAM,YAAsB,EAAE;AAC9B,MAAK,MAAM,KAAK,eAAe;AAC7B,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,eAAe,EAAE,CAAE;AAC7D,MACE,eAAe,cAAc,GAAG,IAChC,CAAC,OAAO,UAAU,eAAe,KAAK,WAAW,gBAAgB,EAAE,CAEnE,WAAU,KAAK,EAAE;;CAIrB,MAAM,UAAU,UAAU,QACvB,MAAM,WAAW,iBAAiB,OAAO,KAAA,EAC3C;AACD,MAAK,UAAU,KAAA,KAAa,WAAW,KAAA,MAAc,QAAQ,SAAS,EACpE,OAAM,IAAI,MACR,gBAAgB,QAAQ,KAAK,KAAK,CAAC,4EACpC;AAEH,KAAI,UAAU,WAAW,KAAK,UAAU,KAAA,KAAa,WAAW,KAAA,EAC9D,QAAO;CAGT,MAAM,YAAY,MAAM,MAAM,uBAAuB;EACnD;EACA,UAAU;EACX,CAAC;AACF,MAAK,MAAM,KAAK,WAAW;EACzB,MAAM,UAAU,UAAU;AAC1B,MAAI,YAAY,KAAA,EAAW;EAC3B,MAAM,WAAW,cAAc,GAAG,eAChC,QAAQ,KACT;AACD,WAAS,aAAa,QAAQ,OAAO;AACpC,WAAyC,KAAK;;AAEjD,QAAO"}
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["EmptyChannelError","getDeltaMaxSuperstepsSinceSnapshot","DeltaSnapshot"],"sources":["../../src/channels/base.ts"],"sourcesContent":["import {\n ReadonlyCheckpoint,\n uuid6,\n Checkpoint,\n DeltaSnapshot,\n type BaseCheckpointSaver,\n type CheckpointMetadata,\n type DeltaChannelHistory,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { EmptyChannelError } from \"../errors.js\";\nimport { getDeltaMaxSuperstepsSinceSnapshot } from \"../constants.js\";\n\n/** Matches Postgres `uuid` / Python `uuid.UUID` (128-bit, 8-4-4-4-12 hex). */\nconst STRUCTURED_UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Structural check for a {@link DeltaChannel} without importing it (avoids an\n * import cycle: `delta.ts` imports `base.ts`).\n */\nexport function isDeltaChannel(channel: BaseChannel): boolean {\n return channel != null && channel.lc_graph_name === \"DeltaChannel\";\n}\n\nexport function isBaseChannel(obj: unknown): obj is BaseChannel {\n return obj != null && (obj as BaseChannel).lg_is_channel === true;\n}\n\n/** @internal */\nexport abstract class BaseChannel<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown,\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n abstract lc_graph_name: string;\n\n /** @ignore */\n lg_is_channel = true;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @param {CheckpointType | undefined} initialValue\n * @returns {this}\n */\n abstract fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n * This method is called by Pregel for all channels at the end of each step.\n * If there are no updates, it is called with an empty sequence.\n *\n * Raises InvalidUpdateError if the sequence of updates is invalid.\n * Returns True if the channel was updated, False otherwise.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n abstract update(values: UpdateType[]): boolean;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n abstract get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n abstract checkpoint(): CheckpointType | undefined;\n\n /**\n * Mark the current value of the channel as consumed. By default, no-op.\n * A channel can use this method to modify its state, preventing the value\n * from being consumed again.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n consume(): boolean {\n return false;\n }\n\n /**\n * Notify the channel that the Pregel run is finishing. By default, no-op.\n * A channel can use this method to modify its state, preventing finish.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n finish(): boolean {\n return false;\n }\n\n /**\n * Return True if the channel is available (not empty), False otherwise.\n * Subclasses should override this method to provide a more efficient\n * implementation than calling get() and catching EmptyChannelError.\n */\n isAvailable(): boolean {\n try {\n this.get();\n return true;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Compare this channel with another channel for equality.\n * Used to determine if two channels with the same key are semantically equivalent.\n * Subclasses should override this method to provide a meaningful comparison.\n *\n * @param {BaseChannel} other - The other channel to compare with.\n * @returns {boolean} True if the channels are equal, false otherwise.\n */\n equals(other: BaseChannel): boolean {\n return this === other;\n }\n}\n\nconst IS_ONLY_BASE_CHANNEL = Symbol.for(\"LG_IS_ONLY_BASE_CHANNEL\");\nexport function getOnlyChannels(\n channels: Record<string, BaseChannel>\n): Record<string, BaseChannel> {\n // @ts-expect-error - we know it's a record of base channels\n if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels;\n\n const newChannels = {} as Record<string, BaseChannel>;\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const value = channels[k];\n if (isBaseChannel(value)) newChannels[k] = value;\n }\n\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\nexport function emptyChannels<Cc extends Record<string, BaseChannel>>(\n channels: Cc,\n checkpoint: ReadonlyCheckpoint\n): Cc {\n const filteredChannels = getOnlyChannels(channels) as Cc;\n\n const newChannels = {} as Cc;\n for (const k in filteredChannels) {\n if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue;\n const channelValue = checkpoint.channel_values[k];\n newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue);\n }\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\n/**\n * Minimal structural view of a {@link DeltaChannel}, used by helpers in this\n * module that must not import the concrete class (import-cycle avoidance).\n */\ninterface DeltaChannelLike extends BaseChannel {\n snapshotFrequency: number;\n replayWrites(writes: DeltaChannelHistory[\"writes\"]): void;\n}\n\n/**\n * Synthetic task id for exit-mode DeltaChannel writes.\n *\n * Embeds the superstep in the first UUID group so `ORDER BY task_id, idx`\n * preserves chronological order while remaining a valid RFC UUID (required by\n * Postgres `checkpoint_writes.task_id uuid` columns).\n */\nexport function exitDeltaTaskId(step: number, taskId: string): string {\n if (!STRUCTURED_UUID.test(taskId)) {\n throw new TypeError(`Invalid task id for exit delta: ${taskId}`);\n }\n const parts = taskId.toLowerCase().split(\"-\");\n const stepPart = String(step).padStart(8, \"0\");\n return `${stepPart}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`;\n}\n\n/**\n * Return the set of {@link DeltaChannel} names that should snapshot now.\n *\n * A channel snapshots when EITHER its accumulated update count reaches\n * `snapshotFrequency` OR the total supersteps since its last snapshot reaches\n * `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel\n * without a version is skipped: it was never written on this branch, so it\n * has nothing to snapshot. Pass `undefined` on a branch without\n * {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes\n * and this snapshot is what bounds its walk. Pure predicate, no mutation.\n */\nexport function deltaChannelsToSnapshot(\n channels: Record<string, BaseChannel>,\n countersSinceDeltaSnapshot: Record<string, [number, number]>,\n channelVersions: Record<string, number | string> | undefined\n): Set<string> {\n const result = new Set<string>();\n const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot();\n for (const name in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;\n const ch = channels[name];\n if (\n !isDeltaChannel(ch) ||\n !ch.isAvailable() ||\n (channelVersions !== undefined && channelVersions[name] === undefined)\n ) {\n continue;\n }\n const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];\n if (\n updates >= (ch as DeltaChannelLike).snapshotFrequency ||\n supersteps >= maxSupersteps\n ) {\n result.add(name);\n }\n }\n return result;\n}\n\nexport function createCheckpoint<ValueType>(\n checkpoint: ReadonlyCheckpoint,\n channels: Record<string, BaseChannel<ValueType>> | undefined,\n step: number,\n options?: {\n id?: string;\n channelsToSnapshot?: Set<string>;\n updatedChannels?: Set<string>;\n getNextVersion?: (current: number | string | undefined) => number | string;\n }\n): Checkpoint {\n const channelsToSnapshot = options?.channelsToSnapshot ?? new Set<string>();\n const { updatedChannels, getNextVersion } = options ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let values: Record<string, any>;\n let channelVersions: Record<string, number | string> =\n checkpoint.channel_versions;\n if (channels === undefined) {\n values = checkpoint.channel_values;\n } else {\n values = {};\n channelVersions = { ...checkpoint.channel_versions };\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const channel = channels[k];\n if (channelsToSnapshot.has(k)) {\n // Snapshot a DeltaChannel: store the materialized value directly. In\n // exit/deferred modes the channel may have reached its snapshot\n // threshold over several supersteps without the LAST superstep\n // writing to it, so its version wouldn't be bumped by applyWrites —\n // bump it here so the saver includes the snapshot blob.\n if (\n getNextVersion !== undefined &&\n (updatedChannels === undefined || !updatedChannels.has(k))\n ) {\n channelVersions[k] = getNextVersion(channelVersions[k]);\n }\n values[k] = new DeltaSnapshot(channel.get());\n continue;\n }\n if (isDeltaChannel(channel)) {\n // Omitted from channel_values; reconstructed from ancestor writes.\n continue;\n }\n try {\n values[k] = channel.checkpoint();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n // no-op\n } else {\n throw error; // Rethrow unexpected errors\n }\n }\n }\n }\n\n return {\n v: 4,\n id: options?.id ?? uuid6(step),\n ts: new Date().toISOString(),\n channel_values: values,\n channel_versions: channelVersions,\n versions_seen: checkpoint.versions_seen,\n };\n}\n\n/**\n * Checkpoint metadata key, `true` when every DeltaChannel write on the\n * checkpoint's branch carries a version. A delta channel with no version there\n * was never written, so it needs no walk. Branches started before this key\n * existed never get it: an older `updateState` stored a delta channel's first\n * write without a version, and only the walk finds such a write.\n */\nexport const DELTA_WRITES_VERSIONED = \"delta_writes_versioned\";\n\nexport function isDeltaWritesVersioned(\n metadata: CheckpointMetadata | undefined\n): boolean {\n return (\n (metadata as Record<string, unknown> | undefined)?.[\n DELTA_WRITES_VERSIONED\n ] === true\n );\n}\n\n/**\n * Delta channels whose value at `checkpoint` the ancestor walk rebuilds.\n *\n * A {@link DeltaSnapshot} or a migrated plain value in `channel_values`\n * resolves directly, so only a channel with nothing stored there needs the\n * walk. With `versionedOnly`, a channel with no version was never written, so\n * it is empty without one; a walk for it would find no snapshot to stop at and\n * read every ancestor, every time the thread is loaded.\n */\nfunction deltaChannelsToReplay(\n specs: Record<string, BaseChannel>,\n checkpoint: ReadonlyCheckpoint,\n versionedOnly: boolean\n): string[] {\n const keys: string[] = [];\n for (const k in specs) {\n if (!Object.prototype.hasOwnProperty.call(specs, k)) continue;\n if (\n isDeltaChannel(specs[k]) &&\n (!versionedOnly || checkpoint.channel_versions[k] !== undefined) &&\n !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)\n ) {\n keys.push(k);\n }\n }\n return keys;\n}\n\n/**\n * Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}\n * whose value is absent from `channel_values` by replaying ancestor writes.\n *\n * For most channels (and for delta channels with a {@link DeltaSnapshot} or a\n * migrated plain value in `channel_values`), {@link emptyChannels} is\n * sufficient and no saver access is required. When a delta channel is absent\n * from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`\n * finds the nearest seed and accumulates the writes between it and the\n * target. All delta channels needing replay are batched into a single saver\n * call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries\n * {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are\n * left empty instead of walked.\n */\nexport async function channelsFromCheckpoint<\n Cc extends Record<string, BaseChannel>,\n>(\n specs: Cc,\n checkpoint: ReadonlyCheckpoint,\n options?: {\n saver?: BaseCheckpointSaver;\n config?: RunnableConfig;\n deltaWritesVersioned?: boolean;\n }\n): Promise<Cc> {\n const channels = emptyChannels(specs, checkpoint);\n const { saver, config } = options ?? {};\n\n const filteredSpecs = getOnlyChannels(specs);\n const deltaKeys = deltaChannelsToReplay(\n filteredSpecs,\n checkpoint,\n options?.deltaWritesVersioned ?? false\n );\n\n const written = deltaKeys.filter(\n (k) => checkpoint.channel_versions[k] !== undefined\n );\n if ((saver === undefined || config === undefined) && written.length > 0) {\n throw new Error(\n `DeltaChannel ${written.join(\", \")} has history to replay but no checkpointer or config was passed to read it`\n );\n }\n if (deltaKeys.length === 0 || saver === undefined || config === undefined) {\n return channels;\n }\n\n const histories = await saver.getDeltaChannelHistory({\n config,\n channels: deltaKeys,\n });\n for (const k of deltaKeys) {\n const history = histories[k];\n if (history === undefined) continue;\n const replayCh = filteredSpecs[k].fromCheckpoint(\n history.seed\n ) as unknown as DeltaChannelLike;\n replayCh.replayWrites(history.writes);\n (channels as Record<string, BaseChannel>)[k] = replayCh;\n }\n return channels;\n}\n"],"mappings":";;;;;AAcA,MAAM,kBACJ;;;;;AAMF,SAAgB,eAAe,SAA+B;AAC5D,QAAO,WAAW,QAAQ,QAAQ,kBAAkB;;AAGtD,SAAgB,cAAc,KAAkC;A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;EACA,UAAU;EACX,CAAC;AACF,MAAK,MAAM,KAAK,WAAW;EACzB,MAAM,UAAU,UAAU;AAC1B,MAAI,YAAY,KAAA,EAAW;EAC3B,MAAM,WAAW,cAAc,GAAG,eAChC,QAAQ,KACT;AACD,WAAS,aAAa,QAAQ,OAAO;AACpC,WAAyC,KAAK;;AAEjD,QAAO"}
|
package/dist/channels/base.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BaseCheckpointSaver, Checkpoint, ReadonlyCheckpoint } from "@langchain/langgraph-checkpoint";
|
|
1
|
+
import { BaseCheckpointSaver, Checkpoint, CheckpointMetadata, ReadonlyCheckpoint } from "@langchain/langgraph-checkpoint";
|
|
2
2
|
import { RunnableConfig } from "@langchain/core/runnables";
|
|
3
3
|
|
|
4
4
|
//#region src/channels/base.d.ts
|
|
@@ -99,9 +99,13 @@ declare function exitDeltaTaskId(step: number, taskId: string): string;
|
|
|
99
99
|
*
|
|
100
100
|
* A channel snapshots when EITHER its accumulated update count reaches
|
|
101
101
|
* `snapshotFrequency` OR the total supersteps since its last snapshot reaches
|
|
102
|
-
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`.
|
|
102
|
+
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel
|
|
103
|
+
* without a version is skipped: it was never written on this branch, so it
|
|
104
|
+
* has nothing to snapshot. Pass `undefined` on a branch without
|
|
105
|
+
* {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes
|
|
106
|
+
* and this snapshot is what bounds its walk. Pure predicate, no mutation.
|
|
103
107
|
*/
|
|
104
|
-
declare function deltaChannelsToSnapshot(channels: Record<string, BaseChannel>, countersSinceDeltaSnapshot: Record<string, [number, number]>): Set<string>;
|
|
108
|
+
declare function deltaChannelsToSnapshot(channels: Record<string, BaseChannel>, countersSinceDeltaSnapshot: Record<string, [number, number]>, channelVersions: Record<string, number | string> | undefined): Set<string>;
|
|
105
109
|
declare function createCheckpoint<ValueType>(checkpoint: ReadonlyCheckpoint, channels: Record<string, BaseChannel<ValueType>> | undefined, step: number, options?: {
|
|
106
110
|
id?: string;
|
|
107
111
|
channelsToSnapshot?: Set<string>;
|
|
@@ -118,11 +122,14 @@ declare function createCheckpoint<ValueType>(checkpoint: ReadonlyCheckpoint, cha
|
|
|
118
122
|
* from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`
|
|
119
123
|
* finds the nearest seed and accumulates the writes between it and the
|
|
120
124
|
* target. All delta channels needing replay are batched into a single saver
|
|
121
|
-
* call.
|
|
125
|
+
* call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries
|
|
126
|
+
* {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are
|
|
127
|
+
* left empty instead of walked.
|
|
122
128
|
*/
|
|
123
129
|
declare function channelsFromCheckpoint<Cc extends Record<string, BaseChannel>>(specs: Cc, checkpoint: ReadonlyCheckpoint, options?: {
|
|
124
130
|
saver?: BaseCheckpointSaver;
|
|
125
131
|
config?: RunnableConfig;
|
|
132
|
+
deltaWritesVersioned?: boolean;
|
|
126
133
|
}): Promise<Cc>;
|
|
127
134
|
//#endregion
|
|
128
135
|
export { BaseChannel, channelsFromCheckpoint, createCheckpoint, deltaChannelsToSnapshot, emptyChannels, exitDeltaTaskId, isDeltaChannel };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.cts","names":[],"sources":["../../src/channels/base.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"base.d.cts","names":[],"sources":["../../src/channels/base.ts"],"mappings":";;;;;;AAqBA;;iBAAgB,cAAA,CAAe,OAAA,EAAS,WAAA;;uBASlB,WAAA;EAKpB,SAAA,EAAW,SAAA;EAEX,UAAA,EAAY,UAAA;EAFD;;;EAAA,SAOF,aAAA;EAoCO;EAjChB,aAAA;EA0Fc;;;;;;;;EAAA,SAhFL,cAAA,CAAe,UAAA,GAAa,cAAA;EAlBzB;;;;;;;;;;;;;EAAA,SAiCH,MAAA,CAAO,MAAA,EAAQ,UAAA;EAmCxB;;;;;;EAAA,SA3BS,GAAA,CAAA,GAAO,SAAA;EAgFF;;;;;;EAAA,SAxEL,UAAA,CAAA,GAAc,cAAA;EA2EtB;;;;;;;EAlED,OAAA,CAAA;EAiEY;;;;;AA8Bd;EArFE,MAAA,CAAA;;;;AAyGF;;EAhGE,WAAA,CAAA;EAiGyB;;;;;;;;EA5EzB,MAAA,CAAO,KAAA,EAAO,WAAA;AAAA;AAAA,iBAuBA,aAAA,YAAyB,MAAA,SAAe,WAAA,EAAA,CACtD,QAAA,EAAU,EAAA,EACV,UAAA,EAAY,kBAAA,GACX,EAAA;;;;;;AA6EH;;iBAhDgB,eAAA,CAAgB,IAAA,UAAc,MAAA;;;;;;;;;;;;iBAoB9B,uBAAA,CACd,QAAA,EAAU,MAAA,SAAe,WAAA,GACzB,0BAAA,EAA4B,MAAA,4BAC5B,eAAA,EAAiB,MAAA,wCAChB,GAAA;AAAA,iBAwBa,gBAAA,WAAA,CACd,UAAA,EAAY,kBAAA,EACZ,QAAA,EAAU,MAAA,SAAe,WAAA,CAAY,SAAA,gBACrC,IAAA,UACA,OAAA;EACE,EAAA;EACA,kBAAA,GAAqB,GAAA;EACrB,eAAA,GAAkB,GAAA;EAClB,cAAA,IAAkB,OAAA;AAAA,IAEnB,UAAA;;AAsHH;;;;;;;;;;;;;iBAAsB,sBAAA,YACT,MAAA,SAAe,WAAA,EAAA,CAE1B,KAAA,EAAO,EAAA,EACP,UAAA,EAAY,kBAAA,EACZ,OAAA;EACE,KAAA,GAAQ,mBAAA;EACR,MAAA,GAAS,cAAA;EACT,oBAAA;AAAA,IAED,OAAA,CAAQ,EAAA"}
|
package/dist/channels/base.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BaseCheckpointSaver, Checkpoint, ReadonlyCheckpoint } from "@langchain/langgraph-checkpoint";
|
|
1
|
+
import { BaseCheckpointSaver, Checkpoint, CheckpointMetadata, ReadonlyCheckpoint } from "@langchain/langgraph-checkpoint";
|
|
2
2
|
import { RunnableConfig } from "@langchain/core/runnables";
|
|
3
3
|
|
|
4
4
|
//#region src/channels/base.d.ts
|
|
@@ -99,9 +99,13 @@ declare function exitDeltaTaskId(step: number, taskId: string): string;
|
|
|
99
99
|
*
|
|
100
100
|
* A channel snapshots when EITHER its accumulated update count reaches
|
|
101
101
|
* `snapshotFrequency` OR the total supersteps since its last snapshot reaches
|
|
102
|
-
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`.
|
|
102
|
+
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel
|
|
103
|
+
* without a version is skipped: it was never written on this branch, so it
|
|
104
|
+
* has nothing to snapshot. Pass `undefined` on a branch without
|
|
105
|
+
* {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes
|
|
106
|
+
* and this snapshot is what bounds its walk. Pure predicate, no mutation.
|
|
103
107
|
*/
|
|
104
|
-
declare function deltaChannelsToSnapshot(channels: Record<string, BaseChannel>, countersSinceDeltaSnapshot: Record<string, [number, number]>): Set<string>;
|
|
108
|
+
declare function deltaChannelsToSnapshot(channels: Record<string, BaseChannel>, countersSinceDeltaSnapshot: Record<string, [number, number]>, channelVersions: Record<string, number | string> | undefined): Set<string>;
|
|
105
109
|
declare function createCheckpoint<ValueType>(checkpoint: ReadonlyCheckpoint, channels: Record<string, BaseChannel<ValueType>> | undefined, step: number, options?: {
|
|
106
110
|
id?: string;
|
|
107
111
|
channelsToSnapshot?: Set<string>;
|
|
@@ -118,11 +122,14 @@ declare function createCheckpoint<ValueType>(checkpoint: ReadonlyCheckpoint, cha
|
|
|
118
122
|
* from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`
|
|
119
123
|
* finds the nearest seed and accumulates the writes between it and the
|
|
120
124
|
* target. All delta channels needing replay are batched into a single saver
|
|
121
|
-
* call.
|
|
125
|
+
* call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries
|
|
126
|
+
* {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are
|
|
127
|
+
* left empty instead of walked.
|
|
122
128
|
*/
|
|
123
129
|
declare function channelsFromCheckpoint<Cc extends Record<string, BaseChannel>>(specs: Cc, checkpoint: ReadonlyCheckpoint, options?: {
|
|
124
130
|
saver?: BaseCheckpointSaver;
|
|
125
131
|
config?: RunnableConfig;
|
|
132
|
+
deltaWritesVersioned?: boolean;
|
|
126
133
|
}): Promise<Cc>;
|
|
127
134
|
//#endregion
|
|
128
135
|
export { BaseChannel, channelsFromCheckpoint, createCheckpoint, deltaChannelsToSnapshot, emptyChannels, exitDeltaTaskId, isDeltaChannel };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/channels/base.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/channels/base.ts"],"mappings":";;;;;;AAqBA;;iBAAgB,cAAA,CAAe,OAAA,EAAS,WAAA;;uBASlB,WAAA;EAKpB,SAAA,EAAW,SAAA;EAEX,UAAA,EAAY,UAAA;EAFD;;;EAAA,SAOF,aAAA;EAoCO;EAjChB,aAAA;EA0Fc;;;;;;;;EAAA,SAhFL,cAAA,CAAe,UAAA,GAAa,cAAA;EAlBzB;;;;;;;;;;;;;EAAA,SAiCH,MAAA,CAAO,MAAA,EAAQ,UAAA;EAmCxB;;;;;;EAAA,SA3BS,GAAA,CAAA,GAAO,SAAA;EAgFF;;;;;;EAAA,SAxEL,UAAA,CAAA,GAAc,cAAA;EA2EtB;;;;;;;EAlED,OAAA,CAAA;EAiEY;;;;;AA8Bd;EArFE,MAAA,CAAA;;;;AAyGF;;EAhGE,WAAA,CAAA;EAiGyB;;;;;;;;EA5EzB,MAAA,CAAO,KAAA,EAAO,WAAA;AAAA;AAAA,iBAuBA,aAAA,YAAyB,MAAA,SAAe,WAAA,EAAA,CACtD,QAAA,EAAU,EAAA,EACV,UAAA,EAAY,kBAAA,GACX,EAAA;;;;;;AA6EH;;iBAhDgB,eAAA,CAAgB,IAAA,UAAc,MAAA;;;;;;;;;;;;iBAoB9B,uBAAA,CACd,QAAA,EAAU,MAAA,SAAe,WAAA,GACzB,0BAAA,EAA4B,MAAA,4BAC5B,eAAA,EAAiB,MAAA,wCAChB,GAAA;AAAA,iBAwBa,gBAAA,WAAA,CACd,UAAA,EAAY,kBAAA,EACZ,QAAA,EAAU,MAAA,SAAe,WAAA,CAAY,SAAA,gBACrC,IAAA,UACA,OAAA;EACE,EAAA;EACA,kBAAA,GAAqB,GAAA;EACrB,eAAA,GAAkB,GAAA;EAClB,cAAA,IAAkB,OAAA;AAAA,IAEnB,UAAA;;AAsHH;;;;;;;;;;;;;iBAAsB,sBAAA,YACT,MAAA,SAAe,WAAA,EAAA,CAE1B,KAAA,EAAO,EAAA,EACP,UAAA,EAAY,kBAAA,EACZ,OAAA;EACE,KAAA,GAAQ,mBAAA;EACR,MAAA,GAAS,cAAA;EACT,oBAAA;AAAA,IAED,OAAA,CAAQ,EAAA"}
|
package/dist/channels/base.js
CHANGED
|
@@ -105,15 +105,19 @@ function exitDeltaTaskId(step, taskId) {
|
|
|
105
105
|
*
|
|
106
106
|
* A channel snapshots when EITHER its accumulated update count reaches
|
|
107
107
|
* `snapshotFrequency` OR the total supersteps since its last snapshot reaches
|
|
108
|
-
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`.
|
|
108
|
+
* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel
|
|
109
|
+
* without a version is skipped: it was never written on this branch, so it
|
|
110
|
+
* has nothing to snapshot. Pass `undefined` on a branch without
|
|
111
|
+
* {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes
|
|
112
|
+
* and this snapshot is what bounds its walk. Pure predicate, no mutation.
|
|
109
113
|
*/
|
|
110
|
-
function deltaChannelsToSnapshot(channels, countersSinceDeltaSnapshot) {
|
|
114
|
+
function deltaChannelsToSnapshot(channels, countersSinceDeltaSnapshot, channelVersions) {
|
|
111
115
|
const result = /* @__PURE__ */ new Set();
|
|
112
116
|
const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot();
|
|
113
117
|
for (const name in channels) {
|
|
114
118
|
if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;
|
|
115
119
|
const ch = channels[name];
|
|
116
|
-
if (!isDeltaChannel(ch) || !ch.isAvailable()) continue;
|
|
120
|
+
if (!isDeltaChannel(ch) || !ch.isAvailable() || channelVersions !== void 0 && channelVersions[name] === void 0) continue;
|
|
117
121
|
const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];
|
|
118
122
|
if (updates >= ch.snapshotFrequency || supersteps >= maxSupersteps) result.add(name);
|
|
119
123
|
}
|
|
@@ -154,6 +158,34 @@ function createCheckpoint(checkpoint, channels, step, options) {
|
|
|
154
158
|
};
|
|
155
159
|
}
|
|
156
160
|
/**
|
|
161
|
+
* Checkpoint metadata key, `true` when every DeltaChannel write on the
|
|
162
|
+
* checkpoint's branch carries a version. A delta channel with no version there
|
|
163
|
+
* was never written, so it needs no walk. Branches started before this key
|
|
164
|
+
* existed never get it: an older `updateState` stored a delta channel's first
|
|
165
|
+
* write without a version, and only the walk finds such a write.
|
|
166
|
+
*/
|
|
167
|
+
const DELTA_WRITES_VERSIONED = "delta_writes_versioned";
|
|
168
|
+
function isDeltaWritesVersioned(metadata) {
|
|
169
|
+
return metadata?.[DELTA_WRITES_VERSIONED] === true;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Delta channels whose value at `checkpoint` the ancestor walk rebuilds.
|
|
173
|
+
*
|
|
174
|
+
* A {@link DeltaSnapshot} or a migrated plain value in `channel_values`
|
|
175
|
+
* resolves directly, so only a channel with nothing stored there needs the
|
|
176
|
+
* walk. With `versionedOnly`, a channel with no version was never written, so
|
|
177
|
+
* it is empty without one; a walk for it would find no snapshot to stop at and
|
|
178
|
+
* read every ancestor, every time the thread is loaded.
|
|
179
|
+
*/
|
|
180
|
+
function deltaChannelsToReplay(specs, checkpoint, versionedOnly) {
|
|
181
|
+
const keys = [];
|
|
182
|
+
for (const k in specs) {
|
|
183
|
+
if (!Object.prototype.hasOwnProperty.call(specs, k)) continue;
|
|
184
|
+
if (isDeltaChannel(specs[k]) && (!versionedOnly || checkpoint.channel_versions[k] !== void 0) && !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)) keys.push(k);
|
|
185
|
+
}
|
|
186
|
+
return keys;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
157
189
|
* Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}
|
|
158
190
|
* whose value is absent from `channel_values` by replaying ancestor writes.
|
|
159
191
|
*
|
|
@@ -163,17 +195,15 @@ function createCheckpoint(checkpoint, channels, step, options) {
|
|
|
163
195
|
* from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`
|
|
164
196
|
* finds the nearest seed and accumulates the writes between it and the
|
|
165
197
|
* target. All delta channels needing replay are batched into a single saver
|
|
166
|
-
* call.
|
|
198
|
+
* call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries
|
|
199
|
+
* {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are
|
|
200
|
+
* left empty instead of walked.
|
|
167
201
|
*/
|
|
168
202
|
async function channelsFromCheckpoint(specs, checkpoint, options) {
|
|
169
203
|
const channels = emptyChannels(specs, checkpoint);
|
|
170
204
|
const { saver, config } = options ?? {};
|
|
171
205
|
const filteredSpecs = getOnlyChannels(specs);
|
|
172
|
-
const deltaKeys =
|
|
173
|
-
for (const k in filteredSpecs) {
|
|
174
|
-
if (!Object.prototype.hasOwnProperty.call(filteredSpecs, k)) continue;
|
|
175
|
-
if (isDeltaChannel(filteredSpecs[k]) && !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)) deltaKeys.push(k);
|
|
176
|
-
}
|
|
206
|
+
const deltaKeys = deltaChannelsToReplay(filteredSpecs, checkpoint, options?.deltaWritesVersioned ?? false);
|
|
177
207
|
const written = deltaKeys.filter((k) => checkpoint.channel_versions[k] !== void 0);
|
|
178
208
|
if ((saver === void 0 || config === void 0) && written.length > 0) throw new Error(`DeltaChannel ${written.join(", ")} has history to replay but no checkpointer or config was passed to read it`);
|
|
179
209
|
if (deltaKeys.length === 0 || saver === void 0 || config === void 0) return channels;
|
|
@@ -191,6 +221,6 @@ async function channelsFromCheckpoint(specs, checkpoint, options) {
|
|
|
191
221
|
return channels;
|
|
192
222
|
}
|
|
193
223
|
//#endregion
|
|
194
|
-
export { BaseChannel, channelsFromCheckpoint, createCheckpoint, deltaChannelsToSnapshot, emptyChannels, exitDeltaTaskId, getOnlyChannels, isBaseChannel, isDeltaChannel };
|
|
224
|
+
export { BaseChannel, DELTA_WRITES_VERSIONED, channelsFromCheckpoint, createCheckpoint, deltaChannelsToSnapshot, emptyChannels, exitDeltaTaskId, getOnlyChannels, isBaseChannel, isDeltaChannel, isDeltaWritesVersioned };
|
|
195
225
|
|
|
196
226
|
//# sourceMappingURL=base.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../src/channels/base.ts"],"sourcesContent":["import {\n ReadonlyCheckpoint,\n uuid6,\n Checkpoint,\n DeltaSnapshot,\n type BaseCheckpointSaver,\n type DeltaChannelHistory,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { EmptyChannelError } from \"../errors.js\";\nimport { getDeltaMaxSuperstepsSinceSnapshot } from \"../constants.js\";\n\n/** Matches Postgres `uuid` / Python `uuid.UUID` (128-bit, 8-4-4-4-12 hex). */\nconst STRUCTURED_UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Structural check for a {@link DeltaChannel} without importing it (avoids an\n * import cycle: `delta.ts` imports `base.ts`).\n */\nexport function isDeltaChannel(channel: BaseChannel): boolean {\n return channel != null && channel.lc_graph_name === \"DeltaChannel\";\n}\n\nexport function isBaseChannel(obj: unknown): obj is BaseChannel {\n return obj != null && (obj as BaseChannel).lg_is_channel === true;\n}\n\n/** @internal */\nexport abstract class BaseChannel<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown,\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n abstract lc_graph_name: string;\n\n /** @ignore */\n lg_is_channel = true;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @param {CheckpointType | undefined} initialValue\n * @returns {this}\n */\n abstract fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n * This method is called by Pregel for all channels at the end of each step.\n * If there are no updates, it is called with an empty sequence.\n *\n * Raises InvalidUpdateError if the sequence of updates is invalid.\n * Returns True if the channel was updated, False otherwise.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n abstract update(values: UpdateType[]): boolean;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n abstract get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n abstract checkpoint(): CheckpointType | undefined;\n\n /**\n * Mark the current value of the channel as consumed. By default, no-op.\n * A channel can use this method to modify its state, preventing the value\n * from being consumed again.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n consume(): boolean {\n return false;\n }\n\n /**\n * Notify the channel that the Pregel run is finishing. By default, no-op.\n * A channel can use this method to modify its state, preventing finish.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n finish(): boolean {\n return false;\n }\n\n /**\n * Return True if the channel is available (not empty), False otherwise.\n * Subclasses should override this method to provide a more efficient\n * implementation than calling get() and catching EmptyChannelError.\n */\n isAvailable(): boolean {\n try {\n this.get();\n return true;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Compare this channel with another channel for equality.\n * Used to determine if two channels with the same key are semantically equivalent.\n * Subclasses should override this method to provide a meaningful comparison.\n *\n * @param {BaseChannel} other - The other channel to compare with.\n * @returns {boolean} True if the channels are equal, false otherwise.\n */\n equals(other: BaseChannel): boolean {\n return this === other;\n }\n}\n\nconst IS_ONLY_BASE_CHANNEL = Symbol.for(\"LG_IS_ONLY_BASE_CHANNEL\");\nexport function getOnlyChannels(\n channels: Record<string, BaseChannel>\n): Record<string, BaseChannel> {\n // @ts-expect-error - we know it's a record of base channels\n if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels;\n\n const newChannels = {} as Record<string, BaseChannel>;\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const value = channels[k];\n if (isBaseChannel(value)) newChannels[k] = value;\n }\n\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\nexport function emptyChannels<Cc extends Record<string, BaseChannel>>(\n channels: Cc,\n checkpoint: ReadonlyCheckpoint\n): Cc {\n const filteredChannels = getOnlyChannels(channels) as Cc;\n\n const newChannels = {} as Cc;\n for (const k in filteredChannels) {\n if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue;\n const channelValue = checkpoint.channel_values[k];\n newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue);\n }\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\n/**\n * Minimal structural view of a {@link DeltaChannel}, used by helpers in this\n * module that must not import the concrete class (import-cycle avoidance).\n */\ninterface DeltaChannelLike extends BaseChannel {\n snapshotFrequency: number;\n replayWrites(writes: DeltaChannelHistory[\"writes\"]): void;\n}\n\n/**\n * Synthetic task id for exit-mode DeltaChannel writes.\n *\n * Embeds the superstep in the first UUID group so `ORDER BY task_id, idx`\n * preserves chronological order while remaining a valid RFC UUID (required by\n * Postgres `checkpoint_writes.task_id uuid` columns).\n */\nexport function exitDeltaTaskId(step: number, taskId: string): string {\n if (!STRUCTURED_UUID.test(taskId)) {\n throw new TypeError(`Invalid task id for exit delta: ${taskId}`);\n }\n const parts = taskId.toLowerCase().split(\"-\");\n const stepPart = String(step).padStart(8, \"0\");\n return `${stepPart}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`;\n}\n\n/**\n * Return the set of {@link DeltaChannel} names that should snapshot now.\n *\n * A channel snapshots when EITHER its accumulated update count reaches\n * `snapshotFrequency` OR the total supersteps since its last snapshot reaches\n * `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Pure predicate — no mutation.\n */\nexport function deltaChannelsToSnapshot(\n channels: Record<string, BaseChannel>,\n countersSinceDeltaSnapshot: Record<string, [number, number]>\n): Set<string> {\n const result = new Set<string>();\n const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot();\n for (const name in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;\n const ch = channels[name];\n if (!isDeltaChannel(ch) || !ch.isAvailable()) continue;\n const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];\n if (\n updates >= (ch as DeltaChannelLike).snapshotFrequency ||\n supersteps >= maxSupersteps\n ) {\n result.add(name);\n }\n }\n return result;\n}\n\nexport function createCheckpoint<ValueType>(\n checkpoint: ReadonlyCheckpoint,\n channels: Record<string, BaseChannel<ValueType>> | undefined,\n step: number,\n options?: {\n id?: string;\n channelsToSnapshot?: Set<string>;\n updatedChannels?: Set<string>;\n getNextVersion?: (current: number | string | undefined) => number | string;\n }\n): Checkpoint {\n const channelsToSnapshot = options?.channelsToSnapshot ?? new Set<string>();\n const { updatedChannels, getNextVersion } = options ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let values: Record<string, any>;\n let channelVersions: Record<string, number | string> =\n checkpoint.channel_versions;\n if (channels === undefined) {\n values = checkpoint.channel_values;\n } else {\n values = {};\n channelVersions = { ...checkpoint.channel_versions };\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const channel = channels[k];\n if (channelsToSnapshot.has(k)) {\n // Snapshot a DeltaChannel: store the materialized value directly. In\n // exit/deferred modes the channel may have reached its snapshot\n // threshold over several supersteps without the LAST superstep\n // writing to it, so its version wouldn't be bumped by applyWrites —\n // bump it here so the saver includes the snapshot blob.\n if (\n getNextVersion !== undefined &&\n (updatedChannels === undefined || !updatedChannels.has(k))\n ) {\n channelVersions[k] = getNextVersion(channelVersions[k]);\n }\n values[k] = new DeltaSnapshot(channel.get());\n continue;\n }\n if (isDeltaChannel(channel)) {\n // Omitted from channel_values; reconstructed from ancestor writes.\n continue;\n }\n try {\n values[k] = channel.checkpoint();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n // no-op\n } else {\n throw error; // Rethrow unexpected errors\n }\n }\n }\n }\n\n return {\n v: 4,\n id: options?.id ?? uuid6(step),\n ts: new Date().toISOString(),\n channel_values: values,\n channel_versions: channelVersions,\n versions_seen: checkpoint.versions_seen,\n };\n}\n\n/**\n * Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}\n * whose value is absent from `channel_values` by replaying ancestor writes.\n *\n * For most channels (and for delta channels with a {@link DeltaSnapshot} or a\n * migrated plain value in `channel_values`), {@link emptyChannels} is\n * sufficient and no saver access is required. When a delta channel is absent\n * from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`\n * finds the nearest seed and accumulates the writes between it and the\n * target. All delta channels needing replay are batched into a single saver\n * call.\n */\nexport async function channelsFromCheckpoint<\n Cc extends Record<string, BaseChannel>,\n>(\n specs: Cc,\n checkpoint: ReadonlyCheckpoint,\n options?: { saver?: BaseCheckpointSaver; config?: RunnableConfig }\n): Promise<Cc> {\n const channels = emptyChannels(specs, checkpoint);\n const { saver, config } = options ?? {};\n\n const filteredSpecs = getOnlyChannels(specs);\n const deltaKeys: string[] = [];\n for (const k in filteredSpecs) {\n if (!Object.prototype.hasOwnProperty.call(filteredSpecs, k)) continue;\n if (\n isDeltaChannel(filteredSpecs[k]) &&\n !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)\n ) {\n deltaKeys.push(k);\n }\n }\n\n const written = deltaKeys.filter(\n (k) => checkpoint.channel_versions[k] !== undefined\n );\n if ((saver === undefined || config === undefined) && written.length > 0) {\n throw new Error(\n `DeltaChannel ${written.join(\", \")} has history to replay but no checkpointer or config was passed to read it`\n );\n }\n if (deltaKeys.length === 0 || saver === undefined || config === undefined) {\n return channels;\n }\n\n const histories = await saver.getDeltaChannelHistory({\n config,\n channels: deltaKeys,\n });\n for (const k of deltaKeys) {\n const history = histories[k];\n if (history === undefined) continue;\n const replayCh = filteredSpecs[k].fromCheckpoint(\n history.seed\n ) as unknown as DeltaChannelLike;\n replayCh.replayWrites(history.writes);\n (channels as Record<string, BaseChannel>)[k] = replayCh;\n }\n return channels;\n}\n"],"mappings":";;;;;AAaA,MAAM,kBACJ;;;;;AAMF,SAAgB,eAAe,SAA+B;AAC5D,QAAO,WAAW,QAAQ,QAAQ,kBAAkB;;AAGtD,SAAgB,cAAc,KAAkC;AAC9D,QAAO,OAAO,QAAS,IAAoB,kBAAkB;;;AAI/D,IAAsB,cAAtB,MAIE;CACA;CAEA;;CAQA,gBAAgB;;;;;;;;CAkDhB,UAAmB;AACjB,SAAO;;;;;;;;CAST,SAAkB;AAChB,SAAO;;;;;;;CAQT,cAAuB;AACrB,MAAI;AACF,QAAK,KAAK;AACV,UAAO;WAEA,OAAY;AACnB,OAAI,MAAM,SAAS,kBAAkB,kBACnC,QAAO;AAET,SAAM;;;;;;;;;;;CAY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,EAAE;CAEvC,MAAM,gBAAgB,gBAAgB,MAAM;CAC5C,MAAM,YAAsB,EAAE;AAC9B,MAAK,MAAM,KAAK,eAAe;AAC7B,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,eAAe,EAAE,CAAE;AAC7D,MACE,eAAe,cAAc,GAAG,IAChC,CAAC,OAAO,UAAU,eAAe,KAAK,WAAW,gBAAgB,EAAE,CAEnE,WAAU,KAAK,EAAE;;CAIrB,MAAM,UAAU,UAAU,QACvB,MAAM,WAAW,iBAAiB,OAAO,KAAA,EAC3C;AACD,MAAK,UAAU,KAAA,KAAa,WAAW,KAAA,MAAc,QAAQ,SAAS,EACpE,OAAM,IAAI,MACR,gBAAgB,QAAQ,KAAK,KAAK,CAAC,4EACpC;AAEH,KAAI,UAAU,WAAW,KAAK,UAAU,KAAA,KAAa,WAAW,KAAA,EAC9D,QAAO;CAGT,MAAM,YAAY,MAAM,MAAM,uBAAuB;EACnD;EACA,UAAU;EACX,CAAC;AACF,MAAK,MAAM,KAAK,WAAW;EACzB,MAAM,UAAU,UAAU;AAC1B,MAAI,YAAY,KAAA,EAAW;EAC3B,MAAM,WAAW,cAAc,GAAG,eAChC,QAAQ,KACT;AACD,WAAS,aAAa,QAAQ,OAAO;AACpC,WAAyC,KAAK;;AAEjD,QAAO"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../src/channels/base.ts"],"sourcesContent":["import {\n ReadonlyCheckpoint,\n uuid6,\n Checkpoint,\n DeltaSnapshot,\n type BaseCheckpointSaver,\n type CheckpointMetadata,\n type DeltaChannelHistory,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { EmptyChannelError } from \"../errors.js\";\nimport { getDeltaMaxSuperstepsSinceSnapshot } from \"../constants.js\";\n\n/** Matches Postgres `uuid` / Python `uuid.UUID` (128-bit, 8-4-4-4-12 hex). */\nconst STRUCTURED_UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Structural check for a {@link DeltaChannel} without importing it (avoids an\n * import cycle: `delta.ts` imports `base.ts`).\n */\nexport function isDeltaChannel(channel: BaseChannel): boolean {\n return channel != null && channel.lc_graph_name === \"DeltaChannel\";\n}\n\nexport function isBaseChannel(obj: unknown): obj is BaseChannel {\n return obj != null && (obj as BaseChannel).lg_is_channel === true;\n}\n\n/** @internal */\nexport abstract class BaseChannel<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown,\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n abstract lc_graph_name: string;\n\n /** @ignore */\n lg_is_channel = true;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @param {CheckpointType | undefined} initialValue\n * @returns {this}\n */\n abstract fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n * This method is called by Pregel for all channels at the end of each step.\n * If there are no updates, it is called with an empty sequence.\n *\n * Raises InvalidUpdateError if the sequence of updates is invalid.\n * Returns True if the channel was updated, False otherwise.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n abstract update(values: UpdateType[]): boolean;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n abstract get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n abstract checkpoint(): CheckpointType | undefined;\n\n /**\n * Mark the current value of the channel as consumed. By default, no-op.\n * A channel can use this method to modify its state, preventing the value\n * from being consumed again.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n consume(): boolean {\n return false;\n }\n\n /**\n * Notify the channel that the Pregel run is finishing. By default, no-op.\n * A channel can use this method to modify its state, preventing finish.\n *\n * Returns True if the channel was updated, False otherwise.\n */\n finish(): boolean {\n return false;\n }\n\n /**\n * Return True if the channel is available (not empty), False otherwise.\n * Subclasses should override this method to provide a more efficient\n * implementation than calling get() and catching EmptyChannelError.\n */\n isAvailable(): boolean {\n try {\n this.get();\n return true;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Compare this channel with another channel for equality.\n * Used to determine if two channels with the same key are semantically equivalent.\n * Subclasses should override this method to provide a meaningful comparison.\n *\n * @param {BaseChannel} other - The other channel to compare with.\n * @returns {boolean} True if the channels are equal, false otherwise.\n */\n equals(other: BaseChannel): boolean {\n return this === other;\n }\n}\n\nconst IS_ONLY_BASE_CHANNEL = Symbol.for(\"LG_IS_ONLY_BASE_CHANNEL\");\nexport function getOnlyChannels(\n channels: Record<string, BaseChannel>\n): Record<string, BaseChannel> {\n // @ts-expect-error - we know it's a record of base channels\n if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels;\n\n const newChannels = {} as Record<string, BaseChannel>;\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const value = channels[k];\n if (isBaseChannel(value)) newChannels[k] = value;\n }\n\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\nexport function emptyChannels<Cc extends Record<string, BaseChannel>>(\n channels: Cc,\n checkpoint: ReadonlyCheckpoint\n): Cc {\n const filteredChannels = getOnlyChannels(channels) as Cc;\n\n const newChannels = {} as Cc;\n for (const k in filteredChannels) {\n if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue;\n const channelValue = checkpoint.channel_values[k];\n newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue);\n }\n Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true });\n return newChannels;\n}\n\n/**\n * Minimal structural view of a {@link DeltaChannel}, used by helpers in this\n * module that must not import the concrete class (import-cycle avoidance).\n */\ninterface DeltaChannelLike extends BaseChannel {\n snapshotFrequency: number;\n replayWrites(writes: DeltaChannelHistory[\"writes\"]): void;\n}\n\n/**\n * Synthetic task id for exit-mode DeltaChannel writes.\n *\n * Embeds the superstep in the first UUID group so `ORDER BY task_id, idx`\n * preserves chronological order while remaining a valid RFC UUID (required by\n * Postgres `checkpoint_writes.task_id uuid` columns).\n */\nexport function exitDeltaTaskId(step: number, taskId: string): string {\n if (!STRUCTURED_UUID.test(taskId)) {\n throw new TypeError(`Invalid task id for exit delta: ${taskId}`);\n }\n const parts = taskId.toLowerCase().split(\"-\");\n const stepPart = String(step).padStart(8, \"0\");\n return `${stepPart}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`;\n}\n\n/**\n * Return the set of {@link DeltaChannel} names that should snapshot now.\n *\n * A channel snapshots when EITHER its accumulated update count reaches\n * `snapshotFrequency` OR the total supersteps since its last snapshot reaches\n * `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Given `channelVersions`, a channel\n * without a version is skipped: it was never written on this branch, so it\n * has nothing to snapshot. Pass `undefined` on a branch without\n * {@link DELTA_WRITES_VERSIONED}, where such a channel can still hold writes\n * and this snapshot is what bounds its walk. Pure predicate, no mutation.\n */\nexport function deltaChannelsToSnapshot(\n channels: Record<string, BaseChannel>,\n countersSinceDeltaSnapshot: Record<string, [number, number]>,\n channelVersions: Record<string, number | string> | undefined\n): Set<string> {\n const result = new Set<string>();\n const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot();\n for (const name in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, name)) continue;\n const ch = channels[name];\n if (\n !isDeltaChannel(ch) ||\n !ch.isAvailable() ||\n (channelVersions !== undefined && channelVersions[name] === undefined)\n ) {\n continue;\n }\n const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0];\n if (\n updates >= (ch as DeltaChannelLike).snapshotFrequency ||\n supersteps >= maxSupersteps\n ) {\n result.add(name);\n }\n }\n return result;\n}\n\nexport function createCheckpoint<ValueType>(\n checkpoint: ReadonlyCheckpoint,\n channels: Record<string, BaseChannel<ValueType>> | undefined,\n step: number,\n options?: {\n id?: string;\n channelsToSnapshot?: Set<string>;\n updatedChannels?: Set<string>;\n getNextVersion?: (current: number | string | undefined) => number | string;\n }\n): Checkpoint {\n const channelsToSnapshot = options?.channelsToSnapshot ?? new Set<string>();\n const { updatedChannels, getNextVersion } = options ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let values: Record<string, any>;\n let channelVersions: Record<string, number | string> =\n checkpoint.channel_versions;\n if (channels === undefined) {\n values = checkpoint.channel_values;\n } else {\n values = {};\n channelVersions = { ...checkpoint.channel_versions };\n for (const k in channels) {\n if (!Object.prototype.hasOwnProperty.call(channels, k)) continue;\n const channel = channels[k];\n if (channelsToSnapshot.has(k)) {\n // Snapshot a DeltaChannel: store the materialized value directly. In\n // exit/deferred modes the channel may have reached its snapshot\n // threshold over several supersteps without the LAST superstep\n // writing to it, so its version wouldn't be bumped by applyWrites —\n // bump it here so the saver includes the snapshot blob.\n if (\n getNextVersion !== undefined &&\n (updatedChannels === undefined || !updatedChannels.has(k))\n ) {\n channelVersions[k] = getNextVersion(channelVersions[k]);\n }\n values[k] = new DeltaSnapshot(channel.get());\n continue;\n }\n if (isDeltaChannel(channel)) {\n // Omitted from channel_values; reconstructed from ancestor writes.\n continue;\n }\n try {\n values[k] = channel.checkpoint();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.name === EmptyChannelError.unminifiable_name) {\n // no-op\n } else {\n throw error; // Rethrow unexpected errors\n }\n }\n }\n }\n\n return {\n v: 4,\n id: options?.id ?? uuid6(step),\n ts: new Date().toISOString(),\n channel_values: values,\n channel_versions: channelVersions,\n versions_seen: checkpoint.versions_seen,\n };\n}\n\n/**\n * Checkpoint metadata key, `true` when every DeltaChannel write on the\n * checkpoint's branch carries a version. A delta channel with no version there\n * was never written, so it needs no walk. Branches started before this key\n * existed never get it: an older `updateState` stored a delta channel's first\n * write without a version, and only the walk finds such a write.\n */\nexport const DELTA_WRITES_VERSIONED = \"delta_writes_versioned\";\n\nexport function isDeltaWritesVersioned(\n metadata: CheckpointMetadata | undefined\n): boolean {\n return (\n (metadata as Record<string, unknown> | undefined)?.[\n DELTA_WRITES_VERSIONED\n ] === true\n );\n}\n\n/**\n * Delta channels whose value at `checkpoint` the ancestor walk rebuilds.\n *\n * A {@link DeltaSnapshot} or a migrated plain value in `channel_values`\n * resolves directly, so only a channel with nothing stored there needs the\n * walk. With `versionedOnly`, a channel with no version was never written, so\n * it is empty without one; a walk for it would find no snapshot to stop at and\n * read every ancestor, every time the thread is loaded.\n */\nfunction deltaChannelsToReplay(\n specs: Record<string, BaseChannel>,\n checkpoint: ReadonlyCheckpoint,\n versionedOnly: boolean\n): string[] {\n const keys: string[] = [];\n for (const k in specs) {\n if (!Object.prototype.hasOwnProperty.call(specs, k)) continue;\n if (\n isDeltaChannel(specs[k]) &&\n (!versionedOnly || checkpoint.channel_versions[k] !== undefined) &&\n !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)\n ) {\n keys.push(k);\n }\n }\n return keys;\n}\n\n/**\n * Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel}\n * whose value is absent from `channel_values` by replaying ancestor writes.\n *\n * For most channels (and for delta channels with a {@link DeltaSnapshot} or a\n * migrated plain value in `channel_values`), {@link emptyChannels} is\n * sufficient and no saver access is required. When a delta channel is absent\n * from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory`\n * finds the nearest seed and accumulates the writes between it and the\n * target. All delta channels needing replay are batched into a single saver\n * call. Pass `deltaWritesVersioned` for a checkpoint whose metadata carries\n * {@link DELTA_WRITES_VERSIONED}, so delta channels without a version are\n * left empty instead of walked.\n */\nexport async function channelsFromCheckpoint<\n Cc extends Record<string, BaseChannel>,\n>(\n specs: Cc,\n checkpoint: ReadonlyCheckpoint,\n options?: {\n saver?: BaseCheckpointSaver;\n config?: RunnableConfig;\n deltaWritesVersioned?: boolean;\n }\n): Promise<Cc> {\n const channels = emptyChannels(specs, checkpoint);\n const { saver, config } = options ?? {};\n\n const filteredSpecs = getOnlyChannels(specs);\n const deltaKeys = deltaChannelsToReplay(\n filteredSpecs,\n checkpoint,\n options?.deltaWritesVersioned ?? false\n );\n\n const written = deltaKeys.filter(\n (k) => checkpoint.channel_versions[k] !== undefined\n );\n if ((saver === undefined || config === undefined) && written.length > 0) {\n throw new Error(\n `DeltaChannel ${written.join(\", \")} has history to replay but no checkpointer or config was passed to read it`\n );\n }\n if (deltaKeys.length === 0 || saver === undefined || config === undefined) {\n return channels;\n }\n\n const histories = await saver.getDeltaChannelHistory({\n config,\n channels: deltaKeys,\n });\n for (const k of deltaKeys) {\n const history = histories[k];\n if (history === undefined) continue;\n const replayCh = filteredSpecs[k].fromCheckpoint(\n history.seed\n ) as unknown as DeltaChannelLike;\n replayCh.replayWrites(history.writes);\n (channels as Record<string, BaseChannel>)[k] = replayCh;\n }\n return channels;\n}\n"],"mappings":";;;;;AAcA,MAAM,kBACJ;;;;;AAMF,SAAgB,eAAe,SAA+B;AAC5D,QAAO,WAAW,QAAQ,QAAQ,kBAAkB;;AAGtD,SAAgB,cAAc,KAAkC;AAC9D,QAAO,OAAO,QAAS,IAAoB,kBAAkB;;;AAI/D,IAAsB,cAAtB,MAIE;CACA;CAEA;;CAQA,gBAAgB;;;;;;;;CAkDhB,UAAmB;AACjB,SAAO;;;;;;;;CAST,SAAkB;AAChB,SAAO;;;;;;;CAQT,cAAuB;AACrB,MAAI;AACF,QAAK,KAAK;AACV,UAAO;WAEA,OAAY;AACnB,OAAI,MAAM,SAAS,kBAAkB,kBACnC,QAAO;AAET,SAAM;;;;;;;;;;;CAYV,OAAO,OAA6B;AAClC,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AAaV,SAAS,sBACP,OACA,YACA,eACU;CACV,MAAM,OAAiB,EAAE;AACzB,MAAK,MAAM,KAAK,OAAO;AACrB,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,EAAE,CAAE;AACrD,MACE,eAAe,MAAM,GAAG,KACvB,CAAC,iBAAiB,WAAW,iBAAiB,OAAO,KAAA,MACtD,CAAC,OAAO,UAAU,eAAe,KAAK,WAAW,gBAAgB,EAAE,CAEnE,MAAK,KAAK,EAAE;;AAGhB,QAAO;;;;;;;;;;;;;;;;AAiBT,eAAsB,uBAGpB,OACA,YACA,SAKa;CACb,MAAM,WAAW,cAAc,OAAO,WAAW;CACjD,MAAM,EAAE,OAAO,WAAW,WAAW,EAAE;CAEvC,MAAM,gBAAgB,gBAAgB,MAAM;CAC5C,MAAM,YAAY,sBAChB,eACA,YACA,SAAS,wBAAwB,MAClC;CAED,MAAM,UAAU,UAAU,QACvB,MAAM,WAAW,iBAAiB,OAAO,KAAA,EAC3C;AACD,MAAK,UAAU,KAAA,KAAa,WAAW,KAAA,MAAc,QAAQ,SAAS,EACpE,OAAM,IAAI,MACR,gBAAgB,QAAQ,KAAK,KAAK,CAAC,4EACpC;AAEH,KAAI,UAAU,WAAW,KAAK,UAAU,KAAA,KAAa,WAAW,KAAA,EAC9D,QAAO;CAGT,MAAM,YAAY,MAAM,MAAM,uBAAuB;EACnD;EACA,UAAU;EACX,CAAC;AACF,MAAK,MAAM,KAAK,WAAW;EACzB,MAAM,UAAU,UAAU;AAC1B,MAAI,YAAY,KAAA,EAAW;EAC3B,MAAM,WAAW,cAAc,GAAG,eAChC,QAAQ,KACT;AACD,WAAS,aAAa,QAAQ,OAAO;AACpC,WAAyC,KAAK;;AAEjD,QAAO"}
|
package/dist/constants.cjs
CHANGED
|
@@ -449,7 +449,7 @@ var Command = class extends CommandInstance {
|
|
|
449
449
|
function isCommand(x) {
|
|
450
450
|
if (typeof x !== "object") return false;
|
|
451
451
|
if (x === null || x === void 0) return false;
|
|
452
|
-
if ("lg_name" in x && x.lg_name === "Command") return true;
|
|
452
|
+
if (!isPlainObject(x) && "lg_name" in x && x.lg_name === "Command") return true;
|
|
453
453
|
return false;
|
|
454
454
|
}
|
|
455
455
|
function isPlainObject(value) {
|
|
@@ -482,7 +482,7 @@ function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map())
|
|
|
482
482
|
} else if (x instanceof Command || x instanceof Send || !isPlainObject(x)) {
|
|
483
483
|
result = x;
|
|
484
484
|
seen.set(x, result);
|
|
485
|
-
} else if (
|
|
485
|
+
} else if ("lg_name" in x && x.lg_name === "Command") {
|
|
486
486
|
result = new Command(x);
|
|
487
487
|
seen.set(x, result);
|
|
488
488
|
} else if (_isSendInterface(x)) {
|
package/dist/constants.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","names":["coerceTimeoutPolicy"],"sources":["../src/constants.ts"],"sourcesContent":["import { PendingWrite } from \"@langchain/langgraph-checkpoint\";\nimport type { JSONSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n coerceTimeoutPolicy,\n type TimeoutPolicy,\n} from \"./pregel/utils/timeout.js\";\n\n/** Special reserved node name denoting the start of a graph. */\nexport const START = \"__start__\";\n/** Special reserved node name denoting the end of a graph. */\nexport const END = \"__end__\";\nexport const INPUT = \"__input__\";\nexport const COPY = \"__copy__\";\nexport const ERROR = \"__error__\";\n/**\n * Special reserved write key recording the name of the node whose execution\n * failed, so node-level error handlers see the same failure provenance after a\n * checkpoint resume. Value format in pending writes:\n * `[taskId, ERROR_SOURCE_NODE, nodeName: string]`.\n */\nexport const ERROR_SOURCE_NODE = \"__error_source_node__\";\n\n/** Special reserved cache namespaces */\nexport const CACHE_NS_WRITES = \"__pregel_ns_writes\";\n\n/**\n * System-wide upper bound on how many supersteps a {@link DeltaChannel} may go\n * without writing a {@link DeltaSnapshot} blob. Once a channel's\n * supersteps-since-snapshot counter reaches this value, a snapshot is forced\n * even if the channel's own `snapshotFrequency` has not been reached — this\n * prevents unbounded ancestor walks on threads where a delta channel exists\n * but is no longer being updated.\n *\n * Overridable via the `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`\n * environment variable. Read lazily so test/runtime overrides take effect.\n *\n * @remarks Beta.\n */\nexport function getDeltaMaxSuperstepsSinceSnapshot(): number {\n const raw =\n typeof process !== \"undefined\"\n ? process.env?.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT\n : undefined;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number.parseInt(raw, 10);\n if (Number.isFinite(parsed) && parsed > 0) return parsed;\n }\n return 5000;\n}\n\nexport const CONFIG_KEY_SEND = \"__pregel_send\";\n/** config key containing function used to call a node (push task) */\nexport const CONFIG_KEY_CALL = \"__pregel_call\";\nexport const CONFIG_KEY_READ = \"__pregel_read\";\nexport const CONFIG_KEY_CHECKPOINTER = \"__pregel_checkpointer\";\nexport const CONFIG_KEY_RESUMING = \"__pregel_resuming\";\nexport const CONFIG_KEY_TASK_ID = \"__pregel_task_id\";\nexport const CONFIG_KEY_STREAM = \"__pregel_stream\";\nexport const CONFIG_KEY_RESUME_VALUE = \"__pregel_resume_value\";\nexport const CONFIG_KEY_RESUME_MAP = \"__pregel_resume_map\";\nexport const CONFIG_KEY_SCRATCHPAD = \"__pregel_scratchpad\";\n/** config key containing state from previous invocation of graph for the given thread */\nexport const CONFIG_KEY_PREVIOUS_STATE = \"__pregel_previous\";\nexport const CONFIG_KEY_DURABILITY = \"__pregel_durability\";\nexport const CONFIG_KEY_CHECKPOINT_ID = \"checkpoint_id\";\nexport const CONFIG_KEY_CHECKPOINT_NS = \"checkpoint_ns\";\n\nexport const CONFIG_KEY_NODE_FINISHED = \"__pregel_node_finished\";\n\n/**\n * Config key holding a {@link NodeError} (failed source node + error) for the\n * current node-level error handler invocation. Injected when an error handler\n * task is prepared after the failing node's retry policy is exhausted.\n */\nexport const CONFIG_KEY_NODE_ERROR = \"__pregel_node_error\";\n\n// this one is part of public API\nexport const CONFIG_KEY_CHECKPOINT_MAP = \"checkpoint_map\";\n\nexport const CONFIG_KEY_REPLAY_STATE = \"__pregel_replay_state\";\n\nexport const CONFIG_KEY_ABORT_SIGNALS = \"__pregel_abort_signals\";\n\n/** Special channel reserved for graph interrupts */\nexport const INTERRUPT = \"__interrupt__\";\n/** Special channel reserved for graph resume */\nexport const RESUME = \"__resume__\";\n/** Special channel reserved for cases when a task exits without any writes */\nexport const NO_WRITES = \"__no_writes__\";\n/** Special channel reserved for graph return */\nexport const RETURN = \"__return__\";\n/** Special channel reserved for graph previous state */\nexport const PREVIOUS = \"__previous__\";\nexport const RUNTIME_PLACEHOLDER = \"__pregel_runtime_placeholder__\";\nexport const RECURSION_LIMIT_DEFAULT = 25;\n\nexport const TAG_HIDDEN = \"langsmith:hidden\";\nexport const TAG_NOSTREAM = \"langsmith:nostream\";\nexport const SELF = \"__self__\";\n\nexport const TASKS = \"__pregel_tasks\";\nexport const PUSH = \"__pregel_push\";\nexport const PULL = \"__pregel_pull\";\n\nexport const TASK_NAMESPACE = \"6ba7b831-9dad-11d1-80b4-00c04fd430c8\";\nexport const NULL_TASK_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport const RESERVED = [\n TAG_HIDDEN,\n INPUT,\n INTERRUPT,\n RESUME,\n ERROR,\n ERROR_SOURCE_NODE,\n NO_WRITES,\n\n // reserved config.configurable keys\n CONFIG_KEY_SEND,\n CONFIG_KEY_READ,\n CONFIG_KEY_CHECKPOINTER,\n CONFIG_KEY_DURABILITY,\n CONFIG_KEY_STREAM,\n CONFIG_KEY_RESUMING,\n CONFIG_KEY_TASK_ID,\n CONFIG_KEY_CALL,\n CONFIG_KEY_RESUME_VALUE,\n CONFIG_KEY_SCRATCHPAD,\n CONFIG_KEY_PREVIOUS_STATE,\n CONFIG_KEY_CHECKPOINT_MAP,\n CONFIG_KEY_CHECKPOINT_NS,\n CONFIG_KEY_CHECKPOINT_ID,\n CONFIG_KEY_REPLAY_STATE,\n];\n\nexport const CHECKPOINT_NAMESPACE_SEPARATOR = \"|\";\nexport const CHECKPOINT_NAMESPACE_END = \":\";\n\n/**\n * Symbol used internally to identify Command instances.\n * Exported to support cross-version type compatibility.\n * @internal\n */\nexport const COMMAND_SYMBOL = Symbol.for(\"langgraph.command\");\n\n/**\n * Instance of a {@link Command} class.\n *\n * This is used to avoid IntelliSense suggesting public fields\n * of {@link Command} class when a plain object is expected.\n *\n * @see {@link Command}\n * @internal\n */\nexport class CommandInstance<\n Resume = unknown,\n Update = Record<string, unknown>,\n Nodes extends string = string,\n> {\n [COMMAND_SYMBOL]: CommandParams<Resume, Update, Nodes>;\n\n constructor(args: CommandParams<Resume, Update, Nodes>) {\n this[COMMAND_SYMBOL] = args;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SendInterface<Node extends string = string, Args = any> {\n node: Node;\n args: Args;\n /**\n * Optional per-task timeout policy that overrides the target node's timeout\n * for this specific pushed task.\n */\n timeout?: TimeoutPolicy;\n}\n\n/** Keyword options for {@link Send}. */\nexport type SendOptions = {\n /**\n * Per-task timeout policy overriding the target node's timeout for this\n * pushed task. A bare number is treated as `runTimeout` (milliseconds).\n */\n timeout?: number | TimeoutPolicy;\n};\n\nexport function _isSendInterface(x: unknown): x is SendInterface {\n const operation = x as SendInterface;\n return (\n operation !== null &&\n operation !== undefined &&\n typeof operation.node === \"string\" &&\n operation.args !== undefined\n );\n}\n\n/**\n *\n * A message or packet to send to a specific node in the graph.\n *\n * The `Send` class is used within a `StateGraph`'s conditional edges to\n * dynamically invoke a node with a custom state at the next step.\n *\n * Importantly, the sent state can differ from the core graph's state,\n * allowing for flexible and dynamic workflow management.\n *\n * One such example is a \"map-reduce\" workflow where your graph invokes\n * the same node multiple times in parallel with different states,\n * before aggregating the results back into the main graph's state.\n *\n * @example\n * ```typescript\n * import { Annotation, Send, StateGraph } from \"@langchain/langgraph\";\n *\n * const ChainState = Annotation.Root({\n * subjects: Annotation<string[]>,\n * jokes: Annotation<string[]>({\n * reducer: (a, b) => a.concat(b),\n * }),\n * });\n *\n * const continueToJokes = async (state: typeof ChainState.State) => {\n * return state.subjects.map((subject) => {\n * return new Send(\"generate_joke\", { subjects: [subject] });\n * });\n * };\n *\n * @remarks\n * A per-task timeout can be supplied via the third argument's `timeout` option\n * to override the target node's configured timeout for this specific pushed task:\n *\n * ```typescript\n * new Send(\"generate_joke\", { subjects: [subject] }, { timeout: { idleTimeout: 5000 } });\n * ```\n *\n * const graph = new StateGraph(ChainState)\n * .addNode(\"generate_joke\", (state) => ({\n * jokes: [`Joke about ${state.subjects}`],\n * }))\n * .addConditionalEdges(\"__start__\", continueToJokes)\n * .addEdge(\"generate_joke\", \"__end__\")\n * .compile();\n *\n * const res = await graph.invoke({ subjects: [\"cats\", \"dogs\"] });\n * console.log(res);\n *\n * // Invoking with two subjects results in a generated joke for each\n * // { subjects: [\"cats\", \"dogs\"], jokes: [`Joke about cats`, `Joke about dogs`] }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class Send<\n Node extends string = string,\n Args = any,\n> implements SendInterface<Node, Args> {\n lg_name = \"Send\";\n\n public node: Node;\n\n public args: Args;\n\n /**\n * Optional per-task timeout policy that overrides the target node's timeout\n * for this specific pushed task. A bare number is treated as a hard\n * `runTimeout` (in milliseconds).\n */\n public timeout?: TimeoutPolicy;\n\n constructor(node: Node, args: Args, options?: SendOptions) {\n this.node = node;\n this.args = _deserializeCommandSendObjectGraph(args) as Args;\n this.timeout = coerceTimeoutPolicy(options?.timeout);\n }\n\n toJSON() {\n return {\n lg_name: this.lg_name,\n node: this.node,\n args: this.args,\n timeout: this.timeout,\n };\n }\n}\n\nexport function _isSend(x: unknown): x is Send {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return x instanceof Send;\n}\n\nexport const OVERWRITE = \"__overwrite__\";\n\n/**\n * An object representing a direct overwrite of a value for a channel.\n * Used to signal that the channel value should be replaced with the given value,\n * bypassing any reducer or binary operator logic.\n *\n * @template ValueType - The type of the value being overwritten.\n * @property {ValueType} [OVERWRITE] - The value to directly set.\n *\n * @example\n * const overwriteObj: OverwriteValue<number> = { __overwrite__: 123 };\n */\nexport interface OverwriteValue<ValueType> {\n [OVERWRITE]: ValueType;\n}\n\n/**\n * Bypass a reducer and write the wrapped value directly to a\n * {@link BinaryOperatorAggregate} channel.\n *\n * Receiving multiple `Overwrite` values for the same channel in a single\n * super-step will raise an {@link InvalidUpdateError}.\n *\n * @example\n * ```typescript\n * import { Annotation, StateGraph, Overwrite } from \"@langchain/langgraph\";\n *\n * const State = Annotation.Root({\n * messages: Annotation<string[]>({\n * reducer: (a, b) => a.concat(b),\n * default: () => [],\n * }),\n * });\n *\n * const replaceMessages = (_state: typeof State.State) => {\n * return { messages: new Overwrite([\"replacement\"]) };\n * };\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class Overwrite<ValueType = any> implements OverwriteValue<ValueType> {\n lg_name = \"Overwrite\";\n\n readonly [OVERWRITE]: ValueType;\n\n constructor(value: ValueType) {\n this[OVERWRITE] = value;\n }\n\n get value(): ValueType {\n return this[OVERWRITE];\n }\n\n toJSON() {\n return { [OVERWRITE]: this[OVERWRITE] };\n }\n\n static isInstance<ValueType>(value: unknown): value is Overwrite<ValueType> {\n if (!value || typeof value !== \"object\") return false;\n if (OVERWRITE in value) return true;\n if (\"lg_name\" in value && value.lg_name === \"Overwrite\") return true;\n return false;\n }\n}\n\n/**\n * Helper function to detect and extract the value from an Overwrite wrapper,\n * supporting both the Overwrite class instance and the serialized object format.\n *\n * Use to check if a provided value represents an Overwrite: returns the\n * unwrapped value if so, or undefined otherwise.\n *\n * - If the value is an Overwrite instance (preferred API), return its `.value`.\n * - If the value is a wire-format object ({ [OVERWRITE]: value }), extract it.\n * - If the value is the discriminator form ({ type: OVERWRITE, value }) that\n * results from JSON-serializing a typed `Overwrite` in another runtime (e.g.\n * a Python dataclass routed through the LangGraph API server, where the typed\n * instance is erased), extract it. Keeps Overwrite semantics intact across\n * cross-runtime JSON boundaries.\n * - Otherwise, returns undefined.\n *\n * @template ValueType - The expected type of the Overwrite value.\n * @param value - The value to check (may be anything).\n * @returns The unwrapped value if value is an Overwrite, or undefined otherwise.\n * @internal\n */\nexport function _getOverwriteValue<ValueType>(\n value: unknown\n): [true, ValueType] | [false, undefined] {\n if (typeof value === \"object\" && value !== null) {\n if (OVERWRITE in value) {\n return [true, (value as Record<string, ValueType>)[OVERWRITE]];\n }\n const rec = value as Record<string, unknown>;\n if (rec.type === OVERWRITE && \"value\" in rec) {\n return [true, rec.value as ValueType];\n }\n }\n return [false, undefined];\n}\n\n/**\n * Type guard to check if a value is an Overwrite value -- either the class\n * instance or the wire format object.\n *\n * @template ValueType - The expected type of the Overwrite value.\n * @param value - The value to check (may be anything).\n * @returns `true` if the value is an Overwrite value, `false` otherwise.\n * @internal\n */\nexport function _isOverwriteValue<ValueType>(\n value: unknown\n): value is OverwriteValue<ValueType> {\n return _getOverwriteValue<ValueType>(value)[0];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Interrupt<Value = any> = {\n id?: string;\n value?: Value;\n /**\n * JSON Schema for the value expected when resuming this interrupt,\n * if the graph provided one via `interrupt(value, { responseSchema })`.\n */\n response_schema?: JSONSchema;\n};\n\n/**\n * Checks if the given graph invoke / stream chunk contains interrupt.\n *\n * @example\n * ```ts\n * import { INTERRUPT, isInterrupted } from \"@langchain/langgraph\";\n *\n * const values = await graph.invoke({ foo: \"bar\" });\n * if (isInterrupted<string>(values)) {\n * const interrupt = values[INTERRUPT][0].value;\n * }\n * ```\n *\n * @param values - The values to check.\n * @returns `true` if the values contain an interrupt, `false` otherwise.\n */\nexport function isInterrupted<Value = unknown>(\n values: unknown\n): values is { [INTERRUPT]: Interrupt<Value>[] } {\n if (!values || typeof values !== \"object\") return false;\n if (!(INTERRUPT in values)) return false;\n return Array.isArray(values[INTERRUPT]);\n}\n\nexport type CommandParams<\n Resume = unknown,\n Update = Record<string, unknown>,\n Nodes extends string = string,\n> = {\n /**\n * A discriminator field used to identify the type of object. Must be populated when serializing.\n *\n * Optional because it's not required to specify this when directly constructing a {@link Command}\n * object.\n */\n lg_name?: \"Command\";\n\n /**\n * Value to resume execution with. To be used together with {@link interrupt}.\n */\n resume?: Resume;\n /**\n * Graph to send the command to. Supported values are:\n * - None: the current graph (default)\n * - The specific name of the graph to send the command to\n * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph)\n */\n graph?: string;\n\n /**\n * Update to apply to the graph's state.\n */\n update?: Update | [string, unknown][];\n\n /**\n * Can be one of the following:\n * - name of the node to navigate to next (any node that belongs to the specified `graph`)\n * - sequence of node names to navigate to next\n * - `Send` object (to execute a node with the input provided)\n * - sequence of `Send` objects\n */\n goto?:\n | Nodes\n | SendInterface<Nodes> // eslint-disable-line @typescript-eslint/no-explicit-any\n | (Nodes | SendInterface<Nodes>)[]; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\n/**\n * One or more commands to update the graph's state and send messages to nodes.\n * Can be used to combine routing logic with state updates in lieu of conditional edges\n *\n * @example\n * ```ts\n * import { Annotation, Command } from \"@langchain/langgraph\";\n *\n * // Define graph state\n * const StateAnnotation = Annotation.Root({\n * foo: Annotation<string>,\n * });\n *\n * // Define the nodes\n * const nodeA = async (_state: typeof StateAnnotation.State) => {\n * console.log(\"Called A\");\n * // this is a replacement for a real conditional edge function\n * const goto = Math.random() > .5 ? \"nodeB\" : \"nodeC\";\n * // note how Command allows you to BOTH update the graph state AND route to the next node\n * return new Command({\n * // this is the state update\n * update: {\n * foo: \"a\",\n * },\n * // this is a replacement for an edge\n * goto,\n * });\n * };\n *\n * // Nodes B and C are unchanged\n * const nodeB = async (state: typeof StateAnnotation.State) => {\n * console.log(\"Called B\");\n * return {\n * foo: state.foo + \"|b\",\n * };\n * }\n *\n * const nodeC = async (state: typeof StateAnnotation.State) => {\n * console.log(\"Called C\");\n * return {\n * foo: state.foo + \"|c\",\n * };\n * }\n * \n * import { StateGraph } from \"@langchain/langgraph\";\n\n * // NOTE: there are no edges between nodes A, B and C!\n * const graph = new StateGraph(StateAnnotation)\n * .addNode(\"nodeA\", nodeA, {\n * ends: [\"nodeB\", \"nodeC\"],\n * })\n * .addNode(\"nodeB\", nodeB)\n * .addNode(\"nodeC\", nodeC)\n * .addEdge(\"__start__\", \"nodeA\")\n * .compile();\n * \n * await graph.invoke({ foo: \"\" });\n *\n * // Randomly oscillates between\n * // { foo: 'a|c' } and { foo: 'a|b' }\n * ```\n */\nexport class Command<\n Resume = unknown,\n Update extends Record<string, unknown> = Record<string, unknown>,\n Nodes extends string = string,\n> extends CommandInstance<Resume, Update, Nodes> {\n readonly lg_name = \"Command\";\n\n lc_direct_tool_output = true;\n\n /**\n * Graph to send the command to. Supported values are:\n * - None: the current graph (default)\n * - The specific name of the graph to send the command to\n * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph)\n */\n graph?: string;\n\n /**\n * Update to apply to the graph's state as a result of executing the node that is returning the command.\n * Written to the state as if the node had simply returned this value instead of the Command object.\n */\n update?: Update | [string, unknown][];\n\n /**\n * Value to resume execution with. To be used together with {@link interrupt}.\n */\n resume?: Resume;\n\n /**\n * Can be one of the following:\n * - name of the node to navigate to next (any node that belongs to the specified `graph`)\n * - sequence of node names to navigate to next\n * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object)\n * - sequence of {@link Send} objects\n */\n goto?: Nodes | Send<Nodes> | (Nodes | Send<Nodes>)[] = [];\n\n static PARENT = \"__parent__\";\n\n constructor(args: Omit<CommandParams<Resume, Update, Nodes>, \"lg_name\">) {\n super(args);\n this.resume = args.resume;\n this.graph = args.graph;\n this.update = args.update;\n if (args.goto) {\n type ValidArg = Nodes | Send<Nodes, Update>;\n\n this.goto = Array.isArray(args.goto)\n ? (_deserializeCommandSendObjectGraph(args.goto) as ValidArg[])\n : [_deserializeCommandSendObjectGraph(args.goto) as ValidArg];\n }\n }\n\n /**\n * Convert the update field to a list of {@link PendingWrite} tuples\n * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`.\n * @internal\n */\n _updateAsTuples(): PendingWrite[] {\n if (\n this.update &&\n typeof this.update === \"object\" &&\n !Array.isArray(this.update)\n ) {\n return Object.entries(this.update);\n } else if (\n Array.isArray(this.update) &&\n this.update.every(\n (t): t is [string, unknown] =>\n Array.isArray(t) && t.length === 2 && typeof t[0] === \"string\"\n )\n ) {\n return this.update;\n } else {\n return [[\"__root__\", this.update]];\n }\n }\n\n toJSON() {\n let serializedGoto;\n if (typeof this.goto === \"string\") {\n serializedGoto = this.goto;\n } else if (_isSend(this.goto)) {\n serializedGoto = this.goto.toJSON();\n } else {\n serializedGoto = this.goto?.map((innerGoto) => {\n if (typeof innerGoto === \"string\") {\n return innerGoto;\n } else {\n return innerGoto.toJSON();\n }\n });\n }\n return {\n lg_name: this.lg_name,\n update: this.update,\n resume: this.resume,\n goto: serializedGoto,\n };\n }\n}\n\n/**\n * A type guard to check if the given value is a {@link Command}.\n *\n * Useful for type narrowing when working with the {@link Command} object.\n *\n * @param x - The value to check.\n * @returns `true` if the value is a {@link Command}, `false` otherwise.\n */\nexport function isCommand(x: unknown): x is Command {\n if (typeof x !== \"object\") {\n return false;\n }\n\n if (x === null || x === undefined) {\n return false;\n }\n\n if (\"lg_name\" in x && x.lg_name === \"Command\") {\n return true;\n }\n\n return false;\n}\n\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Reconstructs Command and Send objects from a deeply nested tree of anonymous objects\n * matching their interfaces.\n *\n * This is only exported for testing purposes. It is NOT intended to be used outside of\n * the Command and Send classes.\n *\n * @internal\n *\n * @param x - The command send tree to convert.\n * @param seen - A map of seen objects to avoid infinite loops.\n * @returns The converted command send tree.\n */\nexport function _deserializeCommandSendObjectGraph(\n x: unknown,\n seen: Map<object, unknown> = new Map()\n): unknown {\n if (x !== undefined && x !== null && typeof x === \"object\") {\n // If we've already processed this object, return the transformed version\n if (seen.has(x)) {\n return seen.get(x);\n }\n\n let result: unknown;\n\n if (Array.isArray(x)) {\n // Create the array first, then populate it\n result = [];\n // Add to seen map before processing elements to handle self-references\n seen.set(x, result);\n\n // Now populate the array\n x.forEach((item, index) => {\n (result as unknown[])[index] = _deserializeCommandSendObjectGraph(\n item,\n seen\n );\n });\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (x instanceof Command || x instanceof Send || !isPlainObject(x)) {\n result = x;\n seen.set(x, result);\n } else if (isCommand(x)) {\n result = new Command(x);\n seen.set(x, result);\n } else if (_isSendInterface(x)) {\n result = new Send(\n x.node,\n x.args,\n x.timeout !== undefined ? { timeout: x.timeout } : undefined\n );\n seen.set(x, result);\n } else if (\"lc_serializable\" in x && x.lc_serializable) {\n result = x;\n seen.set(x, result);\n } else {\n // Create empty object first\n result = {};\n // Add to seen map before processing properties to handle self-references\n seen.set(x, result);\n\n // Now populate the object\n for (const [key, value] of Object.entries(x)) {\n (result as Record<string, unknown>)[key] =\n _deserializeCommandSendObjectGraph(value, seen);\n }\n }\n\n return result;\n }\n return x;\n}\n"],"mappings":";;;AAQA,MAAa,QAAQ;;AAErB,MAAa,MAAM;AACnB,MAAa,QAAQ;AACrB,MAAa,OAAO;AACpB,MAAa,QAAQ;;;;;;;AAOrB,MAAa,oBAAoB;;AAGjC,MAAa,kBAAkB;;;;;;;;;;;;;;AAe/B,SAAgB,qCAA6C;CAC3D,MAAM,MACJ,OAAO,YAAY,cACf,QAAQ,KAAK,gDACb,KAAA;AACN,KAAI,QAAQ,KAAA,KAAa,QAAQ,IAAI;EACnC,MAAM,SAAS,OAAO,SAAS,KAAK,GAAG;AACvC,MAAI,OAAO,SAAS,OAAO,IAAI,SAAS,EAAG,QAAO;;AAEpD,QAAO;;AAGT,MAAa,kBAAkB;;AAE/B,MAAa,kBAAkB;AAC/B,MAAa,kBAAkB;AAC/B,MAAa,0BAA0B;AAC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;;;;;;;;;AAgBzD,SAAgB,mCACd,GACA,uBAA6B,IAAI,KAAK,EAC7B;AACT,KAAI,MAAM,KAAA,KAAa,MAAM,QAAQ,OAAO,MAAM,UAAU;AAE1D,MAAI,KAAK,IAAI,EAAE,CACb,QAAO,KAAK,IAAI,EAAE;EAGpB,IAAI;AAEJ,MAAI,MAAM,QAAQ,EAAE,EAAE;AAEpB,YAAS,EAAE;AAEX,QAAK,IAAI,GAAG,OAAO;AAGnB,KAAE,SAAS,MAAM,UAAU;AACxB,WAAqB,SAAS,mCAC7B,MACA,KACD;KACD;aAEO,aAAa,WAAW,aAAa,QAAQ,CAAC,cAAc,EAAE,EAAE;AACzE,YAAS;AACT,QAAK,IAAI,GAAG,OAAO;aACV,UAAU,EAAE,EAAE;AACvB,YAAS,IAAI,QAAQ,EAAE;AACvB,QAAK,IAAI,GAAG,OAAO;aACV,iBAAiB,EAAE,EAAE;AAC9B,YAAS,IAAI,KACX,EAAE,MACF,EAAE,MACF,EAAE,YAAY,KAAA,IAAY,EAAE,SAAS,EAAE,SAAS,GAAG,KAAA,EACpD;AACD,QAAK,IAAI,GAAG,OAAO;aACV,qBAAqB,KAAK,EAAE,iBAAiB;AACtD,YAAS;AACT,QAAK,IAAI,GAAG,OAAO;SACd;AAEL,YAAS,EAAE;AAEX,QAAK,IAAI,GAAG,OAAO;AAGnB,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,EAAE,CACzC,QAAmC,OAClC,mCAAmC,OAAO,KAAK;;AAIrD,SAAO;;AAET,QAAO"}
|
|
1
|
+
{"version":3,"file":"constants.cjs","names":["coerceTimeoutPolicy"],"sources":["../src/constants.ts"],"sourcesContent":["import { PendingWrite } from \"@langchain/langgraph-checkpoint\";\nimport type { JSONSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n coerceTimeoutPolicy,\n type TimeoutPolicy,\n} from \"./pregel/utils/timeout.js\";\n\n/** Special reserved node name denoting the start of a graph. */\nexport const START = \"__start__\";\n/** Special reserved node name denoting the end of a graph. */\nexport const END = \"__end__\";\nexport const INPUT = \"__input__\";\nexport const COPY = \"__copy__\";\nexport const ERROR = \"__error__\";\n/**\n * Special reserved write key recording the name of the node whose execution\n * failed, so node-level error handlers see the same failure provenance after a\n * checkpoint resume. Value format in pending writes:\n * `[taskId, ERROR_SOURCE_NODE, nodeName: string]`.\n */\nexport const ERROR_SOURCE_NODE = \"__error_source_node__\";\n\n/** Special reserved cache namespaces */\nexport const CACHE_NS_WRITES = \"__pregel_ns_writes\";\n\n/**\n * System-wide upper bound on how many supersteps a {@link DeltaChannel} may go\n * without writing a {@link DeltaSnapshot} blob. Once a channel's\n * supersteps-since-snapshot counter reaches this value, a snapshot is forced\n * even if the channel's own `snapshotFrequency` has not been reached — this\n * prevents unbounded ancestor walks on threads where a delta channel exists\n * but is no longer being updated.\n *\n * Overridable via the `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`\n * environment variable. Read lazily so test/runtime overrides take effect.\n *\n * @remarks Beta.\n */\nexport function getDeltaMaxSuperstepsSinceSnapshot(): number {\n const raw =\n typeof process !== \"undefined\"\n ? process.env?.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT\n : undefined;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number.parseInt(raw, 10);\n if (Number.isFinite(parsed) && parsed > 0) return parsed;\n }\n return 5000;\n}\n\nexport const CONFIG_KEY_SEND = \"__pregel_send\";\n/** config key containing function used to call a node (push task) */\nexport const CONFIG_KEY_CALL = \"__pregel_call\";\nexport const CONFIG_KEY_READ = \"__pregel_read\";\nexport const CONFIG_KEY_CHECKPOINTER = \"__pregel_checkpointer\";\nexport const CONFIG_KEY_RESUMING = \"__pregel_resuming\";\nexport const CONFIG_KEY_TASK_ID = \"__pregel_task_id\";\nexport const CONFIG_KEY_STREAM = \"__pregel_stream\";\nexport const CONFIG_KEY_RESUME_VALUE = \"__pregel_resume_value\";\nexport const CONFIG_KEY_RESUME_MAP = \"__pregel_resume_map\";\nexport const CONFIG_KEY_SCRATCHPAD = \"__pregel_scratchpad\";\n/** config key containing state from previous invocation of graph for the given thread */\nexport const CONFIG_KEY_PREVIOUS_STATE = \"__pregel_previous\";\nexport const CONFIG_KEY_DURABILITY = \"__pregel_durability\";\nexport const CONFIG_KEY_CHECKPOINT_ID = \"checkpoint_id\";\nexport const CONFIG_KEY_CHECKPOINT_NS = \"checkpoint_ns\";\n\nexport const CONFIG_KEY_NODE_FINISHED = \"__pregel_node_finished\";\n\n/**\n * Config key holding a {@link NodeError} (failed source node + error) for the\n * current node-level error handler invocation. Injected when an error handler\n * task is prepared after the failing node's retry policy is exhausted.\n */\nexport const CONFIG_KEY_NODE_ERROR = \"__pregel_node_error\";\n\n// this one is part of public API\nexport const CONFIG_KEY_CHECKPOINT_MAP = \"checkpoint_map\";\n\nexport const CONFIG_KEY_REPLAY_STATE = \"__pregel_replay_state\";\n\nexport const CONFIG_KEY_ABORT_SIGNALS = \"__pregel_abort_signals\";\n\n/** Special channel reserved for graph interrupts */\nexport const INTERRUPT = \"__interrupt__\";\n/** Special channel reserved for graph resume */\nexport const RESUME = \"__resume__\";\n/** Special channel reserved for cases when a task exits without any writes */\nexport const NO_WRITES = \"__no_writes__\";\n/** Special channel reserved for graph return */\nexport const RETURN = \"__return__\";\n/** Special channel reserved for graph previous state */\nexport const PREVIOUS = \"__previous__\";\nexport const RUNTIME_PLACEHOLDER = \"__pregel_runtime_placeholder__\";\nexport const RECURSION_LIMIT_DEFAULT = 25;\n\nexport const TAG_HIDDEN = \"langsmith:hidden\";\nexport const TAG_NOSTREAM = \"langsmith:nostream\";\nexport const SELF = \"__self__\";\n\nexport const TASKS = \"__pregel_tasks\";\nexport const PUSH = \"__pregel_push\";\nexport const PULL = \"__pregel_pull\";\n\nexport const TASK_NAMESPACE = \"6ba7b831-9dad-11d1-80b4-00c04fd430c8\";\nexport const NULL_TASK_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport const RESERVED = [\n TAG_HIDDEN,\n INPUT,\n INTERRUPT,\n RESUME,\n ERROR,\n ERROR_SOURCE_NODE,\n NO_WRITES,\n\n // reserved config.configurable keys\n CONFIG_KEY_SEND,\n CONFIG_KEY_READ,\n CONFIG_KEY_CHECKPOINTER,\n CONFIG_KEY_DURABILITY,\n CONFIG_KEY_STREAM,\n CONFIG_KEY_RESUMING,\n CONFIG_KEY_TASK_ID,\n CONFIG_KEY_CALL,\n CONFIG_KEY_RESUME_VALUE,\n CONFIG_KEY_SCRATCHPAD,\n CONFIG_KEY_PREVIOUS_STATE,\n CONFIG_KEY_CHECKPOINT_MAP,\n CONFIG_KEY_CHECKPOINT_NS,\n CONFIG_KEY_CHECKPOINT_ID,\n CONFIG_KEY_REPLAY_STATE,\n];\n\nexport const CHECKPOINT_NAMESPACE_SEPARATOR = \"|\";\nexport const CHECKPOINT_NAMESPACE_END = \":\";\n\n/**\n * Symbol used internally to identify Command instances.\n * Exported to support cross-version type compatibility.\n * @internal\n */\nexport const COMMAND_SYMBOL = Symbol.for(\"langgraph.command\");\n\n/**\n * Instance of a {@link Command} class.\n *\n * This is used to avoid IntelliSense suggesting public fields\n * of {@link Command} class when a plain object is expected.\n *\n * @see {@link Command}\n * @internal\n */\nexport class CommandInstance<\n Resume = unknown,\n Update = Record<string, unknown>,\n Nodes extends string = string,\n> {\n [COMMAND_SYMBOL]: CommandParams<Resume, Update, Nodes>;\n\n constructor(args: CommandParams<Resume, Update, Nodes>) {\n this[COMMAND_SYMBOL] = args;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SendInterface<Node extends string = string, Args = any> {\n node: Node;\n args: Args;\n /**\n * Optional per-task timeout policy that overrides the target node's timeout\n * for this specific pushed task.\n */\n timeout?: TimeoutPolicy;\n}\n\n/** Keyword options for {@link Send}. */\nexport type SendOptions = {\n /**\n * Per-task timeout policy overriding the target node's timeout for this\n * pushed task. A bare number is treated as `runTimeout` (milliseconds).\n */\n timeout?: number | TimeoutPolicy;\n};\n\nexport function _isSendInterface(x: unknown): x is SendInterface {\n const operation = x as SendInterface;\n return (\n operation !== null &&\n operation !== undefined &&\n typeof operation.node === \"string\" &&\n operation.args !== undefined\n );\n}\n\n/**\n *\n * A message or packet to send to a specific node in the graph.\n *\n * The `Send` class is used within a `StateGraph`'s conditional edges to\n * dynamically invoke a node with a custom state at the next step.\n *\n * Importantly, the sent state can differ from the core graph's state,\n * allowing for flexible and dynamic workflow management.\n *\n * One such example is a \"map-reduce\" workflow where your graph invokes\n * the same node multiple times in parallel with different states,\n * before aggregating the results back into the main graph's state.\n *\n * @example\n * ```typescript\n * import { Annotation, Send, StateGraph } from \"@langchain/langgraph\";\n *\n * const ChainState = Annotation.Root({\n * subjects: Annotation<string[]>,\n * jokes: Annotation<string[]>({\n * reducer: (a, b) => a.concat(b),\n * }),\n * });\n *\n * const continueToJokes = async (state: typeof ChainState.State) => {\n * return state.subjects.map((subject) => {\n * return new Send(\"generate_joke\", { subjects: [subject] });\n * });\n * };\n *\n * @remarks\n * A per-task timeout can be supplied via the third argument's `timeout` option\n * to override the target node's configured timeout for this specific pushed task:\n *\n * ```typescript\n * new Send(\"generate_joke\", { subjects: [subject] }, { timeout: { idleTimeout: 5000 } });\n * ```\n *\n * const graph = new StateGraph(ChainState)\n * .addNode(\"generate_joke\", (state) => ({\n * jokes: [`Joke about ${state.subjects}`],\n * }))\n * .addConditionalEdges(\"__start__\", continueToJokes)\n * .addEdge(\"generate_joke\", \"__end__\")\n * .compile();\n *\n * const res = await graph.invoke({ subjects: [\"cats\", \"dogs\"] });\n * console.log(res);\n *\n * // Invoking with two subjects results in a generated joke for each\n * // { subjects: [\"cats\", \"dogs\"], jokes: [`Joke about cats`, `Joke about dogs`] }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class Send<\n Node extends string = string,\n Args = any,\n> implements SendInterface<Node, Args> {\n lg_name = \"Send\";\n\n public node: Node;\n\n public args: Args;\n\n /**\n * Optional per-task timeout policy that overrides the target node's timeout\n * for this specific pushed task. A bare number is treated as a hard\n * `runTimeout` (in milliseconds).\n */\n public timeout?: TimeoutPolicy;\n\n constructor(node: Node, args: Args, options?: SendOptions) {\n this.node = node;\n this.args = _deserializeCommandSendObjectGraph(args) as Args;\n this.timeout = coerceTimeoutPolicy(options?.timeout);\n }\n\n toJSON() {\n return {\n lg_name: this.lg_name,\n node: this.node,\n args: this.args,\n timeout: this.timeout,\n };\n }\n}\n\nexport function _isSend(x: unknown): x is Send {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return x instanceof Send;\n}\n\nexport const OVERWRITE = \"__overwrite__\";\n\n/**\n * An object representing a direct overwrite of a value for a channel.\n * Used to signal that the channel value should be replaced with the given value,\n * bypassing any reducer or binary operator logic.\n *\n * @template ValueType - The type of the value being overwritten.\n * @property {ValueType} [OVERWRITE] - The value to directly set.\n *\n * @example\n * const overwriteObj: OverwriteValue<number> = { __overwrite__: 123 };\n */\nexport interface OverwriteValue<ValueType> {\n [OVERWRITE]: ValueType;\n}\n\n/**\n * Bypass a reducer and write the wrapped value directly to a\n * {@link BinaryOperatorAggregate} channel.\n *\n * Receiving multiple `Overwrite` values for the same channel in a single\n * super-step will raise an {@link InvalidUpdateError}.\n *\n * @example\n * ```typescript\n * import { Annotation, StateGraph, Overwrite } from \"@langchain/langgraph\";\n *\n * const State = Annotation.Root({\n * messages: Annotation<string[]>({\n * reducer: (a, b) => a.concat(b),\n * default: () => [],\n * }),\n * });\n *\n * const replaceMessages = (_state: typeof State.State) => {\n * return { messages: new Overwrite([\"replacement\"]) };\n * };\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class Overwrite<ValueType = any> implements OverwriteValue<ValueType> {\n lg_name = \"Overwrite\";\n\n readonly [OVERWRITE]: ValueType;\n\n constructor(value: ValueType) {\n this[OVERWRITE] = value;\n }\n\n get value(): ValueType {\n return this[OVERWRITE];\n }\n\n toJSON() {\n return { [OVERWRITE]: this[OVERWRITE] };\n }\n\n static isInstance<ValueType>(value: unknown): value is Overwrite<ValueType> {\n if (!value || typeof value !== \"object\") return false;\n if (OVERWRITE in value) return true;\n if (\"lg_name\" in value && value.lg_name === \"Overwrite\") return true;\n return false;\n }\n}\n\n/**\n * Helper function to detect and extract the value from an Overwrite wrapper,\n * supporting both the Overwrite class instance and the serialized object format.\n *\n * Use to check if a provided value represents an Overwrite: returns the\n * unwrapped value if so, or undefined otherwise.\n *\n * - If the value is an Overwrite instance (preferred API), return its `.value`.\n * - If the value is a wire-format object ({ [OVERWRITE]: value }), extract it.\n * - If the value is the discriminator form ({ type: OVERWRITE, value }) that\n * results from JSON-serializing a typed `Overwrite` in another runtime (e.g.\n * a Python dataclass routed through the LangGraph API server, where the typed\n * instance is erased), extract it. Keeps Overwrite semantics intact across\n * cross-runtime JSON boundaries.\n * - Otherwise, returns undefined.\n *\n * @template ValueType - The expected type of the Overwrite value.\n * @param value - The value to check (may be anything).\n * @returns The unwrapped value if value is an Overwrite, or undefined otherwise.\n * @internal\n */\nexport function _getOverwriteValue<ValueType>(\n value: unknown\n): [true, ValueType] | [false, undefined] {\n if (typeof value === \"object\" && value !== null) {\n if (OVERWRITE in value) {\n return [true, (value as Record<string, ValueType>)[OVERWRITE]];\n }\n const rec = value as Record<string, unknown>;\n if (rec.type === OVERWRITE && \"value\" in rec) {\n return [true, rec.value as ValueType];\n }\n }\n return [false, undefined];\n}\n\n/**\n * Type guard to check if a value is an Overwrite value -- either the class\n * instance or the wire format object.\n *\n * @template ValueType - The expected type of the Overwrite value.\n * @param value - The value to check (may be anything).\n * @returns `true` if the value is an Overwrite value, `false` otherwise.\n * @internal\n */\nexport function _isOverwriteValue<ValueType>(\n value: unknown\n): value is OverwriteValue<ValueType> {\n return _getOverwriteValue<ValueType>(value)[0];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Interrupt<Value = any> = {\n id?: string;\n value?: Value;\n /**\n * JSON Schema for the value expected when resuming this interrupt,\n * if the graph provided one via `interrupt(value, { responseSchema })`.\n */\n response_schema?: JSONSchema;\n};\n\n/**\n * Checks if the given graph invoke / stream chunk contains interrupt.\n *\n * @example\n * ```ts\n * import { INTERRUPT, isInterrupted } from \"@langchain/langgraph\";\n *\n * const values = await graph.invoke({ foo: \"bar\" });\n * if (isInterrupted<string>(values)) {\n * const interrupt = values[INTERRUPT][0].value;\n * }\n * ```\n *\n * @param values - The values to check.\n * @returns `true` if the values contain an interrupt, `false` otherwise.\n */\nexport function isInterrupted<Value = unknown>(\n values: unknown\n): values is { [INTERRUPT]: Interrupt<Value>[] } {\n if (!values || typeof values !== \"object\") return false;\n if (!(INTERRUPT in values)) return false;\n return Array.isArray(values[INTERRUPT]);\n}\n\nexport type CommandParams<\n Resume = unknown,\n Update = Record<string, unknown>,\n Nodes extends string = string,\n> = {\n /**\n * A discriminator field used to identify the type of object. Must be populated when serializing.\n *\n * Optional because it's not required to specify this when directly constructing a {@link Command}\n * object.\n */\n lg_name?: \"Command\";\n\n /**\n * Value to resume execution with. To be used together with {@link interrupt}.\n */\n resume?: Resume;\n /**\n * Graph to send the command to. Supported values are:\n * - None: the current graph (default)\n * - The specific name of the graph to send the command to\n * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph)\n */\n graph?: string;\n\n /**\n * Update to apply to the graph's state.\n */\n update?: Update | [string, unknown][];\n\n /**\n * Can be one of the following:\n * - name of the node to navigate to next (any node that belongs to the specified `graph`)\n * - sequence of node names to navigate to next\n * - `Send` object (to execute a node with the input provided)\n * - sequence of `Send` objects\n */\n goto?:\n | Nodes\n | SendInterface<Nodes> // eslint-disable-line @typescript-eslint/no-explicit-any\n | (Nodes | SendInterface<Nodes>)[]; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\n/**\n * One or more commands to update the graph's state and send messages to nodes.\n * Can be used to combine routing logic with state updates in lieu of conditional edges\n *\n * @example\n * ```ts\n * import { Annotation, Command } from \"@langchain/langgraph\";\n *\n * // Define graph state\n * const StateAnnotation = Annotation.Root({\n * foo: Annotation<string>,\n * });\n *\n * // Define the nodes\n * const nodeA = async (_state: typeof StateAnnotation.State) => {\n * console.log(\"Called A\");\n * // this is a replacement for a real conditional edge function\n * const goto = Math.random() > .5 ? \"nodeB\" : \"nodeC\";\n * // note how Command allows you to BOTH update the graph state AND route to the next node\n * return new Command({\n * // this is the state update\n * update: {\n * foo: \"a\",\n * },\n * // this is a replacement for an edge\n * goto,\n * });\n * };\n *\n * // Nodes B and C are unchanged\n * const nodeB = async (state: typeof StateAnnotation.State) => {\n * console.log(\"Called B\");\n * return {\n * foo: state.foo + \"|b\",\n * };\n * }\n *\n * const nodeC = async (state: typeof StateAnnotation.State) => {\n * console.log(\"Called C\");\n * return {\n * foo: state.foo + \"|c\",\n * };\n * }\n * \n * import { StateGraph } from \"@langchain/langgraph\";\n\n * // NOTE: there are no edges between nodes A, B and C!\n * const graph = new StateGraph(StateAnnotation)\n * .addNode(\"nodeA\", nodeA, {\n * ends: [\"nodeB\", \"nodeC\"],\n * })\n * .addNode(\"nodeB\", nodeB)\n * .addNode(\"nodeC\", nodeC)\n * .addEdge(\"__start__\", \"nodeA\")\n * .compile();\n * \n * await graph.invoke({ foo: \"\" });\n *\n * // Randomly oscillates between\n * // { foo: 'a|c' } and { foo: 'a|b' }\n * ```\n */\nexport class Command<\n Resume = unknown,\n Update extends Record<string, unknown> = Record<string, unknown>,\n Nodes extends string = string,\n> extends CommandInstance<Resume, Update, Nodes> {\n readonly lg_name = \"Command\";\n\n lc_direct_tool_output = true;\n\n /**\n * Graph to send the command to. Supported values are:\n * - None: the current graph (default)\n * - The specific name of the graph to send the command to\n * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph)\n */\n graph?: string;\n\n /**\n * Update to apply to the graph's state as a result of executing the node that is returning the command.\n * Written to the state as if the node had simply returned this value instead of the Command object.\n */\n update?: Update | [string, unknown][];\n\n /**\n * Value to resume execution with. To be used together with {@link interrupt}.\n */\n resume?: Resume;\n\n /**\n * Can be one of the following:\n * - name of the node to navigate to next (any node that belongs to the specified `graph`)\n * - sequence of node names to navigate to next\n * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object)\n * - sequence of {@link Send} objects\n */\n goto?: Nodes | Send<Nodes> | (Nodes | Send<Nodes>)[] = [];\n\n static PARENT = \"__parent__\";\n\n constructor(args: Omit<CommandParams<Resume, Update, Nodes>, \"lg_name\">) {\n super(args);\n this.resume = args.resume;\n this.graph = args.graph;\n this.update = args.update;\n if (args.goto) {\n type ValidArg = Nodes | Send<Nodes, Update>;\n\n this.goto = Array.isArray(args.goto)\n ? (_deserializeCommandSendObjectGraph(args.goto) as ValidArg[])\n : [_deserializeCommandSendObjectGraph(args.goto) as ValidArg];\n }\n }\n\n /**\n * Convert the update field to a list of {@link PendingWrite} tuples\n * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`.\n * @internal\n */\n _updateAsTuples(): PendingWrite[] {\n if (\n this.update &&\n typeof this.update === \"object\" &&\n !Array.isArray(this.update)\n ) {\n return Object.entries(this.update);\n } else if (\n Array.isArray(this.update) &&\n this.update.every(\n (t): t is [string, unknown] =>\n Array.isArray(t) && t.length === 2 && typeof t[0] === \"string\"\n )\n ) {\n return this.update;\n } else {\n return [[\"__root__\", this.update]];\n }\n }\n\n toJSON() {\n let serializedGoto;\n if (typeof this.goto === \"string\") {\n serializedGoto = this.goto;\n } else if (_isSend(this.goto)) {\n serializedGoto = this.goto.toJSON();\n } else {\n serializedGoto = this.goto?.map((innerGoto) => {\n if (typeof innerGoto === \"string\") {\n return innerGoto;\n } else {\n return innerGoto.toJSON();\n }\n });\n }\n return {\n lg_name: this.lg_name,\n update: this.update,\n resume: this.resume,\n goto: serializedGoto,\n };\n }\n}\n\n/**\n * A type guard to check if the given value is a {@link Command}.\n *\n * Useful for type narrowing when working with the {@link Command} object.\n *\n * @param x - The value to check.\n * @returns `true` if the value is a {@link Command}, `false` otherwise.\n */\nexport function isCommand(x: unknown): x is Command {\n if (typeof x !== \"object\") {\n return false;\n }\n\n if (x === null || x === undefined) {\n return false;\n }\n\n // Not `instanceof`: a Command built by another copy of this package must\n // still pass. Plain objects are rejected so JSON input cannot forge one.\n if (!isPlainObject(x) && \"lg_name\" in x && x.lg_name === \"Command\") {\n return true;\n }\n\n return false;\n}\n\nfunction isPlainObject(value: object): value is Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Reconstructs Command and Send objects from a deeply nested tree of anonymous objects\n * matching their interfaces.\n *\n * This is only exported for testing purposes. It is NOT intended to be used outside of\n * the Command and Send classes.\n *\n * @internal\n *\n * @param x - The command send tree to convert.\n * @param seen - A map of seen objects to avoid infinite loops.\n * @returns The converted command send tree.\n */\nexport function _deserializeCommandSendObjectGraph(\n x: unknown,\n seen: Map<object, unknown> = new Map()\n): unknown {\n if (x !== undefined && x !== null && typeof x === \"object\") {\n // If we've already processed this object, return the transformed version\n if (seen.has(x)) {\n return seen.get(x);\n }\n\n let result: unknown;\n\n if (Array.isArray(x)) {\n // Create the array first, then populate it\n result = [];\n // Add to seen map before processing elements to handle self-references\n seen.set(x, result);\n\n // Now populate the array\n x.forEach((item, index) => {\n (result as unknown[])[index] = _deserializeCommandSendObjectGraph(\n item,\n seen\n );\n });\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (x instanceof Command || x instanceof Send || !isPlainObject(x)) {\n result = x;\n seen.set(x, result);\n } else if (\"lg_name\" in x && x.lg_name === \"Command\") {\n result = new Command(x as CommandParams);\n seen.set(x, result);\n } else if (_isSendInterface(x)) {\n result = new Send(\n x.node,\n x.args,\n x.timeout !== undefined ? { timeout: x.timeout } : undefined\n );\n seen.set(x, result);\n } else if (\"lc_serializable\" in x && x.lc_serializable) {\n result = x;\n seen.set(x, result);\n } else {\n // Create empty object first\n result = {};\n // Add to seen map before processing properties to handle self-references\n seen.set(x, result);\n\n // Now populate the object\n for (const [key, value] of Object.entries(x)) {\n (result as Record<string, unknown>)[key] =\n _deserializeC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